text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview Manages navigation within a page.
 * This unifies navigation by the DOM walker and by WebKit selection.
 * NOTE: the purpose of this class is only to hold state
 * and delegate all of its functionality to mostly stateless classes that
 * are easy to test.
 *
 */

goog.provide('cvox.NavigationManager');

goog.require('cvox.ActiveIndicator');
goog.require('cvox.ChromeVox');
goog.require('cvox.ChromeVoxEventSuspender');
goog.require('cvox.CursorSelection');
goog.require('cvox.DescriptionUtil');
goog.require('cvox.DomUtil');
goog.require('cvox.FindUtil');
goog.require('cvox.Focuser');
goog.require('cvox.Interframe');
goog.require('cvox.MathShifter');
goog.require('cvox.NavBraille');
goog.require('cvox.NavDescription');
goog.require('cvox.NavigationHistory');
goog.require('cvox.NavigationShifter');
goog.require('cvox.NavigationSpeaker');
goog.require('cvox.PageSelection');
goog.require('cvox.SelectionUtil');
goog.require('cvox.TableShifter');
goog.require('cvox.TraverseMath');
goog.require('cvox.Widget');

/**
 * @constructor
 */
cvox.NavigationManager = function() {
  this.addInterframeListener_();

  this.reset();
};

/**
 * Stores state variables in a provided object.
 *
 * @param {Object} store The object.
 */
cvox.NavigationManager.prototype.storeOn = function(store) {
  store['reversed'] = this.isReversed();
  store['keepReading'] = this.keepReading_;
  store['findNext'] = this.predicate_;
  this.shifter_.storeOn(store);
};

/**
 * Updates the object with state variables from an earlier storeOn call.
 *
 * @param {Object} store The object.
 */
cvox.NavigationManager.prototype.readFrom = function(store) {
  this.curSel_.setReversed(store['reversed']);
  this.shifter_.readFrom(store);
  if (store['keepReading']) {
    this.startReading(cvox.AbstractTts.QUEUE_MODE_FLUSH);
  }
};

/**
 * Resets the navigation manager to the top of the page.
 */
cvox.NavigationManager.prototype.reset = function() {
  /**
   * @type {!cvox.NavigationSpeaker}
   * @private
   */
  this.navSpeaker_ = new cvox.NavigationSpeaker();

  /**
   * @type {!Array.<Object>}
   * @private
   */
  this.shifterTypes_ = [cvox.NavigationShifter,
                        cvox.TableShifter,
                        cvox.MathShifter];

  /**
   * @type {!Array.<!cvox.AbstractShifter>}
  */
  this.shifterStack_ = [];

  /**
   * The active shifter.
   * @type {!cvox.AbstractShifter}
   * @private
  */
  this.shifter_ = new cvox.NavigationShifter();

  // NOTE(deboer): document.activeElement can not be null (c.f.
  // https://developer.mozilla.org/en-US/docs/DOM/document.activeElement)
  // Instead, if there is no active element, activeElement is set to
  // document.body.
  /**
   * If there is an activeElement, use it.  Otherwise, sync to the page
   * beginning.
   * @type {!cvox.CursorSelection}
   * @private
   */
  this.curSel_ = document.activeElement != document.body ?
      /** @type {!cvox.CursorSelection} **/
      (cvox.CursorSelection.fromNode(document.activeElement)) :
      this.shifter_.begin(this.curSel_, {reversed: false});

  /**
   * @type {!cvox.CursorSelection}
   * @private
   */
  this.prevSel_ = this.curSel_.clone();

  /**
   * Keeps track of whether we have skipped while "reading from here"
   * so that we can insert an earcon.
   * @type {boolean}
   * @private
   */
  this.skipped_ = false;

  /**
   * Keeps track of whether we have recovered from dropped focus
   * so that we can insert an earcon.
   * @type {boolean}
   * @private
   */
  this.recovered_ = false;

  /**
   * True if in "reading from here" mode.
   * @type {boolean}
   * @private
   */
  this.keepReading_ = false;

  /**
   * True if we are at the end of the page and we wrap around.
   * @type {boolean}
   * @private
   */
  this.pageEnd_ = false;

  /**
   * True if we have already announced that we will wrap around.
   * @type {boolean}
   * @private
   */
  this.pageEndAnnounced_ = false;

  /**
   * True if we entered into a shifter.
   * @type {boolean}
   * @private
   */
  this.enteredShifter_ = false;

  /**
   * True if we exited a shifter.
   * @type {boolean}
   * @private
   */
  this.exitedShifter_ = false;

  /**
   * True if we want to ignore iframes no matter what.
   * @type {boolean}
   * @private
   */
  this.ignoreIframesNoMatterWhat_ = false;

  /**
   * @type {cvox.PageSelection}
   * @private
   */
  this.pageSel_ = null;

  /** @type {string} */
  this.predicate_ = '';

  /** @type {cvox.CursorSelection} */
  this.saveSel_ = null;

  // TODO(stoarca): This seems goofy. Why are we doing this?
  if (this.activeIndicator) {
    this.activeIndicator.removeFromDom();
  }
  this.activeIndicator = new cvox.ActiveIndicator();

  /**
   * Makes sure focus doesn't get lost.
   * @type {!cvox.NavigationHistory}
   * @private
   */
  this.navigationHistory_ = new cvox.NavigationHistory();

  /** @type {boolean} */
  this.focusRecovery_ = window.location.protocol != 'chrome:';

  this.iframeIdMap = {};
  this.nextIframeId = 1;

  // Only sync if the activeElement is not document.body; which is shorthand for
  // 'no selection'.  Currently the walkers don't deal with the no selection
  // case -- and it is not clear that they should.
  if (document.activeElement != document.body) {
    this.sync();
  }

  // This object is effectively empty when no math is in the page.
  cvox.TraverseMath.getInstance();
};

/**
 * Determines if we are navigating from a valid node. If not, ask navigation
 * history for an acceptable restart point and go there.
 * @param {function(Node)=} opt_predicate A function that takes in a node and
 *     returns true if it is a valid recovery candidate.
 * @return {boolean} True if we should continue navigation normally.
 */
cvox.NavigationManager.prototype.resolve = function(opt_predicate) {
  if (!this.getFocusRecovery()) {
    return true;
  }

  var current = this.getCurrentNode();

  if (!this.navigationHistory_.becomeInvalid(current)) {
    return true;
  }

  // Only attempt to revert if going next will cause us to restart at the top
  // of the page.
  if (this.hasNext_()) {
    return true;
  }

  // Our current node was invalid. Revert to history.
  var revert = this.navigationHistory_.revert(opt_predicate);

  // If the history is empty, revert.current will be null.  In that case,
  // it is best to continue navigating normally.
  if (!revert.current) {
    return true;
  }

  // Convert to selections.
  var newSel = cvox.CursorSelection.fromNode(revert.current);
  var context = cvox.CursorSelection.fromNode(revert.previous);

  // Default to document body if selections are null.
  newSel = newSel || cvox.CursorSelection.fromBody();
  context = context || cvox.CursorSelection.fromBody();
  newSel.setReversed(this.isReversed());

  this.updateSel(newSel, context);
  this.recovered_ = true;
  return false;
};

/**
 * Gets the state of focus recovery.
 * @return {boolean} True if focus recovery is on; false otherwise.
 */
cvox.NavigationManager.prototype.getFocusRecovery = function() {
  return this.focusRecovery_;
};

/**
 * Enables or disables focus recovery.
 * @param {boolean} value True to enable, false to disable.
 */
cvox.NavigationManager.prototype.setFocusRecovery = function(value) {
  this.focusRecovery_ = value;
};

/**
 * Delegates to NavigationShifter with current page state.
 * @param {boolean=} iframes Jump in and out of iframes if true. Default false.
 * @return {boolean} False if end of document has been reached.
 * @private
 */
cvox.NavigationManager.prototype.next_ = function(iframes) {
  if (this.tryBoundaries_(this.shifter_.next(this.curSel_), iframes)) {
    // TODO(dtseng): An observer interface would help to keep logic like this
    // to a minimum.
    this.pageSel_ && this.pageSel_.extend(this.curSel_);
    return true;
  }
  return false;
};

/**
 * Looks ahead to see if it is possible to navigate forward from the current
 * position.
 * @return {boolean} True if it is possible to navigate forward.
 * @private
 */
cvox.NavigationManager.prototype.hasNext_ = function() {
  // Non-default shifters validly end before page end.
  if (this.shifterStack_.length > 0) {
    return true;
  }
  var dummySel = this.curSel_.clone();
  var result = false;
  var dummyNavShifter = new cvox.NavigationShifter();
  dummyNavShifter.setGranularity(this.shifter_.getGranularity());
  dummyNavShifter.sync(dummySel);
  if (dummyNavShifter.next(dummySel)) {
    result = true;
  }
  return result;
};

/**
 * Delegates to NavigationShifter with current page state.
 * @param {function(Array.<Node>)} predicate A function taking an array
 *     of unique ancestor nodes as a parameter and returning a desired node.
 *     It returns null if that node can't be found.
 * @param {string=} opt_predicateName The programmatic name that exists in
 * cvox.DomPredicates. Used to dispatch calls across iframes since functions
 * cannot be stringified.
 * @param {boolean=} opt_initialNode Whether to start the search from node
 * (true), or the next node (false); defaults to false.
 * @return {cvox.CursorSelection} The newly found selection.
 */
cvox.NavigationManager.prototype.findNext = function(
    predicate, opt_predicateName, opt_initialNode) {
  this.predicate_ = opt_predicateName || '';
  this.resolve();
  this.shifter_ = this.shifterStack_[0] || this.shifter_;
  this.shifterStack_ = [];
  var ret = cvox.FindUtil.findNext(this.curSel_, predicate, opt_initialNode);
  if (!this.ignoreIframesNoMatterWhat_) {
    this.tryIframe_(ret && ret.start.node);
  }
  if (ret) {
    this.updateSelToArbitraryNode(ret.start.node);
  }
  this.predicate_ = '';
  return ret;
};

/**
 * Delegates to NavigationShifter with current page state.
 */
cvox.NavigationManager.prototype.sync = function() {
  this.resolve();
  var ret = this.shifter_.sync(this.curSel_);
  if (ret) {
    this.curSel_ = ret;
  }
};

/**
 * Sync's all possible cursors:
 * - focus
 * - ActiveIndicator
 * - CursorSelection
 * @param {boolean=} opt_skipText Skips focus on text nodes; defaults to false.
 */
cvox.NavigationManager.prototype.syncAll = function(opt_skipText) {
  this.sync();
  this.setFocus(opt_skipText);
  this.updateIndicator();
};

/**
 * Clears a DOM selection made via a CursorSelection.
 * @param {boolean=} opt_announce True to announce the clearing.
 * @return {boolean} If a selection was cleared.
 */
cvox.NavigationManager.prototype.clearPageSel = function(opt_announce) {
  var hasSel = !!this.pageSel_;
  if (hasSel && opt_announce) {
    var announcement = cvox.ChromeVox.msgs.getMsg('clear_page_selection');
    cvox.ChromeVox.tts.speak(announcement, cvox.AbstractTts.QUEUE_MODE_FLUSH,
                             cvox.AbstractTts.PERSONALITY_ANNOTATION);
  }
  this.pageSel_ = null;
  return hasSel;
};

/**
 * Begins or finishes a DOM selection at the current CursorSelection in the
 * document.
 * @return {boolean} Whether selection is on or off after this call.
 */
cvox.NavigationManager.prototype.togglePageSel = function() {
  this.pageSel_ = this.pageSel_ ? null :
      new cvox.PageSelection(this.curSel_.setReversed(false));
  return !!this.pageSel_;
};

// TODO(stoarca): getDiscription is split awkwardly between here and the
// walkers. The walkers should have getBaseDescription() which requires
// very little context, and then this method should tack on everything
// which requires any extensive knowledge.
/**
 * Delegates to NavigationShifter with the current page state.
 * @return {Array.<cvox.NavDescription>} The summary of the current position.
 */
