text:
goog.provide('ol.interaction.Draw');
goog.provide('ol.interaction.DrawEvent');
goog.provide('ol.interaction.DrawEventType');
goog.provide('ol.interaction.DrawMode');

goog.require('ol');
goog.require('ol.events');
goog.require('ol.events.Event');
goog.require('ol.Feature');
goog.require('ol.MapBrowserEvent.EventType');
goog.require('ol.Object');
goog.require('ol.coordinate');
goog.require('ol.functions');
goog.require('ol.events.condition');
goog.require('ol.geom.Circle');
goog.require('ol.geom.GeometryType');
goog.require('ol.geom.LineString');
goog.require('ol.geom.MultiLineString');
goog.require('ol.geom.MultiPoint');
goog.require('ol.geom.MultiPolygon');
goog.require('ol.geom.Point');
goog.require('ol.geom.Polygon');
goog.require('ol.interaction.InteractionProperty');
goog.require('ol.interaction.Pointer');
goog.require('ol.layer.Vector');
goog.require('ol.source.Vector');
goog.require('ol.style.Style');

/**
 * @enum {string}
 */
ol.interaction.DrawEventType = {
  /**
   * Triggered upon feature draw start
   * @event ol.interaction.DrawEvent#drawstart
   * @api stable
   */
  DRAWSTART: 'drawstart',
  /**
   * Triggered upon feature draw end
   * @event ol.interaction.DrawEvent#drawend
   * @api stable
   */
  DRAWEND: 'drawend'
};

/**
 * @classdesc
 * Events emitted by {@link ol.interaction.Draw} instances are instances of
 * this type.
 *
 * @constructor
 * @extends {ol.events.Event}
 * @implements {oli.DrawEvent}
 * @param {ol.interaction.DrawEventType} type Type.
 * @param {ol.Feature} feature The feature drawn.
 */
ol.interaction.DrawEvent = function(type, feature) {

  ol.events.Event.call(this, type);

  /**
   * The feature being drawn.
   * @type {ol.Feature}
   * @api stable
   */
  this.feature = feature;

};
ol.inherits(ol.interaction.DrawEvent, ol.events.Event);

/**
 * @classdesc
 * Interaction for drawing feature geometries.
 *
 * @constructor
 * @extends {ol.interaction.Pointer}
 * @fires ol.interaction.DrawEvent
 * @param {olx.interaction.DrawOptions} options Options.
 * @api stable
 */
ol.interaction.Draw = function(options) {

  ol.interaction.Pointer.call(this, {
    handleDownEvent: ol.interaction.Draw.handleDownEvent_,
    handleEvent: ol.interaction.Draw.handleEvent,
    handleUpEvent: ol.interaction.Draw.handleUpEvent_
  });

  /**
   * @type {ol.Pixel}
   * @private
   */
  this.downPx_ = null;

  /**
   * @type {boolean}
   * @private
   */
  this.freehand_ = false;

  /**
   * Target source for drawn features.
   * @type {ol.source.Vector}
   * @private
   */
  this.source_ = options.source ? options.source : null;

  /**
   * Target collection for drawn features.
   * @type {ol.Collection.<ol.Feature>}
   * @private
   */
  this.features_ = options.features ? options.features : null;

  /**
   * Pixel distance for snapping.
   * @type {number}
   * @private
   */
  this.snapTolerance_ = options.snapTolerance ? options.snapTolerance : 12;

  /**
   * Geometry type.
   * @type {ol.geom.GeometryType}
   * @private
   */
  this.type_ = options.type;

  /**
   * Drawing mode (derived from geometry type.
   * @type {ol.interaction.DrawMode}
   * @private
   */
  this.mode_ = ol.interaction.Draw.getMode_(this.type_);

  /**
   * The number of points that must be drawn before a polygon ring or line
   * string can be finished.  The default is 3 for polygon rings and 2 for
   * line strings.
   * @type {number}
   * @private
   */
  this.minPoints_ = options.minPoints ?
      options.minPoints :
      (this.mode_ === ol.interaction.DrawMode.POLYGON ? 3 : 2);

  /**
   * The number of points that can be drawn before a polygon ring or line string
   * is finished. The default is no restriction.
   * @type {number}
   * @private
   */
  this.maxPoints_ = options.maxPoints ? options.maxPoints : Infinity;

  /**
   * A function to decide if a potential finish coordinate is permissable
   * @private
   * @type {ol.EventsConditionType}
   */
  this.finishCondition_ = options.finishCondition ? options.finishCondition : ol.functions.TRUE;

  var geometryFunction = options.geometryFunction;
  if (!geometryFunction) {
    if (this.type_ === ol.geom.GeometryType.CIRCLE) {
      /**
       * @param {ol.Coordinate|Array.<ol.Coordinate>|Array.<Array.<ol.Coordinate>>} coordinates
       *     The coordinates.
       * @param {ol.geom.SimpleGeometry=} opt_geometry Optional geometry.
       * @return {ol.geom.SimpleGeometry} A geometry.
       */
      geometryFunction = function(coordinates, opt_geometry) {
        var circle = opt_geometry ? /** @type {ol.geom.Circle} */ (opt_geometry) :
            new ol.geom.Circle([NaN, NaN]);
        var squaredLength = ol.coordinate.squaredDistance(
            coordinates[0], coordinates[1]);
        circle.setCenterAndRadius(coordinates[0], Math.sqrt(squaredLength));
        return circle;
      };
    } else {
      var Constructor;
      var mode = this.mode_;
      if (mode === ol.interaction.DrawMode.POINT) {
        Constructor = ol.geom.Point;
      } else if (mode === ol.interaction.DrawMode.LINE_STRING) {
        Constructor = ol.geom.LineString;
      } else if (mode === ol.interaction.DrawMode.POLYGON) {
        Constructor = ol.geom.Polygon;
      }
      /**
       * @param {ol.Coordinate|Array.<ol.Coordinate>|Array.<Array.<ol.Coordinate>>} coordinates
       *     The coordinates.
       * @param {ol.geom.SimpleGeometry=} opt_geometry Optional geometry.
       * @return {ol.geom.SimpleGeometry} A geometry.
       */
      geometryFunction = function(coordinates, opt_geometry) {
        var geometry = opt_geometry;
        if (geometry) {
          geometry.setCoordinates(coordinates);
        } else {
          geometry = new Constructor(coordinates);
        }
        return geometry;
      };
    }
  }

  /**
   * @type {ol.DrawGeometryFunctionType}
   * @private
   */
  this.geometryFunction_ = geometryFunction;

  /**
   * Finish coordinate for the feature (first point for polygons, last point for
   * linestrings).
   * @type {ol.Coordinate}
   * @private
   */
  this.finishCoordinate_ = null;

  /**
   * Sketch feature.
   * @type {ol.Feature}
   * @private
   */
  this.sketchFeature_ = null;

  /**
   * Sketch point.
   * @type {ol.Feature}
   * @private
   */
  this.sketchPoint_ = null;

  /**
   * Sketch coordinates. Used when drawing a line or polygon.
   * @type {ol.Coordinate|Array.<ol.Coordinate>|Array.<Array.<ol.Coordinate>>}
   * @private
   */
  this.sketchCoords_ = null;

  /**
   * Sketch line. Used when drawing polygon.
   * @type {ol.Feature}
   * @private
   */
  this.sketchLine_ = null;

  /**
   * Sketch line coordinates. Used when drawing a polygon or circle.
   * @type {Array.<ol.Coordinate>}
   * @private
   */
  this.sketchLineCoords_ = null;

  /**
   * Squared tolerance for handling up events.  If the squared distance
   * between a down and up event is greater than this tolerance, up events
   * will not be handled.
   * @type {number}
   * @private
   */
  this.squaredClickTolerance_ = options.clickTolerance ?
      options.clickTolerance * options.clickTolerance : 36;

  /**
   * Draw overlay where our sketch features are drawn.
   * @type {ol.layer.Vector}
   * @private
   */
  this.overlay_ = new ol.layer.Vector({
    source: new ol.source.Vector({
      useSpatialIndex: false,
      wrapX: options.wrapX ? options.wrapX : false
    }),
    style: options.style ? options.style :
        ol.interaction.Draw.getDefaultStyleFunction()
  });

  /**
   * Name of the geometry attribute for newly created features.
   * @type {string|undefined}
   * @private
   */
  this.geometryName_ = options.geometryName;

  /**
   * @private
   * @type {ol.EventsConditionType}
   */
  this.condition_ = options.condition ?
      options.condition : ol.events.condition.noModifierKeys;

  /**
   * @private
   * @type {ol.EventsConditionType}
   */
  this.freehandCondition_ = options.freehandCondition ?
      options.freehandCondition : ol.events.condition.shiftKeyOnly;

  ol.events.listen(this,
      ol.Object.getChangeEventType(ol.interaction.InteractionProperty.ACTIVE),
      this.updateState_, this);

};
ol.inherits(ol.interaction.Draw, ol.interaction.Pointer);

/**
 * @return {ol.StyleFunction} Styles.
 */
ol.interaction.Draw.getDefaultStyleFunction = function() {
  var styles = ol.style.Style.createDefaultEditing();
  return function(feature, resolution) {
    return styles[feature.getGeometry().getType()];
  };
};

/**
 * @inheritDoc
 */
ol.interaction.Draw.prototype.setMap = function(map) {
  ol.interaction.Pointer.prototype.setMap.call(this, map);
  this.updateState_();
};

/**
 * Handles the {@link ol.MapBrowserEvent map browser event} and may actually
 * draw or finish the drawing.
 * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event.
 * @return {boolean} `false` to stop event propagation.
 * @this {ol.interaction.Draw}
 * @api
 */
ol.interaction.Draw.handleEvent = function(mapBrowserEvent) {
  if ((this.mode_ === ol.interaction.DrawMode.LINE_STRING ||
    this.mode_ === ol.interaction.DrawMode.POLYGON) &&
    this.freehandCondition_(mapBrowserEvent)) {
    this.freehand_ = true;
  }
  var pass = !this.freehand_;
  if (this.freehand_ &&
      mapBrowserEvent.type === ol.MapBrowserEvent.EventType.POINTERDRAG) {
    this.addToDrawing_(mapBrowserEvent);
    pass = false;
  } else if (mapBrowserEvent.type ===
      ol.MapBrowserEvent.EventType.POINTERMOVE) {
    pass = this.handlePointerMove_(mapBrowserEvent);
  } else if (mapBrowserEvent.type === ol.MapBrowserEvent.EventType.DBLCLICK) {
    pass = false;
  }
  return ol.interaction.Pointer.handleEvent.call(this, mapBrowserEvent) && pass;
};

/**
 * @param {ol.MapBrowserPointerEvent} event Event.
 * @return {boolean} Start drag sequence?
 * @this {ol.interaction.Draw}
 * @private
 */
ol.interaction.Draw.handleDownEvent_ = function(event) {
  if (this.condition_(event)) {
    this.downPx_ = event.pixel;
    return true;
  } else if (this.freehand_) {
    this.downPx_ = event.pixel;
    if (!this.finishCoordinate_) {
      this.startDrawing_(event);
    }
    return true;
  } else {
    return false;
  }
};

