text:
goog.provide('ol.test.interaction.Draw');

goog.require('ol.array');
goog.require('ol.events');
goog.require('ol.Feature');
goog.require('ol.Map');
goog.require('ol.MapBrowserPointerEvent');
goog.require('ol.View');
goog.require('ol.geom.Circle');
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.Draw');
goog.require('ol.interaction.Interaction');
goog.require('ol.layer.Vector');
goog.require('ol.pointer.PointerEvent');
goog.require('ol.source.Vector');

describe('ol.interaction.Draw', function() {
  var target, map, source;

  var width = 360;
  var height = 180;

  beforeEach(function(done) {
    target = document.createElement('div');
    var style = target.style;
    style.position = 'absolute';
    style.left = '-1000px';
    style.top = '-1000px';
    style.width = width + 'px';
    style.height = height + 'px';
    document.body.appendChild(target);
    source = new ol.source.Vector();
    var layer = new ol.layer.Vector({source: source});
    map = new ol.Map({
      target: target,
      layers: [layer],
      view: new ol.View({
        projection: 'EPSG:4326',
        center: [0, 0],
        resolution: 1
      })
    });
    map.once('postrender', function() {
      done();
    });
  });

  afterEach(function() {
    map.dispose();
    document.body.removeChild(target);
  });

  /**
   * Simulates a browser event on the map viewport.  The client x/y location
   * will be adjusted as if the map were centered at 0,0.
   * @param {string} type Event type.
   * @param {number} x Horizontal offset from map center.
   * @param {number} y Vertical offset from map center.
   * @param {boolean=} opt_shiftKey Shift key is pressed.
   */
  function simulateEvent(type, x, y, opt_shiftKey) {
    var viewport = map.getViewport();
    // calculated in case body has top < 0 (test runner with small window)
    var position = viewport.getBoundingClientRect();
    var shiftKey = opt_shiftKey !== undefined ? opt_shiftKey : false;
    var event = new ol.pointer.PointerEvent(type, {
      clientX: position.left + x + width / 2,
      clientY: position.top + y + height / 2,
      shiftKey: shiftKey
    });
    map.handleMapBrowserEvent(new ol.MapBrowserPointerEvent(type, map, event));
  }

  describe('constructor', function() {

    it('creates a new interaction', function() {
      var draw = new ol.interaction.Draw({
        source: source,
        type: 'Point'
      });
      expect(draw).to.be.a(ol.interaction.Draw);
      expect(draw).to.be.a(ol.interaction.Interaction);
    });

    it('accepts a freehand option', function() {
      var draw = new ol.interaction.Draw({
        source: source,
        type: 'LineString',
        freehand: true
      });

      var event = new ol.pointer.PointerEvent('pointerdown', {
        clientX: 0,
        clientY: 0,
        shiftKey: false
      });

      expect(draw.freehandCondition_(event)).to.be(true);
    });

  });

  describe('specifying a geometryName', function() {

    beforeEach(function() {
      var draw = new ol.interaction.Draw({
        source: source,
        geometryName: 'the_geom',
        type: 'Point'
      });
      map.addInteraction(draw);
    });

    it('creates a feature with the correct geometryName', function() {
      simulateEvent('pointermove', 10, 20);
      simulateEvent('pointerdown', 10, 20);
      simulateEvent('pointerup', 10, 20);
      var features = source.getFeatures();
      var geometry = features[0].getGeometry();
      expect(features[0].getGeometryName()).to.equal('the_geom');
      expect(geometry).to.be.a(ol.geom.Point);
    });
  });

  describe('specifying a clickTolerance', function() {
    beforeEach(function() {
      var draw = new ol.interaction.Draw({
        source: source,
        type: 'Point',
        clickTolerance: 6
      });
      map.addInteraction(draw);
    });

    it('adds a point when below the tolerance', function() {
      var features;

      simulateEvent('pointermove', 10, 20);
      simulateEvent('pointerdown', 10, 20);
      simulateEvent('pointerup', 15, 25);
      features = source.getFeatures();
      expect(features).to.length(0);

      simulateEvent('pointermove', 10, 20);
      simulateEvent('pointerdown', 10, 20);
      simulateEvent('pointerup', 14, 24);
      features = source.getFeatures();
      expect(features).to.length(1);
    });
  });

  describe('drawing points', function() {
    var draw;

    beforeEach(function() {
      draw = new ol.interaction.Draw({
        source: source,
        type: 'Point'
      });
      map.addInteraction(draw);
    });

    it('draws a point on click', function() {
      simulateEvent('pointermove', 10, 20);
      simulateEvent('pointerdown', 10, 20);
      simulateEvent('pointerup', 10, 20);
      var features = source.getFeatures();
      expect(features).to.have.length(1);
      var geometry = features[0].getGeometry();
      expect(geometry).to.be.a(ol.geom.Point);
      expect(geometry.getCoordinates()).to.eql([10, -20]);
    });

    it('does not draw a point with a significant drag', function() {
      simulateEvent('pointermove', 10, 20);
      simulateEvent('pointerdown', 10, 20);
      simulateEvent('pointermove', 18, 20);
      simulateEvent('pointerup', 18, 20);
      var features = source.getFeatures();
      expect(features).to.have.length(0);
    });

    it('does not draw a point when modifier key is pressed', function() {
      simulateEvent('pointermove', 10, 20);
      simulateEvent('pointerdown', 10, 20, true);
      simulateEvent('pointerup', 10, 20);
      var features = source.getFeatures();
      expect(features).to.have.length(0);
    });

    it('triggers draw events', function() {
      var ds = sinon.spy();
      var de = sinon.spy();
      ol.events.listen(draw, 'drawstart', ds);
      ol.events.listen(draw, 'drawend', de);
      simulateEvent('pointermove', 10, 20);
      simulateEvent('pointerdown', 10, 20);
      simulateEvent('pointerup', 10, 20);
      expect(ds).to.be.called();
      expect(de).to.be.called();
      simulateEvent('pointermove', 20, 20);
      expect(ds.callCount).to.be(1);
      expect(de.callCount).to.be(1);
    });

    it('triggers drawend event before inserting the feature', function() {
      var receivedEvents = {
        end: 0,
        addfeature: 0
      };
      ol.events.listen(draw, 'drawend',
          function() {
            expect(receivedEvents.end).to.be(0);
            expect(receivedEvents.addfeature).to.be(0);
            ++receivedEvents.end;
          });
      source.on('addfeature', function() {
        expect(receivedEvents.end).to.be(1);
        expect(receivedEvents.addfeature).to.be(0);
        receivedEvents.addfeature++;
      });
      simulateEvent('pointermove', 10, 20);
      simulateEvent('pointerdown', 10, 20);
      simulateEvent('pointerup', 10, 20);
      simulateEvent('pointermove', 20, 20);
      expect(receivedEvents.end).to.be(1);
      expect(receivedEvents.addfeature).to.be(1);
    });
  });

  describe('drawing multipoints', function() {

    beforeEach(function() {
      map.addInteraction(new ol.interaction.Draw({
        source: source,
        type: 'MultiPoint'
      }));
    });

    it('draws multipoint on click', function() {
      simulateEvent('pointermove', 30, 15);
      simulateEvent('pointerdown', 30, 15);
      simulateEvent('pointerup', 30, 15);
      var features = source.getFeatures();
      expect(features).to.have.length(1);
      var geometry = features[0].getGeometry();
      expect(geometry).to.be.a(ol.geom.MultiPoint);
      expect(geometry.getCoordinates()).to.eql([[30, -15]]);
    });

  });

  describe('drawing linestrings', function() {
    var draw;

    beforeEach(function() {
      draw = new ol.interaction.Draw({
        source: source,
        type: 'LineString'
      });
      map.addInteraction(draw);
    });

    it('draws linestring with clicks, finishing on last point', function() {
      // first point
      simulateEvent('pointermove', 10, 20);
      simulateEvent('pointerdown', 10, 20);
      simulateEvent('pointerup', 10, 20);

      // second point
      simulateEvent('pointermove', 30, 20);
      simulateEvent('pointerdown', 30, 20);
      simulateEvent('pointerup', 30, 20);

      // finish on second point
      simulateEvent('pointerdown', 30, 20);
      simulateEvent('pointerup', 30, 20);

      var features = source.getFeatures();
      expect(features).to.have.length(1);
      var geometry = features[0].getGeometry();
      expect(geometry).to.be.a(ol.geom.LineString);
      expect(geometry.getCoordinates()).to.eql([[10, -20], [30, -20]]);
    });

    it('supports freehand drawing for linestrings', function() {
      // freehand sequence
      simulateEvent('pointermove', 10, 20);
      simulateEvent('pointerdown', 10, 20, true);
      simulateEvent('pointermove', 20, 30, true);
      simulateEvent('pointerdrag', 20, 30, true);
      simulateEvent('pointermove', 20, 40, true);
      simulateEvent('pointerdrag', 20, 40, true);
      simulateEvent('pointerup', 20, 40, true);

      var features = source.getFeatures();
      expect(features).to.have.length(1);
      var geometry = features[0].getGeometry();
      expect(geometry).to.be.a(ol.geom.LineString);
      expect(geometry.getCoordinates()).to.eql(
          [[10, -20], [20, -30], [20, -40]]);
    });

    it('allows freehand mode for part of the drawing', function() {

      // non-freehand
      simulateEvent('pointerdown', 10, 20);
      simulateEvent('pointerup', 10, 20);
      simulateEvent('pointermove', 20, 30);

      // freehand
      simulateEvent('pointerdown', 20, 30, true);
      simulateEvent('pointermove', 20, 30, true);
      simulateEvent('pointerdrag', 20, 30, true);
      simulateEvent('pointermove', 30, 40, true);
      simulateEvent('pointerdrag', 30, 40, true);
      simulateEvent('pointermove', 40, 50, true);
      simulateEvent('pointerdrag', 40, 50, true);

      // non-freehand
      simulateEvent('pointerup', 40, 50);
      simulateEvent('pointermove', 50, 60);
      simulateEvent('pointerdown', 50, 60);
      simulateEvent('pointerup', 50, 60);
      simulateEvent('pointermove', 60, 70);
      simulateEvent('pointerdown', 60, 70);
      simulateEvent('pointerup', 60, 70);

      // finish
      simulateEvent('pointerdown', 60, 70);
      simulateEvent('pointerup', 60, 70);

      var features = source.getFeatures();
      // expect(features).to.have.length(1);
      var geometry = features[0].getGeometry();
      expect(geometry).to.be.a(ol.geom.LineString);
      expect(geometry.getCoordinates()).to.eql(
          [[10, -20], [20, -30], [30, -40], [40, -50], [50, -60], [60, -70]]);
    });

    it('does not add a point with a significant drag', function() {
      // first point
      simulateEvent('pointermove', 10, 20);
      simulateEvent('pointerdown', 10, 20);
      simulateEvent('pointerup', 10, 20);

      // drag map
      simulateEvent('pointermove', 15, 20);
      simulateEvent('pointerdown', 15, 20);
      simulateEvent('pointermove', 23, 20);
      simulateEvent('pointerup', 23, 20);

      // second point
      simulateEvent('pointermove', 30, 20);
      simulateEvent('pointerdown', 30, 20);
      simulateEvent('pointerup', 30, 20);

      // finish on second point
      simulateEvent('pointerdown', 30, 20);
      simulateEvent('pointerup', 30, 20);

      var features = source.getFeatures();
      expect(features).to.have.length(1);
      var geometry = features[0].getGeometry();
      expect(geometry).to.be.a(ol.geom.LineString);
      expect(geometry.getCoordinates()).to.eql([[10, -20], [30, -20]]);
    });

    it('triggers draw events', function() {
      var ds = sinon.spy();
      var de = sinon.spy();
      ol.events.listen(draw, 'drawstart', ds);
      ol.events.listen(draw, 'drawend', de);

      // first point
      simulateEvent('pointermove', 10, 20);
      simulateEvent('pointerdown', 10, 20);
      simulateEvent('pointerup', 10, 20);

      // second point
      simulateEvent('pointermove', 30, 20);
      simulateEvent('pointerdown', 30, 20);
      simulateEvent('pointerup', 30, 20);

      // finish on second point
      simulateEvent('pointerdown', 30, 20);
      simulateEvent('pointerup', 30, 20);
      simulateEvent('pointermove', 10, 20);

      expect(ds).to.be.called();
      expect(ds.callCount).to.be(1);
      expect(de).to.be.called();
      expect(de.callCount).to.be(1);
    });

  });

  describe('drawing with a finishCondition', function() {
    beforeEach(function() {
      var draw = new ol.interaction.Draw({
        source: source,
        type: 'LineString',
        finishCondition: function(event) {
          if (ol.array.equals(event.coordinate,[30,-20])) {
            return true;
          }
          return false;
        }
      });
      map.addInteraction(draw);
    });

    it('draws a linestring failing to finish it first, the finishes it', function() {
      var features;

      // first point
      simulateEvent('pointermove', 10, 20);
      simulateEvent('pointerdown', 10, 20);
      simulateEvent('pointerup', 10, 20);

      // second point
      simulateEvent('pointermove', 40, 30);
      simulateEvent('pointerdown', 40, 30);
      simulateEvent('pointerup', 40, 30);

      // try to finish on this point
      simulateEvent('pointerdown', 40, 30);
      simulateEvent('pointerup', 40, 30);

      features = source.getFeatures();
      expect(features).to.have.length(0);

      // third point
      simulateEvent('pointermove', 30, 20);
      simulateEvent('pointerdown', 30, 20);
      simulateEvent('pointerup', 30, 20);

      //  finish on this point
      simulateEvent('pointerdown', 30, 20);
      simulateEvent('pointerup', 30, 20);

      features = source.getFeatures();
      expect(features).to.have.length(1);
    });
  });

  describe('drawing multi-linestrings', function() {

    beforeEach(function() {
      map.addInteraction(new ol.interaction.Draw({
        source: source,
        type: 'MultiLineString'
      }));
    });

    it('draws multi with clicks, finishing on last point', function() {
      // first point
      simulateEvent('pointermove', 10, 20);
      simulateEvent('pointerdown', 10, 20);
      simulateEvent('pointerup', 10, 20);

      // second point
      simulateEvent('pointermove', 30, 20);
      simulateEvent('pointerdown', 30, 20);
      simulateEvent('pointerup', 30, 20);

      // finish on second point
      simulateEvent('pointerdown', 30, 20);
      simulateEvent('pointerup', 30, 20);

      var features = source.getFeatures();
      expect(features).to.have.length(1);
      var geometry = features[0].getGeometry();
      expect(geometry).to.be.a(ol.geom.MultiLineString);
      expect(geometry.getCoordinates()).to.eql([[[10, -20], [30, -20]]]);
    });

  });

  describe('drawing polygons', function() {
    var draw;

    beforeEach(function() {
      draw = new ol.interaction.Draw({
        source: source,
        type: 'Polygon'
      });
      map.addInteraction(draw);
    });

    it('draws polygon with clicks, finishing on first point', function() {
      // first point
      simulateEvent('pointermove', 10, 20);
      simulateEvent('pointerdown', 10, 20);
      simulateEvent('pointerup', 10, 20);

      // second point
      simulateEvent('pointermove', 30, 20);
      simulateEvent('pointerdown', 30, 20);
      simulateEvent('pointerup', 30, 20);

      // third point
      simulateEvent('pointermove', 40, 10);
      simulateEvent('pointerdown', 40, 10);
      simulateEvent('pointerup', 40, 10);

      // finish on first point
      simulateEvent('pointermove', 10, 20);
      simulateEvent('pointerdown', 10, 20);
      simulateEvent('pointerup', 10, 20);

      var features = source.getFeatures();
      expect(features).to.have.length(1);
      var geometry = features[0].getGeometry();
      expect(geometry).to.be.a(ol.geom.Polygon);

      expect(geometry.getCoordinates()).to.eql([
        [[10, -20], [30, -20], [40, -10], [10, -20]]
      ]);
    });

    it('draws polygon with clicks, finishing on last point', function() {
      // first point
      simulateEvent('pointermove', 10, 20);
      simulateEvent('pointerdown', 10, 20);
      simulateEvent('pointerup', 10, 20);

      // second point
      simulateEvent('pointermove', 30, 20);
      simulateEvent('pointerdown', 30, 20);
      simulateEvent('pointerup', 30, 20);

      // third point
      simulateEvent('pointermove', 40, 10);
      simulateEvent('pointerdown', 40, 10);
      simulateEvent('pointerup', 40, 10);

      // finish on last point
      simulateEvent('pointerdown', 40, 10);
      simulateEvent('pointerup', 40, 10);

      var features = source.getFeatures();
      expect(features).to.have.length(1);
      var geometry = features[0].getGeometry();
      expect(geometry).to.be.a(ol.geom.Polygon);

      expect(geometry.getCoordinates()).to.eql([
        [[10, -20], [30, -20], [40, -10], [10, -20]]
      ]);
    });

    it('supports freehand drawing for polygons', function() {
      // freehand sequence
      simulateEvent('pointermove', 10, 20);
      simulateEvent('pointerdown', 10, 20, true);
      simulateEvent('pointermove', 30, 20, true);
      simulateEvent('pointerdrag', 30, 20, true);
      simulateEvent('pointermove', 40, 10, true);
      simulateEvent('pointerdrag', 40, 10, true);
      simulateEvent('pointerup', 40, 10, true);

      // finish on last point
      simulateEvent('pointerdown', 40, 10);
      simulateEvent('pointerup', 40, 10);

      var features = source.getFeatures();
      expect(features).to.have.length(1);
      var geometry = features[0].getGeometry();
      expect(geometry).to.be.a(ol.geom.Polygon);

      expect(geometry.getCoordinates()).to.eql([
        [[10, -20], [30, -20], [40, -10], [10, -20]]
      ]);
    });

    it('triggers draw events', function() {
      var ds = sinon.spy();
      var de = sinon.spy();
      ol.events.listen(draw, 'drawstart', ds);
      ol.events.listen(draw, 'drawend', de);

      // first point
      simulateEvent('pointermove', 10, 20);
      simulateEvent('pointerdown', 10, 20);
      simulateEvent('pointerup', 10, 20);

      // second point
      simulateEvent('pointermove', 30, 20);
      simulateEvent('pointerdown', 30, 20);
      simulateEvent('pointerup', 30, 20);

      // third point
      simulateEvent('pointermove', 30, 10);
      simulateEvent('pointerdown', 30, 10);
      simulateEvent('pointerup', 30, 10);

      // finish on first point
      simulateEvent('pointermove', 10, 20);
      simulateEvent('pointerdown', 10, 20);
      simulateEvent('pointerup', 10, 20);

      expect(ds).to.be.called();
      expect(ds.callCount).to.be(1);
      expect(de).to.be.called();
      expect(de.callCount).to.be(1);
    });

  });

  describe('drawing multi-polygons', function() {

    beforeEach(function() {
      map.addInteraction(new ol.interaction.Draw({
        source: source,
        type: 'MultiPolygon'
      }));
    });

    it('draws multi with clicks, finishing on first point', function() {
      // first point
      simulateEvent('pointermove', 10, 20);
      simulateEvent('pointerdown', 10, 20);
      simulateEvent('pointerup', 10, 20);

      // second point
      simulateEvent('pointermove', 30, 20);
      simulateEvent('pointerdown', 30, 20);
      simulateEvent('pointerup', 30, 20);

      // third point
      simulateEvent('pointermove', 40, 10);
      simulateEvent('pointerdown', 40, 10);
      simulateEvent('pointerup', 40, 10);

      // finish on first point
      simulateEvent('pointermove', 10, 20);
      simulateEvent('pointerdown', 10, 20);
      simulateEvent('pointerup', 10, 20);

      var features = source.getFeatures();
      expect(features).to.have.length(1);
      var geometry = features[0].getGeometry();
      expect(geometry).to.be.a(ol.geom.MultiPolygon);
      var coordinates = geometry.getCoordinates();
      expect(coordinates).to.have.length(1);

      expect(coordinates[0]).to.eql([
        [[10, -20], [30, -20], [40, -10], [10, -20]]
      ]);
    });

    it('draws multi with clicks, finishing on last point', function() {
      // first point
      simulateEvent('pointermove', 10, 20);
      simulateEvent('pointerdown', 10, 20);
      simulateEvent('pointerup', 10, 20);

      // second point
      simulateEvent('pointermove', 30, 20);
      simulateEvent('pointerdown', 30, 20);
      simulateEvent('pointerup', 30, 20);

      // third point
      simulateEvent('pointermove', 40, 10);
      simulateEvent('pointerdown', 40, 10);
      simulateEvent('pointerup', 40, 10);

      // finish on last point
      simulateEvent('pointerdown', 40, 10);
      simulateEvent('pointerup', 40, 10);

      var features = source.getFeatures();
      expect(features).to.have.length(1);
      var geometry = features[0].getGeometry();
      expect(geometry).to.be.a(ol.geom.MultiPolygon);
      var coordinates = geometry.getCoordinates();
      expect(coordinates).to.have.length(1);

      expect(coordinates[0]).to.eql([
        [[10, -20], [30, -20], [40, -10], [10, -20]]
      ]);
    });

  });

  describe('drawing circles', function() {
    var draw;

    beforeEach(function() {
      draw = new ol.interaction.Draw({
        source: source,
        type: 'Circle'
      });
      map.addInteraction(draw);
    });

    it('draws circle with clicks, finishing on second point', function() {
      // first point
      simulateEvent('pointermove', 10, 20);
      simulateEvent('pointerdown', 10, 20);
      simulateEvent('pointerup', 10, 20);

      // finish on second point
      simulateEvent('pointermove', 30, 20);
      simulateEvent('pointerdown', 30, 20);
      simulateEvent('pointerup', 30, 20);

      var features = source.getFeatures();
      expect(features).to.have.length(1);
      var geometry = features[0].getGeometry();
      expect(geometry).to.be.a(ol.geom.Circle);
      expect(geometry.getCenter()).to.eql([10, -20]);
      expect(geometry.getRadius()).to.eql(20);
    });

    it('triggers draw events', function() {
      var ds = sinon.spy();
      var de = sinon.spy();
      ol.events.listen(draw, 'drawstart', ds);
      ol.events.listen(draw, 'drawend', de);

      // first point
      simulateEvent('pointermove', 10, 20);
      simulateEvent('pointerdown', 10, 20);
      simulateEvent('pointerup', 10, 20);

      // finish on second point
      simulateEvent('pointermove', 30, 20);
      simulateEvent('pointerdown', 30, 20);
      simulateEvent('pointerup', 30, 20);

      expect(ds).to.be.called();
      expect(ds.callCount).to.be(1);
      expect(de).to.be.called();
      expect(de.callCount).to.be(1);
    });

  });

  describe('#setActive()', function() {
    var interaction;

    beforeEach(function() {
      interaction = new ol.interaction.Draw({
        type: 'LineString'
      });

      expect(interaction.getActive()).to.be(true);

      map.addInteraction(interaction);

      // first point
      simulateEvent('pointermove', 10, 20);
      simulateEvent('pointerdown', 10, 20);
      simulateEvent('pointerup', 10, 20);

      expect(interaction.sketchFeature_).not.to.be(null);
    });

    afterEach(function() {
      map.removeInteraction(interaction);
    });

    describe('#setActive(false)', function() {
      it('unsets the map from the feature overlay', function() {
        var spy = sinon.spy(interaction.overlay_, 'setMap');
        interaction.setActive(false);
        expect(spy.getCall(0).args[0]).to.be(null);
      });
      it('aborts the drawing', function() {
        interaction.setActive(false);
        expect(interaction.sketchFeature_).to.be(null);
      });
      it('fires change:active', function() {
        var spy = sinon.spy(interaction.overlay_, 'setMap');
        var listenerSpy = sinon.spy(function() {
          // test that the interaction's change:active listener is called first
          expect(spy.getCall(0).args[0]).to.be(null);
        });
        interaction.on('change:active', listenerSpy);
        interaction.setActive(false);
        expect(listenerSpy.callCount).to.be(1);
      });
    });

    describe('#setActive(true)', function() {
      beforeEach(function() {
        interaction.setActive(false);
      });
      it('sets the map into the feature overlay', function() {
        var spy = sinon.spy(interaction.overlay_, 'setMap');
        interaction.setActive(true);
        expect(spy.getCall(0).args[0]).to.be(map);
      });
      it('fires change:active', function() {
        var spy = sinon.spy(interaction.overlay_, 'setMap');
        var listenerSpy = sinon.spy(function() {
          // test that the interaction's change:active listener is called first
          expect(spy.getCall(0).args[0]).to.be(map);
        });
        interaction.on('change:active', listenerSpy);
        interaction.setActive(true);
        expect(listenerSpy.callCount).to.be(1);
      });
    });

  });

  describe('#setMap()', function() {
    var interaction;

    beforeEach(function() {
      interaction = new ol.interaction.Draw({
        type: 'LineString'
      });
      expect(interaction.getActive()).to.be(true);
    });

    describe('#setMap(null)', function() {
      beforeEach(function() {
        map.addInteraction(interaction);
        // first point
        simulateEvent('pointermove', 10, 20);
        simulateEvent('pointerdown', 10, 20);
        simulateEvent('pointerup', 10, 20);
        expect(interaction.sketchFeature_).not.to.be(null);
      });
      afterEach(function() {
        map.removeInteraction(interaction);
      });
      describe('#setMap(null) when interaction is active', function() {
        it('unsets the map from the feature overlay', function() {
          var spy = sinon.spy(interaction.overlay_, 'setMap');
          interaction.setMap(null);
          expect(spy.getCall(0).args[0]).to.be(null);
        });
        it('aborts the drawing', function() {
          interaction.setMap(null);
          expect(interaction.sketchFeature_).to.be(null);
        });
      });
    });

    describe('#setMap(map)', function() {
      describe('#setMap(map) when interaction is active', function() {
        it('sets the map into the feature overlay', function() {
          var spy = sinon.spy(interaction.overlay_, 'setMap');
          interaction.setMap(map);
          expect(spy.getCall(0).args[0]).to.be(map);
        });
      });
      describe('#setMap(map) when interaction is not active', function() {
        it('does not set the map into the feature overlay', function() {
          interaction.setActive(false);
          var spy = sinon.spy(interaction.overlay_, 'setMap');
          interaction.setMap(map);
          expect(spy.getCall(0).args[0]).to.be(null);
        });
      });

    });
  });

  describe('ol.interaction.Draw.createRegularPolygon', function() {
    it('creates a regular polygon in Circle mode', function() {
      var draw = new ol.interaction.Draw({
        source: source,
        type: 'Circle',
        geometryFunction:
            ol.interaction.Draw.createRegularPolygon(4, Math.PI / 4)
      });
      map.addInteraction(draw);

      // first point
      simulateEvent('pointermove', 0, 0);
      simulateEvent('pointerdown', 0, 0);
      simulateEvent('pointerup', 0, 0);

      // finish on second point
      simulateEvent('pointermove', 20, 20);
      simulateEvent('pointerdown', 20, 20);
      simulateEvent('pointerup', 20, 20);

      var features = source.getFeatures();
      var geometry = features[0].getGeometry();
      expect(geometry).to.be.a(ol.geom.Polygon);
      var coordinates = geometry.getCoordinates();
      expect(coordinates[0].length).to.eql(5);
      expect(coordinates[0][0][0]).to.roughlyEqual(20, 1e-9);
      expect(coordinates[0][0][1]).to.roughlyEqual(20, 1e-9);
    });
  });

  describe('ol.interaction.Draw.createBox', function() {
    it('creates a box-shaped polygon in Circle mode', function() {
      var draw = new ol.interaction.Draw({
        source: source,
        type: 'Circle',
        geometryFunction: ol.interaction.Draw.createBox()
      });
      map.addInteraction(draw);

      // first point
      simulateEvent('pointermove', 0, 0);
      simulateEvent('pointerdown', 0, 0);
      simulateEvent('pointerup', 0, 0);

      // finish on second point
      simulateEvent('pointermove', 20, 20);
      simulateEvent('pointerdown', 20, 20);
      simulateEvent('pointerup', 20, 20);

      var features = source.getFeatures();
      var geometry = features[0].getGeometry();
      expect(geometry).to.be.a(ol.geom.Polygon);
      var coordinates = geometry.getCoordinates();
      expect(coordinates[0]).to.have.length(5);
      expect(geometry.getArea()).to.equal(400);
      expect(geometry.getExtent()).to.eql([0, -20, 20, 0]);
    });
  });

  describe('extend an existing feature', function() {
    var draw;
    var feature;

    beforeEach(function() {
      draw = new ol.interaction.Draw({
        source: source,
        type: 'LineString'
      });
      map.addInteraction(draw);
      feature = new ol.Feature(
          new ol.geom.LineString([[0, 0], [1, 1], [2, 0]]));
    });

    it('sets the initial state', function() {
      draw.extend(feature);
      expect(draw.sketchCoords_).to.have.length(4);
      expect(draw.sketchCoords_).to.eql([[0, 0], [1, 1], [2, 0], [2, 0]]);
      expect(draw.finishCoordinate_).to.eql([2, 0]);
    });

    it('dispatches a drawstart event', function() {
      var spy = sinon.spy();
      ol.events.listen(draw, 'drawstart', spy);
      draw.extend(feature);
      expect(spy.callCount).to.be(1);
    });

  });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ptrprograms.streetview" >

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="com.ptrprograms.streetview.permission.MAPS_RECEIVE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".activities.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="@string/maps_api_key" />
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

    </application>

</manifest>

redpajama_set_name: RedPajamaGithub


text:
"""
Michael duPont - michael@mdupont.com
FindMe - Primary facial recognition and location function
"""

import numpy as np
from findme.imageutil import crop, preprocess
from findme.models import find_faces#, get_model

# MODEL = get_model()

# def target_in_img(img: np.ndarray) -> (bool, np.array([int])):
#     """Returns whether the target is in a given image and where"""
#     for bbox in find_faces(img):
#         face = preprocess(crop(img, *bbox))
#         if MODEL.predict(np.array([face])) == 1:
#             return True, bbox
#     return False, None


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.contoso.app.trident</groupId>
	<artifactId>eventhub-blobwriter</artifactId>
	<packaging>jar</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>eventhub-blobwriter</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.storm</groupId>
			<artifactId>storm-core</artifactId>
			<version>0.9.1-incubating</version>
			<!-- keep storm out of the jar-with-dependencies -->
			<scope>${storm.scope}</scope>
		</dependency>
		<dependency>
			<groupId>com.google.guava</groupId>
			<artifactId>guava</artifactId>
			<version>13.0.1</version>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.2</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.7.7</version>
			<!-- keep out of the jar-with-dependencies -->
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>com.microsoft.eventhubs</groupId>
			<artifactId>eventhubs-storm-spout</artifactId>
			<version>0.9</version>
		</dependency>
		<dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
			<version>2.3</version>
		</dependency>
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
			<version>2.6.2</version>
		</dependency>

		<dependency>
			<groupId>com.microsoft.azure</groupId>
			<artifactId>azure-storage</artifactId>
			<version>1.3.1</version>
		</dependency>

		<dependency>
			<groupId>com.microsoft.azure</groupId>
			<artifactId>azure-management</artifactId>
			<version>0.6.0</version>
		</dependency>
		<dependency>
			<groupId>com.microsoft.azure</groupId>
			<artifactId>azure-management</artifactId>
			<version>0.6.0</version>
		</dependency>
		<dependency>
			<groupId>com.microsoft.azure</groupId>
			<artifactId>azure-management-compute</artifactId>
			<version>0.6.0</version>
		</dependency>
		<dependency>
			<groupId>com.microsoft.azure</groupId>
			<artifactId>azure-management-network</artifactId>
			<version>0.6.0</version>
		</dependency>
		<dependency>
			<groupId>com.microsoft.azure</groupId>
			<artifactId>azure-management-sql</artifactId>
			<version>0.6.0</version>
		</dependency>
		<dependency>
			<groupId>com.microsoft.azure</groupId>
			<artifactId>azure-management-storage</artifactId>
			<version>0.6.0</version>
		</dependency>
		<dependency>
			<groupId>com.microsoft.azure</groupId>
			<artifactId>azure-management-websites</artifactId>
			<version>0.6.0</version>
		</dependency>
		<dependency>
			<groupId>com.microsoft.azure</groupId>
			<artifactId>azure-media</artifactId>
			<version>0.6.0</version>
		</dependency>
		<dependency>
			<groupId>com.microsoft.azure</groupId>
			<artifactId>azure-servicebus</artifactId>
			<version>0.6.0</version>
		</dependency>
		<dependency>
			<groupId>com.microsoft.azure</groupId>
			<artifactId>azure-serviceruntime</artifactId>
			<version>0.6.0</version>
		</dependency>
		<dependency>
			<groupId>com.microsoft.windowsazure.storage</groupId>
			<artifactId>microsoft-windowsazure-storage-sdk</artifactId>
			<version>0.6.0</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.2</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-shade-plugin</artifactId>
				<version>2.3</version>
				<configuration>
					<createDependencyReducedPom>true</createDependencyReducedPom>
					<transformers>
						<transformer
							implementation="org.apache.maven.plugins.shade.resource.ApacheLicenseResourceTransformer">
						</transformer>
					</transformers>
				</configuration>
				<executions>
					<execution>
						<phase>package</phase>
						<goals>
							<goal>shade</goal>
						</goals>
						<configuration>
							<transformers>
								<transformer
									implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
								<transformer
									implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
									<mainClass></mainClass>
								</transformer>
							</transformers>
						</configuration>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>exec-maven-plugin</artifactId>
				<version>1.2.1</version>
				<executions>
					<execution>
						<goals>
							<goal>exec</goal>
						</goals>
					</execution>
				</executions>
				<configuration>
					<executable>java</executable>
					<includeProjectDependencies>true</includeProjectDependencies>
					<includePluginDependencies>false</includePluginDependencies>
					<classpathScope>compile</classpathScope>
					<mainClass>${storm.topology}</mainClass>
				</configuration>
			</plugin>
		</plugins>
		<resources>
			<resource>
				<directory>${basedir}/conf</directory>
				<filtering>false</filtering>
				<includes>
					<include>Config.properties</include>
				</includes>
			</resource>
		</resources>
	</build>
</project>


text:
package utilities;

import java.sql.Date;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import model.Book;
//TODO EVERYTHING OF BOOKING
public class BookingDAO {

	/*
	 * We are going to use a CRUD to access the Objects at the Database
	 */
	public BookingDAO() {

	}

	/**
	 * This method adds the Booking object passed as parameter of the database.
	 * @see JDBCHelper
	 * @param book
	 */
	public void addBooking(Book book) {
		JDBCHelper jdbc = new JDBCHelper();
		ArrayList<Object> param = new ArrayList<Object>();
		//param.add(new Date());
		//param.add(book.getBookingId());

		param.add(book.getFlightIds());
		param.add(book.getNumberOfSeats());
		param.add(book.getAccountId());
		param.add(book.getUserId());
		param.add(book.getTotalCost());

		try {
			// Insert in Booking table
			ResultSet rs1 = jdbc.insertDB(
					"INSERT INTO mmoraesg.booking (date_of_booking, flight_ids, number_of_seats, account_id, user_id, total_cost) VALUES (NOW(), ?, ?, ?, ?, ?);",
					param);

			int bookingId = getBookingId(param);

			ArrayList<Object> param_bf = new ArrayList<Object>();
			param_bf.add(bookingId);
			param_bf.add(book.getFlightIds());

			ResultSet rs2 = jdbc.insertDB("INSERT INTO mmoraesg.booking_flight (booking_id, flight_id) VALUES (?, ?)", param_bf);

			jdbc.conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * This method gets the booking id of the order.
	 * @see JDBCHelper
	 * @param param
	 */
	public int getBookingId(ArrayList<Object> param) throws SQLException {

		JDBCHelper jdbc = new JDBCHelper();

		ResultSet rs1 = jdbc
				.queryDB(
						"SELECT id FROM mmoraesg.booking WHERE  "
						+ "flight_ids = ? AND number_of_seats = ? AND account_id = ? AND  user_id = ? AND total_cost = ?;",
						param);

		List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
		ResultSetMetaData metaData = rs1.getMetaData();

		while (rs1.next()) {
		    Map<String, Object> columns = new LinkedHashMap<String, Object>();

		    for (int i = 1; i <= metaData.getColumnCount(); i++) {
		        columns.put(metaData.getColumnLabel(i), rs1.getObject(i));
		    }

		    rows.add(columns);
		}

		try {
			if (rows.size() != 0) {
				int returnBook;
				returnBook = ((int) rows.get(0).get("id"));

				return returnBook;
			}
			jdbc.conn.close();

		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}
}


text:
function u = dahlquist1sln(t)
%DAHLQUIST100SLN Exact solution of dahlquist100 problem with u0=1.
u = exp(-1*t);
end


text:
/**
 */
package org.liquibase.xml.ns.dbchangelog;

import org.eclipse.emf.common.util.EList;

import org.eclipse.emf.ecore.EObject;

/**
 *
 * A representation of the model object 'Execute Command Type'.
 *
 *
 *

 * The following features are supported:
 *

 *
{@link org.liquibase.xml.ns.dbchangelog.ExecuteCommandType#getArg Arg}

 *
{@link org.liquibase.xml.ns.dbchangelog.ExecuteCommandType#getExecutable Executable}

 *
{@link org.liquibase.xml.ns.dbchangelog.ExecuteCommandType#getOs Os}

 *

 *

 *
 * @see org.liquibase.xml.ns.dbchangelog.DbchangelogPackage#getExecuteCommandType()
 * @model extendedMetaData="name='executeCommand_._type' kind='elementOnly'"
 * @generated
 */
public interface ExecuteCommandType extends EObject {
	/**
	 * Returns the value of the 'Arg' containment reference list.
	 * The list contents are of type {@link org.liquibase.xml.ns.dbchangelog.ArgType}.
	 *
	 *

	 * If the meaning of the 'Arg' containment reference list isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Arg' containment reference list.
	 * @see org.liquibase.xml.ns.dbchangelog.DbchangelogPackage#getExecuteCommandType_Arg()
	 * @model containment="true"
	 *        extendedMetaData="kind='element' name='arg' namespace='##targetNamespace'"
	 * @generated
	 */
	EList<ArgType> getArg();

	/**
	 * Returns the value of the 'Executable' attribute.
	 *
	 *

	 * If the meaning of the 'Executable' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Executable' attribute.
	 * @see #setExecutable(String)
	 * @see org.liquibase.xml.ns.dbchangelog.DbchangelogPackage#getExecuteCommandType_Executable()
	 * @model dataType="org.eclipse.emf.ecore.xml.type.String" required="true"
	 *        extendedMetaData="kind='attribute' name='executable'"
	 * @generated
	 */
	String getExecutable();

	/**
	 * Sets the value of the '{@link org.liquibase.xml.ns.dbchangelog.ExecuteCommandType#getExecutable Executable}' attribute.
	 *
	 *
	 * @param value the new value of the 'Executable' attribute.
	 * @see #getExecutable()
	 * @generated
	 */
	void setExecutable(String value);

	/**
	 * Returns the value of the 'Os' attribute.
	 *
	 *

	 * If the meaning of the 'Os' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Os' attribute.
	 * @see #setOs(String)
	 * @see org.liquibase.xml.ns.dbchangelog.DbchangelogPackage#getExecuteCommandType_Os()
	 * @model dataType="org.eclipse.emf.ecore.xml.type.String"
	 *        extendedMetaData="kind='attribute' name='os'"
	 * @generated
	 */
	String getOs();

	/**
	 * Sets the value of the '{@link org.liquibase.xml.ns.dbchangelog.ExecuteCommandType#getOs Os}' attribute.
	 *
	 *
	 * @param value the new value of the 'Os' attribute.
	 * @see #getOs()
	 * @generated
	 */
	void setOs(String value);

} // ExecuteCommandType


text:
package main

import (
	"github.com/koding/kite"
	"fmt"
	"github.com/nsabine/microservices/square/squarelib"
)

func main() {
	k := kite.New("square", "1.0.0")
	k.Config.Port = 6001
	k.Config.DisableAuthentication = true
	k.HandleFunc("square", square)
	k.Run()
}

func square(r *kite.Request) (interface{}, error) {
	// Unmarshal method arguments.
	var params squarelib.SquareRequest
	if err := r.Args.One().Unmarshal(&params); err != nil {
		return nil, err
	}

	result := params.Number * params.Number

	fmt.Printf("Call received from '%s', sending result '%.0d' back\n", params.Name, result)

	// Print a log on remote Kite.
	// This message will be printed on client's console.
	r.Client.Go("kite.log", fmt.Sprintf("Message from %s: \"You have requested square of %.0d\"", r.LocalKite.Kite().Name, params.Number))

	// You can return anything as result, as long as it is JSON marshalable.
	return result, nil
}


text:
package org.apache.hadoop.hdfs.tools.offlineImageViewer;

import com.google.common.base.Preconditions;
import org.apache.hadoop.hdfs.server.namenode.FsImageProto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * The PBImageCorruptionDetector detects corruptions in the image.
 * It produces a file with the found issues similar to the Delimited
 * processor. The default delimiter is tab, as this is an unlikely value
 * to be included in an inode path. The delimiter value can be changed
 * via the constructor.
 *
 * It looks for the following kinds of corruptions:
 *  - an INode id is mentioned in the INodeDirectorySection, but not present
 *    in the INodeSection (corrupt INode case)
 *  - an INode has children, but at least one of them is corrupted
 *    (missing children case)
 * If multiple layers of directory structure are damaged then it is possible
 * that an INode is corrupted and also having corrupted children.
 *
 * Note that the OIV DetectCorruption processor check is not exhaustive,
 * and only catches the corruptions like above. This processor may be up to
 * extension in the future when new aspects of corruption are found.
 */
public class PBImageCorruptionDetector extends PBImageTextWriter {
  private static final Logger LOG =
      LoggerFactory.getLogger(PBImageCorruptionDetector.class);

  /**
   * Builder object for producing entries (lines) for
   * PBImageCorruptionDetector. The isSnapshot field is mandatory.
   */
  static class OutputEntryBuilder {
    private static final String MISSING = "Missing";

    private PBImageCorruptionDetector corrDetector;
    private PBImageCorruption corruption;
    private boolean isSnapshot;
    private String parentPath;
    private long parentId;
    private String name;
    private String nodeType;

    OutputEntryBuilder(PBImageCorruptionDetector corrDetector,
        boolean isSnapshot) {
      this.corrDetector = corrDetector;
      this.isSnapshot = isSnapshot;
      this.parentId = -1;
      this.parentPath = "";
      this.name = "";
      this.nodeType = "";
    }

    OutputEntryBuilder setCorruption(PBImageCorruption corr) {
      this.corruption = corr;
      return this;
    }

    OutputEntryBuilder setParentPath(String path) {
      this.parentPath = path;
      return this;
    }

    OutputEntryBuilder setParentId(long id) {
      this.parentId = id;
      return this;
    }

    OutputEntryBuilder setName(String n) {
      this.name = n;
      return this;
    }

    OutputEntryBuilder setNodeType(String nType) {
      this.nodeType = nType;
      return this;
    }

    public String build() {
      StringBuffer buffer = new StringBuffer();
      buffer.append(corruption.getType());
      corrDetector.append(buffer, corruption.getId());
      corrDetector.append(buffer, String.valueOf(isSnapshot));
      corrDetector.append(buffer, parentPath);
      if (parentId == -1) {
        corrDetector.append(buffer, MISSING);
      } else {
        corrDetector.append(buffer, parentId);
      }
      corrDetector.append(buffer, name);
      corrDetector.append(buffer, nodeType);
      corrDetector.append(buffer, corruption.getNumOfCorruptChildren());
      return buffer.toString();
    }
  }

  private static class CorruptionChecker {
    private static final String NODE_TYPE = "Node";
    private static final String REF_TYPE = "Ref";
    private static final String UNKNOWN_TYPE = "Unknown";

    /** Contains all existing INode IDs. */
    private Set<Long> nodeIds;
    /** Contains all existing INodeReference IDs. */
    private Set<Long> nodeRefIds;

    CorruptionChecker() {
      nodeIds = new HashSet<>();
    }

    /**
     * Collect a INode Id.
     */
    void saveNodeId(long id) {
      Preconditions.checkState(nodeIds != null && !nodeIds.contains(id));
      nodeIds.add(id);
    }

    /**
     * Returns whether the given INode id was saved previously.
     */
    boolean isNodeIdExist(long id) {
      return nodeIds.contains(id);
    }

    /**
     * Returns whether the given INodeReference id was saved previously.
     */
    boolean isNodeRefIdExist(long id) {
      return nodeRefIds.contains(id);
    }

    /**
     * Saves the INodeReference ids.
     */
    void saveNodeRefIds(List<Long> nodeRefIdList) {
      nodeRefIds = new HashSet<>(nodeRefIdList);
    }

    String getTypeOfId(long id) {
      if (isNodeIdExist(id)) {
        return NODE_TYPE;
      } else if (isNodeRefIdExist(id)) {
        return REF_TYPE;
      } else {
        return UNKNOWN_TYPE;
      }
    }
  }

  /** Delimiter string used while producing output. */
  private final CorruptionChecker corrChecker;
  /** Id to corruption mapping. */
  private final Map<Long, PBImageCorruption> corruptionsMap;

  PBImageCorruptionDetector(PrintStream out, String delimiter,
        String tempPath) throws IOException {
    super(out, delimiter, tempPath);
    corrChecker = new CorruptionChecker();
    corruptionsMap = new TreeMap<Long, PBImageCorruption>();
  }

  @Override
  public String getHeader() {
    StringBuffer buffer = new StringBuffer();
    buffer.append("CorruptionType");
    append(buffer, "Id");
    append(buffer, "IsSnapshot");
    append(buffer, "ParentPath");
    append(buffer, "ParentId");
    append(buffer, "Name");
    append(buffer, "NodeType");
    append(buffer, "CorruptChildren");
    return buffer.toString();
  }

  @Override
  public String getEntry(String parentPath,
      FsImageProto.INodeSection.INode inode) {
    long id = inode.getId();
    if (corruptionsMap.containsKey(id)) {
      OutputEntryBuilder entryBuilder =
          new OutputEntryBuilder(this, false);
      long parentId = -1;
      try {
        parentId = getParentId(id);
      } catch (IOException ignore) {
      }
      entryBuilder.setCorruption(corruptionsMap.get(id))
          .setParentPath(parentPath)
          .setName(inode.getName().toStringUtf8())
          .setNodeType(corrChecker.getTypeOfId(id));
      if (parentId != -1) {
        entryBuilder.setParentId(parentId);
      }
      corruptionsMap.remove(id);
      return entryBuilder.build();
    } else {
      return "";
    }
  }

  @Override
  protected void checkNode(FsImageProto.INodeSection.INode p,
        AtomicInteger numDirs) throws IOException {
    super.checkNode(p, numDirs);
    corrChecker.saveNodeId(p.getId());
  }

  private void addCorruptedNode(long childId) {
    if (!corruptionsMap.containsKey(childId)) {
      PBImageCorruption c = new PBImageCorruption(childId, false, true, 0);
      corruptionsMap.put(childId, c);
    } else {
      PBImageCorruption c = corruptionsMap.get(childId);
      c.addCorruptNodeCorruption();
      corruptionsMap.put(childId, c);
    }
  }

  private void addCorruptedParent(long id, int numOfCorruption) {
    if (!corruptionsMap.containsKey(id)) {
      PBImageCorruption c = new PBImageCorruption(id, true, false,
          numOfCorruption);
      corruptionsMap.put(id, c);
    } else {
      PBImageCorruption c = corruptionsMap.get(id);
      c.addMissingChildCorruption();
      c.setNumberOfCorruption(numOfCorruption);
      corruptionsMap.put(id, c);
    }
  }

  /**
   * Scan the INodeDirectory section to construct the namespace.
   */
  @Override
  protected void buildNamespace(InputStream in, List<Long> refIdList)
      throws IOException {
    corrChecker.saveNodeRefIds(refIdList);
    LOG.debug("Saved INodeReference ids of size {}.", refIdList.size());
    int count = 0;
    while (true) {
      FsImageProto.INodeDirectorySection.DirEntry e =
          FsImageProto.INodeDirectorySection.DirEntry.parseDelimitedFrom(in);
      if (e == null) {
        break;
      }
      count++;
      if (LOG.isDebugEnabled() && count % 10000 == 0) {
        LOG.debug("Scanned {} directories.", count);
      }
      long parentId = e.getParent();
      if (!corrChecker.isNodeIdExist(parentId)) {
        LOG.debug("Corruption detected! Parent node is not contained " +
            "in the list of known ids!");
        addCorruptedNode(parentId);
      }
      int numOfCorruption = 0;
      for (int i = 0; i < e.getChildrenCount(); i++) {
        long childId = e.getChildren(i);
        putDirChildToMetadataMap(parentId, childId);
        if (!corrChecker.isNodeIdExist(childId)) {
          addCorruptedNode(childId);
          numOfCorruption++;
        }
      }
      if (numOfCorruption > 0) {
        if (LOG.isDebugEnabled()) {
          LOG.debug("{} corruption detected! Child nodes are missing.",
              numOfCorruption);
        }
        addCorruptedParent(parentId, numOfCorruption);
      }
      for (int i = e.getChildrenCount();
           i < e.getChildrenCount() + e.getRefChildrenCount(); i++) {
        int refId = e.getRefChildren(i - e.getChildrenCount());
        // In this case the refNode is referred directly (by its position),
        // so we couldn't make sure of the correctness
        putDirChildToMetadataMap(parentId, refIdList.get(refId));
      }
    }
    LOG.info("Scanned {} INode directories to build namespace.", count);
  }

  @Override
  public void afterOutput() throws IOException {
    if (!corruptionsMap.isEmpty()) {
      // Also write out corruptions when the path could be not be decided
      LOG.info("Outputting {} more corrupted nodes.", corruptionsMap.size());
      for (PBImageCorruption c : corruptionsMap.values()) {
        long id = c.getId();
        String name = "";
        long parentId = -1;
        try {
          name = getNodeName(id);
        } catch (IgnoreSnapshotException ignored) {
        }
        try {
          parentId = getParentId(id);
        } catch (IgnoreSnapshotException ignored) {
        }
        OutputEntryBuilder entryBuilder =
            new OutputEntryBuilder(this, true);
        entryBuilder.setCorruption(corruptionsMap.get(id))
            .setName(name)
            .setNodeType(corrChecker.getTypeOfId(id));
        if (parentId != -1) {
          entryBuilder.setParentId(parentId);
        }
        printIfNotEmpty(entryBuilder.build());
      }
    }
  }
}


text:
import { fatal } from 'utils/log';
import bind from 'utils/bind';
import { createFunctionFromString } from '../config/runtime-parser';
import { isFunction, isString, isObjectType } from 'utils/is';

export default function getComputationSignature(ractive, key, signature) {
  let getter;
  let setter;

  // useful for debugging
  let getterString;
  let getterUseStack;
  let setterString;

  if (isFunction(signature)) {
    getter = bind(signature, ractive);
    getterString = signature.toString();
    getterUseStack = true;
  }

  if (isString(signature)) {
    getter = createFunctionFromString(signature, ractive);
    getterString = signature;
  }

  if (isObjectType(signature)) {
    if (isString(signature.get)) {
      getter = createFunctionFromString(signature.get, ractive);
      getterString = signature.get;
    } else if (isFunction(signature.get)) {
      getter = bind(signature.get, ractive);
      getterString = signature.get.toString();
      getterUseStack = true;
    } else {
      fatal('`%s` computation must have a `get()` method', key);
    }

    if (isFunction(signature.set)) {
      setter = bind(signature.set, ractive);
      setterString = signature.set.toString();
    }
  }

  return {
    getter,
    setter,
    getterString,
    setterString,
    getterUseStack
  };
}


text:
<?php require_once $abs_us_root.$us_url_root.'users/helpers/helpers.php'; ?>

<?php require_once $abs_us_root.$us_url_root.'users/includes/user_spice_ver.php'; ?>

<?php

//check for a custom page

$currentPage = currentPage();

if(file_exists($abs_us_root.$us_url_root.'usersc/'.$currentPage)){

	if(currentFolder()!= 'usersc'){

		Redirect::to($us_url_root.'usersc/'.$currentPage);

	}

}

$db = DB::getInstance();

$settingsQ = $db->query("Select * FROM settings");

$settings = $settingsQ->first();

if ($settings->site_offline==1){

	die("The site is currently offline.");

}

if ($settings->force_ssl==1){

	if (!isset($_SERVER['HTTPS']) || !$_SERVER['HTTPS']) {

		// if request is not secure, redirect to secure url

		$url = 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

		Redirect::to($url);

		exit;

	}

}

//if track_guest enabled AND there is a user logged in

if($settings->track_guest == 1 && $user->isLoggedIn()){

	if ($user->isLoggedIn()){

		$user_id=$user->data()->id;

	}else{

		$user_id=0;

	}

	new_user_online($user_id);

}

?>

<!DOCTYPE html>

<html lang="en">

<head>

	<meta charset="utf-8">

	<meta http-equiv="X-UA-Compatible" content="IE=edge">

	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

	<meta name="description" content="Chakravyuha will be the online cryptic hunt which will be a collection of multiple rounds each carrying a question. As the user answers a question correctly, he proceeds to the next round">

	<meta name="author" content="Siddharth Yadav">
	<meta property="og:url"                content="https://chakravyuha.in" />
<meta property="og:type"               content="article" />
<meta property="og:title"              content="Chakravyuha - Online Cryptic Hunt" />
<meta property="og:description"        content="Chakravyuha will be the online cryptic hunt which will be a collection of multiple rounds each carrying a question. As the user answers a question correctly, he proceeds to the next round" />
<meta property="og:image"              content="http://52.66.75.233/img/fb_og.png" />
<meta property="og:author" content="https://www.facebook.com/EsyaIIITD/">

	<?php

	if(file_exists($abs_us_root.$us_url_root.'usersc/includes/head_tags.php')){

		require_once $abs_us_root.$us_url_root.'usersc/includes/head_tags.php';

	}

	?>

	<title><?=$settings->site_name;?></title>

	<!-- Bootstrap Core CSS -->

	<!-- AKA Primary CSS -->

	<link href="<?=$us_url_root?><?=str_replace('../','',$settings->us_css1);?>" rel="stylesheet">

	<!-- Template CSS -->

	<!-- AKA Secondary CSS -->

	<link href="<?=$us_url_root?><?=str_replace('../','',$settings->us_css2);?>" rel="stylesheet">

	<!-- Your Custom CSS Goes Here!-->

	<link href="<?=$us_url_root?><?=str_replace('../','',$settings->us_css3);?>" rel="stylesheet">

	<!-- Custom Fonts -->

	<link href="<?=$us_url_root?>users/fonts/css/font-awesome.min.css" rel="stylesheet" type="text/css">

    <link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">

    <link href="https://fonts.googleapis.com/css?family=Open+Sans:300" rel="stylesheet">

</head>

<body>


text:
DD-ColorPicker
================

A color picker that allows you to choose only amongst a set of color (i.e. Pantone colors)


text:
package com.ameron32.apps.projectbandit.core.trial;

import android.os.Bundle;
import android.view.View;
import butterknife.ButterKnife;
import butterknife.OnClick;

import com.ameron32.apps.projectbandit.R;
import com.ameron32.apps.projectbandit.core.fragment.AbsContentFragment;
import com.ameron32.apps.projectbandit.manager._ParseUtils;

public class RollDiceFragment extends AbsContentFragment {

	@Override
	protected int getCustomLayoutResource() {
		return R.layout.fragment_dice_roll;
	}

	@Override public void onViewCreated(
	    View view,
	    Bundle savedInstanceState) {
	  super.onViewCreated(view, savedInstanceState);
	  ButterKnife.inject(this, view);
	}

	@OnClick(R.id.button_roll) void onRoll() {
	  _ParseUtils.rollDice();
	}

	@Override public void onDestroyView() {
	  super.onDestroyView();
	  ButterKnife.reset(this);
	}

}


text:
// Copyright (C) 2012 Vicente J. Botet Escriba
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

// <boost/thread/shared_lock_guard.hpp>

// <mutex>

// template <class Mutex>
// class shared_lock_guard
// {
// public:
//     typedef Mutex mutex_type;
//     ...
// };

#include <boost/thread/shared_mutex.hpp>
#include <boost/thread/shared_lock_guard.hpp>
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/detail/lightweight_test.hpp>

int main()
{
  BOOST_STATIC_ASSERT_MSG((boost::is_same<boost::shared_lock_guard<boost::shared_mutex>::mutex_type,
      boost::shared_mutex>::value), "");

  return boost::report_errors();
}


text:
Simple, fast & type safe code that leverages the JavaScript & OCaml ecosystems.

This package provides support for using Reason with native OCaml compilers.

[![Build Status](https://dev.azure.com/reasonml/reason/_apis/build/status/facebook.reason?branchName=master)](https://dev.azure.com/reasonml/reason/_build/latest?definitionId=2?branchName=master) [![Build Status](https://travis-ci.org/facebook/reason.svg?branch=master)](https://travis-ci.org/facebook/reason) [![CircleCI](https://circleci.com/gh/facebook/reason/tree/master.svg?style=svg)](https://circleci.com/gh/facebook/reason/tree/master)

## [Native Quick Start With Esy](https://reasonml.github.io/docs/en/quickstart-ocaml)

## [Community](https://reasonml.github.io/docs/en/community.html)

## [Roadmap & Contribution](https://reasonml.github.io/docs/en/roadmap)

### Documentations

Go to https://github.com/reasonml/reasonml.github.io to contribute to the Reason documentation.

### Contributing

See the [docs folder's `GETTING_STARTED_CONTRIBUTING.md`](../docs/GETTING_STARTED_CONTRIBUTING.md).