cvox.NavigationManager.prototype.getDescription = function() {
  // Handle description of special content. Consider moving to DescriptionUtil.
  // Specially annotated nodes.
  if (this.getCurrentNode().hasAttribute &&
      this.getCurrentNode().hasAttribute('cvoxnodedesc')) {
    var preDesc = cvox.ChromeVoxJSON.parse(
        this.getCurrentNode().getAttribute('cvoxnodedesc'));
    var currentDesc = new Array();
    for (var i = 0; i < preDesc.length; ++i) {
      var inDesc = preDesc[i];
      // TODO: this can probably be replaced with just NavDescription(inDesc)
      // need test case to ensure this change will work
      currentDesc.push(new cvox.NavDescription({
        context: inDesc.context,
        text: inDesc.text,
        userValue: inDesc.userValue,
        annotation: inDesc.annotation
      }));
    }
    return currentDesc;
  }

  // Selected content.
  var desc = this.pageSel_ ? this.pageSel_.getDescription(
          this.shifter_, this.prevSel_, this.curSel_) :
      this.shifter_.getDescription(this.prevSel_, this.curSel_);
  var earcons = [];

  // Earcons.
  if (this.skipped_) {
    earcons.push(cvox.AbstractEarcons.PARAGRAPH_BREAK);
    this.skipped_ = false;
  }
  if (this.recovered_) {
    earcons.push(cvox.AbstractEarcons.FONT_CHANGE);
    this.recovered_ = false;
  }
  if (this.pageEnd_) {
    earcons.push(cvox.AbstractEarcons.WRAP);
    this.pageEnd_ = false;
  }
  if (this.enteredShifter_) {
    earcons.push(cvox.AbstractEarcons.OBJECT_ENTER);
    this.enteredShifter_ = false;
  }
  if (this.exitedShifter_) {
    earcons.push(cvox.AbstractEarcons.OBJECT_EXIT);
    this.exitedShifter_ = false;
  }
  if (earcons.length > 0 && desc.length > 0) {
    earcons.forEach(function(earcon) {
        desc[0].pushEarcon(earcon);
    });
  }
  return desc;
};

/**
 * Delegates to NavigationShifter with the current page state.
 * @return {!cvox.NavBraille} The braille description.
 */
cvox.NavigationManager.prototype.getBraille = function() {
  return this.shifter_.getBraille(this.prevSel_, this.curSel_);
};

/**
 * Delegates an action to the current walker.
 * @param {string} name Action name.
 * @return {boolean} True if action performed.
 */
cvox.NavigationManager.prototype.performAction = function(name) {
  var newSel = null;
  switch (name) {
    case 'enterShifter':
    case 'enterShifterSilently':
      for (var i = this.shifterTypes_.length - 1, shifterType;
           shifterType = this.shifterTypes_[i];
           i--) {
        var shifter = shifterType.create(this.curSel_);
        if (shifter && shifter.getName() != this.shifter_.getName()) {
          this.shifterStack_.push(this.shifter_);
          this.shifter_ = shifter;
          this.sync();
          this.enteredShifter_ = name != 'enterShifterSilently';
          break;
        } else if (shifter && this.shifter_.getName() == shifter.getName()) {
          break;
        }
      }
      break;
    case 'exitShifter':
      if (this.shifterStack_.length == 0) {
        return false;
      }
      this.shifter_ = this.shifterStack_.pop();
      this.sync();
      this.exitedShifter_ = true;
      break;
    case 'exitShifterContent':
      if (this.shifterStack_.length == 0) {
        return false;
      }
      this.updateSel(this.shifter_.performAction(name, this.curSel_));
      this.shifter_ = this.shifterStack_.pop() || this.shifter_;
      this.sync();
      this.exitedShifter_ = true;
      break;
      default:
        if (this.shifter_.hasAction(name)) {
          return this.updateSel(
              this.shifter_.performAction(name, this.curSel_));
        } else {
          return false;
        }
    }
  return true;
};

/**
 * Returns the current navigation strategy.
 *
 * @return {string} The name of the strategy used.
 */
cvox.NavigationManager.prototype.getGranularityMsg = function() {
  return this.shifter_.getGranularityMsg();
};

/**
 * Delegates to NavigationShifter.
 * @param {boolean=} opt_persist Persist the granularity to all running tabs;
 * defaults to true.
 */
cvox.NavigationManager.prototype.makeMoreGranular = function(opt_persist) {
  this.shifter_.makeMoreGranular();
  this.sync();
  this.persistGranularity_(opt_persist);
};

/**
 * Delegates to current shifter.
 * @param {boolean=} opt_persist Persist the granularity to all running tabs;
 * defaults to true.
 */
cvox.NavigationManager.prototype.makeLessGranular = function(opt_persist) {
  this.shifter_.makeLessGranular();
  this.sync();
  this.persistGranularity_(opt_persist);
};

/**
 * Delegates to navigation shifter. Behavior is not defined if granularity
 * was not previously gotten from a call to getGranularity(). This method is
 * only supported by NavigationShifter which exposes a random access
 * iterator-like interface. The caller has the option to force granularity
  which results in exiting any entered shifters. If not forced, and there has
 * been a shifter entered, setting granularity is a no-op.
 * @param {number} granularity The desired granularity.
 * @param {boolean=} opt_force Forces current shifter to NavigationShifter;
 * false by default.
 * @param {boolean=} opt_persist Persists setting to all running tabs; defaults
 * to false.
 */
cvox.NavigationManager.prototype.setGranularity = function(
    granularity, opt_force, opt_persist) {
  if (!opt_force && this.shifterStack_.length > 0) {
    return;
  }
  this.shifter_ = this.shifterStack_.shift() || this.shifter_;
  this.shifters_ = [];
  this.shifter_.setGranularity(granularity);
  this.persistGranularity_(opt_persist);
};

/**
 * Delegates to NavigationShifter.
 * @return {number} The current granularity.
 */
cvox.NavigationManager.prototype.getGranularity = function() {
  var shifter = this.shifterStack_[0] || this.shifter_;
  return shifter.getGranularity();
};

/**
 * Delegates to NavigationShifter.
 */
cvox.NavigationManager.prototype.ensureSubnavigating = function() {
  if (!this.shifter_.isSubnavigating()) {
    this.shifter_.ensureSubnavigating();
    this.sync();
  }
};

/**
 * Stops subnavigating, specifying that we should navigate at a less granular
 * level than the current navigation strategy.
 */
cvox.NavigationManager.prototype.ensureNotSubnavigating = function() {
  if (this.shifter_.isSubnavigating()) {
    this.shifter_.ensureNotSubnavigating();
    this.sync();
  }
};

/**
 * Delegates to NavigationSpeaker.
 * @param {Array.<cvox.NavDescription>} descriptionArray The array of
 *     NavDescriptions to speak.
 * @param {number} initialQueueMode The initial queue mode.
 * @param {Function} completionFunction Function to call when finished speaking.
 * @param {Object=} opt_personality Optional personality for all descriptions.
 * @param {string=} opt_category Optional category for all descriptions.
 */
cvox.NavigationManager.prototype.speakDescriptionArray = function(
    descriptionArray,
    initialQueueMode,
    completionFunction,
    opt_personality,
    opt_category) {
  if (opt_personality) {
    descriptionArray.forEach(function(desc) {
      if (!desc.personality) {
        desc.personality = opt_personality;
      }
    });
  }
  if (opt_category) {
    descriptionArray.forEach(function(desc) {
      if (!desc.category) {
        desc.category = opt_category;
      }
    });
  }

  this.navSpeaker_.speakDescriptionArray(
      descriptionArray, initialQueueMode, completionFunction);
};

/**
 * Add the position of the node on the page.
 * @param {Node} node The node that ChromeVox should update the position.
 */
cvox.NavigationManager.prototype.updatePosition = function(node) {
  var msg = cvox.ChromeVox.position;
  msg[document.location.href] =
      cvox.DomUtil.elementToPoint(node);

  cvox.ChromeVox.host.sendToBackgroundPage({
    'target': 'Prefs',
    'action': 'setPref',
    'pref': 'position',
    'value': JSON.stringify(msg)
  });
};

// TODO(stoarca): The stuff below belongs in its own layer.
/**
 * Perform all of the actions that should happen at the end of any
 * navigation operation: update the lens, play earcons, and speak the
 * description of the object that was navigated to.
 *
 * @param {string=} opt_prefix The string to be prepended to what
 * is spoken to the user.
 * @param {boolean=} opt_setFocus Whether or not to focus the current node.
 * Defaults to true.
 * @param {number=} opt_queueMode Initial queue mode to use.
 * @param {function(): ?=} opt_callback Function to call after speaking.
 */
cvox.NavigationManager.prototype.finishNavCommand = function(
    opt_prefix, opt_setFocus, opt_queueMode, opt_callback) {
  if (this.pageEnd_ && !this.pageEndAnnounced_) {
    this.pageEndAnnounced_ = true;
    cvox.ChromeVox.tts.stop();
    cvox.ChromeVox.earcons.playEarcon(cvox.AbstractEarcons.WRAP);
    if (cvox.ChromeVox.verbosity === cvox.VERBOSITY_VERBOSE) {
      var msg = cvox.ChromeVox.msgs.getMsg('wrapped_to_top');
      if (this.isReversed()) {
        msg = cvox.ChromeVox.msgs.getMsg('wrapped_to_bottom');
      }
      cvox.ChromeVox.tts.speak(msg, cvox.AbstractTts.QUEUE_MODE_QUEUE,
          cvox.AbstractTts.PERSONALITY_ANNOTATION);
    }
    return;
  }

  if (this.enteredShifter_ || this.exitedShifter_) {
    opt_prefix = cvox.ChromeVox.msgs.getMsg(
        'enter_content_say', [this.shifter_.getName()]);
  }

  var descriptionArray = cvox.ChromeVox.navigationManager.getDescription();

  opt_setFocus = opt_setFocus === undefined ? true : opt_setFocus;

  if (opt_setFocus) {
    this.setFocus();
  }
  this.updateIndicator();

  var queueMode = opt_queueMode || cvox.AbstractTts.QUEUE_MODE_FLUSH;

  if (opt_prefix) {
    cvox.ChromeVox.tts.speak(
        opt_prefix, queueMode, cvox.AbstractTts.PERSONALITY_ANNOTATION);
    queueMode = cvox.AbstractTts.QUEUE_MODE_QUEUE;
  }
  this.speakDescriptionArray(descriptionArray,
                             queueMode,
                             opt_callback || null,
                             null,
                             'nav');

  this.getBraille().write();

  this.updatePosition(this.getCurrentNode());
};

/**
 * Moves forward. Stops any subnavigation.
 * @param {boolean=} opt_ignoreIframes Ignore iframes when navigating. Defaults
 * to not ignore iframes.
 * @param {number=} opt_granularity Optionally, switches to granularity before
 * navigation.
 * @return {boolean} False if end of document reached.
 */
cvox.NavigationManager.prototype.navigate = function(
    opt_ignoreIframes, opt_granularity) {
  this.pageEndAnnounced_ = false;
  if (this.pageEnd_) {
    this.pageEnd_ = false;
    this.syncToBeginning(opt_ignoreIframes);
    return true;
  }
  if (!this.resolve()) {
    return false;
  }
  this.ensureNotSubnavigating();
  if (opt_granularity !== undefined &&
      (opt_granularity !== this.getGranularity() ||
          this.shifterStack_.length > 0)) {
    this.setGranularity(opt_granularity, true);
    this.sync();
  }
  return this.next_(!opt_ignoreIframes);
};

/**
 * Moves forward after switching to a lower granularity until the next
 * call to navigate().
 */
cvox.NavigationManager.prototype.subnavigate = function() {
  this.pageEndAnnounced_ = false;
  if (!this.resolve()) {
    return;
  }
  this.ensureSubnavigating();
  this.next_(true);
};

/**
 * Moves forward. Starts reading the page from that node.
 * Uses QUEUE_MODE_FLUSH to flush any previous speech.
 * @return {boolean} False if not "reading from here". True otherwise.
 */
cvox.NavigationManager.prototype.skip = function() {
  if (!this.keepReading_) {
    return false;
  }
  if (cvox.ChromeVox.host.hasTtsCallback()) {
    this.skipped_ = true;
    this.setReversed(false);
    this.startCallbackReading_(cvox.AbstractTts.QUEUE_MODE_FLUSH);
  }
  return true;
};