/**
 * @param {ol.MapBrowserPointerEvent} event Event.
 * @return {boolean} Stop drag sequence?
 * @this {ol.interaction.Draw}
 * @private
 */
ol.interaction.Draw.handleUpEvent_ = function(event) {
  this.freehand_ = false;
  var downPx = this.downPx_;
  var clickPx = event.pixel;
  var dx = downPx[0] - clickPx[0];
  var dy = downPx[1] - clickPx[1];
  var squaredDistance = dx * dx + dy * dy;
  var pass = true;
  if (squaredDistance <= this.squaredClickTolerance_) {
    this.handlePointerMove_(event);
    if (!this.finishCoordinate_) {
      this.startDrawing_(event);
      if (this.mode_ === ol.interaction.DrawMode.POINT) {
        this.finishDrawing();
      }
    } else if (this.mode_ === ol.interaction.DrawMode.CIRCLE) {
      this.finishDrawing();
    } else if (this.atFinish_(event)) {
      if (this.finishCondition_(event)) {
        this.finishDrawing();
      }
    } else {
      this.addToDrawing_(event);
    }
    pass = false;
  }
  return pass;
};

/**
 * Handle move events.
 * @param {ol.MapBrowserEvent} event A move event.
 * @return {boolean} Pass the event to other interactions.
 * @private
 */
ol.interaction.Draw.prototype.handlePointerMove_ = function(event) {
  if (this.finishCoordinate_) {
    this.modifyDrawing_(event);
  } else {
    this.createOrUpdateSketchPoint_(event);
  }
  return true;
};

/**
 * Determine if an event is within the snapping tolerance of the start coord.
 * @param {ol.MapBrowserEvent} event Event.
 * @return {boolean} The event is within the snapping tolerance of the start.
 * @private
 */
ol.interaction.Draw.prototype.atFinish_ = function(event) {
  var at = false;
  if (this.sketchFeature_) {
    var potentiallyDone = false;
    var potentiallyFinishCoordinates = [this.finishCoordinate_];
    if (this.mode_ === ol.interaction.DrawMode.LINE_STRING) {
      potentiallyDone = this.sketchCoords_.length > this.minPoints_;
    } else if (this.mode_ === ol.interaction.DrawMode.POLYGON) {
      potentiallyDone = this.sketchCoords_[0].length >
          this.minPoints_;
      potentiallyFinishCoordinates = [this.sketchCoords_[0][0],
        this.sketchCoords_[0][this.sketchCoords_[0].length - 2]];
    }
    if (potentiallyDone) {
      var map = event.map;
      for (var i = 0, ii = potentiallyFinishCoordinates.length; i < ii; i++) {
        var finishCoordinate = potentiallyFinishCoordinates[i];
        var finishPixel = map.getPixelFromCoordinate(finishCoordinate);
        var pixel = event.pixel;
        var dx = pixel[0] - finishPixel[0];
        var dy = pixel[1] - finishPixel[1];
        var freehand = this.freehand_ && this.freehandCondition_(event);
        var snapTolerance = freehand ? 1 : this.snapTolerance_;
        at = Math.sqrt(dx * dx + dy * dy) <= snapTolerance;
        if (at) {
          this.finishCoordinate_ = finishCoordinate;
          break;
        }
      }
    }
  }
  return at;
};

/**
 * @param {ol.MapBrowserEvent} event Event.
 * @private
 */
ol.interaction.Draw.prototype.createOrUpdateSketchPoint_ = function(event) {
  var coordinates = event.coordinate.slice();
  if (!this.sketchPoint_) {
    this.sketchPoint_ = new ol.Feature(new ol.geom.Point(coordinates));
    this.updateSketchFeatures_();
  } else {
    var sketchPointGeom = /** @type {ol.geom.Point} */ (this.sketchPoint_.getGeometry());
    sketchPointGeom.setCoordinates(coordinates);
  }
};

/**
 * Start the drawing.
 * @param {ol.MapBrowserEvent} event Event.
 * @private
 */
ol.interaction.Draw.prototype.startDrawing_ = function(event) {
  var start = event.coordinate;
  this.finishCoordinate_ = start;
  if (this.mode_ === ol.interaction.DrawMode.POINT) {
    this.sketchCoords_ = start.slice();
  } else if (this.mode_ === ol.interaction.DrawMode.POLYGON) {
    this.sketchCoords_ = [[start.slice(), start.slice()]];
    this.sketchLineCoords_ = this.sketchCoords_[0];
  } else {
    this.sketchCoords_ = [start.slice(), start.slice()];
    if (this.mode_ === ol.interaction.DrawMode.CIRCLE) {
      this.sketchLineCoords_ = this.sketchCoords_;
    }
  }
  if (this.sketchLineCoords_) {
    this.sketchLine_ = new ol.Feature(
        new ol.geom.LineString(this.sketchLineCoords_));
  }
  var geometry = this.geometryFunction_(this.sketchCoords_);
  goog.DEBUG && console.assert(geometry !== undefined, 'geometry should be defined');
  this.sketchFeature_ = new ol.Feature();
  if (this.geometryName_) {
    this.sketchFeature_.setGeometryName(this.geometryName_);
  }
  this.sketchFeature_.setGeometry(geometry);
  this.updateSketchFeatures_();
  this.dispatchEvent(new ol.interaction.DrawEvent(
      ol.interaction.DrawEventType.DRAWSTART, this.sketchFeature_));
};

/**
 * Modify the drawing.
 * @param {ol.MapBrowserEvent} event Event.
 * @private
 */
ol.interaction.Draw.prototype.modifyDrawing_ = function(event) {
  var coordinate = event.coordinate;
  var geometry = /** @type {ol.geom.SimpleGeometry} */ (this.sketchFeature_.getGeometry());
  var coordinates, last;
  if (this.mode_ === ol.interaction.DrawMode.POINT) {
    last = this.sketchCoords_;
  } else if (this.mode_ === ol.interaction.DrawMode.POLYGON) {
    coordinates = this.sketchCoords_[0];
    last = coordinates[coordinates.length - 1];
    if (this.atFinish_(event)) {
      // snap to finish
      coordinate = this.finishCoordinate_.slice();
    }
  } else {
    coordinates = this.sketchCoords_;
    last = coordinates[coordinates.length - 1];
  }
  last[0] = coordinate[0];
  last[1] = coordinate[1];
  goog.DEBUG && console.assert(this.sketchCoords_, 'sketchCoords_ expected');
  this.geometryFunction_(
      /** @type {!ol.Coordinate|!Array.<ol.Coordinate>|!Array.<Array.<ol.Coordinate>>} */ (this.sketchCoords_),
      geometry);
  if (this.sketchPoint_) {
    var sketchPointGeom = /** @type {ol.geom.Point} */ (this.sketchPoint_.getGeometry());
    sketchPointGeom.setCoordinates(coordinate);
  }
  var sketchLineGeom;
  if (geometry instanceof ol.geom.Polygon &&
      this.mode_ !== ol.interaction.DrawMode.POLYGON) {
    if (!this.sketchLine_) {
      this.sketchLine_ = new ol.Feature(new ol.geom.LineString(null));
    }
    var ring = geometry.getLinearRing(0);
    sketchLineGeom = /** @type {ol.geom.LineString} */ (this.sketchLine_.getGeometry());
    sketchLineGeom.setFlatCoordinates(
        ring.getLayout(), ring.getFlatCoordinates());
  } else if (this.sketchLineCoords_) {
    sketchLineGeom = /** @type {ol.geom.LineString} */ (this.sketchLine_.getGeometry());
    sketchLineGeom.setCoordinates(this.sketchLineCoords_);
  }
  this.updateSketchFeatures_();
};

/**
 * Add a new coordinate to the drawing.
 * @param {ol.MapBrowserEvent} event Event.
 * @private
 */
ol.interaction.Draw.prototype.addToDrawing_ = function(event) {
  var coordinate = event.coordinate;
  var geometry = /** @type {ol.geom.SimpleGeometry} */ (this.sketchFeature_.getGeometry());
  var done;
  var coordinates;
  if (this.mode_ === ol.interaction.DrawMode.LINE_STRING) {
    this.finishCoordinate_ = coordinate.slice();
    coordinates = this.sketchCoords_;
    coordinates.push(coordinate.slice());
    done = coordinates.length > this.maxPoints_;
    this.geometryFunction_(coordinates, geometry);
  } else if (this.mode_ === ol.interaction.DrawMode.POLYGON) {
    coordinates = this.sketchCoords_[0];
    coordinates.push(coordinate.slice());
    done = coordinates.length > this.maxPoints_;
    if (done) {
      this.finishCoordinate_ = coordinates[0];
    }
    this.geometryFunction_(this.sketchCoords_, geometry);
  }
  this.updateSketchFeatures_();
  if (done) {
    this.finishDrawing();
  }
};

/**
 * Remove last point of the feature currently being drawn.
 * @api
 */
ol.interaction.Draw.prototype.removeLastPoint = function() {
  var geometry = /** @type {ol.geom.SimpleGeometry} */ (this.sketchFeature_.getGeometry());
  var coordinates, sketchLineGeom;
  if (this.mode_ === ol.interaction.DrawMode.LINE_STRING) {
    coordinates = this.sketchCoords_;
    coordinates.splice(-2, 1);
    this.geometryFunction_(coordinates, geometry);
  } else if (this.mode_ === ol.interaction.DrawMode.POLYGON) {
    coordinates = this.sketchCoords_[0];
    coordinates.splice(-2, 1);
    sketchLineGeom = /** @type {ol.geom.LineString} */ (this.sketchLine_.getGeometry());
    sketchLineGeom.setCoordinates(coordinates);
    this.geometryFunction_(this.sketchCoords_, geometry);
  }

  if (coordinates.length === 0) {
    this.finishCoordinate_ = null;
  }

  this.updateSketchFeatures_();
};

/**
 * Stop drawing and add the sketch feature to the target layer.
 * The {@link ol.interaction.DrawEventType.DRAWEND} event is dispatched before
 * inserting the feature.
 * @api
 */