/**
 * Starts reading the page from the current selection.
 * @param {number} queueMode Either flush or queue.
 */
cvox.NavigationManager.prototype.startReading = function(queueMode) {
  this.keepReading_ = true;
  if (cvox.ChromeVox.host.hasTtsCallback()) {
    this.startCallbackReading_(queueMode);
  } else {
    this.startNonCallbackReading_(queueMode);
  }
  cvox.ChromeVox.stickyOverride = true;
};

/**
 * Stops continuous read.
 * @param {boolean} stopTtsImmediately True if the TTS should immediately stop
 * speaking.
 */
cvox.NavigationManager.prototype.stopReading = function(stopTtsImmediately) {
  this.keepReading_ = false;
  this.navSpeaker_.stopReading = true;
  if (stopTtsImmediately) {
    cvox.ChromeVox.tts.stop();
  }
  cvox.ChromeVox.stickyOverride = null;
};

/**
 * The current current state of continuous read.
 * @return {boolean} The state.
 */
cvox.NavigationManager.prototype.isReading = function() {
  return this.keepReading_;
};

/**
 * Starts reading the page from the current selection if there are callbacks.
 * @param {number} queueMode Either flush or queue.
 * @private
 */
cvox.NavigationManager.prototype.startCallbackReading_ =
    cvox.ChromeVoxEventSuspender.withSuspendedEvents(function(queueMode) {
  this.finishNavCommand('', true, queueMode, goog.bind(function() {
    if (this.next_(true) && this.keepReading_) {
      this.startCallbackReading_(cvox.AbstractTts.QUEUE_MODE_QUEUE);
    }
  }, this));
});

/**
 * Starts reading the page from the current selection if there are no callbacks.
 * With this method, we poll the keepReading_ var and stop when it is false.
 * @param {number} queueMode Either flush or queue.
 * @private
 */
cvox.NavigationManager.prototype.startNonCallbackReading_ =
    cvox.ChromeVoxEventSuspender.withSuspendedEvents(function(queueMode) {
  if (!this.keepReading_) {
    return;
  }

  if (!cvox.ChromeVox.tts.isSpeaking()) {
    this.finishNavCommand('', true, queueMode, null);
    if (!this.next_(true)) {
      this.keepReading_ = false;
    }
  }
  window.setTimeout(goog.bind(this.startNonCallbackReading_, this), 1000);
});

/**
 * Returns a complete description of the current position, including
 * the text content and annotations such as "link", "button", etc.
 * Unlike getDescription, this does not shorten the position based on the
 * previous position.
 *
 * @return {Array.<cvox.NavDescription>} The summary of the current position.
 */
cvox.NavigationManager.prototype.getFullDescription = function() {
  if (this.pageSel_) {
    return this.pageSel_.getFullDescription();
  }
  return [cvox.DescriptionUtil.getDescriptionFromAncestors(
      cvox.DomUtil.getAncestors(this.curSel_.start.node),
      true,
      cvox.ChromeVox.verbosity)];
};

/**
 * Sets the browser's focus to the current node.
 * @param {boolean=} opt_skipText Skips focusing text nodes or any of their
 * ancestors; defaults to false.
 */
cvox.NavigationManager.prototype.setFocus = function(opt_skipText) {
  // TODO(dtseng): cvox.DomUtil.setFocus() totally destroys DOM ranges that have
  // been set on the page; this requires further investigation, but
  // PageSelection won't work without this.
  if (this.pageSel_ ||
      (opt_skipText && this.curSel_.start.node.constructor == Text)) {
    return;
  }
  cvox.Focuser.setFocus(this.curSel_.start.node);
};

/**
 * Returns the node of the directed start of the selection.
 * @return {Node} The current node.
 */
cvox.NavigationManager.prototype.getCurrentNode = function() {
  return this.curSel_.absStart().node;
};

/**
 * Listen to messages from other frames and respond to messages that
 * tell our frame to take focus and preseve the navigation granularity
 * from the other frame.
 * @private
 */
cvox.NavigationManager.prototype.addInterframeListener_ = function() {
  /**
   * @type {!cvox.NavigationManager}
   */
  var self = this;

  cvox.Interframe.addListener(function(message) {
    if (message['command'] != 'enterIframe' &&
        message['command'] != 'exitIframe') {
      return;
    }
    cvox.ChromeVox.serializer.readFrom(message);
    if (self.keepReading_) {
      return;
    }
    cvox.ChromeVoxEventSuspender.withSuspendedEvents(function() {
      window.focus();

      if (message['findNext']) {
        var predicateName = message['findNext'];
        var predicate = cvox.DomPredicates[predicateName];
        var found = self.findNext(predicate, predicateName, true);
        if (predicate && (!found || found.start.node.tagName == 'IFRAME')) {
          return;
        }
      } else if (message['command'] == 'exitIframe') {
        var id = message['sourceId'];
        var iframeElement = self.iframeIdMap[id];
        var reversed = message['reversed'];
        var granularity = message['granularity'];
        if (iframeElement) {
          self.updateSel(cvox.CursorSelection.fromNode(iframeElement));
        }
        self.setReversed(reversed);
        self.sync();
        self.navigate();
      } else {
        self.syncToBeginning();

        // if we have an empty body, then immediately exit the iframe
        if (!cvox.DomUtil.hasContent(document.body)) {
          self.tryIframe_(null);
          return;
        }
      }

      // Now speak what ended up being selected.
      // TODO(deboer): Some of this could be moved to readFrom
      self.finishNavCommand('', true);
    })();
  });
};

/**
 * Update the active indicator to reflect the current node or selection.
 */
cvox.NavigationManager.prototype.updateIndicator = function() {
  this.activeIndicator.syncToCursorSelection(this.curSel_);
};

/**
 * Update the active indicator in case the active object moved or was
 * removed from the document.
 */
cvox.NavigationManager.prototype.updateIndicatorIfChanged = function() {
  this.activeIndicator.updateIndicatorIfChanged();
};

/**
 * Show or hide the active indicator based on whether ChromeVox is
 * active or not.
 *
 * If 'active' is true, cvox.NavigationManager does not do anything.
 * However, callers to showOrHideIndicator also need to call updateIndicator
 * to update the indicator -- which also does the work to show the
 * indicator.
 *
 * @param {boolean} active True if we should show the indicator, false
 *     if we should hide the indicator.
 */
cvox.NavigationManager.prototype.showOrHideIndicator = function(active) {
  if (!active) {
    this.activeIndicator.removeFromDom();
  }
};

/**
 * Collapses the selection to directed cursor start.
 */
cvox.NavigationManager.prototype.collapseSelection = function() {
  this.curSel_.collapse();
};

/**
 * This is used to update the selection to arbitrary nodes because there are
 * browser events, cvox API's, and user commands that require selection around a
 * precise node. As a consequence, calling this method will result in a shift to
 * object granularity without explicit user action or feedback. Also, note that
 * this selection will be sync'ed to ObjectWalker by default unless explicitly
 * ttold not to. We assume object walker can describe the node in the latter
 * case.
 * @param {Node} node The node to update to.
 * @param {boolean=} opt_precise Whether selection will sync exactly to the
 * given node. Defaults to false (and selection will sync according to object
 * walker).
 */
cvox.NavigationManager.prototype.updateSelToArbitraryNode = function(
    node, opt_precise) {
  if (node) {
    this.setGranularity(cvox.NavigationShifter.GRANULARITIES.OBJECT, true);
    this.updateSel(cvox.CursorSelection.fromNode(node));
    if (!opt_precise) {
      this.sync();
    }
  } else {
    this.syncToBeginning();
  }
};

/**
 * Updates curSel_ to the new selection and sets prevSel_ to the old curSel_.
 * This should be called exactly when something user-perceivable happens.
 * @param {cvox.CursorSelection} sel The selection to update to.
 * @param {cvox.CursorSelection=} opt_context An optional override for prevSel_.
 * Used to override both curSel_ and prevSel_ when jumping back in nav history.
 * @return {boolean} False if sel is null. True otherwise.
 */
cvox.NavigationManager.prototype.updateSel = function(sel, opt_context) {
  if (sel) {
    this.prevSel_ = opt_context || this.curSel_;
    this.curSel_ = sel;
  }
  // Only update the history if we aren't just trying to peek ahead.
  var currentNode = this.getCurrentNode();
  this.navigationHistory_.update(currentNode);
  return !!sel;
};

/**
 * Sets the direction.
 * @param {!boolean} r True to reverse.
 */
cvox.NavigationManager.prototype.setReversed = function(r) {
  this.curSel_.setReversed(r);
};

/**
 * Returns true if currently reversed.
 * @return {boolean} True if reversed.
 */
cvox.NavigationManager.prototype.isReversed = function() {
  return this.curSel_.isReversed();
};

/**
 * Checks if boundary conditions are met and updates the selection.
 * @param {cvox.CursorSelection} sel The selection.
 * @param {boolean=} iframes If true, tries to enter iframes. Default false.
 * @return {boolean} False if end of page is reached.
 * @private
 */
cvox.NavigationManager.prototype.tryBoundaries_ = function(sel, iframes) {
  iframes = (!!iframes && !this.ignoreIframesNoMatterWhat_) || false;
  this.pageEnd_ = false;
  if (iframes && this.tryIframe_(sel && sel.start.node)) {
    return true;
  }
  if (sel) {
    this.updateSel(sel);
    return true;
  }
  if (this.shifterStack_.length > 0) {
    return true;
  }
  this.syncToBeginning(!iframes);
  this.clearPageSel(true);
  this.stopReading(true);
  this.pageEnd_ = true;
  return false;
};

/**
 * Given a node that we just navigated to, try to jump in and out of iframes
 * as needed. If the node is an iframe, jump into it. If the node is null,
 * assume we reached the end of an iframe and try to jump out of it.
 * @param {Node} node The node to try to jump into.
 * @return {boolean} True if we jumped into an iframe.
 * @private
 */
cvox.NavigationManager.prototype.tryIframe_ = function(node) {
  if (node == null && cvox.Interframe.isIframe()) {
    var message = {
      'command': 'exitIframe',
      'reversed': this.isReversed(),
      'granularity': this.getGranularity()
    };
    cvox.ChromeVox.serializer.storeOn(message);
    cvox.Interframe.sendMessageToParentWindow(message);
    return true;
  }

  if (node == null || node.tagName != 'IFRAME' || !node.src) {
    return false;
  }
  var iframeElement = /** @type {HTMLIFrameElement} */(node);

  var iframeId = undefined;
  for (var id in this.iframeIdMap) {
    if (this.iframeIdMap[id] == iframeElement) {
      iframeId = id;
      break;
    }
  }
  if (iframeId == undefined) {
    iframeId = this.nextIframeId;
    this.nextIframeId++;
    this.iframeIdMap[iframeId] = iframeElement;
    cvox.Interframe.sendIdToIFrame(iframeId, iframeElement);
  }

  var message = {
    'command': 'enterIframe',
    'id': iframeId
  };
  cvox.ChromeVox.serializer.storeOn(message);
  cvox.Interframe.sendMessageToIFrame(message, iframeElement);

  return true;
};

/**
 * Delegates to NavigationShifter. Tries to enter any iframes or tables if
 * requested.
 * @param {boolean=} opt_skipIframe True to skip iframes.
 */
cvox.NavigationManager.prototype.syncToBeginning = function(opt_skipIframe) {
  var ret = this.shifter_.begin(this.curSel_, {
      reversed: this.curSel_.isReversed()
  });
  if (!opt_skipIframe && this.tryIframe_(ret && ret.start.node)) {
    return;
  }
  this.updateSel(ret);
};

/**
 * Used during testing since there are iframes and we don't always want to
 * interact with them so that we can test certain features.
 */
cvox.NavigationManager.prototype.ignoreIframesNoMatterWhat = function() {
  this.ignoreIframesNoMatterWhat_ = true;
};

/**
 * Save a cursor selection during an excursion.
 */
cvox.NavigationManager.prototype.saveSel = function() {
  this.saveSel_ = this.curSel_;
};

/**
 * Save a cursor selection after an excursion.
 */