ol.interaction.Draw.prototype.finishDrawing = function() {
  var sketchFeature = this.abortDrawing_();
  var coordinates = this.sketchCoords_;
  var geometry = /** @type {ol.geom.SimpleGeometry} */ (sketchFeature.getGeometry());
  if (this.mode_ === ol.interaction.DrawMode.LINE_STRING) {
    // remove the redundant last point
    coordinates.pop();
    this.geometryFunction_(coordinates, geometry);
  } else if (this.mode_ === ol.interaction.DrawMode.POLYGON) {
    // When we finish drawing a polygon on the last point,
    // the last coordinate is duplicated as for LineString
    // we force the replacement by the first point
    coordinates[0].pop();
    coordinates[0].push(coordinates[0][0]);
    this.geometryFunction_(coordinates, geometry);
  }

  // cast multi-part geometries
  if (this.type_ === ol.geom.GeometryType.MULTI_POINT) {
    sketchFeature.setGeometry(new ol.geom.MultiPoint([coordinates]));
  } else if (this.type_ === ol.geom.GeometryType.MULTI_LINE_STRING) {
    sketchFeature.setGeometry(new ol.geom.MultiLineString([coordinates]));
  } else if (this.type_ === ol.geom.GeometryType.MULTI_POLYGON) {
    sketchFeature.setGeometry(new ol.geom.MultiPolygon([coordinates]));
  }

  // First dispatch event to allow full set up of feature
  this.dispatchEvent(new ol.interaction.DrawEvent(
      ol.interaction.DrawEventType.DRAWEND, sketchFeature));

  // Then insert feature
  if (this.features_) {
    this.features_.push(sketchFeature);
  }
  if (this.source_) {
    this.source_.addFeature(sketchFeature);
  }
};

/**
 * Stop drawing without adding the sketch feature to the target layer.
 * @return {ol.Feature} The sketch feature (or null if none).
 * @private
 */
ol.interaction.Draw.prototype.abortDrawing_ = function() {
  this.finishCoordinate_ = null;
  var sketchFeature = this.sketchFeature_;
  if (sketchFeature) {
    this.sketchFeature_ = null;
    this.sketchPoint_ = null;
    this.sketchLine_ = null;
    this.overlay_.getSource().clear(true);
  }
  return sketchFeature;
};

/**
 * Extend an existing geometry by adding additional points. This only works
 * on features with `LineString` geometries, where the interaction will
 * extend lines by adding points to the end of the coordinates array.
 * @param {!ol.Feature} feature Feature to be extended.
 * @api
 */
ol.interaction.Draw.prototype.extend = function(feature) {
  var geometry = feature.getGeometry();
  goog.DEBUG && console.assert(this.mode_ == ol.interaction.DrawMode.LINE_STRING,
      'interaction mode must be "line"');
  goog.DEBUG && console.assert(geometry.getType() == ol.geom.GeometryType.LINE_STRING,
      'feature geometry must be a line string');
  var lineString = /** @type {ol.geom.LineString} */ (geometry);
  this.sketchFeature_ = feature;
  this.sketchCoords_ = lineString.getCoordinates();
  var last = this.sketchCoords_[this.sketchCoords_.length - 1];
  this.finishCoordinate_ = last.slice();
  this.sketchCoords_.push(last.slice());
  this.updateSketchFeatures_();
  this.dispatchEvent(new ol.interaction.DrawEvent(
      ol.interaction.DrawEventType.DRAWSTART, this.sketchFeature_));
};

/**
 * @inheritDoc
 */
ol.interaction.Draw.prototype.shouldStopEvent = ol.functions.FALSE;

/**
 * Redraw the sketch features.
 * @private
 */
ol.interaction.Draw.prototype.updateSketchFeatures_ = function() {
  var sketchFeatures = [];
  if (this.sketchFeature_) {
    sketchFeatures.push(this.sketchFeature_);
  }
  if (this.sketchLine_) {
    sketchFeatures.push(this.sketchLine_);
  }
  if (this.sketchPoint_) {
    sketchFeatures.push(this.sketchPoint_);
  }
  var overlaySource = this.overlay_.getSource();
  overlaySource.clear(true);
  overlaySource.addFeatures(sketchFeatures);
};

/**
 * @private
 */
ol.interaction.Draw.prototype.updateState_ = function() {
  var map = this.getMap();
  var active = this.getActive();
  if (!map || !active) {
    this.abortDrawing_();
  }
  this.overlay_.setMap(active ? map : null);
};

/**
 * Create a `geometryFunction` for `mode: 'Circle'` that will create a regular
 * polygon with a user specified number of sides and start angle instead of an
 * `ol.geom.Circle` geometry.
 * @param {number=} opt_sides Number of sides of the regular polygon. Default is
 *     32.
 * @param {number=} opt_angle Angle of the first point in radians. 0 means East.
 *     Default is the angle defined by the heading from the center of the
 *     regular polygon to the current pointer position.
 * @return {ol.DrawGeometryFunctionType} Function that draws a
 *     polygon.
 * @api
 */
ol.interaction.Draw.createRegularPolygon = function(opt_sides, opt_angle) {
  return (
      /**
       * @param {ol.Coordinate|Array.<ol.Coordinate>|Array.<Array.<ol.Coordinate>>} coordinates
       * @param {ol.geom.SimpleGeometry=} opt_geometry
       * @return {ol.geom.SimpleGeometry}
       */
      function(coordinates, opt_geometry) {
        var center = coordinates[0];
        var end = coordinates[1];
        var radius = Math.sqrt(
            ol.coordinate.squaredDistance(center, end));
        var geometry = opt_geometry ? /** @type {ol.geom.Polygon} */ (opt_geometry) :
            ol.geom.Polygon.fromCircle(new ol.geom.Circle(center), opt_sides);
        var angle = opt_angle ? opt_angle :
            Math.atan((end[1] - center[1]) / (end[0] - center[0]));
        ol.geom.Polygon.makeRegular(geometry, center, radius, angle);
        return geometry;
      }
  );
};

/**
 * Get the drawing mode.  The mode for mult-part geometries is the same as for
 * their single-part cousins.
 * @param {ol.geom.GeometryType} type Geometry type.
 * @return {ol.interaction.DrawMode} Drawing mode.
 * @private
 */
ol.interaction.Draw.getMode_ = function(type) {
  var mode;
  if (type === ol.geom.GeometryType.POINT ||
      type === ol.geom.GeometryType.MULTI_POINT) {
    mode = ol.interaction.DrawMode.POINT;
  } else if (type === ol.geom.GeometryType.LINE_STRING ||
      type === ol.geom.GeometryType.MULTI_LINE_STRING) {
    mode = ol.interaction.DrawMode.LINE_STRING;
  } else if (type === ol.geom.GeometryType.POLYGON ||
      type === ol.geom.GeometryType.MULTI_POLYGON) {
    mode = ol.interaction.DrawMode.POLYGON;
  } else if (type === ol.geom.GeometryType.CIRCLE) {
    mode = ol.interaction.DrawMode.CIRCLE;
  }
  return /** @type {!ol.interaction.DrawMode} */ (mode);
};

/**
 * Draw mode.  This collapses multi-part geometry types with their single-part
 * cousins.
 * @enum {string}
 */
ol.interaction.DrawMode = {
  POINT: 'Point',
  LINE_STRING: 'LineString',
  POLYGON: 'Polygon',
  CIRCLE: 'Circle'
};


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class de.hdu.pvs.crashfinder.analysis.IRStatement</title>
<meta name="date" content="2015-05-30">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
de.hdu.pvs.crashfinder.analysis.IRStatement

Packages that use IRStatement

Package
Description

de.hdu.pvs.crashfinder.analysis

de.hdu.pvs.crashfinder.experiments

Uses of IRStatement in de.hdu.pvs.crashfinder.analysis

Fields in de.hdu.pvs.crashfinder.analysis with type parameters of type IRStatement

Modifier and Type
Field and Description

java.util.Set<IRStatement>
SlicingOutput.statements

java.util.Map<IRStatement,java.lang.Integer>
SlicingOutput.stmtDistances

Methods in de.hdu.pvs.crashfinder.analysis that return IRStatement

Modifier and Type
Method and Description

IRStatement
SlicingOutput.getStatement(java.lang.String methodSig,
            int instructionIndex)

Methods in de.hdu.pvs.crashfinder.analysis that return types with arguments of type IRStatement

Modifier and Type
Method and Description

static java.util.Collection<IRStatement>
Slicing.convert(java.util.Collection<com.ibm.wala.ipa.slicer.Statement> stmts)

static java.util.Set<IRStatement>
SlicingOutput.excludeIgnorableStatements(java.util.Collection<IRStatement> set)

static java.util.Set<IRStatement>
SlicingOutput.extractBranchStatements(java.util.Collection<IRStatement> set)

static java.util.Set<IRStatement>
SlicingOutput.filterStatementsForFullSliceResult(java.util.Collection<IRStatement> set)

A method designed specifically for speeding up processing full slicing results,
 since the slice is so large that it is hard to fit into memory

java.util.Set<IRStatement>
SlicingOutput.getNumberedBranches()

java.util.Set<IRStatement>
SlicingOutput.getNumberedBranchesInSource()

java.util.Set<IRStatement>
SlicingOutput.getNumberedStatements()

Method parameters in de.hdu.pvs.crashfinder.analysis with type arguments of type IRStatement

Modifier and Type
Method and Description

static void
IRStatement.dumpIRStatements(java.util.Collection<IRStatement> slice,
                java.io.PrintWriter w)

static java.util.Set<IRStatement>
SlicingOutput.excludeIgnorableStatements(java.util.Collection<IRStatement> set)

static java.util.Set<IRStatement>
SlicingOutput.extractBranchStatements(java.util.Collection<IRStatement> set)

static java.util.Set<IRStatement>
SlicingOutput.filterStatementsForFullSliceResult(java.util.Collection<IRStatement> set)

A method designed specifically for speeding up processing full slicing results,
 since the slice is so large that it is hard to fit into memory

Constructors in de.hdu.pvs.crashfinder.analysis with parameters of type IRStatement

Constructor and Description

ShrikePoint(IRStatement ir)

Constructor parameters in de.hdu.pvs.crashfinder.analysis with type arguments of type IRStatement

Constructor and Description

SlicingOutput(java.util.Collection<IRStatement> stmts)

SlicingOutput(java.util.Collection<IRStatement> stmts,
             java.lang.String targetPackage)

Uses of IRStatement in de.hdu.pvs.crashfinder.experiments

Method parameters in de.hdu.pvs.crashfinder.experiments with type arguments of type IRStatement

Modifier and Type
Method and Description

static void
CommonUtils.dumpStatements(java.util.Collection<IRStatement> stmts)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

redpajama_set_name: RedPajamaGithub


text:
package com.wsfmn.view;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.wsfmn.controller.ImageController;
import com.wsfmn.controller.ProfileNameController;
import com.wsfmn.model.Date;

import com.wsfmn.model.Habit;
import com.wsfmn.exceptions.HabitCommentTooLongException;
import com.wsfmn.model.HabitEvent;
import com.wsfmn.exceptions.HabitEventCommentTooLongException;
import com.wsfmn.controller.HabitHistoryController;
import com.wsfmn.controller.HabitListController;

import java.text.ParseException;

/**
 * Called when the user wants to adds a HabitEvent for a Habit.
 * @version 1.0
 * @see AppCompatActivity
 */
public class AddNewHabitEventActivity extends HabitHistorySuper {