cvox.NavigationManager.prototype.restoreSel = function() {
  this.curSel_ = this.saveSel_ || this.curSel_;
};

/**
 * @param {boolean=} opt_persist Persist the granularity to all running tabs;
 * defaults to false.
 * @private
 */
cvox.NavigationManager.prototype.persistGranularity_ = function(opt_persist) {
  opt_persist = opt_persist === undefined ? false : opt_persist;
  if (opt_persist) {
    cvox.ChromeVox.host.sendToBackgroundPage({
      'target': 'Prefs',
      'action': 'setPref',
      'pref': 'granularity',
      'value': this.getGranularity()
    });
  }
};


text:
//
//  Program.cs
//
//  Author:
//       Benito Palacios Sánchez <benito356@gmail.com>
//
//  Copyright (c) 2015 Benito Palacios Sánchez
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Xml.Linq;
using Libgame;

namespace Downlitor
{
	public static class Program
	{
		[STAThread]
		public static void Main(string[] args)
		{
			string xmlEdit = "Ninokuni español.xml";
			var document = XDocument.Load(xmlEdit);
			Configuration.Initialize(document);

            if (args.Length > 0) {
                CommandLine(args);
                return;
            }

            MainWindow window = new MainWindow();
            window.ShowDialog();
            window.Dispose();
		}

        private static void CommandLine(string[] args)
        {
            DlcBinaryFlags dlc;
            if ((args.Length == 2 || args.Length == 3) && args[0] == "-e") {
                dlc = new DlcBinaryFlags();
                if (args.Length == 3)
                    dlc = DlcBinaryFlags.FromDlc(args[1]);

                dlc.Export(args[2]);
            } else if (args.Length == 3 && args[0] == "-i") {
                dlc = DlcBinaryFlags.FromXml(args[1]);
                dlc.Write(args[2]);
            }
        }
	}
}

redpajama_set_name: RedPajamaGithub


text:
#include "paddle/fluid/inference/tensorrt/convert/op_converter.h"
#include "paddle/fluid/inference/tensorrt/plugin/gather_nd_op_plugin.h"

namespace paddle {
namespace inference {
namespace tensorrt {

class GatherNdOpConverter : public OpConverter {
 public:
  void operator()(const framework::proto::OpDesc& op,
                  const framework::Scope& scope,
                  bool test_mode) override {
    VLOG(4) << "convert a paddle gather_nd op to tensorrt gather_nd plugin";
    framework::OpDesc op_desc(op, nullptr);

    // Declare inputs
    std::vector<nvinfer1::ITensor*> inputs;
    auto* input = engine_->GetITensor(op_desc.Input("X")[0]);
    auto* index = engine_->GetITensor(op_desc.Input("Index")[0]);
    inputs.emplace_back(input);
    inputs.emplace_back(index);

    nvinfer1::ILayer* layer = nullptr;
    bool with_fp16 = engine_->WithFp16() && !engine_->disable_trt_plugin_fp16();
    plugin::GatherNdPluginDynamic* plugin =
        new plugin::GatherNdPluginDynamic(with_fp16);
    layer = engine_->AddDynamicPlugin(inputs.data(), inputs.size(), plugin);

    std::string layer_name = "gather_nd (Output: ";
    auto output_name = op_desc.Output("Out")[0];
    layer->getOutput(0)->setName(output_name.c_str());
    engine_->SetITensor(output_name, layer->getOutput(0));
    layer_name += output_name;
    if (test_mode) {
      engine_->DeclareOutput(output_name);
    }
    layer->setName((layer_name + ")").c_str());
  }
};

}  // namespace tensorrt
}  // namespace inference
}  // namespace paddle

REGISTER_TRT_OP_CONVERTER(gather_nd, GatherNdOpConverter);


text:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace OOM.Web.Extensions
{
    public class JsonHandlerAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            var jsonResult = filterContext.Result as JsonResult;

            if (jsonResult != null)
            {
                filterContext.Result = new JsonNetResult
                {
                    ContentEncoding = jsonResult.ContentEncoding,
                    ContentType = jsonResult.ContentType,
                    Data = jsonResult.Data,
                    JsonRequestBehavior = jsonResult.JsonRequestBehavior
                };
            }

            base.OnActionExecuted(filterContext);
        }
    }

    public class JsonNetResult : JsonResult
    {
        public JsonNetResult()
        {
            Settings = new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Error
            };
        }

        public JsonSerializerSettings Settings { get; private set; }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
                throw new InvalidOperationException("JSON GET is not allowed");

            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = string.IsNullOrEmpty(ContentType) ? "application/json" : ContentType;

            if (ContentEncoding != null)
                response.ContentEncoding = ContentEncoding;

            if (Data == null)
                return;

            if (Debugger.IsAttached)
                Settings.Formatting = Formatting.Indented;

            var scriptSerializer = JsonSerializer.Create(Settings);
            scriptSerializer.Serialize(response.Output, Data);
        }
    }
}


text:
require "bundler/setup"
Bundler.require(:default, :development)

require "smart_slug"

RSpec.configure do |config|
  config.expect_with :rspec do |c|
    c.syntax = :expect
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Drawable when a word is being selected -->
    <item android:drawable="@color/pressed_tile" android:state_pressed="true" />
    <!-- Drawable when a word is selected -->
    <item android:drawable="@color/selected_tile" android:state_selected="true" />
    <!-- Default drawable when nothing is selected -->
    <item android:drawable="@android:color/transparent" android:state_pressed="false" android:state_selected="false" />
</selector>


text:
. GetGlobals.sh
export PATH=$CXXTEST/bin:$PATH

# @main:
cxxtestgen --error-printer -o runner.cpp MockTestSuite.h
# @:main

# @compile:
g++ -o runner -I. -I$CXXTEST runner.cpp time_mock.cpp rand_example.cpp
# @:compile

./runner
\rm -f runner runner.cpp


text:
//
//  MPChartboostRouter.h
//  MoPubSDK
//
//  Copyright (c) 2015 MoPub. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <Chartboost/Chartboost.h>

@class ChartboostInterstitialCustomEvent;
@class ChartboostRewardedVideoCustomEvent;

/*
 * Maps all Chartboost locations for both interstitial and rewarded video ads to their
 * corresponding custom event objects. Also acts as primary Chartboost delegate and distributes
 * callbacks to their appropriate custom events.
 */
@interface MPChartboostRouter : NSObject <ChartboostDelegate>

@property (nonatomic, strong) NSMutableDictionary *interstitialEvents;
@property (nonatomic, strong) NSMutableSet *activeInterstitialLocations;
@property (nonatomic, strong) NSMutableDictionary *rewardedVideoEvents;

+ (MPChartboostRouter *)sharedRouter;

/*
 * Interstitial Ads
 */
- (void)cacheInterstitialWithAppId:(NSString *)appId appSignature:(NSString *)appSignature location:(NSString *)location forChartboostInterstitialCustomEvent:(ChartboostInterstitialCustomEvent *)event;
- (BOOL)hasCachedInterstitialForLocation:(NSString *)location;
- (void)showInterstitialForLocation:(NSString *)location;
- (void)unregisterInterstitialEvent:(ChartboostInterstitialCustomEvent *)event;

/*
 * Rewarded Video Ads
 */

- (void)cacheRewardedAdWithAppId:(NSString *)appId appSignature:(NSString *)appSignature location:(NSString *)location forChartboostRewardedVideoCustomEvent:(ChartboostRewardedVideoCustomEvent *)event;
- (BOOL)hasCachedRewardedVideoForLocation:(NSString *)location;
- (void)showRewardedVideoForLocation:(NSString *)location;

@end


text:
package io.gatling.recorder.ui.swing.component

import scala.swing._
import scala.swing.BorderPanel.Position._

private[swing] class TextAreaPanel(title: String, initialSize: Dimension) extends BorderPanel {

  preferredSize = initialSize

  val textArea = new TextArea { editable = false }
  private val titleLabel = new Label(title) { horizontalAlignment = Alignment.Center }

  layout(titleLabel) = North
  layout(textArea) = Center
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Gherkin</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="/stylesheets/pygments/TomorrowNightEightiesStyle.css" rel="stylesheet">
    <link href="/stylesheets/bootstrap.css" rel="stylesheet">
    <link href="/stylesheets/styles.css" rel="stylesheet">
    <link href="/images/favicon.png" rel="icon" type="image/png">

      BDD Kickstart
      San Francisco CA, 21-23 Apr

        Docs
        Blog
        School
        Training
        Cucumber Pro
        Support

                    Install

Platforms

Install Cucumber-JVM

Install Cucumber-Ruby

Install Cucumber-Rails

Install Cucumber-JavaScript

                    Running

                    Gherkin

                    API

API Overview

Glue Code

Step Definitions

Hooks

Reports

Cucumber-JVM

Dependency Injection

                    Learn more

Browser Automation

Reports

Databases

Gherkin

Gherkin is the format for Cucumber Specifications. Technically speaking it is a small computer language with a well-defined syntax, but it's so simple that you don't have to know how to program in order to use it. Here is a simple Gherkin document:

Feature: Password management
  Scenario: Forgot password
    Given a user with email "cukes@cukes.info" exists
    When I ask for a password reset
    Then an email with a password reset link should be sent

The only syntax here is the colored keywords at the beginning of each line. The rest is entirely up to you. Gherkin documents are stored in regular text files with a .feature file extension. The file above could be stored in a password_management.feature file.

When you run Cucumber, it will generate a report that verifies whether or not the software behaves the way the Gherkin document says.

How is that possible? You (or someone else on your team) can then write some code that translates the text in the Gherkin document into interactions with the software.

TODO: MORE

            Copyright © Cucumber Ltd 2014-2015 ‑
            Press

            +44 20 8720 6842 (Europe)

            1-844-414-4961 (USA)

            Edit this page


text:
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
                    Toggle navigation

                </button>

<<<<<<< HEAD

connect with facebook

=======

connect with facebook

>>>>>>> origin/master

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

 Create new event

<form role="form" ng-submit="addEvent()">

                Title
                <input type="text" class="form-control" ng-model="form.Title" placeholder="Title of the event" value="">

                Spot
                <input type="text" class="form-control" ng-model="form.Spot"  placeholder="Where is the event going take place" value="">

                Date
                <input id="datetimepicker" ng-model="form.Date" class="form-control" type="text" value="">

                Duration

                <input type="tatdetime" class="form-control"  ng-model="form.Duration" placeholder="example: 1h or 3h or ..." value="">

                Description
                <textarea name="comment" class="form-control"  ng-model="form.Descrpition" form="usrform" placeholder="tell people what is the event about"></textarea>

                Event cover page
                <input type="file" id="exampleInputFile">

        <button type="reset" class="btn btn-sm btn-info" >reset</button>
        <button  class="btn btn-sm btn-success" type="submit">Save and continue</button>

  </form>


text:
Aggregated data
===============
These are the API components of ``datreant.data`` for working with datasets
from multiple Treants at once, and treating them in aggregate.

.. _AggData_api:

AggData
```````
The class :class:`datreant.data.agglimbs.AggData` is the interface used by
Bundles and Views to access their members' datasets in aggregate.

.. autoclass:: datreant.data.agglimbs.AggData
    :members:
    :inherited-members:


text:
#include "ModelBase/BioSIMModelBase.h"
#include "ModelBase/ContinuingRatio.h"

namespace WBSF
{
	enum TSpringInstar { S_EGG, S_L1, S_L2, S_L3, S_L4, S_L5, S_SOIL, S_PUPA, S_ADULT, NB_SPRING_STAGES };
	enum TSpringParam { S_PUPA_ADULT, S_ADULT_EGG, S_EGG_L1, S_L1_L2, S_L2_L3, S_L3_L4, S_L4_L5, S_L5_SOIL, S_SOIL_PUPA, NB_SPRING_PARAMS };

	extern const char SpringCankerworms_header[];
	typedef CContinuingRatio<NB_SPRING_PARAMS, S_EGG-2, S_PUPA, SpringCankerworms_header> CSpringCankerwormsCR;

	class CSpringCankerwormsModel : public CBioSIMModelBase
	{
	public:

		CSpringCankerwormsModel();
		virtual ~CSpringCankerwormsModel();

		virtual ERMsg OnExecuteDaily();
		virtual ERMsg ProcessParameters(const CParameterVector& parameters);
		virtual void AddDailyResult(const StringVector& header, const StringVector& data);
		virtual void GetFValueDaily(CStatisticXY& stat);
		static CBioSIMModelBase* CreateObject(){ return new CSpringCankerwormsModel; }

	protected:

		CSpringCankerwormsCR m_springCR;

		//Simulated Annealing
		enum TSpringInput { I_S_ADULT, I_S_EGG, I_S_L1, I_S_L2, I_S_L3, I_S_L4, I_S_L5, I_S_L5_SOIL, I_S_PUPE, NB_SPRING_INPUT };

		static const double A[NB_SPRING_PARAMS];
		static const double B[NB_SPRING_PARAMS];
		static const double THRESHOLD;

	};

}


text:
//ÓÉqsort.c¸ÄÔì

#pragma once

#pragma optimize("t", on)

#include "Index.h"

__forceinline void _swap(PIndexElemType a, PIndexElemType b)
{
	IndexElemType tmp;
	tmp = *a;
	*a = *b;
	*b = tmp;
}

#define INSERT_SORT
//#define SELECT_SORT

__forceinline void shortsort(PIndexElemType lo, PIndexElemType hi, int(*comp)(IndexElemType, IndexElemType))
#ifdef INSERT_SORT  //²åÈëÅÅÐò
{
	PIndexElemType pBase, p;
	IndexElemType tmp;
	for (pBase = lo + 1; pBase <= hi; ++pBase){
		tmp = *pBase;
		for (p = pBase - 1; p >= lo && comp(*p, tmp)>0; --p){
			*(p + 1) = *p;
		}
		*(p + 1) = tmp;
	}
}
#elif defined(SELECT_SORT)   //Ñ¡ÔñÅÅÐò
{
	DWORD *p, *max;
	for (; hi>lo; --hi){
		max = lo;
		for (p = lo + 1; p <= hi; ++p){
			if (comp(*p, *max)>0){
				max = p;
			}
		}
		_swap(max, hi);
	}
}
#else
{

}
#endif

#define CUTOFF 32
#define STKSIZ 30 //(8*sizeof(void*) - 2)

inline void name_qsort(PIndexElemType base, DWORD num, int(*comp)(IndexElemType, IndexElemType))
{
	/* Note: the number of stack entries required is no more than
	1 + log2(num), so 30 is sufficient for any array */
	PIndexElemType lo = base, hi = base + num - 1;         /* ends of sub-array currently sorting */
	PIndexElemType mid;                             /* points to middle of subarray */
	PIndexElemType loguy, higuy;                   /* traveling pointers for partition step */
	DWORD size;                             /* size of the sub-array */
	PIndexElemType lostk[STKSIZ], histk[STKSIZ];
	int stkptr;                             /* stack for saving sub-array to be processed */

	if (num < 2) return;

	stkptr = 0;                             /* initialize stack */

	/* this entry point is for pseudo-recursion calling: setting
	lo and hi and jumping to here is like recursion, but stkptr is
	preserved, locals aren't, so we preserve stuff on the stack */
recurse:

	size = hi - lo + 1;        /* number of el's to sort */

	/* below a certain size, it is faster to use a O(n^2) sorting method */
	if (size <= CUTOFF) {
		shortsort(lo, hi, comp);
	}
	else {
		/* First we pick a partitioning element.  The efficiency of the
		algorithm demands that we find one that is approximately the median
		of the values, but also that we select one fast.  We choose the
		median of the first, middle, and last elements, to avoid bad
		performance in the face of already sorted data, or data that is made
		up of multiple sorted runs appended together.  Testing shows that a
		median-of-three algorithm provides better performance than simply
		picking the middle element for the latter case. */

		mid = lo + (size >> 1);      /* find middle element */

		/* Sort the first, middle, last elements into order */
		if (comp(*lo, *mid) > 0) {
			_swap(lo, mid);
		}
		if (comp(*lo, *hi) > 0) {
			_swap(lo, hi);
		}
		if (comp(*mid, *hi) > 0) {
			_swap(mid, hi);
		}

		/* We now wish to partition the array into three pieces, one consisting
		of elements <= partition element, one of elements equal to the
		partition element, and one of elements > than it.  This is done
		below; comments indicate conditions established at every step. */

		loguy = lo;
		higuy = hi;

		/* Note that higuy decreases and loguy increases on every iteration,
		so loop must terminate. */
		for (;;) {
			/* lo <= loguy < hi, lo < higuy <= hi,
			A[i] <= A[mid] for lo <= i <= loguy,
			A[i] > A[mid] for higuy <= i < hi,
			A[hi] >= A[mid] */

			/* The doubled loop is to avoid calling comp(mid,mid), since some
			existing comparison funcs don't work when passed the same
			value for both pointers. */

			if (mid > loguy) {
				do  {
					++loguy;
				} while (loguy < mid && comp(*loguy, *mid) <= 0);
			}
			if (mid <= loguy) {
				do  {
					++loguy;
				} while (loguy <= hi && comp(*loguy, *mid) <= 0);
			}

			/* lo < loguy <= hi+1, A[i] <= A[mid] for lo <= i < loguy,
			either loguy > hi or A[loguy] > A[mid] */

			do  {
				--higuy;
			} while (higuy > mid && comp(*higuy, *mid) > 0);

			/* lo <= higuy < hi, A[i] > A[mid] for higuy < i < hi,
			either higuy == lo or A[higuy] <= A[mid] */

			if (higuy < loguy)
				break;

			/* if loguy > hi or higuy == lo, then we would have exited, so
			A[loguy] > A[mid], A[higuy] <= A[mid],
			loguy <= hi, higuy > lo */

			_swap(loguy, higuy);

			/* If the partition element was moved, follow it.  Only need
			to check for mid == higuy, since before the swap,
			A[loguy] > A[mid] implies loguy != mid. */

			if (mid == higuy)
				mid = loguy;

			/* A[loguy] <= A[mid], A[higuy] > A[mid]; so condition at top
			of loop is re-established */
		}

		/*     A[i] <= A[mid] for lo <= i < loguy,
		A[i] > A[mid] for higuy < i < hi,
		A[hi] >= A[mid]
		higuy < loguy
		implying:
		higuy == loguy-1
		or higuy == hi - 1, loguy == hi + 1, A[hi] == A[mid] */

		/* Find adjacent elements equal to the partition element.  The
		doubled loop is to avoid calling comp(mid,mid), since some
		existing comparison funcs don't work when passed the same value
		for both pointers. */

		++higuy;
		if (mid < higuy) {
			do  {
				--higuy;
			} while (higuy > mid && comp(*higuy, *mid) == 0);
		}
		if (mid >= higuy) {
			do  {
				--higuy;
			} while (higuy > lo && comp(*higuy, *mid) == 0);
		}

		/* OK, now we have the following:
		higuy < loguy
		lo <= higuy <= hi
		A[i]  <= A[mid] for lo <= i <= higuy
		A[i]  == A[mid] for higuy < i < loguy
		A[i]  >  A[mid] for loguy <= i < hi
		A[hi] >= A[mid] */

		/* We've finished the partition, now we want to sort the subarrays
		[lo, higuy] and [loguy, hi].
		We do the smaller one first to minimize stack usage.
		We only sort arrays of length 2 or more.*/

		if (higuy - lo >= hi - loguy) {
			if (lo < higuy) {
				lostk[stkptr] = lo;
				histk[stkptr] = higuy;
				++stkptr;
			}                           /* save big recursion for later */

			if (loguy < hi) {
				lo = loguy;
				goto recurse;           /* do small recursion */
			}
		}
		else {
			if (loguy < hi) {
				lostk[stkptr] = loguy;
				histk[stkptr] = hi;
				++stkptr;               /* save big recursion for later */
			}

			if (lo < higuy) {
				hi = higuy;
				goto recurse;           /* do small recursion */
			}
		}
	}

	/* We have sorted the array, except for any pending sorts on the stack.
	Check if there are any, and do them. */

	--stkptr;
	if (stkptr >= 0) {
		lo = lostk[stkptr];
		hi = histk[stkptr];
		goto recurse;           /* pop subarray from stack */
	}
	else
		return;                 /* all subarrays done */
}

typedef int(*PComp)(PBYTE, PBYTE const, PBYTE, PBYTE const);
extern PComp comp_name;//ÎļþÃû±È½Ïº¯Êý
BOOL Help_InitCompare();
int comp_dir(IndexElemType, IndexElemType);
int comp_file(IndexElemType, IndexElemType);


text:
package org.javers.repository.api;

import org.javers.common.validation.Validate;
import org.javers.core.commit.CommitId;
import org.joda.time.LocalDateTime;

/**
 * @author michal wesolowski
 */
public class QueryParamsBuilder {
    private int limit;
    private int skip;
    private LocalDateTime from;
    private LocalDateTime to;
    private CommitId commitId;
    private Long version;

    private QueryParamsBuilder(int limit) {
        this.limit = limit;
        this.skip = 0;
    };

    /**
     * Initializes builder with a given limit - number of snapshots to be fetched from database.
     */
    public static QueryParamsBuilder withLimit(int limit) {
        checkLimit(limit);
        return new QueryParamsBuilder(limit);
    }

    /**
     * Initializes builder with parameters from a given queryParams instance
     */
    public static QueryParamsBuilder initializeWith(QueryParams queryParams) {
        Validate.argumentIsNotNull(queryParams);

        QueryParamsBuilder builder = QueryParamsBuilder.withLimit(queryParams.limit());
        builder.skip(queryParams.skip());
        if (queryParams.from().isPresent()) {
            builder = builder.from(queryParams.from().get());
        }
        if (queryParams.to().isPresent()) {
            builder = builder.to(queryParams.to().get());
        }
        if (queryParams.commitId().isPresent()) {
            builder = builder.commitId(queryParams.commitId().get());
        }
        if (queryParams.version().isPresent()) {
            builder = builder.version(queryParams.version().get());
        }
        return builder;
    }

    /**
     * @see #withLimit(int)
     */
    public QueryParamsBuilder limit(int limit) {
        checkLimit(limit);
        this.limit = limit;
        return this;
    }

    /**
     * skips a given number of latest snapshots
     */
    public QueryParamsBuilder skip(int skip) {
        Validate.argumentCheck(limit >= 0, "Skip is not a non-negative number.");
        this.skip = skip;
        return this;
    }

    /**
     * limits results to Snapshots created after given date
     */
    public QueryParamsBuilder from(LocalDateTime from) {
        this.from = from;
        return this;
    }

    /**
     * limits results to Snapshots created before given date
     */
    public QueryParamsBuilder to(LocalDateTime to) {
        this.to = to;
        return this;
    }

    /*
     * limits results to Snapshots with a given commitId
     */
    public QueryParamsBuilder commitId(CommitId commitId) {
        this.commitId = commitId;
        return this;
    }

    /*
     * limits results to Snapshots with a given version
     */
    public QueryParamsBuilder version(Long version) {
        this.version = version;
        return this;
    }

    private static void checkLimit(int limit) {
        Validate.argumentCheck(limit > 0, "Limit is not a positive number.");
    }

    public QueryParams build() {
        return new QueryParams(limit, skip, from, to, commitId, version);
    }
}


text:
package Exceptions;

public class NotOK extends Exception {
	public NotOK() { super(); }
	public NotOK(String message) { super(message); }
	public NotOK(String message, Throwable cause) { super(message, cause); }
	public NotOK(Throwable cause) { super(cause); }
}


text:
'use strict';

module.exports = function(sequelize, DataTypes) {
    var User = sequelize.define("User", {
        userName: {
            type: DataTypes.STRING(45),
            allowNull: false,
            primaryKey: true
        },
        firstName: {
            type: DataTypes.STRING(45),
            allowNull: true
        },
        lastName: {
            type: DataTypes.STRING(45),
            allowNull: true
        },
        email: {
            type: DataTypes.STRING(45),
            allowNull: false
        },
        address: {
            type: DataTypes.STRING(100),
            allowNull: false
        },
        password: {
            type: DataTypes.STRING(45),
            allowNull: false
        },
        isAdmin: {
            type: DataTypes.BOOLEAN,
            allowNull: false
        }
    }, {
        classMethods: {
            associate: function(models) {
                User.belongsTo(models.City, {foreignKey: {name: 'cityId', allowNull: false, onDelete: 'RESTRICT'}})
            }
        },
        tableName: 'user'
    });

    return User;
};


text:
This is a native Distributed Interactive Simulation (DIS) websockets
implementation.

Websockets are Javascript implementations of TCP sockets
(plus some extra special sauce.) This enables Javascript running
inside an HTML page can send and receive binary DIS messages over
TCP. The implications for M&S can be significant; with WebGL
this enables 3D graphics inside the web page. Even without
3D graphics many useful applications can be created via web
mashups with, for example, Google Maps, Open Street Map, and
D3.js graphics.

This distribution uses Jetty (a Java-based web application server
similar to Apache Tomcat in functionality) to implement the server
side of websockets. The application is configured via the
GatewayConfiguration.properties file in the root directory.

Included are web pages that implement a simple Google Maps web
page that displays the location of DIS entities. These pages
are in the content directory.

This distribution includes a Javascript implementation of DIS
that encodes and decodes the standard IEEE binary format. Thus
DIS messages from legacy applications can be  forwarded
to the web page from the server side and decoded there.

There are a number of experimental features you probably shouldn't
mess with, including a Redis server for cloud-based distributions
that can scale, and an area of interest (AOIM)/distributed data management
(DDM) implementation that uses Javascript to filter packets on the
server side on a per-connection basis.

License is BSD. Copyright 2008-2016 MOVES Institute, Naval Postgraduate
School.


text:
module RuboCop
  module Cop
    module Lint
      # This cop checks if each_with_object is called with an immutable
      # argument. Since the argument is the object that the given block shall
      # make calls on to build something based on the enumerable that
      # each_with_object iterates over, an immutable argument makes no sense.
      # It's definitely a bug.
      #
      # @example
      #
      #   sum = numbers.each_with_object(0) { |e, a| a += e }
      class EachWithObjectArgument < Cop
        MSG = 'The argument to each_with_object can not be immutable.'.freeze

        def_node_matcher :each_with_object?, '(send _ :each_with_object $_)'

        def on_send(node)
          each_with_object?(node) do |arg|
            add_offense(node, :expression) if arg.immutable_literal?
          end
        end
      end
    end
  end
end


text:
<?xml version="1.0"?>
<!DOCTYPE document [
  <!ENTITY project SYSTEM "project.xml">
]>
<document url="jndi-datasource-examples-howto.html">

    &project;

    <properties>
        <author email="leslie.hughes@rubus.com">Les Hughes</author>
        <author email="david-tomcat@haraburda.com">David Haraburda</author>
        <author>Glenn Nielsen</author>
        <title>JNDI Datasource HOW-TO</title>
    </properties>

Introduction

Database Connection Pool (DBCP) Configurations

Non DBCP Solutions

Oracle 8i with OCI client

Common Problems

JNDI Datasource configuration is covered extensively in the
JNDI-Resources-HOWTO however, feedback from tomcat-user has
shown that specifics for individual configurations can be rather tricky.

Here then are some example configurations that have been posted to
tomcat-user for popular databases and some general tips for db useage.

You should be aware that since these notes are derived from configuration
and/or feedback posted to tomcat-user YMMV :-). Please let us
know if you have any other tested configurations that you feel may be of use
to the wider audience, or if you feel we can improve this section in anyway.

DBCP provides support for JDBC 2.0.  On systems using a 1.4 JVM DBCP
will support JDBC 3.0. Please let us know if you have used DBCP and its
JDBC 3.0 features with a 1.4 JVM.

See the
DBCP Javadocs BasicDataSource class for a complete list
of configuration parameters.

<subsection name="Installation">

DBCP uses the Jakarta-Commons Database Connection Pool. It relies on
number of Jakarta-Commons componenets:

Jakarta-Commons DBCP 1.0

Jakarta-Commons Collections 2.0

Jakarta-Commons Pool 1.0

These jar files along with your the jar file for your JDBC driver should
be installed in $CATALINA_HOME/common/lib.

NOTE:Third Party drivers should be in jarfiles, not zipfiles.
Tomcat only adds $CATALINA_HOME/common/lib/*.jar to the classpath.

NOTE:
Do not install these jarfiles in your /WEB-INF/lib, or
$JAVA_HOME/jre/lib/ext, or anywhere else.  You will
experience problems if you install them anyplace other than
$CATALINA_HOME/common/lib.

</subsection>

<subsection name="Preventing dB connection pool leaks">

A database connection pool creates and manages a pool of connections
to a database. Recycling and reusing already existing connections
to a dB is more efficient than opening a new connection.

There is one problem with connection pooling.  A web application has
to explicetely close ResultSet's, Statement's, and Connection's.
Failure of a web application to close these resources can result in
them never being available again for reuse, a db connection pool "leak".
This can eventually result in your web application db connections failing
if there are no more available connections.

There is a solution to this problem.  The Jakarta-Commons DBCP can be
configured to track and recover these abandoned dB connections.  Not
only can it recover them, but also generate a stack trace for the code
which opened these resources and never closed them.

To configure a DBCP DataSource so that abandoned dB connections are
removed and recycled add the following paramater to the
ResourceParams configuration for your DBCP DataSource
Resource:
<source>
            <parameter>
              <name>removeAbandoned</name>
              <value>true</value>
            </parameter>
</source>
When available db connections run low DBCP will recover and recyle
any abandoned dB connections it finds. The default is false.

Use the removeAbandonedTimeout parameter to set the number
of seconds a dB connection has been idle before it is considered abandoned.
<source>
            <parameter>
              <name>removeAbandonedTimeout</name>
              <value>60</value>
            </parameter>
</source>
The default timeout for removing abandoned connections is 300 seconds.

The logAbandoned parameter can be set to true
if you want DBCP to log a stack trace of the code which abandoned the
dB connection resources.
<source>
            <parameter>
              <name>logAbandoned</name>
              <value>true</value>
            </parameter>
</source>
The default is false.

</subsection>

<subsection name="MySQL DBCP Example">

0. Introduction

Versions of MySQL and the mm.mysql JDBC driver when have been
reported to work:

MySQL 3.23.47, MySQL 3.23.47 using InnoDB, MySQL 4.0.1alpha

mm.mysql 2.0.14 (JDBC Driver)

Please let us know if you have tested the new MySQL mm.mysql 3.0 driver.

1. MySQL configuration

Ensure that you follow these instructions as variations can cause problems.

Create a new test user, a new database and a single test table.
Your MySQL user must have a password assigned. The driver
will fail if you try to connect with an empty password.
<source>
mysql> GRANT ALL PRIVILEGES ON *.* TO javauser@localhost
    ->   IDENTIFIED BY 'javadude' WITH GRANT OPTION;
mysql> create database javatest;
mysql> use javatest;
mysql> create table testdata (
    ->   id int not null auto_increment primary key,
    ->   foo varchar(25),
    ->   bar int);
</source>

Note: the above user should be removed once testing is
complete!

Next insert some test data into the testdata table.
<source>
mysql> insert into testdata values(null, 'hello', 12345);
Query OK, 1 row affected (0.00 sec)

mysql> select * from testdata;
+----+-------+-------+
| ID | FOO   | BAR   |
+----+-------+-------+
|  1 | hello | 12345 |
+----+-------+-------+
1 row in set (0.00 sec)

mysql>
</source>

2. server.xml configuration

Configure the JNDI DataSource in Tomcat by adding a declaration for your
resource to $CATALINA_HOME/conf/server.xml.

Add this in between the </Context> tag of the examples
context and the </Host> tag closing the localhost definition.<source>
<Context path="/DBTest" docBase="DBTest"
        debug="5" reloadable="true" crossContext="true">

  <Logger className="org.apache.catalina.logger.FileLogger"
             prefix="localhost_DBTest_log." suffix=".txt"
             timestamp="true"/>

  <Resource name="jdbc/TestDB"
               auth="Container"
               type="javax.sql.DataSource"/>

  <ResourceParams name="jdbc/TestDB">
    <parameter>
      <name>factory</name>
      <value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
    </parameter>

    <!-- Maximum number of dB connections in pool. Make sure you
         configure your mysqld max_connections large enough to handle
         all of your db connections. Set to 0 for no limit.
         -->
    <parameter>
      <name>maxActive</name>
      <value>100</value>
    </parameter>

    <!-- Maximum number of idle dB connections to retain in pool.
         Set to 0 for no limit.
         -->
    <parameter>
      <name>maxIdle</name>
      <value>30</value>
    </parameter>

    <!-- Maximum time to wait for a dB connection to become available
         in ms, in this example 10 seconds. An Exception is thrown if
         this timeout is exceeded.  Set to -1 to wait indefinitely.
         -->
    <parameter>
      <name>maxWait</name>
      <value>10000</value>
    </parameter>

    <!-- MySQL dB username and password for dB connections  -->
    <parameter>
     <name>username</name>
     <value>javauser</value>
    </parameter>
    <parameter>
     <name>password</name>
     <value>javadude</value>
    </parameter>

    <!-- Class name for mm.mysql JDBC driver -->
    <parameter>
       <name>driverClassName</name>
       <value>org.gjt.mm.mysql.Driver</value>
    </parameter>

    <!-- The JDBC connection url for connecting to your MySQL dB.
         The autoReconnect=true argument to the url makes sure that the
         mm.mysql JDBC Driver will automatically reconnect if mysqld closed the
         connection.  mysqld by default closes idle connections after 8 hours.
         -->
    <parameter>
      <name>url</name>
      <value>jdbc:mysql://localhost:3306/javatest?autoReconnect=true</value>
    </parameter>
  </ResourceParams>
</Context>
</source>

3. web.xml configuration

Now create a WEB-INF/web.xml for this test application.
<source>
<?xml version="1.0" encoding="ISO-8859-1"?>
    <!DOCTYPE web-app PUBLIC
    "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
  <description>MySQL Test App</description>
  <resource-ref>
      <description>DB Connection</description>
      <res-ref-name>jdbc/TestDB</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
  </resource-ref>
</web-app>
</source>

4. Test code

Now create a simple test.jsp for use later.
<source>
<html>
  <head>
    <title>DB Test</title>
  </head>
  <body>

  <%
    foo.DBTest tst = new foo.DBTest();
    tst.init();
  %>

  <h2>Results</h2>
    Foo <%= tst.getFoo() %><br/>
    Bar <%= tst.getBar() %>

  </body>
</html>
</source>

And create a Java class to actually use your new Datasource and connection
pool. Note: this code isn't anywhere near production ready - it's only
supposed to be used as a simple test :-)
<source>
package foo;

import javax.naming.*;
import javax.sql.*;
import java.sql.*;

public class DBTest {

  String foo = "Not Connected";
  int bar = -1;

  public void init() {
    try{
      Context ctx = new InitialContext();
      if(ctx == null )
          throw new Exception("Boom - No Context");

      DataSource ds =
            (DataSource)ctx.lookup(
               "java:comp/env/jdbc/TestDB");

      if (ds != null) {
        Connection conn = ds.getConnection();

        if(conn != null)  {
            foo = "Got Connection "+conn.toString();
            Statement stmt = conn.createStatement();
            ResultSet rst =
                stmt.executeQuery(
                  "select id, foo, bar from testdata");
            if(rst.next()) {
               foo=rst.getString(2);
               bar=rst.getInt(3);
            }
            conn.close();
        }
      }
    }catch(Exception e) {
      e.printStackTrace();
    }
 }

 public String getFoo() { return foo; }
 public int getBar() { return bar;}
}
</source>

Finally deploy your web app into $CATALINA_HOME/webapps either
as a warfile called DBTest.war or into a sub-directory called
DBTest

Once deployed, point a browser at
http://localhost:8080/DBTest/test.jsp to view the fruits of
your hard work.

</subsection>

<subsection name="Oracle 8i">

0.    Introduction

We would appreciate comments on this section as I'm not an Oracle DBA :-)

Oracle requires minimal changes from the MySQL configuration except for the usual gotchas :-) Firstly
by default, Tomcat will only use *.jar files installed in $CATALINA_HOME/common/lib
 therefore classes111.zip or classes12.zip will need to be renamed with a .jar
extension. Since jarfiles are zipfiles, there is no need to unzip and jar these files - a simple rename will suffice.
Also, you should be aware that some (early) versions of Tomcat 4.0 when used with JDK 1.4 will not load classes12.zip unless
you unzip the file, remove the javax.sql.* class heirarchy and rejar.

1.    server.xml configuration

In a similar manner to the mysql config above, you will need to define your Datasource in your server.xml
file. Here we define a Datasource called myoracle using the thin driver to connect as user scott, password tiger
to the schema called myschema in the sid called mysid. (Note: with the thin driver this sid is not the same as the tnsname)

Use of the OCI driver should simply involve a changing thin to oci in the URL string.
<source>
<Resource name="jdbc/myoracle" auth="Container"
              type="javax.sql.DataSource"/>

<ResourceParams name="jdbc/myoracle">
  <parameter>
    <name>factory</name>
    <value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
  </parameter>
  <parameter>
    <name>driverClassName</name>
    <value>oracle.jdbc.driver.OracleDriver</value>
  </parameter>
  <parameter>
    <name>url</name>
    <value>jdbc:oracle:thin:myschema@127.0.0.1:1521:mysid</value>
  </parameter>
  <parameter>
    <name>username</name>
    <value>scott</value>
  </parameter>
  <parameter>
    <name>password</name>
    <value>tiger</value>
  </parameter>
  <parameter>
    <name>maxActive</name>
    <value>20</value>
  </parameter>
  <parameter>
    <name>maxIdle</name>
    <value>10</value>
  </parameter>
  <parameter>
    <name>maxWait</name>
    <value>-1</value>
  </parameter>
</ResourceParams>
</source>

2.    web.xml configuration

You should ensure that you respect the elemeent ordering defined by the DTD when you
create you applications web.xml file.

<source>
<resource-ref>
 <description>Oracle Datasource example</description>
 <res-ref-name>jdbc/myoracle</res-ref-name>
 <res-type>javax.sql.DataSource</res-type>
 <res-auth>Container</res-auth>
</resource-ref>
</source>

3.   Code example

You can use the same example application as above (asuming you create the required DB
instance, tables etc.) replacing the Datasource code with something like

<source>
Context initContext = new InitialContext();
Context envContext  = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/myoracle");
Connection conn = ds.getConnection();
//etc.
</source>
</subsection>

<subsection name="PostgreSQL">

0.    Introduction

PostgreSQL is configured in a similar manner to Oracle. Again, highlighting the differences.
These notes are untested as yet and we would appreciate feedback.

1.    server.xml configuration

<source>
<Resource name="jdbc/postgres" auth="Container"
          type="javax.sql.DataSource"/>

<ResourceParams name="jdbc/postgres">
  <parameter>
    <name>factory</name>
    <value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
  </parameter>
  <parameter>
    <name>driverClassName</name>
    <value>org.postgresql.Driver</value>
  </parameter>
  <parameter>
    <name>url</name>
    <value>jdbc:postgresql://127.0.0.1:5432/mydb</value>
  </parameter>
  <parameter>
    <name>username</name>
    <value>myuser</value>
  </parameter>
  <parameter>
    <name>password</name>
    <value>mypasswd</value>
  </parameter>
  <parameter>
    <name>maxActive</name>
    <value>20</value>
  </parameter>
  <parameter>
    <name>maxIdle</name>
    <value>10</value>
  </parameter>
  <parameter>
    <name>maxWait</name>
    <value>-1</value>
  </parameter>
</ResourceParams>
</source>

2.    web.xml configuration

<source>
<resource-ref>
 <description>postgreSQL Datasource example</description>
 <res-ref-name>jdbc/mydb</res-ref-name>
 <res-type>javax.sql.DataSource</res-type>
 <res-auth>Container</res-auth>
</resource-ref>
</source>
</subsection>

These solutions either utilise a single connection to the database (not recommended for anything other
than testing!) or some other pooling technology.

<subsection name="Introduction">

Whilst not strictly addressing the creation of a JNDI DataSource using the OCI client, these notes can be combined with the
Oracle and DBCP solution above.

In order to use OCI driver, you should have an Oracle client installed. You should have installed
Oracle8i(8.1.7) client from cd,  and download the suitable JDBC/OCI
driver(Oracle8i 8.1.7.1 JDBC/OCI Driver) from otn.oracle.com.

After renaming classes12.zip file to classes12.jar
for Tomcat, copy it into $CATALINA_HOME/common/lib.
You may also have to remove the javax.sql.* classes
from this file depending upon the version of Tomcat and JDK you are using.

</subsection>

<subsection name="Putting it all together">

Ensure that you have the ocijdbc8.dll or .so in your $PATH or LD_LIBRARY_PATH
 (possibly in $ORAHOME\bin) and also confirm that the native library can be loaded by a simple test program
using System.loadLibrary("ocijdbc8");

You should next create a simple test servlet or jsp that has these
critical lines:

<source>
DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver());
conn =
DriverManager.getConnection("jdbc:oracle:oci8:@database","username","password");
</source>

where database is of the form host:port:SID Now if you try to access the URL of your
test servlet/jsp and what you get is a
ServletException with a root cause of java.lang.UnsatisfiedLinkError:get_env_handle.

First, the UnsatisfiedLinkError indicates that you have

a mismatch between your JDBC classes file and
your Oracle client version. The giveaway here is the message stating that a needed library file cannot be
found. For example, you may be using a classes12.zip file from Oracle Version 8.1.6 with a Version 8.1.5
Oracle client. The classeXXXs.zip file and Oracle client software versions must match.

A $PATH, LD_LIBRARY_PATH problem.

It has been reported that ignoring the driver you have downloded from otn and using
the classes12.zip file from the directory $ORAHOME\jdbc\lib will also work.

Next you may experience the error ORA-06401 NETCMN: invalid driver designator

The Oracle documentation says : "Cause: The login (connect) string contains an invalid
driver designator. Action: Correct the string and re-submit."

Change the database connect string (of the form host:port:SID) with this one:
(description=(address=(host=myhost)(protocol=tcp)(port=1521))(connect_data=(sid=orcl)))

Ed. Hmm, I don't think this is really needed if you sort out your TNSNames - but I'm not an Oracle DBA :-)

</subsection>

Here are some common problems encountered with a web application which
uses a database and tips for how to solve them.

<subsection name="Intermittent dB Connection Failures">

Tomcat runs within a JVM.  The JVM periodically performs garbage collection
(GC) to remove java objects which are no longer being used.  When the JVM
performs GC execution of code within Tomcat freezes. If the maximum time
configured for establishment of a dB connection is less than the amount
of time garbage collection took you can get a db conneciton failure.

To collect data on how long garbage collection is taking add the
-verbose:gc argument to your CATALINA_OPTS
environment variable when starting Tomcat.  When verbose gc is enabled
your $CATALINA_BASE/logs/catalina.out log file will include
data for every garbage collection including how long it took.

When your JVM is tuned correctly 99% of the time a GC will take less
than one second.  The remainder will only take a few seconds.  Rarely,
if ever should a GC take more than 10 seconds.

Make sure that the db connection timeout is set to 10-15 seconds.
For the DBCP you set this using the parameter maxWait.

</subsection>

<subsection name="Random Connection Closed Exceptions">

These can occur when one request gets a db connection from the connection
pool and closes it twice.  When using a connection pool, closing the
connection just returns it to the pool for reuse by another request,
it doesn't close the connection.  And Tomcat uses multiple threads to
handle concurrent requests. Here is an example of the sequence
of events which could cause this error in Tomcat:

  Request 1 running in Thread 1 gets a db connection.

  Request 1 closes the db connection.

  The JVM switches the running thread to Thread 2

  Request 2 running in Thread 2 gets a db connection
  (the same db connection just closed by Request 1).

  The JVM switches the running thread back to Thread 1

  Request 1 closes the db connection a second time in a finally block.

  The JVM switches the running thread back to Thread 2

  Request 2 Thread 2 tries to use the db connection but fails
  because Request 1 closed it.

Here is an example of properly written code to use a db connection
obtained from a connection pool:

  Connection conn = null;
  Statement stmt = null;  // Or PreparedStatement if needed
  ResultSet rs = null;
  try {
    conn = ... get connection from connection pool ...
    stmt = conn.createStatement("select ...");
    rs = stmt.executeQuery();
    ... iterate through the result set ...
    rs.close();
    rs = null;
    stmt.close();
    stmt = null;
    conn.close(); // Return to connection pool
    conn = null;  // Make sure we don't close it twice
  } catch (SQLException e) {
    ... deal with errors ...
  } finally {
    // Always make sure result sets and statements are closed,
    // and the connection is returned to the pool
    if (rs != null) {
      try { rs.close(); } catch (SQLException e) { ; }
      rs = null;
    }
    if (stmt != null) {
      try { stmt.close(); } catch (SQLException e) { ; }
      stmt = null;
    }
    if (conn != null) {
      try { conn.close(); } catch (SQLException e) { ; }
      conn = null;
    }
  }

</subsection>

</document>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Configuration;
using GW.Mail.Entity;

namespace GW.Mail
{
    public class ConfigurationInfo
    {
        //private static ConfigurationInfo _instance = null;
        private static Dictionary<string, ConfigurationInfo> _instanceDict = new Dictionary<string, ConfigurationInfo>();
        public static ConfigurationInfo GetInstance(string key)
        {
            if (_instanceDict.Keys.Contains(key))
                return _instanceDict[key];
            else
            {
                NameValueCollection nameValues = (NameValueCollection)ConfigurationSettings.GetConfig(key);
                string subject = nameValues["subject"];
                string server = nameValues["server"];
                int port = string.IsNullOrEmpty(nameValues["port"]) ? 0 : Convert.ToInt32(nameValues["port"]);
                string sender = nameValues["sender"];
                string receivers = nameValues["receivers"];
                string cc = nameValues["cc"];
                string bcc = nameValues["bcc"];
                string userName = nameValues["userName"];
                string password = nameValues["password"];
                bool enableSSL = nameValues["enableSSL"] == "1";
                ConfigurationInfo item = new ConfigurationInfo();
                item.DeflautSubject = subject;
                item.AddressInfo = new MailAddressInfo(sender, receivers, cc, bcc);
                item.ServerInfo = new MailServerInfo(server, port, userName, password);
                _instanceDict.Add(key, item);
                return item;
            }
        }
        public static MailInfo GetMainInfo(string key)
        {
            ConfigurationInfo configurationInfo = GetInstance(key);
            MailInfo mainInfo = new MailInfo() {
                MailAddressInfo = configurationInfo.AddressInfo,
                MailServerInfo = configurationInfo.ServerInfo,
                Subject = configurationInfo.DeflautSubject,
                EnableSsl = configurationInfo.enableSSL
            };
            return mainInfo;
        }
         public bool enableSSL { get; set; }

        public MailAddressInfo AddressInfo { get; set; }
        public MailServerInfo ServerInfo { get; set; }
        public string DeflautSubject { get; set; }
    }
}


text:
#include <aws/external/gtest.h>
#include <aws/core/Aws.h>
#include <aws/testing/platform/PlatformTesting.h>

int main(int argc, char** argv)
{
    Aws::SDKOptions options;

    Aws::Testing::InitPlatformTest(options);

    options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Trace;
    Aws::InitAPI(options);
    ::testing::InitGoogleTest(&argc, argv);
    int exitCode = RUN_ALL_TESTS();
    Aws::ShutdownAPI(options);

    Aws::Testing::ShutdownPlatformTest(options);
    return exitCode;
}


text:
import {normalizeSearchConfigs} from './normalize'

describe('searchConfig.normalize', () => {
  describe('normalizeSearchConfigs', () => {
    it('should keep numbers as numbers in path segments', () => {
      const normalized = normalizeSearchConfigs([
        {weight: 10, path: ['retain', 0, 'numbers']},
        {weight: 1, path: 'with.0.number'},
        {path: 'missing.weight'},
        {weight: 2, path: ['map', 'with'], mapWith: 'datetime'},
      ])

      expect(normalized).toEqual([
        {weight: 10, path: ['retain', 0, 'numbers'], mapWith: undefined},
        {weight: 1, path: ['with', 0, 'number'], mapWith: undefined},
        {weight: 1, path: ['missing', 'weight'], mapWith: undefined},
        {weight: 2, path: ['map', 'with'], mapWith: 'datetime'},
      ])
    })
  })
})


text:
<?php

namespace Symfony\Component\Mime\Tests\HtmlToTextConverter;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Mime\HtmlToTextConverter\DefaultHtmlToTextConverter;

class DefaultHtmlToTextConverterTest extends TestCase
{
    public function testConvert()
    {
        $converter = new DefaultHtmlToTextConverter();
        $this->assertSame('HTML', $converter->convert('<meta charset="utf-8">HTML', 'UTF-8'));
    }
}


text:
package net.sf.mmm.code.base.type;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;

import net.sf.mmm.code.api.copy.CodeCopyMapper;
import net.sf.mmm.code.api.copy.CodeCopyType;
import net.sf.mmm.code.api.element.CodeElement;
import net.sf.mmm.code.api.language.CodeLanguage;
import net.sf.mmm.code.api.type.CodeGenericType;
import net.sf.mmm.code.api.type.CodeParameterizedType;
import net.sf.mmm.code.base.arg.BaseOperationArg;
import net.sf.mmm.code.base.element.BaseElement;
import net.sf.mmm.code.base.member.BaseOperation;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Base implementation of {@link CodeParameterizedType}.
 *
 * @author Joerg Hohwiller (hohwille at users.sourceforge.net)
 * @since 1.0.0
 */
public class BaseParameterizedType extends BaseGenericType implements CodeParameterizedType {

  private static final Logger LOG = LoggerFactory.getLogger(BaseParameterizedType.class);

  private final BaseElement parent;

  private final BaseTypeParameters typeVariables;

  private final ParameterizedType reflectiveObject;

  private BaseParameterizedType sourceCodeObject;

  private BaseType type;

  /**
   * The constructor.
   *
   * @param parent the {@link #getParent() parent}.
   * @param type the {@link #getType() type} that gets parameterized. Should have the same number of
   *        {@link BaseType#getTypeParameters() type variables} as the {@link #getTypeParameters() type parameters of
   *        this type} when initialized.
   */
  public BaseParameterizedType(BaseElement parent, BaseType type) {

    this(parent, null, type);
  }

  /**
   * The constructor.
   *
   * @param parent the {@link #getParent() parent}.
   * @param reflectiveObject the {@link #getReflectiveObject() reflective object}. May be {@code null}.
   */
  public BaseParameterizedType(BaseElement parent, ParameterizedType reflectiveObject) {

    this(parent, reflectiveObject, null);
  }

  /**
   * The constructor.
   *
   * @param parent the {@link #getParent() parent}.
   * @param reflectiveObject the {@link #getReflectiveObject() reflective object}. May be {@code null}.
   * @param type the {@link #getType() type} that gets parameterized. Should have the same number of
   *        {@link BaseType#getTypeParameters() type variables} as the {@link #getTypeParameters() type parameters of
   *        this type} when initialized.
   */
  public BaseParameterizedType(BaseElement parent, ParameterizedType reflectiveObject, BaseType type) {

    super();
    this.parent = parent;
    this.typeVariables = new BaseTypeParameters(this);
    this.reflectiveObject = reflectiveObject;
    this.type = type;
  }

  /**
   * The copy-constructor.
   *
   * @param template the {@link BaseParameterizedType} to copy.
   * @param mapper the {@link CodeCopyMapper}.
   */
  public BaseParameterizedType(BaseParameterizedType template, CodeCopyMapper mapper) {

    super(template, mapper);
    this.parent = mapper.map(template.parent, CodeCopyType.PARENT);
    this.typeVariables = template.typeVariables.copy(mapper);
    this.reflectiveObject = null;
    this.type = mapper.map(template.type, CodeCopyType.REFERENCE);
  }

  @Override
  protected void doInitialize() {

    super.doInitialize();
    getType();
  }

  @Override
  public BaseElement getParent() {

    return this.parent;
  }

  @Override
  public BaseTypeParameters getTypeParameters() {

    return this.typeVariables;
  }

  @Override
  public ParameterizedType getReflectiveObject() {

    return this.reflectiveObject;
  }

  @Override
  public BaseParameterizedType getSourceCodeObject() {

    if ((this.sourceCodeObject == null) && !isInitialized()) {
      CodeElement sourceElement = this.parent.getSourceCodeObject();
      if (sourceElement != null) {
        this.sourceCodeObject = null; // TODO
      }
    }
    return this.sourceCodeObject;
  }

  @Override
  public BaseType getDeclaringType() {

    return getType();
  }

  @Override
  public BaseOperation getDeclaringOperation() {

    return getDeclaringOperation(this.parent);
  }

  private BaseOperation getDeclaringOperation(CodeElement parentNode) {

    if (parentNode instanceof BaseOperationArg) {
      return ((BaseOperationArg) parentNode).getDeclaringOperation();
    } else if (parentNode instanceof BaseParameterizedType) {
      return ((BaseParameterizedType) parentNode).getDeclaringOperation();
    } else if (parentNode instanceof BaseArrayType) {
      return getDeclaringOperation(((BaseArrayType) parentNode).getParent());
    }
    return null;
  }

  @Override
  public BaseType asType() {

    return getType().asType();
  }

  @Override
  public BaseType getType() {

    if ((this.type == null) && (this.reflectiveObject != null)) {
      Class<?> rawClass = (Class<?>) this.reflectiveObject.getRawType();
      this.type = (BaseType) getContext().getType(rawClass);
    }
    return this.type;
  }

  @Override
  public void setType(CodeGenericType type) {

    verifyMutalbe();
    this.type = (BaseType) type;
  }

  @Override
  public BaseTypeVariable asTypeVariable() {

    return null;
  }

  @Override
  public BaseGenericType resolve(CodeGenericType context) {

    // TODO Auto-generated method stub
    return this;
  }

  @Override
  public String getSimpleName() {

    return getType().getSimpleName();
  }

  @Override
  public String getQualifiedName() {

    return getType().getQualifiedName();
  }

  @Override
  protected void doWrite(Appendable sink, String newline, String defaultIndent, String currentIndent, CodeLanguage language)
      throws IOException {

    super.doWrite(sink, newline, null, "", language);
    writeReference(sink, true);
  }

  @Override
  public BaseParameterizedType copy() {

    return copy(getDefaultCopyMapper());
  }

  @Override
  public BaseParameterizedType copy(CodeCopyMapper mapper) {

    return new BaseParameterizedType(this, mapper);
  }

  @Override
  public void writeReference(Appendable sink, boolean declaration, Boolean qualified) throws IOException {

    BaseType myType = getType();
    if (myType == null) {
      LOG.warn("Parameterized type with undefined type declared in {}", getDeclaringType().getSimpleName());
      sink.append("Undefined");
    } else {
      myType.writeReference(sink, false, qualified);
      getTypeParameters().write(sink, DEFAULT_NEWLINE, null, "");
    }
  }

}


text:
var defaults = exports.defaults = {
  PORT: 3474,
  HOST: '127.0.0.1',
  DIRECTORY: process.cwd()
};

module.exports = defaults;


text:
package com.ajah.servlet.util;

import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.java.Log;

import com.ajah.util.AjahUtils;

/**
 * Class for utilities that deal with {@link Cookie}s.
 *
 * @author Eric F. Savage <code@efsavage.com>
 *
 */
@Log
public class CookieUtils {

	/**
	 * Clears all cookies by setting {@link Cookie#setMaxAge(int)} to 0;
	 *
	 * @param request
	 *            Request to get cookies from, required.
	 * @param response
	 *            Response to set updated cookies on, required.
	 */
	public static void clearAllCookies(final HttpServletRequest request, final HttpServletResponse response) {
		AjahUtils.requireParam(request, "request");
		AjahUtils.requireParam(response, "response");
		if (request.getCookies() == null) {
			log.finest("No cookies to clear");
			return;
		}
		for (final Cookie cookie : request.getCookies()) {
			cookie.setMaxAge(0);
			cookie.setDomain(request.getServerName());
			cookie.setPath("/");
			response.addCookie(cookie);
			log.finest("Cleared cookie: " + cookie.getName());
		}
	}

	/**
	 * Clears a cookies by setting its {@link Cookie#setMaxAge(int)} to 0;
	 *
	 * @param cookieName
	 *            The name of the cookie to clear
	 * @param response
	 *            Response to set updated cookies on, required.
	 * @param request
	 */
	public static void clearCookie(final String cookieName, final HttpServletRequest request, final HttpServletResponse response) {
		AjahUtils.requireParam(cookieName, "cookieName");
		AjahUtils.requireParam(request, "request");
		AjahUtils.requireParam(response, "response");
		final Cookie cookie = getCookie(request, cookieName);
		if (cookie != null) {
			cookie.setMaxAge(0);
			response.addCookie(cookie);
		}
	}

	/**
	 * Finds a cookie by name and returns it if found.
	 *
	 * @param request
	 *            Request to look for cookies on, required.
	 * @param name
	 *            Name of cookies to look for, required.
	 * @return Cookie if found, otherwise null.
	 */
	public static Cookie getCookie(final HttpServletRequest request, final String name) {
		AjahUtils.requireParam(request, "request");
		AjahUtils.requireParam(name, "name");
		final Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (final Cookie cookie : cookies) {
				if (cookie.getName().equals(name)) {
					return cookie;
				}
			}
		}
		return null;
	}

	/**
	 * Alternate signature for
	 * {@link CookieUtils#getCookie(HttpServletRequest, String)}.
	 *
	 * @param request
	 *            Request to look for cookies on, required.
	 * @param name
	 *            Name of cookies to look for, required.
	 * @return Cookie if found, otherwise null.
	 */
	public static Cookie getCookie(final ServletRequest request, final String name) {
		return getCookie((HttpServletRequest) request, name);
	}

}


text:
minimask
=======================
Light-weight routines for processing sky survey masks

.. image:: https://travis-ci.org/bengranett/minimask.svg?branch=master
    :target: https://travis-ci.org/bengranett/minimask

Philosophy
----------

A survey coverage mask is made up of a large number of tiles forming a mosaic
on the sky.  Each tile can be represented as a group of convex spherical
polygons.  We will optimize for the case when the polygons are small, less
than 1 degree, and the mosaic covers a large fraction of the sky. So we can
reference the polygons efficiently by a center point and sort them with
spatial indices.

The main operations to be carried out are:

* query polygons that contain a given point
* draw random samples of points from the area covered

Demos
-----
Check out the python notebooks in the `demos/` subdirectory.  They may be viewed online:
http://nbviewer.jupyter.org/github/bengranett/minimask/tree/master/demos/

Quick start
-----------

Load a mask polygon file and generate uniform random samples:

>>> M = minimask.Mask("survey.txt.gz")
>>> ra, dec = M.sample(n=10000)         # generate 10,000 points
>>> ra, dec = M.sample(density=10)      # ...or with number density 10 / square degree

Check if points are inside a polygon:

>>> inside = M.contains(ra, dec)
>>> print inside
[ True  True  True ...,  True  True  True]

Query weights:

>>> w = M.get_combined_weight(ra, dec, operation='sum')

Make plots:

>>> healpy.mollview()
>>> for x,y in M.render():
>>>    healpy.projplot(x, y, lonlat=True)
>>> pylab.show()

.. image:: docs/images/demo_mask.png
        :alt: demo mask plot
        :align: center

Pixelize with healpix:

>>> map = M.pixelize(nside=64)
>>> healpy.mollview(map)

.. image:: docs/images/demo_mask_pix.png
        :alt: demo mask plot
        :align: center

Dependencies
------------
* `python 2.7 <https://python.org>`_
* `numpy <https://numpy.org>`_
* `scipy <https://scipy.org>`_
* `scikit-learn <https://scikit-learn.org>`_
* `healpy <https://github.com/healpy/healpy>`_

Contributors
------------
Ben Granett, Dida Markovic