    /**
     * Setup the activity for adding a new HabitEvent to HabitHistory.
     * @param savedInstanceState
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_new_habit_event);

        // Variables for the UI
        title = (TextView)findViewById(R.id.habitName);
        comment = (EditText) findViewById(R.id.Comment);
        date = (TextView) findViewById(R.id.eventDate);
        address = (TextView) findViewById(R.id.T_showAdress);
        addPicture = (Button) findViewById(R.id.Picture);
        viewPicture = (Button) findViewById(R.id.ViewImg);

        // Check if the Habit has been set by a call from the HabitForTodayActivity
        Bundle b = getIntent().getExtras();
        if(b!=null) {
            if (b.getString("caller").equals("TODAY")) {
                habitIdx = b.getInt("positionToday");

                addedHabit = HLC.getHabitsForToday().get(habitIdx);
                title.setText(addedHabit.getTitle().toString());
            }
        }
        // Set date for the HabitEvent created
        String dateAndTime = new Date(0).toString();
        date.setText(dateAndTime);

        // Check if device has a camera
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)) {
            addPicture.setEnabled(false);
        }

        FIRST_PHOTO = true; // Adding new HabitEvent starts with no photo
        viewPicture.setEnabled(false);

        // React when the date has been set
        mDateSetListener = new DatePickerDialog.OnDateSetListener(){
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                month += 1;
                date.setText(year + " / " + month + " / " + dayOfMonth);
                date.getText();
            }
        };
    }

    /**
     * Create and save a new valid HabitEvent with the current on-screen parameters.
     * @param view
     */
    public void addHE(View view) {
        Intent intent = new Intent(this, ViewHabitHistoryActivity.class);

        // Encode image as a string for online storage
        String photoStringEncoding = IC.convertImageToString(photoPath);
        try {
            //CREATE THE NEW HABIT EVENT
            HabitEvent NEW_HABIT_EVENT = new HabitEvent(
                    addedHabit,
                    addedHabit.getTitle(),
                    comment.getText().toString(),
                    photoStringEncoding,
                    photoPath,
                    getDateUIHE(),
                    geolocation);

            //Add the Habit Event to HabitHistory
            HHC.addAndStore(NEW_HABIT_EVENT);
            HHC.storeAll();

            // Update User's Score
            ProfileNameController.getInstance().updateScore();
            startActivity(intent);

        }catch(HabitCommentTooLongException e){
            e.printStackTrace();
        }catch(HabitEventCommentTooLongException e){
            Toast.makeText(AddNewHabitEventActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
        }catch(NullPointerException e){
            Toast.makeText(AddNewHabitEventActivity.this, "Habit Event needs to contain Habit", Toast.LENGTH_LONG).show();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}


text:
package org.apache.flink.connector.pulsar.testutils.cases;

import org.apache.flink.api.connector.source.Boundedness;
import org.apache.flink.api.connector.source.Source;
import org.apache.flink.connector.pulsar.source.PulsarSource;
import org.apache.flink.connector.pulsar.source.PulsarSourceBuilder;
import org.apache.flink.connector.pulsar.source.enumerator.cursor.StopCursor;
import org.apache.flink.connector.pulsar.source.enumerator.topic.TopicNameUtils;
import org.apache.flink.connector.pulsar.testutils.PulsarPartitionDataWriter;
import org.apache.flink.connector.pulsar.testutils.PulsarTestContext;
import org.apache.flink.connector.pulsar.testutils.PulsarTestEnvironment;
import org.apache.flink.connectors.test.common.external.SourceSplitDataWriter;

import org.apache.pulsar.client.api.RegexSubscriptionMode;
import org.apache.pulsar.client.api.SubscriptionType;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.apache.flink.connector.pulsar.source.reader.deserializer.PulsarDeserializationSchema.pulsarSchema;
import static org.apache.pulsar.client.api.Schema.STRING;

/**
 * Pulsar external context template that will create multiple topics with only one partitions as
 * source splits.
 */
public abstract class MultipleTopicTemplateContext extends PulsarTestContext<String> {
    private static final long serialVersionUID = 7333807392445848344L;

    private int numTopics = 0;

    private final String topicPattern = "pulsar-multiple-topic-[0-9]+-" + randomAlphabetic(8);

    private final Map<String, SourceSplitDataWriter<String>> topicNameToSplitWriters =
            new HashMap<>();

    public MultipleTopicTemplateContext(PulsarTestEnvironment environment) {
        super(environment);
    }

    @Override
    public Source<String, ?, ?> createSource(Boundedness boundedness) {
        PulsarSourceBuilder<String> builder =
                PulsarSource.builder()
                        .setDeserializationSchema(pulsarSchema(STRING))
                        .setServiceUrl(serviceUrl())
                        .setAdminUrl(adminUrl())
                        .setTopicPattern(topicPattern, RegexSubscriptionMode.AllTopics)
                        .setSubscriptionType(subscriptionType())
                        .setSubscriptionName(subscriptionName());
        if (boundedness == Boundedness.BOUNDED) {
            // Using latest stop cursor for making sure the source could be stopped.
            // This is required for SourceTestSuiteBase.
            builder.setBoundedStopCursor(StopCursor.latest());
        }

        return builder.build();
    }

    @Override
    public SourceSplitDataWriter<String> createSourceSplitDataWriter() {
        String topicName = topicPattern.replace("[0-9]+", String.valueOf(numTopics));
        operator.createTopic(topicName, 1);

        String partitionName = TopicNameUtils.topicNameWithPartition(topicName, 0);
        PulsarPartitionDataWriter writer = new PulsarPartitionDataWriter(operator, partitionName);

        topicNameToSplitWriters.put(partitionName, writer);
        numTopics++;

        return writer;
    }

    @Override
    public List<String> generateTestData(int splitIndex, long seed) {
        return generateStringTestData(splitIndex, seed);
    }

    @Override
    public void close() throws Exception {
        for (SourceSplitDataWriter<String> writer : topicNameToSplitWriters.values()) {
            writer.close();
        }

        topicNameToSplitWriters.clear();
    }

    protected abstract String subscriptionName();

    protected abstract SubscriptionType subscriptionType();

    protected String serviceUrl() {
        return operator.serviceUrl();
    }

    protected String adminUrl() {
        return operator.adminUrl();
    }
}


text:
{% include "site_base.html" %}

Register Vehicle

                    View your status

                {% load crispy_forms_tags %}
                {% crispy form form.helper %}

All fields are mandatory

                {% block  javascript %}

                {% load staticfiles %}

                {{ form.media }}

                {% endblock %}


text:
define([
    '../../../util/Color',
    './KmlColorStyle',
    './../KmlElements',
    '../util/NodeTransformers'
], function (
    Color,
    KmlColorStyle,
    KmlElements,
    NodeTransformers
) {
    "use strict";

    /**
     * Constructs an KmlPolyStyle. Application usually don't call this constructor. It is called by {@link KmlFile} as
     * Objects from KmlFile are read. It is concrete implementation.
     * @alias KmlPolyStyle
     * @constructor
     * @classdesc Contains the data associated with Kml poly style
     * @param options {Object}
     * @param options.objectNode {Node} Node representing the Kml poly style.
     * @throws {ArgumentError} If either the node is null or undefined.
     * @see https://developers.google.com/kml/documentation/kmlreference#polystyle
     * @augments KmlColorStyle
     */
    var KmlPolyStyle = function (options) {
        KmlColorStyle.call(this, options);
    };

    KmlPolyStyle.prototype = Object.create(KmlColorStyle.prototype);

    Object.defineProperties(KmlPolyStyle.prototype, {
        /**
         * If true the polygon's surface will be filled with color
         * @memberof KmlPolyStyle.prototype
         * @readonly
         * @type {Boolean}
         */
        kmlFill: {
            get: function(){
                return this._factory.specific(this, {name: 'fill', transformer: NodeTransformers.boolean});
            }
        },

        /**
         * Specifies whether outline polygon. Outline style is defined by line style if present.
         * @memberof KmlPolyStyle.prototype
         * @readonly
         * @type {Boolean}
         */
        kmlOutline: {
            get: function(){
                return this._factory.specific(this, {name: 'outline', transformer: NodeTransformers.boolean});
            }
        }
    });

    KmlPolyStyle.update = function (style, options) {
        style = style || {};
        var shapeOptions = options || {};
        shapeOptions._drawInterior = style.kmlFill || true;
        shapeOptions._drawOutline = style.kmlOutline || false;
        shapeOptions._outlineColor = options._outlineColor || Color.WHITE;
        shapeOptions._interiorColor = style.kmlColor && Color.colorFromKmlHex(style.kmlColor) || Color.WHITE;
        shapeOptions._colorMode = style.kmlColorMode || 'normal'; // TODO Not yet supported.

        return shapeOptions;
    };

    /**
     * @inheritDoc
     */
    KmlPolyStyle.prototype.getTagNames = function () {
        return ['PolyStyle'];
    };

    KmlElements.addKey(KmlPolyStyle.prototype.getTagNames()[0], KmlPolyStyle);

    return KmlPolyStyle;
});


text:
<?php

namespace FacebookAds\Object;

use FacebookAds\Object\Fields\ProductFeedUploadErrorFields;
use FacebookAds\Object\Traits\CannotCreate;
use FacebookAds\Object\Traits\CannotDelete;
use FacebookAds\Object\Traits\CannotUpdate;
use FacebookAds\Cursor;

class ProductFeedUploadError extends AbstractCrudObject {
  use CannotDelete;
  use CannotCreate;
  use CannotUpdate;

  /**
   * @return string
   */
  protected function getEndpoint() {
    return 'errors';
  }

  /**
   * @return ProductFeedUploadErrorFields
   */
  public static function getFieldsEnum() {
    return ProductFeedUploadErrorFields::getInstance();
  }

  /**
   * @param array $fields
   * @param array $params
   * @return Cursor
   */
  public function getSamples(array $fields = array(), array $params = array()) {
    return $this->getManyByConnection(
      ProductFeedUploadErrorSample::className(), $fields, $params, 'samples');
  }
}


text:
<?php

namespace Magento\LayeredNavigation\Observer\Grid;

use Magento\Framework\Module\Manager;
use Magento\Framework\Event\ObserverInterface;

class ProductAttributeGridBuildObserver implements ObserverInterface
{
    /**
     * @var \Magento\Framework\Module\Manager
     */
    protected $moduleManager;

    /**
     * @param Manager $moduleManager
     */
    public function __construct(Manager $moduleManager)
    {
        $this->moduleManager = $moduleManager;
    }

    /**
     * @param \Magento\Framework\Event\Observer $observer
     * @return void
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        if (!$this->moduleManager->isOutputEnabled('Magento_LayeredNavigation')) {
            return;
        }

        /** @var \Magento\Catalog\Block\Adminhtml\Product\Attribute\Grid $grid */
        $grid = $observer->getGrid();

        $grid->addColumnAfter(
            'is_filterable',
            [
                    'header' => __('Use in Layered Navigation'),
                    'sortable' => true,
                    'index' => 'is_filterable',
                    'type' => 'options',
                    'options' => [
                        '1' => __('Filterable (with results)'),
                        '2' => __('Filterable (no results)'),
                        '0' => __('No'),
                    ],
                    'align' => 'center',
            ],
            'is_searchable'
        );
    }
}


text:
/**
 ******************************************************************************
 * Elemental Forms : a lightweight user interface framework                   *
 ******************************************************************************
 * ©2015 Ben Vanik. All rights reserved. Released under the BSD license.      *
 * Portions ©2011-2015 Emil Segerås: https://github.com/fruxo/turbobadger     *
 ******************************************************************************
 */

#ifndef TESTBED_APPLICATION_H_
#define TESTBED_APPLICATION_H_

#include "el/config.h"
#include "el/elements.h"
#include "el/elements/parts/scroller.h"

namespace testbed {

using namespace el;

class TestbedApplication;

// Called from the platform main function.
int app_main();

// Backend interface that handles platform window & creating the renderer.
class ApplicationBackend {
 public:
  static ApplicationBackend* Create(TestbedApplication* app, int width,
                                    int height, const char* title);
  virtual ~ApplicationBackend() = default;
  virtual void Run() = 0;
  virtual Element* GetRoot() = 0;
  virtual graphics::Renderer* GetRenderer() = 0;
};

// Application interface, for setting up the application using elemental.
class TestbedApplication {
 public:
  TestbedApplication() = default;
  virtual ~TestbedApplication() = default;

  Element* GetRoot() { return m_backend->GetRoot(); }

  // Runs the message loop. Does not return until exiting.
  void Run();

  bool Init();
  void ShutDown();
  void Process();
  void RenderFrame(int window_w, int window_h);

  void OnBackendAttached(ApplicationBackend* backend) { m_backend = backend; }
  void OnBackendDetached() { m_backend = nullptr; }

 private:
  ApplicationBackend* m_backend;
};

class DemoWindow : public elements::Form {
 public:
  DemoWindow();
  bool LoadResourceFile(const std::string& filename);
  void LoadResourceData(const char* data);
  void LoadResource(parsing::ParseNode& node);

  virtual bool OnEvent(const Event& ev);
};

class MainWindow : public DemoWindow, public MessageHandler {
 public:
  MainWindow();
  virtual bool OnEvent(const Event& ev);

  // Implement MessageHandler
  virtual void OnMessageReceived(Message* msg);
};

class ImageWindow : public DemoWindow {
 public:
  ImageWindow();
  virtual bool OnEvent(const Event& ev);
};

class PageWindow : public DemoWindow,
                   public el::elements::parts::ScrollerSnapListener {
 public:
  PageWindow();
  virtual bool OnEvent(const Event& ev);
  virtual void OnScrollSnap(Element* target_element, int* target_x,
                            int* target_y);
};

class AnimationsWindow : public DemoWindow {
 public:
  AnimationsWindow();
  void Animate();
  virtual bool OnEvent(const Event& ev);
};

class EditWindow : public DemoWindow {
 public:
  EditWindow();
  void OnProcessStates() override;
  bool OnEvent(const Event& ev) override;
};

class LayoutWindow : public DemoWindow {
 public:
  LayoutWindow(const std::string& filename);
  virtual bool OnEvent(const Event& ev);
};

class TabContainerWindow : public DemoWindow {
 public:
  TabContainerWindow();
  virtual bool OnEvent(const Event& ev);
};

class ConnectionWindow : public DemoWindow {
 public:
  ConnectionWindow();
  virtual bool OnEvent(const Event& ev);
};

class ScrollContainerWindow : public DemoWindow, public MessageHandler {
 public:
  ScrollContainerWindow();
  virtual bool OnEvent(const Event& ev);

  // Implement MessageHandler
  virtual void OnMessageReceived(Message* msg);
};

}  // namespace testbed

#endif  // TESTBED_APPLICATION_H_


text:
package core

import (
	"runtime"

	"github.com/apcera/logray"
	"github.com/opencontainers/runc/libcontainer"
)

func Run() error {
	logray.AddDefaultOutput("stdout://", logray.ALL)
	cs := &containerSetup{
		log:           logray.New(),
		stagerConfig:  defaultStagerConfig,
		appContainers: make(map[string]libcontainer.Container),
		appProcesses:  make(map[string]*libcontainer.Process),
		appWaitch:     make(map[string]chan struct{}),
	}

	if err := run(cs); err != nil {
		cs.log.Errorf("Startup function errored: %s", err)
		cs.log.Flush()
		return err
	}

	runtime.Goexit()
	return nil
}


text:
require 'spec_helper'

describe PS::CreditCardAccount do
  before { connect() }
  let(:customer_id) do
    PS::Customer.create(FactoryGirl.attributes_for(:customer)).ps_reference_id
  end

  describe "class methods" do
    describe "#create" do
      subject do
        PS::CreditCardAccount.create(
          FactoryGirl.attributes_for(:credit_card_account, :customer_id => customer_id)
        )
      end

      it "should create a credit card account" do
        subject.class.should == PS::CreditCardAccount
      end

    end

    context "bad save" do
      subject do
        PS::CreditCardAccount.new(
          FactoryGirl.attributes_for(:credit_card_account)
        ).save
      end

      it "should catch the exception and return false" do
        subject.should == false
      end
    end

    describe "#default_for_customer_id" do
      let(:credit_card) { FactoryGirl.create(:credit_card_account, :customer_id => customer_id) }
      before { credit_card.make_default }
      subject { PS::CreditCardAccount.default_for_customer_id(customer_id) }

      it "should get the default credit card for a customer" do
        subject.ps_reference_id.should == credit_card.ps_reference_id
      end
    end
  end

  describe "instance methods" do
    let(:credit_card) { FactoryGirl.create(:credit_card_account, :customer_id => customer_id) }

    describe ".update" do
      before do
        credit_card.c_c_expiry = "11/2016"
      end
      subject { credit_card.update }

      it "should update the credit card's attributes" do
        subject
      end
    end

    describe ".delete" do
      subject { credit_card.delete() }

      it "should delete the credit_card" do
        subject
      end
    end
  end
end


text:
<?php
declare(strict_types=1);

namespace Ytake\LaravelAspect\Annotation;

use Doctrine\Common\Annotations\Annotation;

/**
 * Class Lazy
 *
 * @Annotation
 */
class LazyQueue extends Annotation implements Delayed
{
    /** @var int  Delayed Dispatching */
    public $value = 0;

    /**
     * @return int
     */
    public function delay(): int
    {
        return $this->value;
    }
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _assign = require('lodash/object/assign');

var _assign2 = _interopRequireDefault(_assign);

var _isObject = require('lodash/lang/isObject');

var _isObject2 = _interopRequireDefault(_isObject);

var _linkClass = require('./linkClass');

var _linkClass2 = _interopRequireDefault(_linkClass);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/* eslint-disable react/prop-types */

var wrapStatelessFunction = undefined;

/**
 * @see https://facebook.github.io/react/blog/2015/09/10/react-v0.14-rc1.html#stateless-function-components
 * @param {Function} Component
 * @param {Object} defaultStyles
 * @param {Object} options
 * @returns {Function}
 */
wrapStatelessFunction = function (Component, defaultStyles, options) {
    var WrappedComponent = undefined;

    WrappedComponent = function () {
        for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
            args[_key - 1] = arguments[_key];
        }

        var props = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];

        var renderResult = undefined,
            styles = undefined,
            useProps = undefined;

        if (props.styles) {
            useProps = props;
            styles = props.styles;
        } else if ((0, _isObject2.default)(defaultStyles)) {
            useProps = (0, _assign2.default)({}, props, {
                styles: defaultStyles
            });

            styles = defaultStyles;
        } else {
            useProps = props;
            styles = {};
        }

        renderResult = Component.apply(undefined, [useProps].concat(args));

        if (renderResult) {
            return (0, _linkClass2.default)(renderResult, styles, options);
        }

        return _react2.default.createElement('noscript');
    };

    (0, _assign2.default)(WrappedComponent, Component);

    return WrappedComponent;
};

exports.default = wrapStatelessFunction;
//# sourceMappingURL=wrapStatelessFunction.js.map


text:
package org.javacs.lsp;

import java.util.List;

public class TextDocumentEdit {
    public VersionedTextDocumentIdentifier textDocument;
    public List<TextEdit> edits;
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

	<meta http-equiv="content-type" content="text/html; charset=windows-1252"/>
	<title>Bedienung</title>
	<meta name="generator" content="LibreOffice 5.0.2.2 (Windows)"/>
	<meta name="created" content="00:00:00"/>
	<meta name="changedby" content="Paul Bichler"/>
	<meta name="changed" content="2015-10-26T15:46:59.973000000"/>
	<meta name="created" content="00:00:00">
	<meta name="changedby" content="Paul Bichler">
	<meta name="changed" content="2015-10-26T15:34:43.573000000">
	<meta name="created" content="00:00:00">
	<meta name="changedby" content="Paul Bichler">
	<meta name="changed" content="2015-09-15T15:07:56.034000000">
	<meta name="created" content="00:00:00">
	<meta name="changedby" content="Paul Bichler">
	<meta name="changed" content="2015-06-26T14:48:35.919000000">
	<meta name="created" content="00:00:00">
	<meta name="changedby" content="Paul Bichler">
	<meta name="changed" content="2015-06-23T19:00:27.431000000">
	<meta name="created" content="00:00:00">
	<meta name="changedby" content="Paul Bichler">
	<meta name="changed" content="2015-06-21T20:03:19.829000000">
	<meta name="created" content="00:00:00">
	<meta name="changedby" content="Paul Bichler">
	<meta name="changed" content="2015-06-17T18:51:30.682000000">
	<meta name="CHANGEDBY" content="Paul Bichler">
	<meta name="CHANGEDBY" content="Paul Bichler">
	<meta name="CHANGEDBY" content="Paul Bichler">
	<meta name="CHANGEDBY" content="Paul Bichler">
	<meta name="CHANGEDBY" content="Paul Bichler">
	<meta name="CHANGEDBY" content="Paul Bichler">

Welcome

Base Frame makes an installer for your AutoHotkey
application! It has following features:

Make an installer.

Normal and / or portable installation

Multiple installer languages

Shows a license during installation

Can show a changelog during installation

Do updates

Update checker (optional)

Does automatic or manual checks for update and notifies
		user.

Downloads the update and starts an update.

Make your app automatically check for updates on each run


text:
package ninja.siden.okite.compiler;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.SourceVersion;

/**
 * @author taichi
 */
public abstract class BaseProcessor extends AbstractProcessor {

	@Override
	public SourceVersion getSupportedSourceVersion() {
		return SourceVersion.latest();
	}

	@Override
	public Set<String> getSupportedAnnotationTypes() {
		return new HashSet<>(Arrays.asList("*"));
	}

	protected Env env;

	@Override
	public synchronized void init(ProcessingEnvironment processingEnv) {
		super.init(processingEnv);
		this.env = new Env(processingEnv);
	}

}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>remote point editor</title>

This is the remote point editor

Connect with this to see this editor working!

    <svg id="container"></svg>


text:
__author__ = 'yinjun'

"""
Definition of ListNode
class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""
class Solution:
    """
    @param head: The first node of linked list.
    @return: The head of linked list.
    """
    def insertionSortList(self, head):
        # write your code here

        if head == None or head.next == None:
            return head

        h = ListNode(0)
        h.next = head

        p = head
        while p!=None and p.next!=None:
            n = p.next
            s = h
            moved = False
            while s!=p:
                if n.val <= s.next.val:
                    p.next = p.next.next
                    n.next = s.next
                    s.next = n
                    moved = True
                    break
                else:
                    s = s.next
            if moved == False:
                p = p.next
            #print h.next

        return h.next

__author__ = 'yinjun'

'''
ListNode for lintcode and leetcode
'''
class ListNode:

    '''
    construction without parameter, default value is 0
    @:param x integer value
    '''
    def __init__(self, x):
        self.val = x
        self.next = None

    '''
    convert ListNode into list
    '''
    def toList(self):
        v = [self.val]
        c = self.next
        while c!=None:
            v.append(c.val)
            c = c.next
        return v

    '''
    convert ListNode into string
    '''
    def __str__(self):
        return str(self.toList())

    '''
    '''
    @staticmethod
    def fromList(list):
        head = ListNode(0)
        h = head
        for v in list:
            n = ListNode(v)
            h.next = n
            h = h.next

        return head.next

    @staticmethod
    def createLists(lists):
        l = []
        c = len(lists)
        for i in range(c):
            li = list(lists[i])
            lic = len(li)
            head = ListNode(0)
            chead = head
            #print lists[i]
            for j in range(lic):
                chead.next = ListNode(li[j])
                chead = chead.next
            l.append(head.next)

        return l

    @staticmethod
    def output(n):
        b = n
        print '[',
        while b != None:
            print b.val,
            b = b.next
        print ']'

s = Solution()
print s.insertionSortList(ListNode.fromList([3,2,1]))


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui.interfazdeusuario;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import modelo.Alumno;
import modelo.ListaDeAlumnos;

/**
 *
 * @author Jorge
 */
public class VistaAdministradorDeCalificaciones extends javax.swing.JFrame {

    /**
     * Creates new form VistaAdministradorDeCalificaciones
     */
    public VistaAdministradorDeCalificaciones() {
        initComponents();
        CentradorDeVistas.getCentradorDeVistas().centrarJFrame(this);
        this.alumnosCoincidentes = ListaDeAlumnos.getListaDeAlumnos().getAlumnos();
        llenarJListConAlumnos();
        setListListener();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        campoTextoBuscar = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        botonBuscarAlumno = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        botonSalir = new javax.swing.JButton();
        botonVerCalificacionAlumno = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Calificaciones de Alumnos");

        jLabel2.setText("Buscar Alumno");

        botonBuscarAlumno.setText("Buscar");
        botonBuscarAlumno.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonBuscarAlumnoActionPerformed(evt);
            }
        });

        jScrollPane1.setViewportView(jList1);

        botonSalir.setText("Salir");
        botonSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonSalirActionPerformed(evt);
            }
        });

        botonVerCalificacionAlumno.setText("Calificaciones");
        botonVerCalificacionAlumno.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonVerCalificacionAlumnoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel2)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(campoTextoBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(botonBuscarAlumno)
                                .addGap(0, 232, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jScrollPane1)
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(botonSalir, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(botonVerCalificacionAlumno)))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(293, 293, 293)
                        .addComponent(jLabel1)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(botonVerCalificacionAlumno)
                        .addGap(18, 18, 18)
                        .addComponent(botonSalir))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(campoTextoBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)
                            .addComponent(botonBuscarAlumno))
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 405, Short.MAX_VALUE)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void botonVerCalificacionAlumnoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonVerCalificacionAlumnoActionPerformed
        // TODO add your handling code here:
        int indexEnJList = this.jList1.getSelectedIndex();
        new VistaModificarCalificaciones(alumnosCoincidentes.get(indexEnJList)).setVisible(true);
    }//GEN-LAST:event_botonVerCalificacionAlumnoActionPerformed

    private void botonSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonSalirActionPerformed
        // TODO add your handling code here:
        new VistaPrincipal().setVisible(true);
        this.dispose();
    }//GEN-LAST:event_botonSalirActionPerformed

    private void botonBuscarAlumnoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonBuscarAlumnoActionPerformed
        // TODO add your handling code here:
        String textoABuscar = this.campoTextoBuscar.getText();
        encontrarAlumnoCoincidente(textoABuscar);
    }//GEN-LAST:event_botonBuscarAlumnoActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VistaAdministradorDeCalificaciones.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VistaAdministradorDeCalificaciones.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VistaAdministradorDeCalificaciones.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VistaAdministradorDeCalificaciones.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new VistaAdministradorDeCalificaciones().setVisible(true);
            }
        });
    }

    protected Alumno getAlumnoSeleccionado(){
        return alumno;
    }

    private void llenarJListConAlumnos(){
        DefaultListModel listModel = helper.llenarJListConAlumnos(alumnosCoincidentes);
        jList1.setModel(listModel);
    }

    private void setListListener() {
        jList1.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent evt) {
                JList list = (JList) evt.getSource();
                if (evt.getClickCount() == 2) {
                    int indexEnJList = list.locationToIndex(evt.getPoint());
                    new VistaModificarAlumno(alumnosCoincidentes.get(indexEnJList)).setVisible(true);
                }
            }
        });
    }

    private void  encontrarAlumnoCoincidente(String textoABuscar){
        alumnosCoincidentes = helper.encontrarAlumnoCoincidente(textoABuscar);
        llenarJListConAlumnos();
    }

    private Alumno alumno;
    private ArrayList<Alumno> alumnosCoincidentes;
    private HelperVistaAdministradorDeCalificaciones helper = new HelperVistaAdministradorDeCalificaciones();
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botonBuscarAlumno;
    private javax.swing.JButton botonSalir;
    private javax.swing.JButton botonVerCalificacionAlumno;
    private javax.swing.JTextField campoTextoBuscar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JList jList1;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package tankapplication1;

import java.awt.Image;

/**
 *
 * @author Michael
 */
public class Entity {

    private Tank model = null;
    private Image image = null;
    private double x = 0;
    private double y = 0;
    private double height = 0;
    private double width = 0;

    /**
     * @return the model
     */
    public Tank getModel() {
        return model;
    }

    /**
     * @param model the model to set
     */
    public void setModel(Tank model) {
        this.model = model;
    }

    /**
     * @return the image
     */
    public Image getImage() {
        return image;
    }

    /**
     * @param image the image to set
     */
    public void setImage(Image image) {
        this.image = image;
    }

    /**
     * @return the x
     */
    public double getX() {
        return x;
    }

    /**
     * @param x the x to set
     */
    public void setX(double x) {
        this.x = x;
    }

    /**
     * @return the y
     */
    public double getY() {
        return y;
    }

    /**
     * @param y the y to set
     */
    public void setY(double y) {
        this.y = y;
    }

    /**
     * @return the height
     */
    public double getHeight() {
        return height;
    }

    /**
     * @param height the height to set
     */
    public void setHeight(double height) {
        this.height = height;
    }

    /**
     * @return the width
     */
    public double getWidth() {
        return width;
    }

    /**
     * @param width the width to set
     */
    public void setWidth(double width) {
        this.width = width;
    }

}


text: poetry generator hacks


text:
package eu.jokre.games.idleDungeoneer.ability;

import eu.jokre.games.idleDungeoneer.entity.EntityCharacter;

import java.time.Duration;

import static eu.jokre.games.idleDungeoneer.ability.Ability.abilityCategories.SPELL;
import static eu.jokre.games.idleDungeoneer.ability.Ability.abilityHitCategories.ABILITY_CRIT;
import static eu.jokre.games.idleDungeoneer.ability.Ability.abilityHitCategories.ABILITY_HIT;
import static eu.jokre.games.idleDungeoneer.ability.Ability.damageTypes.MAGIC;
import static eu.jokre.games.idleDungeoneer.ability.Ability.statusEffectTargets.CASTER;
import static eu.jokre.games.idleDungeoneer.ability.Ability.targetCategories.ENEMIES;

/**
 * Created by jokre on 22-May-17.
 */
public class AbilityPriestSmite extends Ability {
    public AbilityPriestSmite(EntityCharacter owner) {
        super(owner);
        this.setRange(6);
        this.setCooldown(Duration.ZERO);
        this.setCost(0);
        this.setScaleFactor(1);
        this.setDamageType(MAGIC);
        this.setAbilityCategory(SPELL);
        this.setTargetCategory(ENEMIES);
        this.setCastTime(Duration.ofSeconds(2));
        this.setName("Smite");
        this.setOnGlobalCooldown(true);
        this.setAreaOfEffectRange(0.0f);
        this.isOnGlobalCooldown = true;
    }

    @Override
    public void onCast(EntityCharacter target) {
        super.onCast(target);
    }

    @Override
    public void onHit(EntityCharacter target) {

    }

    @Override
    public void onCrit(EntityCharacter target) {
        this.owner.applyBuff(new StatusEffectBuffInstantHeal(this.owner, this.owner));
    }

    @Override
    public void onParry(EntityCharacter target) {

    }

    @Override
    public void onDodge(EntityCharacter target) {

    }

    @Override
    public void onBlock(EntityCharacter target) {

    }

    @Override
    public void onMiss(EntityCharacter target) {

    }
}


text:
using namespace Corona;

// generates single floating point random number between 0 and 1
float FLT_RAND() {
	return float(rand()) / RAND_MAX;
}

// Simple implementation of the Logger class from the API. Simply outputs all messages to the standard output.
class MyLogger : public Abstract::Logger {
public:

	MyLogger(ICore* core) : Abstract::Logger(&core->getStats()) {}

	virtual void logMsg(const Corona::LogMessage& message)
	{
#ifdef _DEBUG
		std::cout << message.text.cStr() << std::endl;
#endif
	}
	virtual void setProgress(const float progress) {
		std::cout << "Progress: " << progress << std::endl;
	}
};

// Basic settings implementation - stores all settings in a std::map. Real plugin implementation would probably
// want to utilize some system for settings management in a host 3D application for a subset of the settings (the
// ones exposed to the user)
class MySettings : public Abstract::Settings {
protected:
	std::map<int, Abstract::Settings::Property> values;
public:
	virtual Abstract::Settings::Property get(const int id) const {
		const std::map<int, Abstract::Settings::Property>::const_iterator result = values.find(id);
		if (result != values.end()) {
			return result->second;
		}
		else {
			throw Exception::propertyNotFound(PropertyDescriptor::get(id)->name);
		}
	}
	virtual void set(const int id, const Abstract::Settings::Property& property) {
		values[id] = property;
	}

};

// Callbacks for handling user actions in the wx frame buffer.
class MyVfbCallbacks : public Abstract::VfbCallbacks {
public:
	ICore* core;
	bool isWindowClosed;

	MyVfbCallbacks() {
		isWindowClosed = false;
	}
	virtual void windowClosed() {
		this->isWindowClosed = true;
		core->cancelRender();
		core->getWxVfb().renderFinished();
	}
	virtual void renderStop(const bool) {
		core->cancelRender();
		core->getWxVfb().renderFinished();
	}
	virtual void renderStart(const bool interactive) {}
	virtual void renderPause() {}
	virtual void duplicate(const int selectedChannelId) {}
	virtual void save(const int selectedChannelId) {}

	virtual wxMenuBar* buildMenu() {
		return NULL;
	}
	virtual void menuCommand(const int menuId, const bool checked) {}
	virtual void sidebarActivated(const bool activated) {}
	virtual void sidebarTabChanged(const WxVfbTab tab) {}
	virtual void textEditFocus() {}
	virtual void textEditDefocus() {}
	virtual void colorMappingChanged(const ColorMappingData& newValues) {}
	virtual void saveAll() {}
	virtual void canvasSizeChanged(const Pixel newSize) {}
	virtual bool zoomingEnabled() {
		return true;
	}
};

// A sample texture, that just maps the world position to a red-blue grid
class MyCheckerMap : public Abstract::Map {
public:
	virtual Rgb evalColor(const IShadeContext& context, TextureCache* cache, float& outAlpha) {
		const Pos pos = context.getPosition() *2.f;
		const int tmp = int(floor(pos.x())) + int(floor(pos.y())) + int(floor(pos.z()));
		outAlpha = 1.f;
		if (tmp % 2) {
			return Rgb::RED;
		}
		else {
			return Rgb::BLUE;
		}
	}

	virtual float evalMono(const IShadeContext& context, TextureCache* cache, float& outAlpha) {
		return evalColor(context, cache, outAlpha).grayValue();
	}

	virtual Dir evalBump(const IShadeContext&, TextureCache*) {
		STOP; //currently not supported
	}

	virtual void renderTo(Bitmap<Rgb>& output) {
		STOP; //currently not supported
	}
	virtual void getChildren(Stack<Resource*>& output) { }
};

// advanced example - custom light shader
class MyLight : public Abstract::LightShader, public Noncopyable {
public:

	const Pos LIGHT_POS;
	const Dir LIGHT_DIR;

	MyLight() : LIGHT_POS(Pos(-3, -3, -7)), LIGHT_DIR(Dir(1, 1, -1.f).getNormalized()) { }

	// simulate spot light with colorful directional falloff
	virtual BsdfComponents getIllumination(IShadeContext& context, Spectrum& transport) const {
		const Pos surface = context.getPosition();
		float distance;
		const Dir toLight = (LIGHT_POS - surface).getNormalized(distance); // direction + distance to light

		const float cosAngle = Utils::max(0.f, -dot(toLight, LIGHT_DIR));
		// calculate the light emission: divide by d^2 to get physical attenuation
		const Spectrum emitted = 50 * cosAngle* Spectrum::max(Spectrum::BLACK, Spectrum(cosAngle * 2 - 1, 1 - 2 * abs(cosAngle - 0.5f), (1 - cosAngle) * 2 - 1)) / (distance*distance);

		// shadow transmission, including occlusion effects
		transport = context.shadowTransmission(LIGHT_POS, RAY_NORMAL);
		float dummy;

		// bsdf value: amount of light incident from light reflected to camera/previous point
		BsdfComponents brdf;
		context.forwardBsdfCos(toLight, brdf, dummy);

		return brdf * (PI*emitted);
	}
};


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=fn.walk_fn_ret_ty.html">

Redirecting to fn.walk_fn_ret_ty.html...


text:
package com.example.handlingexception.misc;

import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.stereotype.Component;

@Component("helper")
public class Helper {

	private final AtomicInteger counter = new AtomicInteger();

	public boolean helperMethod() throws Exception {
		if (counter.getAndIncrement() % 2 == 1) {
			throw new Exception();
		}
		return true;
	}
}


text:
require 'guard/compat/test/helper'

require_relative 'shared_examples'

require 'guard/chef/inspectors/focused_inspector'

klass = Guard::Chef::Inspectors::FocusedInspector

RSpec.describe klass do
  include_examples 'inspector', klass

  # Use real paths because BaseInspector#_clean will be used to clean them
  let(:other_paths) do
    [
      'spec/guard/chef/inspectors/simple_inspector_spec.rb',
      'spec/guard/chef/runner_spec.rb'
    ]
  end

  let(:other_failed_locations) do
    %w(./spec/guard/chef/deprecator_spec.rb:446)
  end

  it "remembers failed paths and returns them until they all pass" do
    allow(File).to receive(:directory?)
      .with("spec/guard/chef/inspectors/base_inspector_spec.rb")
      .and_return(false)

    allow(File).to receive(:directory?)
      .with("spec/guard/chef/inspectors/simple_inspector_spec.rb")
      .and_return(false)

    allow(File).to receive(:directory?)
      .with("spec/guard/chef/runner_spec.rb").and_return(false)

    allow(File).to receive(:directory?)
      .with("spec/guard/chef/deprecator_spec.rb").and_return(false)

    allow(Dir).to receive(:[]).with("spec/**{,/*/**}/*[_.]spec.rb")
      .and_return(paths + other_paths)

    allow(Dir).to receive(:[]).with("myspec/**{,/*/**}/*[_.]spec.rb")
      .and_return([])

    allow(Dir).to receive(:[]).with("myspec/**{,/*/**}/*.feature")
      .and_return([])

    allow(Dir).to receive(:[]).with("spec/**{,/*/**}/*.feature")
      .and_return([])

    expect(inspector.paths(paths)).to match_array(paths)
    inspector.failed(failed_locations)

    # Return failed_locations until they pass
    3.times do
      expect(inspector.paths(other_paths)).to match_array(failed_locations)
      inspector.failed(other_failed_locations)

      expect(inspector.paths(paths)).to match_array(failed_locations)
      inspector.failed(other_failed_locations)

      expect(inspector.paths([])).to match_array(failed_locations)
      inspector.failed(failed_locations)
    end

    # Now all pass
    expect(inspector.paths(paths)).to match_array(failed_locations)
    inspector.failed([])

    # And some fails again
    expect(inspector.paths(other_paths)).to match_array(other_paths)
    inspector.failed(other_failed_locations)

    # Return other_failed_locations until they pass
    3.times do
      expect(inspector.paths(other_paths))
        .to match_array(other_failed_locations)

      inspector.failed(other_failed_locations)

      expect(inspector.paths(paths)).to match_array(other_failed_locations)
      inspector.failed(other_failed_locations)

      expect(inspector.paths([])).to match_array(other_failed_locations)
      inspector.failed(failed_locations)
    end

    # Now all pass
    expect(inspector.paths(paths)).to match_array(other_failed_locations)
    inspector.failed([])

    expect(inspector.paths(paths)).to match_array(paths)
    inspector.failed([])

    expect(inspector.paths(other_paths)).to match_array(other_paths)
    inspector.failed([])

    expect(inspector.paths([])).to eq([])
  end

  describe "#reload" do
    it "force to forget about focused locations" do
      allow(File).to receive(:directory?)
        .with("spec/guard/chef/inspectors/base_inspector_spec.rb")
        .and_return(false)

      allow(File).to receive(:directory?)
        .with("spec/guard/chef/runner_spec.rb")
        .and_return(false)

      allow(File).to receive(:directory?)
        .with("spec/guard/chef/deprecator_spec.rb")
        .and_return(false)

      allow(Dir).to receive(:[]).with("spec/**{,/*/**}/*[_.]spec.rb")
        .and_return(paths + other_paths)

      allow(Dir).to receive(:[]).with("myspec/**{,/*/**}/*[_.]spec.rb")
        .and_return([])

      allow(Dir).to receive(:[]).with("myspec/**{,/*/**}/*.feature")
        .and_return([])

      allow(Dir).to receive(:[]).with("spec/**{,/*/**}/*.feature")
        .and_return([])

      allow(File).to receive(:directory?)
        .with("spec/guard/chef/inspectors/simple_inspector_spec.rb")
        .and_return(false)

      expect(inspector.paths(paths)).to match_array(paths)
      inspector.failed(failed_locations)

      inspector.reload
      expect(inspector.paths(other_paths)).to match_array(other_paths)
    end
  end
end


text:
using MacroGit;
using MacroGuards;
using Verbot.Commits;

namespace Verbot.Refs
{
    class TheMasterBranchInfo : MasterBranchInfo
    {

        protected TheMasterBranchInfo(RefContext refContext, CommitContext commitContext, GitRef @ref)
            : base(refContext, commitContext, @ref)
        {
        }

        public new static TheMasterBranchInfo TryCreate(RefContext refContext, CommitContext commitContext, GitRef @ref)
        {
            Guard.NotNull(@ref, nameof(@ref));
            if (!@ref.IsBranch) return null;
            if (@ref.Name != "master") return null;
            return new TheMasterBranchInfo(refContext, commitContext, @ref);
        }

    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NLog;

using DotaBird.Core.Steam;
using DotaBird.Core.Net;

namespace DotaBird.Apps
{
    public class Program : BaseApp
    {
        private readonly Logger logger = LogManager.GetCurrentClassLogger();

        protected override string AppName
        {
            get { return "DotaBirdPollingApp"; }
        }

        public static void Main(string[] args)
        {
            new Program().Run();
        }

        public static bool testMode = true;

        private readonly IMatchPoller poller;

        public Program()
        {
            var webClient = new WebClient();
            var api = new DotaWebApi(webClient);
            poller = new MatchPoller(api);
        }

        public void Run() {

            //// With real data, let's up this to say... 30 minutes and see how many matches come through.
            //// Try to get some idea of the amount of data we're dealing with.

            //var count = CountMatches(poller, TimeSpan.FromMinutes(30), myList);          // 540 matches found -- hmmm? seems low.
            var count = CountMatches(TimeSpan.FromMinutes(30));        // 502 matches found
            logger.Info("{0} matches counted.", count);

            //if (testMode)
            //    TestOverlapping(myList);

            Console.WriteLine("Done, press enter.");
            Console.ReadLine();
        }

        private long CountMatches(TimeSpan span)
        {
            var start = DateTime.Now;
            var matches = poller.PollMatches().GetEnumerator();
            var count = 0L;

            while (matches.MoveNext() && ((DateTime.Now - start) < span))
            {
                count++;
                var match = matches.Current;

                logger.Info("Match: {0} @ {1}", match.Id, match.StartTime);
            }

            return count;
        }

        private static void TestOverlapping(List<string> myList)
        {
            string[] lines = myList.ToArray();
            int length = lines.Length;
            int numRepeats = 0;

            for (int i = 0; i < length; i++)
            {
                for (int j = i; j < length - 1; j++)
                {
                    if (lines[i] == lines[j] && i != j)
                    {
                        numRepeats++;
                        break;
                    }

                }
            }

            Console.WriteLine("Number of repeats counted: {0}", numRepeats);
        }
    }
}


text:
package org.elasticsearch.indices.mapping;

import com.google.common.collect.Maps;
import org.elasticsearch.action.admin.indices.mapping.get.GetFieldMappingsResponse;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.test.ElasticsearchIntegrationTest;
import org.hamcrest.Matchers;
import org.junit.Test;

import java.io.IOException;
import java.util.Arrays;
import java.util.Map;

import static org.elasticsearch.cluster.metadata.IndexMetaData.*;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertBlocked;
import static org.hamcrest.Matchers.*;

/**
 *
 */
public class SimpleGetFieldMappingsTests extends ElasticsearchIntegrationTest {

    @Test
    public void getMappingsWhereThereAreNone() {
        createIndex("index");
        ensureYellow();
        GetFieldMappingsResponse response = client().admin().indices().prepareGetFieldMappings().get();
        assertThat(response.mappings().size(), equalTo(1));
        assertThat(response.mappings().get("index").size(), equalTo(0));

        assertThat(response.fieldMappings("index", "type", "field"), Matchers.nullValue());
    }

    private XContentBuilder getMappingForType(String type) throws IOException {
        return jsonBuilder().startObject().startObject(type).startObject("properties")
                .startObject("field1").field("type", "string").endObject()
                .startObject("obj").startObject("properties").startObject("subfield").field("type", "string").field("index", "not_analyzed").endObject().endObject().endObject()
                .endObject().endObject().endObject();
    }

    @Test
    public void simpleGetFieldMappings() throws Exception {

        assertAcked(prepareCreate("indexa")
                .addMapping("typeA", getMappingForType("typeA"))
                .addMapping("typeB", getMappingForType("typeB")));
        assertAcked(client().admin().indices().prepareCreate("indexb")
                .addMapping("typeA", getMappingForType("typeA"))
                .addMapping("typeB", getMappingForType("typeB")));

        ensureYellow();

        // Get mappings by full name
        GetFieldMappingsResponse response = client().admin().indices().prepareGetFieldMappings("indexa").setTypes("typeA").setFields("field1", "obj.subfield").get();
        assertThat(response.fieldMappings("indexa", "typeA", "field1").fullName(), equalTo("field1"));
        assertThat(response.fieldMappings("indexa", "typeA", "field1").sourceAsMap(), hasKey("field1"));
        assertThat(response.fieldMappings("indexa", "typeA", "obj.subfield").fullName(), equalTo("obj.subfield"));
        assertThat(response.fieldMappings("indexa", "typeA", "obj.subfield").sourceAsMap(), hasKey("subfield"));
        assertThat(response.mappings().get("indexa"), not(hasKey("typeB")));
        assertThat(response.fieldMappings("indexa", "typeB", "field1"), nullValue());
        assertThat(response.mappings(), not(hasKey("indexb")));
        assertThat(response.fieldMappings("indexb", "typeB", "field1"), nullValue());

        // Get mappings by name
        response = client().admin().indices().prepareGetFieldMappings("indexa").setTypes("typeA").setFields("field1", "subfield").get();
        assertThat(response.fieldMappings("indexa", "typeA", "field1").fullName(), equalTo("field1"));
        assertThat(response.fieldMappings("indexa", "typeA", "field1").sourceAsMap(), hasKey("field1"));
        assertThat(response.fieldMappings("indexa", "typeA", "subfield").fullName(), equalTo("obj.subfield"));
        assertThat(response.fieldMappings("indexa", "typeA", "subfield").sourceAsMap(), hasKey("subfield"));
        assertThat(response.fieldMappings("indexa", "typeB", "field1"), nullValue());
        assertThat(response.fieldMappings("indexb", "typeB", "field1"), nullValue());

        // get mappings by name across multiple indices
        response = client().admin().indices().prepareGetFieldMappings().setTypes("typeA").setFields("subfield").get();
        assertThat(response.fieldMappings("indexa", "typeA", "subfield").fullName(), equalTo("obj.subfield"));
        assertThat(response.fieldMappings("indexa", "typeA", "subfield").sourceAsMap(), hasKey("subfield"));
        assertThat(response.fieldMappings("indexa", "typeB", "subfield"), nullValue());
        assertThat(response.fieldMappings("indexb", "typeA", "subfield").fullName(), equalTo("obj.subfield"));
        assertThat(response.fieldMappings("indexb", "typeA", "subfield").sourceAsMap(), hasKey("subfield"));
        assertThat(response.fieldMappings("indexb", "typeB", "subfield"), nullValue());

        // get mappings by name across multiple types
        response = client().admin().indices().prepareGetFieldMappings("indexa").setFields("subfield").get();
        assertThat(response.fieldMappings("indexa", "typeA", "subfield").fullName(), equalTo("obj.subfield"));
        assertThat(response.fieldMappings("indexa", "typeA", "subfield").sourceAsMap(), hasKey("subfield"));
        assertThat(response.fieldMappings("indexa", "typeA", "field1"), nullValue());
        assertThat(response.fieldMappings("indexa", "typeB", "subfield").fullName(), equalTo("obj.subfield"));
        assertThat(response.fieldMappings("indexa", "typeB", "subfield").sourceAsMap(), hasKey("subfield"));
        assertThat(response.fieldMappings("indexa", "typeB", "field1"), nullValue());
        assertThat(response.fieldMappings("indexb", "typeA", "subfield"), nullValue());
        assertThat(response.fieldMappings("indexb", "typeA", "field1"), nullValue());
        assertThat(response.fieldMappings("indexb", "typeB", "subfield"), nullValue());
        assertThat(response.fieldMappings("indexb", "typeB", "field1"), nullValue());

        // get mappings by name across multiple types & indices
        response = client().admin().indices().prepareGetFieldMappings().setFields("subfield").get();
        assertThat(response.fieldMappings("indexa", "typeA", "subfield").fullName(), equalTo("obj.subfield"));
        assertThat(response.fieldMappings("indexa", "typeA", "subfield").sourceAsMap(), hasKey("subfield"));
        assertThat(response.fieldMappings("indexa", "typeA", "field1"), nullValue());
        assertThat(response.fieldMappings("indexa", "typeB", "subfield").fullName(), equalTo("obj.subfield"));
        assertThat(response.fieldMappings("indexa", "typeB", "subfield").sourceAsMap(), hasKey("subfield"));
        assertThat(response.fieldMappings("indexa", "typeB", "field1"), nullValue());
        assertThat(response.fieldMappings("indexb", "typeA", "subfield").fullName(), equalTo("obj.subfield"));
        assertThat(response.fieldMappings("indexb", "typeA", "subfield").sourceAsMap(), hasKey("subfield"));
        assertThat(response.fieldMappings("indexb", "typeB", "field1"), nullValue());
        assertThat(response.fieldMappings("indexb", "typeB", "subfield").fullName(), equalTo("obj.subfield"));
        assertThat(response.fieldMappings("indexb", "typeB", "subfield").sourceAsMap(), hasKey("subfield"));
        assertThat(response.fieldMappings("indexb", "typeB", "field1"), nullValue());

    }

    @SuppressWarnings("unchecked")
    @Test
    public void simpleGetFieldMappingsWithDefaults() throws Exception {
        assertAcked(prepareCreate("test").addMapping("type", getMappingForType("type")));

        client().prepareIndex("test", "type", "1").setSource("num", 1).get();
        ensureYellow();
        waitForConcreteMappingsOnAll("test", "type", "num"); // for num, we need to wait...

        GetFieldMappingsResponse response = client().admin().indices().prepareGetFieldMappings().setFields("num", "field1", "subfield").includeDefaults(true).get();

        assertThat((Map<String, Object>) response.fieldMappings("test", "type", "num").sourceAsMap().get("num"), hasEntry("index", (Object) "not_analyzed"));
        assertThat((Map<String, Object>) response.fieldMappings("test", "type", "num").sourceAsMap().get("num"), hasEntry("type", (Object) "long"));
        assertThat((Map<String, Object>) response.fieldMappings("test", "type", "field1").sourceAsMap().get("field1"), hasEntry("index", (Object) "analyzed"));
        assertThat((Map<String, Object>) response.fieldMappings("test", "type", "field1").sourceAsMap().get("field1"), hasEntry("type", (Object) "string"));
        assertThat((Map<String, Object>) response.fieldMappings("test", "type", "subfield").sourceAsMap().get("subfield"), hasEntry("index", (Object) "not_analyzed"));
        assertThat((Map<String, Object>) response.fieldMappings("test", "type", "subfield").sourceAsMap().get("subfield"), hasEntry("type", (Object) "string"));

    }

    //fix #6552
    @Test
    public void simpleGetFieldMappingsWithPretty() throws Exception {
        assertAcked(prepareCreate("index").addMapping("type", getMappingForType("type")));
        Map<String, String> params = Maps.newHashMap();
        params.put("pretty", "true");
        ensureYellow();
        GetFieldMappingsResponse response = client().admin().indices().prepareGetFieldMappings("index").setTypes("type").setFields("field1", "obj.subfield").get();
        XContentBuilder responseBuilder = XContentFactory.jsonBuilder().prettyPrint();
        responseBuilder.startObject();
        response.toXContent(responseBuilder, new ToXContent.MapParams(params));
        responseBuilder.endObject();
        String responseStrings = responseBuilder.string();

        XContentBuilder prettyJsonBuilder = XContentFactory.jsonBuilder().prettyPrint();
        prettyJsonBuilder.copyCurrentStructure(XContentFactory.xContent(responseStrings).createParser(responseStrings));
        assertThat(responseStrings, equalTo(prettyJsonBuilder.string()));

        params.put("pretty", "false");

        response = client().admin().indices().prepareGetFieldMappings("index").setTypes("type").setFields("field1", "obj.subfield").get();
        responseBuilder = XContentFactory.jsonBuilder().prettyPrint().lfAtEnd();
        responseBuilder.startObject();
        response.toXContent(responseBuilder, new ToXContent.MapParams(params));
        responseBuilder.endObject();
        responseStrings = responseBuilder.string();

        prettyJsonBuilder = XContentFactory.jsonBuilder().prettyPrint();
        prettyJsonBuilder.copyCurrentStructure(XContentFactory.xContent(responseStrings).createParser(responseStrings));
        assertThat(responseStrings, not(equalTo(prettyJsonBuilder.string())));

    }

    @Test
    public void testGetFieldMappingsWithBlocks() throws Exception {
        assertAcked(prepareCreate("test")
                .addMapping("typeA", getMappingForType("typeA"))
                .addMapping("typeB", getMappingForType("typeB")));
        ensureYellow();

        for (String block : Arrays.asList(SETTING_BLOCKS_READ, SETTING_BLOCKS_WRITE, SETTING_READ_ONLY)) {
            try {
                enableIndexBlock("test", block);
                GetFieldMappingsResponse response = client().admin().indices().prepareGetFieldMappings("test").setTypes("typeA").setFields("field1", "obj.subfield").get();
                assertThat(response.fieldMappings("test", "typeA", "field1").fullName(), equalTo("field1"));
            } finally {
                disableIndexBlock("test", block);
            }
        }

        try {
            enableIndexBlock("test", SETTING_BLOCKS_METADATA);
            assertBlocked(client().admin().indices().prepareGetMappings(), INDEX_METADATA_BLOCK);
        } finally {
            disableIndexBlock("test", SETTING_BLOCKS_METADATA);
        }
    }
}