text:
import sinon from 'sinon';
import raf from 'raf';
import { get } from 'ol/proj';
import View from 'ol/View';
import * as extent from 'ol/extent';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import Polygon from 'ol/geom/Polygon';
import Draw from 'ol/interaction/Draw';
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import WKTReader from 'jsts/org/locationtech/jts/io/WKTReader';
import * as utils from '../../utils/mapUtils';
import { convertGeoJSONtoJSTS, covers } from '../../utils/mapUtils';

// this polyfills requestAnimationFrame in the test browser, required for ol3
raf.polyfill();

describe('mapUtils', () => {
    it('jstsGeomToOlGeom should convert JSTS to Ol', () => {
        const Reader = new WKTReader();
        const jstsGeom = Reader.read('POINT (-20 0)');
        expect(jstsGeom.getCoordinate()).toEqual({ x: -20, y: 0, z: undefined });
        const olGeom = utils.jstsGeomToOlGeom(jstsGeom);
        expect(olGeom instanceof Point).toBe(true);
        const expected = [-20, 0];
        expect(olGeom.getCoordinates()).toEqual(expected);
    });

    it('convertJSTSGeometry should covert a JSTS from one SRS to another', () => {
        const Reader = new WKTReader();
        const jstsGeom = Reader.read('POINT (-20 0)');
        expect(jstsGeom.getCoordinate()).toEqual({ x: -20, y: 0, z: undefined });
        const newGeom = utils.transformJSTSGeometry(jstsGeom, 'EPSG:4326', 'EPSG:3857');
        expect(newGeom.getCoordinate()).toEqual({
            x: -2226389.8158654715,
            y: -7.081154551613622e-10,
            z: undefined,
        });
        const newerGeom = utils.transformJSTSGeometry(newGeom, 'EPSG:3857', 'EPSG:4326');
        expect(newerGeom.getCoordinate()).toEqual({ x: -20, y: 0, z: undefined });
        expect(newerGeom).toEqual(jstsGeom);
    });

    it('bufferGeometry should covert a point to a polygon', () => {
        const reader = new WKTReader();
        const jstsGeom = reader.read('POINT (-20 0)');
        expect(jstsGeom.getGeometryType()).toEqual('Point');
        const returnedGeom = utils.bufferGeometry(jstsGeom);
        expect(returnedGeom.getGeometryType()).toEqual('Polygon');
    });

    it('bufferGeometry should not change a polygon', () => {
        const reader = new WKTReader();
        const jstsGeom = reader.read('POLYGON ((30 10, 40 40, 20 40, 10 20, 30 10))');
        expect(jstsGeom.getGeometryType()).toEqual('Polygon');
        const returnedGeom = utils.bufferGeometry(jstsGeom);
        expect(returnedGeom.getGeometryType()).toEqual('Polygon');
        expect(jstsGeom).toEqual(returnedGeom);
    });

    it('bufferGeometry should change a polygon', () => {
        const reader = new WKTReader();
        const jstsGeom = reader.read('POLYGON ((30 10, 40 40, 20 40, 10 20, 30 10))');
        expect(jstsGeom.getGeometryType()).toEqual('Polygon');
        const returnedGeom = utils.bufferGeometry(jstsGeom, 10, true);
        expect(returnedGeom.getGeometryType()).toEqual('Polygon');
        expect(jstsGeom).not.toEqual(returnedGeom);
    });

    it('convertGeoJSONtoJSTS should convert GeoJSON Point to JSTS Geometry', () => {
        const point = { type: 'Point', coordinates: [100.0, 0.0] };
        const returnedGeom = utils.convertGeoJSONtoJSTS(point);
        expect(returnedGeom.getGeometryType()).toEqual('Polygon');
    });

    it('convertGeoJSONtoJSTS should convert GeoJSON LineString to JSTS Geometry', () => {
        const lineString = {
            type: 'LineString',
            coordinates: [[100.0, 0.0], [101.0, 1.0]],
        };
        const returnedGeom = utils.convertGeoJSONtoJSTS(lineString);
        expect(returnedGeom.getGeometryType()).toEqual('Polygon');
    });

    it('convertGeoJSONtoJSTS should convert GeoJSON Polygon(no holes) to JSTS Geometry', () => {
        const polygon = {
            type: 'Polygon',
            coordinates: [
                [[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]],
            ],
        };
        const returnedGeom = utils.convertGeoJSONtoJSTS(polygon);
        expect(returnedGeom.getGeometryType()).toEqual('Polygon');
    });

    it('convertGeoJSONtoJSTS should convert GeoJSON Polygon(holes) to JSTS Geometry', () => {
        const polygon = {
            type: 'Polygon',
            coordinates: [
                [[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]],
                [[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]],
            ],
        };
        const returnedGeom = utils.convertGeoJSONtoJSTS(polygon);
        expect(returnedGeom.getGeometryType()).toEqual('Polygon');
    });

    it('convertGeoJSONtoJSTS should convert GeoJSON MultiPoint to JSTS Geometry', () => {
        const multiPoint = {
            type: 'MultiPoint',
            coordinates: [[100.0, 0.0], [101.0, 1.0]],
        };
        const returnedGeom = utils.convertGeoJSONtoJSTS(multiPoint);
        expect(returnedGeom.getGeometryType()).toEqual('MultiPolygon');
    });

    it('convertGeoJSONtoJSTS should convert GeoJSON MultiLineString to JSTS Geometry', () => {
        const multiLineString = {
            type: 'MultiLineString',
            coordinates: [
                [[100.0, 0.0], [101.0, 1.0]],
                [[102.0, 2.0], [103.0, 3.0]],
            ],
        };
        const returnedGeom = utils.convertGeoJSONtoJSTS(multiLineString);
        expect(returnedGeom.getGeometryType()).toEqual('MultiPolygon');
    });

    it('convertGeoJSONtoJSTS should convert GeoJSON MultiPolygon to JSTS Geometry', () => {
        const multiPolygon = {
            type: 'MultiPolygon',
            coordinates: [
                [[[102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0]]],
                [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]],
                    [[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]],
            ],
        };
        const returnedGeom = utils.convertGeoJSONtoJSTS(multiPolygon);
        expect(returnedGeom.getGeometryType()).toEqual('MultiPolygon');
    });

    it('convertGeoJSONtoJSTS should convert GeoJSON GeometryCollection to JSTS Geometry', () => {
        const geometryCollection = {
            type: 'GeometryCollection',
            geometries: [
                {
                    type: 'Point',
                    coordinates: [100.0, 0.0],
                },
                {
                    type: 'LineString',
                    coordinates: [[101.0, 0.0], [102.0, 1.0]],
                },
            ],
        };
        const returnedGeom = utils.convertGeoJSONtoJSTS(geometryCollection);
        expect(returnedGeom.getGeometryType()).toEqual('MultiPolygon');
    });

    it('convertGeoJSONtoJSTS should convert GeoJSON FeatureCollection to JSTS Geometry', () => {
        const featureCollection = {
            type: 'FeatureCollection',
            features: [{
                type: 'Feature',
                geometry: {
                    type: 'Point',
                    coordinates: [102.0, 0.5],
                },
                properties: {
                    prop0: 'value0',
                },
            }, {
                type: 'Feature',
                geometry: {
                    type: 'LineString',
                    coordinates: [
                        [102.0, 0.0],
                        [103.0, 1.0],
                        [104.0, 0.0],
                        [105.0, 1.0],
                    ],
                },
                properties: {
                    prop0: 'value0',
                    prop1: 0.0,
                },
            }, {
                type: 'Feature',
                geometry: {
                    type: 'Polygon',
                    coordinates: [
                        [
                            [100.0, 0.0],
                            [101.0, 0.0],
                            [101.0, 1.0],
                            [100.0, 1.0],
                            [100.0, 0.0],
                        ],
                    ],
                },
                properties: {
                    prop0: 'value0',
                    prop1: {
                        this: 'that',
                    },
                },
            }],
        };
        const returnedGeom = utils.convertGeoJSONtoJSTS(featureCollection);
        expect(returnedGeom.getGeometryType()).toEqual('MultiPolygon');
    });

    it('bufferGeojson should read in feature collection and buffer each feature, then return a new feature collection', () => {
        const featureCollection = {
            type: 'FeatureCollection',
            features: [
                {
                    type: 'Feature',
                    properties: { name: 'feature1' },
                    geometry: { type: 'Point', coordinates: [1, 1] },
                },
                {
                    type: 'Feature',
                    properties: { name: 'feature2' },
                    geometry: { type: 'Point', coordinates: [2, 2] },
                },
                {
                    type: 'Feature',
                    properties: { name: 'feature3' },
                    geometry: { type: 'Point', coordinates: [3, 3] },
                },
            ],
        };
        const ret = utils.bufferGeojson(featureCollection, 10, false);
        expect(ret.features[0].geometry.type).toEqual('Polygon');
        expect(ret.features[0].properties.name).toEqual('feature1');
        expect(ret.features[1].geometry.type).toEqual('Polygon');
        expect(ret.features[1].properties.name).toEqual('feature2');
        expect(ret.features[2].geometry.type).toEqual('Polygon');
        expect(ret.features[2].properties.name).toEqual('feature3');
    });

    it('bufferGeojson should not return features with no area', () => {
        const featureCollection = {
            type: 'FeatureCollection',
            features: [
                {
                    type: 'Feature',
                    properties: { name: 'feature1' },
                    geometry: { type: 'Point', coordinates: [1, 1] },
                },
                {
                    type: 'Feature',
                    properties: { name: 'feature2' },
                    geometry: { type: 'Point', coordinates: [2, 2] },
                },
                {
                    type: 'Feature',
                    properties: { name: 'feature3' },
                    geometry: { type: 'Point', coordinates: [3, 3] },
                },
            ],
        };
        const expectedCollection = {
            type: 'FeatureCollection',
            features: [],
        };
        expect(utils.bufferGeojson(featureCollection, -10, true)).toEqual(expectedCollection);
    });

    it('generateDrawBoxInteraction should setup a new interaction', () => {
        const setActiveStub = sinon.stub(Draw.prototype, 'setActive');
        const layer = new VectorLayer({
            source: new VectorSource(),
        });
        const drawInteraction = utils.generateDrawBoxInteraction(layer);
        expect(drawInteraction instanceof Draw).toBe(true);
        expect(setActiveStub.called).toBe(true);
        expect(setActiveStub.calledWith(false)).toBe(true);
        setActiveStub.restore();
    });

    it('generateDrawFreeInteraction should setup a new interaction', () => {
        const setActiveStub = sinon.stub(Draw.prototype, 'setActive');
        const layer = new VectorLayer({
            source: new VectorSource(),
        });
        const drawInteraction = utils.generateDrawFreeInteraction(layer);
        expect(drawInteraction instanceof Draw).toBe(true);
        expect(setActiveStub.calledWith(false)).toBe(true);
        setActiveStub.restore();
    });

    it('featureToBbox should take a geojson feature and return the bbox', () => {
        const feature = {
            type: 'Feature',
            properties: {},
            geometry: {
                type: 'Polygon',
                coordinates: [
                    [
                        [21.708984375, 52.45600939264076],
                        [20.214843749999996, 52.214338608258196],
                        [21.181640624999996, 51.33061163769853],
                        [23.027343749999996, 52.669720383688166],
                        [21.423339843749996, 53.212612189941574],
                        [21.1376953125, 52.736291655910925],
                        [21.708984375, 52.45600939264076],
                    ],
                ],
            },
        };
        const bbox = [
            20.214843749999996,
            51.33061163769853,
            23.027343749999996,
            53.212612189941574,
        ];

        expect(utils.featureToBbox(feature)).toEqual(bbox);
    });

    it('serialize should transform to wgs84 and return a rounded bbox extent', () => {
        // this bbox extends past -180 and 180 and should be corrected
        const bbox = [
            -203.90625,
            -70.61261423801925,
            220.78125,
            83.27770503961696,
        ];
        // returned bbox should have overflow corrected and decimals rounded
        const expected = [
            -180,
            -70.61261,
            180,
            83.27771,
        ];

        const deserialized = utils.deserialize(bbox);

        const serialized = utils.serialize(deserialized);
        expect(serialized).toEqual(expected);
    });

    it('isGeoJSONValid should read the geom from a feature collection and return if it is valid', () => {
        const invalid = {
            type: 'FeatureCollection',
            features: [
                {
                    type: 'Feature',
                    properties: {},
                    geometry: {
                        type: 'Polygon',
                        coordinates: [
                            [
                                [36.2109375, 47.040182144806664],
                                [20.390625, 37.16031654673677],
                                [52.734375, 31.952162238024975],
                                [16.875, 44.59046718130883],
                                [7.734374999999999, 38.272688535980976],
                                [34.453125, 51.17934297928927],
                                [31.289062500000004, 28.92163128242129],
                                [36.2109375, 47.040182144806664],
                            ],
                        ],
                    },
                },
            ],
        };
        expect(utils.isGeoJSONValid(invalid)).toBe(false);

        const valid = {
            type: 'FeatureCollection',
            features: [
                {
                    type: 'Feature',
                    properties: {},
                    geometry: {
                        type: 'Polygon',
                        coordinates: [
                            [
                                [11.953125, 26.115985925333536],
                                [10.546875, 16.636191878397664],
                                [29.53125, 13.581920900545844],
                                [30.234375, 25.799891182088334],
                                [18.6328125, 30.14512718337613],
                                [11.953125, 26.115985925333536],
                            ],
                        ],
                    },
                },
            ],
        };
        expect(utils.isGeoJSONValid(valid)).toBe(true);
    });

    it('createGeoJSON should take an ol3 geom and return a feature collection containing a feature with that geom', () => {
        const extentSpy = sinon.spy(Point.prototype, 'getExtent');
        const coords = [-1, 1];
        const geom = new Point(coords);
        const expected = {
            type: 'FeatureCollection',
            features: [
                {
                    type: 'Feature',
                    bbox: [-1, 1, -1, 1],
                    geometry: {
                        type: 'Point', coordinates: [-1, 1],
                    },
                },
            ],
        };
        const geojson = utils.createGeoJSON(geom);
        expect(extentSpy.calledOnce).toBe(true);
        expect(geojson).toEqual(expected);
    });

    it('createGeoJSONGeometry should take a ol3 geom and return the geom in geojson format', () => {
        const coords = [-1, 1];
        const geom = new Point(coords);
        const expected = { type: 'Point', coordinates: [-1, 1] };
        const cloneSpy = sinon.spy(Point.prototype, 'clone');
        const coordsSpy = sinon.spy(Point.prototype, 'getCoordinates');
        expect(utils.createGeoJSONGeometry(geom)).toEqual(expected);
        expect(cloneSpy.calledOnce).toBe(true);
        expect(coordsSpy.calledOnce).toBe(true);
        cloneSpy.restore();
        coordsSpy.restore();
    });

    it('clearDraw should get the layer source then clear it', () => {
        const clear = sinon.spy();
        const layer = {
            getSource: sinon.spy(() => ({ clear })),
        };
        utils.clearDraw(layer);
        expect(layer.getSource.calledOnce).toBe(true);
        expect(clear.calledOnce).toBe(true);
    });

    it('zoomToFeature should fit view to geom if its not a point type', () => {
        const feature = new Feature({
            geometry: new Polygon([[
                [-98, -31],
                [68, -31],
                [68, 57],
                [-98, 57],
                [-98, -31],
            ]]),
        });
        const featureSpy = sinon.spy(Feature.prototype, 'getGeometry');
        const geomSpy = sinon.spy(Polygon.prototype, 'getType');
        const fit = sinon.spy(() => {
        });
        const map = { getView: sinon.spy(() => ({ fit })) };
        utils.zoomToFeature(feature, map);
        expect(featureSpy.calledOnce).toBe(true);
        expect(geomSpy.calledOnce).toBe(true);
        expect(map.getView.calledOnce).toBe(true);
        expect(fit.calledOnce).toBe(true);
        featureSpy.restore();
        geomSpy.restore();
    });

    it('zoomToFeature should fit bbox if point feature has one', () => {
        const feature = new Feature({ geometry: new Point([1, 1]) });
        feature.setProperties({ bbox: [1, 1, 1, 1] });
        const fitSpy = sinon.spy();
        const map = { getView: sinon.spy(() => ({ fit: fitSpy })) };
        utils.zoomToFeature(feature, map);
        expect(fitSpy.calledOnce).toBe(true);
        expect(fitSpy.calledWith([1, 1, 1, 1])).toBe(true);
    });

    it('zoomToFeature should center on geom if it is a point type', () => {
        const feature = new Feature({ geometry: new Point([1, 1]) });
        const getTypeSpy = sinon.spy(Point.prototype, 'getType');
        const getCoordsSpy = sinon.spy(Point.prototype, 'getCoordinates');
        const center = sinon.spy();
        const map = { getView: sinon.spy(() => ({ setCenter: center })) };
        utils.zoomToFeature(feature, map);
        expect(getTypeSpy.calledOnce).toBe(true);
        expect(map.getView.calledOnce).toBe(true);
        expect(center.calledOnce).toBe(true);
        expect(getCoordsSpy.calledOnce).toBe(true);
        getTypeSpy.restore();
        getCoordsSpy.restore();
    });

    it('featureToPoint should return a point representing the center of a feature\'s extent', () => {
        expect(utils.featureToPoint()).toBe(null);
        const coords = [[[-15, -14], [14, -14], [14, 12], [-15, 12], [-15, -14]]];
        const bbox = [-15, -14, 14, 12];
        const feature = new Feature({
            geometry: new Polygon(coords),
        });
        const expectedCoords = extent.getCenter(bbox);
        const centerSpy = sinon.spy(extent, 'getCenter');
        const geomSpy = sinon.spy(Feature.prototype, 'getGeometry');
        const extentSpy = sinon.spy(Polygon.prototype, 'getExtent');
        const point = utils.featureToPoint(feature);
        expect(centerSpy.calledOnce).toBe(true);
        expect(centerSpy.calledWith(bbox)).toBe(true);
        expect(geomSpy.calledOnce).toBe(true);
        expect(extentSpy.calledOnce).toBe(true);
        expect(point.getCoordinates()).toEqual(expectedCoords);
        centerSpy.restore();
        geomSpy.restore();
        extentSpy.restore();
    });

    it('unwrapCoordinates should adjust x coords to be in valid extent', () => {
        const coordProj = get('EPSG:4326');
        const coords = [[[-380, 20], [-160, 20], [-160, -20], [-380, -20]]];
        const expected = [[[-20, 20], [-160, 20], [-160, -20], [-20, -20]]];
        expect(utils.unwrapCoordinates(coords, coordProj)).toEqual(expected);
    });

    it('unwrapExtent should adjust min and max x coords to be in valid extent', () => {
        const coordProj = get('EPSG:4326');
        const coordExtent = [700, -90, 740, 90];
        const expected = [-20, -90, 20, 90];
        expect(utils.unwrapExtent(coordExtent, coordProj)).toEqual(expected);
    });

    it('unwrapExtent should adjust min and max x coords to be in valid extent', () => {
        const coordProj = get('EPSG:4326');
        const coordExtent = [-540, -90, -185, 90];
        const expected = [-180, -90, 175, 90];
        expect(utils.unwrapExtent(coordExtent, coordProj)).toEqual(expected);
    });

    it('unwrapExtent should return the extent unmodified', () => {
        const coordProj = get('EPSG:4326');
        const coordExtent = [-120, -90, 180, 90];
        const expected = [-120, -90, 180, 90];
        expect(utils.unwrapExtent(coordExtent, coordProj)).toEqual(expected);
    });

    it('isViewOutsideValidExtent should return true or false', () => {
        const view = new View({ center: [-190, 40], projection: 'EPSG:4326', zoom: 1 });
        expect(utils.isViewOutsideValidExtent(view)).toBe(true);
        const view2 = new View({ center: [-20, 20], projection: 'EPSG:4326', zoom: 1 });
        expect(utils.isViewOutsideValidExtent(view2)).toBe(false);
    });

    it('goToValidExtent should set the center of view to be inside the valid map extent', () => {
        const view = new View({ center: [-190, 20], projection: 'EPSG:4326', zoom: 1 });
        expect(utils.goToValidExtent(view)).toEqual([170, 20]);
        expect(view.getCenter()).toEqual([170, 20]);
    });

    it('isBox should return false if the feature has more than 5 coordinate pairs', () => {
        const feature = new Feature({
            geometry: new Polygon([
                [
                    [99.30541992187499, 2.6467632307409725],
                    [99.195556640625, 2.2296616399183624],
                    [100.074462890625, 2.04302395742204],
                    [100.03051757812499, 2.591888984149953],
                    [99.65698242187499, 2.943040910055132],
                    [99.107666015625, 3.0417830279332634],
                    [98.44848632812499, 2.8223442468940902],
                    [98.997802734375, 2.756504385543263],
                    [99.30541992187499, 2.6467632307409725],
                ],
            ]),
        });
        expect(utils.isBox(feature)).toBe(false);
    });

    it('isBox should return false if the extent coords of a 4 vertex feature are not the same as the feature coords', () => {
        const feature = new Feature({
            geometry: new Polygon([
                [
                    [101.75537109375, -0.37353251022880474],
                    [101.3818359375, -0.8239462091017558],
                    [102.041015625, -1.197422590365017],
                    [102.293701171875, -0.7140928403610857],
                    [101.75537109375, -0.37353251022880474],
                ],
            ]),
        });
        expect(utils.isBox(feature)).toBe(false);
    });

    it('isBox should return true if the extent coords are same as feature coords', () => {
        const feature = new Feature({
            geometry: new Polygon([
                [
                    [101.57958984375, 0.9667509997666425],
                    [101.79931640625, 0.9667509997666425],
                    [101.79931640625, 1.2962761196418218],
                    [101.57958984375, 1.2962761196418218],
                    [101.57958984375, 0.9667509997666425],
                ],
            ]),
        });
        expect(utils.isBox(feature)).toBe(true);
    });

    it('isVertx should check to see if a feature coordinate lies on the pixel and return the vertex if its with the tolerance', () => {
        const pixel = [10, 10];
        const tolerance = 2;
        const feature = new Feature({ geometry: new Point([1, 1]) });
        const getPixelStub = sinon.stub().returns([8, 8]);
        const map = { getPixelFromCoordinate: getPixelStub };
        expect(utils.isVertex(pixel, feature, tolerance, map)).toEqual([1, 1]);
    });

    it('isVertex should return false if feature coords are not within the tolerance', () => {
        const pixel = [10, 10];
        const tolerance = 2;
        const feature = new Feature({ geometry: new Point([1, 1]) });
        const getPixelStub = sinon.stub().returns([7, 7]);
        const map = { getPixelFromCoordinate: getPixelStub };
        expect(utils.isVertex(pixel, feature, tolerance, map)).toBe(false);
    });

    it('allHaveArea should return false if there are no features', () => {
        const collection = {
            type: 'FeatureCollection',
            features: [],
        };
        expect(utils.allHaveArea(collection)).toBe(false);
    });

    it('allHaveArea should return false if polygon has no area', () => {
        const collection = {
            type: 'FeatureCollection',
            features: [
                {
                    type: 'Feature',
                    geometry: {
                        type: 'Polygon',
                        coordinates: [[
                            [0, 0],
                            [0, 0],
                            [0, 0],
                            [0, 0],
                            [0, 0],
                        ]],
                    },
                },
            ],
        };
        expect(utils.allHaveArea(collection)).toBe(false);
    });

    it('allHaveArea should return false for points (no getArea func in ol)', () => {
        const collection = {
            type: 'FeatureCollection',
            features: [
                {
                    type: 'Feature',
                    geometry: {
                        type: 'Point',
                        coordinates: [
                            20.3,
                            24.9,
                        ],
                    },
                },
            ],
        };
        expect(utils.allHaveArea(collection)).toBe(false);
    });

    it('allHaveArea should retunr true', () => {
        const collection = {
            type: 'FeatureCollection',
            features: [
                {
                    type: 'Feature',
                    geometry: {
                        type: 'Polygon',
                        coordinates: [[
                            [1, 1],
                            [2, 1],
                            [2, 2],
                            [1, 2],
                            [1, 1],
                        ]],
                    },
                },
            ],
        };
        expect(utils.allHaveArea(collection)).toBe(true);
    });

    it('getDominantGeometry should return Point', () => {
        const collection = {
            type: 'FeatureCollection',
            features: [
                {
                    type: 'Feature',
                    geometry: {
                        type: 'Point',
                    },
                },
                {
                    type: 'Feature',
                    geometry: {
                        type: 'Point',
                    },
                },
            ],
        };
        expect(utils.getDominantGeometry(collection)).toEqual('Point');
    });

    it('getDominantGeometry should return Line', () => {
        const collection = {
            type: 'FeatureCollection',
            features: [
                {
                    type: 'Feature',
                    geometry: {
                        type: 'PolyLine',
                    },
                },
                {
                    type: 'Feature',
                    geometry: {
                        type: 'PolyLine',
                    },
                },
            ],
        };
        expect(utils.getDominantGeometry(collection)).toEqual('Line');
    });

    it('getDominantGeometry should return Polygon', () => {
        const collection = {
            type: 'FeatureCollection',
            features: [
                {
                    type: 'Feature',
                    geometry: {
                        type: 'Polygon',
                    },
                },
                {
                    type: 'Feature',
                    geometry: {
                        type: 'MultiPolygon',
                    },
                },
            ],
        };
        expect(utils.getDominantGeometry(collection)).toEqual('Polygon');
    });

    it('getDominantGeometry should return Collection', () => {
        const collection = {
            type: 'FeatureCollection',
            features: [
                {
                    type: 'Feature',
                    geometry: {
                        type: 'Point',
                    },
                },
                {
                    type: 'Feature',
                    geometry: {
                        type: 'MultiPolygon',
                    },
                },
            ],
        };
        expect(utils.getDominantGeometry(collection)).toEqual('Collection');
    });

    it('getDominantGeometry should return null', () => {
        const collection1 = {
            type: 'FeatureCollection',
            features: [
                {
                    type: 'Feature',
                    geometry: {
                        type: 'blah',
                    },
                },
                {
                    type: 'Feature',
                    geometry: {
                        type: 'blah',
                    },
                },
            ],
        };
        expect(utils.getDominantGeometry(collection1)).toEqual(null);
        const collection2 = {
            type: 'FeatureCollection',
            features: [],
        };
        expect(utils.getDominantGeometry(collection2)).toEqual(null);
    });

    it('should confirm two overlapping extents are covered', () => {
        const featureCollectionExtent = convertGeoJSONtoJSTS({
            type: 'FeatureCollection',
            features: [{
                type: 'Feature',
                geometry: {
                    type: 'Polygon',
                    coordinates: [
                        [
                            [100.0, 0.0],
                            [101.0, 0.0],
                            [101.0, 1.0],
                            [100.0, 1.0],
                            [100.0, 0.0],
                        ],
                    ],
                },
            }],
        }, 1, false);

        const featureCollectionPolicy = convertGeoJSONtoJSTS({
            type: 'FeatureCollection',
            features: [{
                type: 'Feature',
                geometry: {
                    type: 'Polygon',
                    coordinates: [
                        [
                            [100.0, 0.0],
                            [102.0, 0.0],
                            [102.0, 1.0],
                            [100.0, 1.0],
                            [100.0, 0.0],
                        ],
                    ],
                },
            }],
        }, 1, false);
        expect(covers(featureCollectionExtent, featureCollectionPolicy)).toBe(true);
    });

    it('should confirm two non-overlapping extents are not covered', () => {
        const featureCollectionExtent = convertGeoJSONtoJSTS({
            type: 'FeatureCollection',
            features: [{
                type: 'Feature',
                geometry: {
                    type: 'Polygon',
                    coordinates: [
                        [
                            [100.0, 0.0],
                            [101.0, 0.0],
                            [101.0, 1.0],
                            [100.0, 1.0],
                            [100.0, 0.0],
                        ],
                    ],
                },
            }],
        }, 1, false);

        const featureCollectionPolicy = convertGeoJSONtoJSTS({
            type: 'FeatureCollection',
            features: [{
                type: 'Feature',
                geometry: {
                    type: 'Polygon',
                    coordinates: [
                        [
                            [98.0, 0.0],
                            [99.0, 0.0],
                            [99.0, 0.5],
                            [98.0, 0.5],
                            [98.0, 0.0],
                        ],
                    ],
                },
            }],
        }, 1, false);
        expect(covers(featureCollectionExtent, featureCollectionPolicy)).toBe(false);
    });
});


text:
namespace XSharp.Assembler.x86
{
    public interface IInstructionWithSize {
        byte Size {
            get;
            set;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe Api::Endpoints::MatchesEndpoint do
  include Api::Test::EndpointTest

  let!(:team) { Team.first || Fabricate(:team) }

  before do
    @cursor_params = { team_id: team.id.to_s }
  end

  it_behaves_like 'a cursor api', Match

  context 'match' do
    let(:existing_match) { Fabricate(:match) }
    it 'returns a match' do
      match = client.match(id: existing_match.id)
      expect(match.id).to eq existing_match.id.to_s
      expect(match._links.self._url).to eq "http://example.org/matches/#{existing_match.id}"
    end
  end

  context 'match' do
    let(:existing_match) { Fabricate(:match) }
    it 'returns a match with links to challenge' do
      match = client.match(id: existing_match.id)
      expect(match.id).to eq existing_match.id.to_s
      expect(match._links.challenge._url).to eq "http://example.org/challenges/#{existing_match.challenge.id}"
      expect(match._links.winners._url).to eq existing_match.winners.map { |user| "http://example.org/users/#{user.id}" }
      expect(match._links.losers._url).to eq existing_match.losers.map { |user| "http://example.org/users/#{user.id}" }
    end
  end
end


text:
require 'open-uri'
require 'nokogiri'

from = 000 #300000 # start from 300000 because most old docs aren't rich
feed = Nokogiri::XML(open("http://data.rechtspraak.nl/uitspraken/zoeken?return=DOC&max=1000&from=#{from}"))
feed.remove_namespaces!
id_nodes = feed.xpath('/feed/entry/id')

subtitle_node = feed.xpath('/feed/subtitle')
total = subtitle_node.text.gsub('Aantal gevonden ECLI\'s: ', '')
while id_nodes.length > 0 do
  id_nodes.each do |id_node|
    id = id_node.text
    #/ECLI:[A-Za-z]*:([^:]*):[^:]*:[^:]*/ =~ id
    filename = "#{id}.xml"
    filename.gsub! ':', '.'

    unless File.exists? "rich/#{filename}" or File.exists? "notrich/#{filename}"
      # puts id.text
      doc_url = "http://data.rechtspraak.nl/uitspraken/content?id=#{id_node.text}"
      doc = Nokogiri::XML(open(doc_url))

      root = doc.xpath '/open-rechtspraak/rs:conclusie|/open-rechtspraak/rs:uitspraak', {:rs => 'http://www.rechtspraak.nl/schema/rechtspraak-1.0'}
      if root.length != 1
        # Empty docs:
        #
        # ECLI:NL:RBNHO:2014:347
        # ECLI:NL:RBAMS:2014:2748
        # ECLI:NL:GHDHA:2014:1688
        # ECLI:NL:RBOVE:2014:2747
        puts "ERROR: number conclusie/uitspraak elements in #{id} was not 1"
      else
        # TODO don't need to traverse *entire* tree; finding the first is good enough
        non_para_elements = root.xpath(".//*[local-name()!='para' and local-name()!='parablock' and local-name()!='paragroup']")
        # puts "#{id}: #{all.length}-#{para_block_elements.length}-#{para_elements.length}=#{non_para}"
        if non_para_elements.length>0
          path = "rich/#{filename}"
          # puts "#{id} had #{non_para_elements.length} non-para items"
        else
          #puts "#{id} had only para items"
          path = "notrich/#{filename}"
        end
        FileUtils.mkdir_p File.dirname(path) unless File.exists? File.dirname(path)
        File.open(path, 'w') do |file|
          file.write(doc.to_s)
        end
      end
      # else
      # puts "Already downloaded #{path}"
    end
  end
  from += 1000
  puts "#{from} / #{total}"
  feed = Nokogiri::XML(open("http://data.rechtspraak.nl/uitspraken/zoeken?return=DOC&max=1000&from=#{from}"))
  feed.remove_namespaces!
  id_nodes = feed.xpath('/feed/entry/id')
end


text:
import React, { createElement } from "react"
import pageFinderFactory from "./find-page"
import emitter from "./emitter"
let findPage

let syncRequires = {}
let asyncRequires = {}
let pathScriptsCache = {}
let resourceStrCache = {}
let resourceCache = {}
let pages = []
// Note we're not actively using the path data atm. There
// could be future optimizations however around trying to ensure
// we load all resources for likely-to-be-visited paths.
let pathArray = []
let pathCount = {}
let resourcesArray = []
let resourcesCount = {}
const preferDefault = m => (m && m.default) || m
let prefetcher
let inInitialRender = true

// Prefetcher logic
if (process.env.NODE_ENV === `production`) {
  prefetcher = require(`./prefetcher`)({
    getNextQueuedResources: () => resourcesArray.slice(-1)[0],
    createResourceDownload: resourceName => {
      fetchResource(resourceName, () => {
        resourcesArray = resourcesArray.filter(r => r !== resourceName)
        prefetcher.onResourcedFinished(resourceName)
      })
    },
  })
  emitter.on(`onPreLoadPageResources`, e => {
    prefetcher.onPreLoadPageResources(e)
  })
  emitter.on(`onPostLoadPageResources`, e => {
    prefetcher.onPostLoadPageResources(e)
  })
}

const sortResourcesByCount = (a, b) => {
  if (resourcesCount[a] > resourcesCount[b]) {
    return 1
  } else if (resourcesCount[a] < resourcesCount[b]) {
    return -1
  } else {
    return 0
  }
}

const sortPagesByCount = (a, b) => {
  if (pathCount[a] > pathCount[b]) {
    return 1
  } else if (pathCount[a] < pathCount[b]) {
    return -1
  } else {
    return 0
  }
}

const fetchResource = (resourceName, cb = () => {}) => {
  if (resourceStrCache[resourceName]) {
    process.nextTick(() => {
      cb(null, resourceStrCache[resourceName])
    })
  } else {
    // Find resource
    const resourceFunction =
      resourceName.slice(0, 12) === `component---`
        ? asyncRequires.components[resourceName] ||
          asyncRequires.layouts[resourceName]
        : asyncRequires.json[resourceName]

    // Download the resource
    resourceFunction((err, executeChunk) => {
      resourceStrCache[resourceName] = executeChunk
      cb(err, executeChunk)
    })
  }
}

const getResourceModule = (resourceName, cb) => {
  if (resourceCache[resourceName]) {
    process.nextTick(() => {
      cb(null, resourceCache[resourceName])
    })
  } else {
    fetchResource(resourceName, (err, executeChunk) => {
      if (err) {
        cb(err)
      } else {
        const module = preferDefault(executeChunk())
        resourceCache[resourceName] = module
        cb(err, module)
      }
    })
  }
}

let mountOrder = 1
const queue = {
  empty: () => {
    pathArray = []
    pathCount = {}
    resourcesCount = {}
    resourcesArray = []
    pages = []
  },
  addPagesArray: newPages => {
    pages = newPages
    let pathPrefix = ``
    if (typeof __PREFIX_PATHS__ !== `undefined`) {
      pathPrefix = __PATH_PREFIX__
    }
    findPage = pageFinderFactory(newPages, pathPrefix)
  },
  addDevRequires: devRequires => {
    syncRequires = devRequires
  },
  addProdRequires: prodRequires => {
    asyncRequires = prodRequires
  },
  dequeue: path => pathArray.pop(),
  enqueue: path => {
    // Check page exists.
    if (!pages.some(p => p.path === path)) {
      return false
    }

    const mountOrderBoost = 1 / mountOrder
    mountOrder += 1
    // console.log(
    // `enqueue "${path}", mountOrder: "${mountOrder}, mountOrderBoost: ${mountOrderBoost}`
    // )

    // Add to path counts.
    if (!pathCount[path]) {
      pathCount[path] = 1
    } else {
      pathCount[path] += 1
    }

    // Add path to queue.
    if (!queue.has(path)) {
      pathArray.unshift(path)
    }

    // Sort pages by pathCount
    pathArray.sort(sortPagesByCount)

    // Add resources to queue.
    const page = findPage(path)
    if (page.jsonName) {
      if (!resourcesCount[page.jsonName]) {
        resourcesCount[page.jsonName] = 1 + mountOrderBoost
      } else {
        resourcesCount[page.jsonName] += 1 + mountOrderBoost
      }

      // Before adding, checking that the JSON resource isn't either
      // already queued or been downloading.
      if (
        resourcesArray.indexOf(page.jsonName) === -1 &&
        !resourceStrCache[page.jsonName]
      ) {
        resourcesArray.unshift(page.jsonName)
      }
    }
    if (page.componentChunkName) {
      if (!resourcesCount[page.componentChunkName]) {
        resourcesCount[page.componentChunkName] = 1 + mountOrderBoost
      } else {
        resourcesCount[page.componentChunkName] += 1 + mountOrderBoost
      }

      // Before adding, checking that the component resource isn't either
      // already queued or been downloading.
      if (
        resourcesArray.indexOf(page.componentChunkName) === -1 &&
        !resourceStrCache[page.jsonName]
      ) {
        resourcesArray.unshift(page.componentChunkName)
      }
    }

    // Sort resources by resourcesCount.
    resourcesArray.sort(sortResourcesByCount)
    if (process.env.NODE_ENV === `production`) {
      prefetcher.onNewResourcesAdded()
    }

    return true
  },
  getResources: () => {
    return {
      resourcesArray,
      resourcesCount,
    }
  },
  getPages: () => {
    return {
      pathArray,
      pathCount,
    }
  },
  getPage: pathname => findPage(pathname),
  has: path => pathArray.some(p => p === path),
  getResourcesForPathname: (path, cb = () => {}) => {
    if (
      inInitialRender &&
      navigator &&
      navigator.serviceWorker &&
      navigator.serviceWorker.controller &&
      navigator.serviceWorker.controller.state === `activated`
    ) {
      // If we're loading from a service worker (it's already activated on
      // this initial render) and we can't find a page, there's a good chance
      // we're on a new page that this (now old) service worker doesn't know
      // about so we'll unregister it and reload.
      if (!findPage(path)) {
        navigator.serviceWorker
          .getRegistrations()
          .then(function(registrations) {
            for (let registration of registrations) {
              registration.unregister()
            }
            window.location.reload()
          })
      }
    }
    inInitialRender = false
    // In development we know the code is loaded already
    // so we just return with it immediately.
    if (process.env.NODE_ENV !== `production`) {
      const page = findPage(path)
      if (!page) return
      const pageResources = {
        component: syncRequires.components[page.componentChunkName],
        json: syncRequires.json[page.jsonName],
        layout: syncRequires.layouts[page.layoutComponentChunkName],
        page,
      }
      cb(pageResources)
      return pageResources
      // Production code path
    } else {
      const page = findPage(path)

      if (!page) {
        console.log(`A page wasn't found for "${path}"`)
        return
      }

      // Use the path from the page so the pathScriptsCache uses
      // the normalized path.
      path = page.path

      // Check if it's in the cache already.
      if (pathScriptsCache[path]) {
        process.nextTick(() => {
          cb(pathScriptsCache[path])
          emitter.emit(`onPostLoadPageResources`, {
            page,
            pageResources: pathScriptsCache[path],
          })
        })
        return pathScriptsCache[path]
      }

      emitter.emit(`onPreLoadPageResources`, { path })
      // Nope, we need to load resource(s)
      let component
      let json
      let layout
      // Load the component/json/layout and parallel and call this
      // function when they're done loading. When both are loaded,
      // we move on.
      const done = () => {
        if (component && json && (!page.layoutComponentChunkName || layout)) {
          pathScriptsCache[path] = { component, json, layout }
          const pageResources = { component, json, layout }
          cb(pageResources)
          emitter.emit(`onPostLoadPageResources`, {
            page,
            pageResources,
          })
        }
      }
      getResourceModule(page.componentChunkName, (err, c) => {
        if (err) {
          console.log(`Loading the component for ${page.path} failed`)
        }
        component = c
        done()
      })
      getResourceModule(page.jsonName, (err, j) => {
        if (err) {
          console.log(`Loading the JSON for ${page.path} failed`)
        }
        json = j
        done()
      })

      page.layoutComponentChunkName &&
        getResourceModule(page.layoutComponentChunkName, (err, l) => {
          if (err) {
            console.log(`Loading the Layout for ${page.path} failed`)
          }
          layout = l
          done()
        })

      return undefined
    }
  },
  peek: path => pathArray.slice(-1)[0],
  length: () => pathArray.length,
  indexOf: path => pathArray.length - pathArray.indexOf(path) - 1,
}

module.exports = queue


text:
#import <Xcode3UI/Xcode3InfoSliceController.h>

@class DVTStackView_ML, NSArray, NSMutableArray, NSPredicate, NSView;

@interface Xcode3InfoArraySliceController : Xcode3InfoSliceController
{
    NSMutableArray *_info;
    NSMutableArray *_sliceControllers;
    DVTStackView_ML *_stackView;
    NSView *_emptyContentView;
    NSPredicate *_entryFilter;
    NSArray *_filteredEntries;
}

+ (id)keyPathsForValuesAffectingTitleForDisplay;
+ (void)initialize;
- (void).cxx_destruct;
- (void)addItems:(id)arg1;
@property(copy) NSArray *sliceControllers; // @dynamic sliceControllers;
@property(copy) NSArray *info;
- (id)titleForDisplay;
- (void)controllerInfoChanged:(id)arg1;
- (void)sliceControllersChanged:(id)arg1 changeDictionary:(id)arg2;
- (void)_rebuildStackView;
- (void)_recomputeInfoFromSliceControllers;
- (BOOL)validateMenuItem:(id)arg1;
- (void)removeSlice:(id)arg1;
- (void)addSlice:(id)arg1;
- (id)_sliceControllerForInfoDict:(id)arg1;
- (void)primitiveInvalidate;
- (void)_hideEmptyContentView;
- (void)_showEmptyContentView;
- (void)loadView;
- (id)initWithSliceIdentifier:(id)arg1 infoArray:(id)arg2 infoEditor:(id)arg3;

// Remaining properties
@property(readonly) NSMutableArray *mutableSliceControllers; // @dynamic mutableSliceControllers;

@end


text:
copyright:
  years: 2015, 2017
lastupdated: "2016-10-14"

---

{:new_window: target="_blank"}
{:shortdesc: .shortdesc}
{:screen:.screen}
{:codeblock:.codeblock}

# Migrando dados de recurso da versão beta
{: #globalizationpipeline_betaresourcedatamigration}

A versão beta do {{site.data.keyword.GlobalizationPipeline_full}} será finalizada após um determinado período após a liberação da versão GA. Os dados do usuário nas instâncias beta não serão movidos para as instâncias de serviço GA. Para manter os dados após o GA, é possível exportar os dados de recurso para arquivos e depois importar para a nova instância. Observe que não é possível executar essa operação usando o painel de serviço. Além disso, a exportação de dados de recurso em um formato de arquivo de recursos não preservará outros metadados associados às entradas de recursos.

Para suportar migração de dados de beta para GA, foi incluído um recurso na ferramenta de linha de comandos Java do {{site.data.keyword.GlobalizationPipeline_short}}. A origem da ferramenta é hospedada em https://github.com/IBM-Bluemix/gp-java-tools e sua liberação binária também estará disponível no repositório github. A captura instantânea de desenvolvimento mais recente foi postada. [Faça o download.
](https://w3-connections.ibm.com/communities/service/html/communityview?communityUuid=589d87cf-d0c7-4e06-ab95-4108547f90aa#fullpageWidgetId=Wa22bb771e29b_4aa9_a114_cfe53fda2cc8&file=5cdaf089-ec7c-4881-b5a0-7ab651491237)

A ferramenta usa uma API REST aprimorada após a liberação beta para ***fazer upload das entradas de recursos***, portanto, a instância de serviço de destino deve ser a versão GA.
* Origem: beta ou GA
* Destino: somente GA

Para copiar todos os dados de pacote configurável em uma instância de serviço de Globalização para outra instância, use o comando a seguir:

```> java -jar gp-cli.jar copy-all-bundles -s <source-service-url> -i <source-instance-id> -u <source-user-id> -p <source-password> --dest-url <dest-service-url> --dest-instance-id <dest-instance-id> --dest-user-id <dest-user-id> --dest-password <dest-password>```

`source/target-service-url` e os outros valores de parâmetro estão localizados nas credenciais do serviço de origem/destino, por exemplo:

```
{
  "gp-beta": [
    {
      "name": "Globalization Pipeline-7x",
      "label": "gp-beta",
      "plan": "gp-beta-plan",
      "credentials": {

      "url": "https://gp-beta-rest.ng.bluemix.net/translate/rest",
        "userId": "bd0b84362c6934d222c3a0a40fc1443b",
        "password": "OGxp6jDqCLCL1ui8kQSPTt1mZDi4EQwu",
        "instanceId": "bd0b84362c6934d222c3a0a40fc1233e"
      }
    }
  ]
}
```
Além disso, toda a CLI do GP foi atualizada para suportar credenciais em formato json,
além das opções individuais `(-s / -i / -u / -p)`. É possível criar
um arquivo json com conteúdo, como este abaixo:

creds.json
```
 {

        "url": "https://gp-rest.stage1.ng.bluemix.net/translate/rest",
        "userId": "36cad58b3a65dc9fe0183208305be137",
        "password": "43F9MRMu9Q8BWRXMLctunUsAe8LTdwq1",
        "instanceId": "b157e3fc63e62d76c50d9f689d7fc965"

}
```
Em seguida, é possível especificar o arquivo por `-j
<json-file>`. No comando `copy/copy-all-bundles`, é possível substituir

```-s https://gp-rest.stage1.ng.bluemix.net/translate/rest -i b157e3fc63e62d76c50d9f689d7fc965 -u 36cad58b3a65dc9fe0183208305be137 -p 43F9MRMu9Q8BWRXMLctunUsAe8LTdwq1```

com

`-j creds.json `

Como alternativa, é possível copiar o pacote configurável de um local para outro usando o comando:

```> java -jar gp-cli.jar copy -s <source-service-url> -i <source-instance-id> -u <source-user-id> -p <source-password> -b <source-bundle-id> --dest-url <dest-service-url> --dest-instance-id <dest-instance-id> --dest-user-id <dest-user-id> --dest-password <dest-password> -d <dest-bundle-id>```

**Nota:** dois parâmetros adicionais, `-b <source-bundle-id>` e `-d <dest-bundle-id>`, podem ser usados além daquelas para copiar todos os pacotes configuráveis (copy-all-bundles). Esse comando pode ser usado para copiar um pacote configurável dentro da mesma instância. Nesse caso, é possível eliminar os parâmetros de credencial de serviço de destino `(--dest-*)`.

Os comandos acima extraem dados existentes de pacote configurável e de entrada de recurso e faz o upload deles para o novo local. Durante o processo, alguns campos controlados pelo servidor REST serão atualizados (como o campo updatedBy/updatedAt). Além disso, como esses comandos não copiam dados de ligação e configuração de serviço, você pode precisar configurar serviços de MT na instância de destino.

Por exemplo, a versão beta suporta a tradução árabe por meio do Watson Language Translator. Na versão GA, a tradução em árabe não é mais oferecida gratuitamente. Quando você portar dados beta na nova instância GA, o conteúdo em árabe já traduzido será preservado. Nenhuma mudança no idioma de origem acionará a tradução em árabe automaticamente, a menos que você configure a ligação do Watson para ativar a tradução em árabe. Esse também é o caso de quando a instância de origem é a versão GA. A ligação de serviços de MT externa é específica de uma instância GP; a ligação/configuração para outra instância não será portada automaticamente.


text:
import { VertexBuffer } from "../platform/VertexBuffer";
import { ElementArray } from "../platform/ElementArray";

/**
 * The drawable interface.
 */
export interface Drawable {

  /**
   * The vertex buffer.
   */
  vertexBuffer: VertexBuffer;

  /**
   * The element array.
   */
  elementArray: ElementArray;
}


text:
#import <UIKit/UIKit.h>

@class FKTextRangeView;

@class FKSelectionGrabberDot; //, UITextRangeView;

/*!
 @abstract Selection Grabber Type
 @discussion
 */
typedef enum {
    FKSelectionStartGrabber,
    FKSelectionEndGrabber
} FKSelectionGrabberType;

@interface FKSelectionGrabber : UIView
{
    int _applicationDeactivationReason;
    BOOL m_activeFlattened;
    BOOL m_alertFlattened;
    BOOL m_animating;
    FKSelectionGrabberDot * _dotView;
    //BOOL m_isDotted;
    BOOL m_navigationTransitionFlattened;
    int m_orientation;

    FKSelectionGrabberType _grabberType;
}

@property BOOL activeFlattened;
@property BOOL alertFlattened;
@property BOOL animating;
@property(unsafe_unretained, readonly) FKTextRangeView * hostView;
@property BOOL isDotted;
@property BOOL navigationTransitionFlattened;
@property int orientation;

@property (nonatomic) FKSelectionGrabberType grabberType;

//+ (id)_grabberDot;
//
//- (id)_dotView;
//- (BOOL)activeFlattened;
//- (BOOL)alertFlattened;
//- (BOOL)animating;
//- (BOOL)autoscrolled;
//- (void)canExpandAfterAlert:(id)arg1;
//- (void)canExpandAfterBecomeActive:(id)arg1;
//- (void)canExpandAfterNavigationTransition:(id)arg1;
//- (BOOL)clipDot:(struct CGRect { struct CGPoint { float x_1_1_1; float x_1_1_2; } x1; struct CGSize { float x_2_1_1; float x_2_1_2; } x2; })arg1;
//- (void)dealloc;
//- (void)didMoveToSuperview;
//- (BOOL)dotIsVisbleInDocument:(struct CGRect { struct CGPoint { float x_1_1_1; float x_1_1_2; } x1; struct CGSize { float x_2_1_1; float x_2_1_2; } x2; })arg1;
//- (void)drawRect:(struct CGRect { struct CGPoint { float x_1_1_1; float x_1_1_2; } x1; struct CGSize { float x_2_1_1; float x_2_1_2; } x2; })arg1;
//- (id)hostView;
//- (id)initWithFrame:(struct CGRect { struct CGPoint { float x_1_1_1; float x_1_1_2; } x1; struct CGSize { float x_2_1_1; float x_2_1_2; } x2; })arg1;
//- (BOOL)inputViewIsChanging;
//- (BOOL)isDotted;
//- (BOOL)isPointedDown;
//- (BOOL)isPointedLeft;
//- (BOOL)isPointedRight;
//- (BOOL)isPointedUp;
//- (BOOL)isRotating;
//- (BOOL)isScaling;
//- (BOOL)isScrolling;
//- (BOOL)isVertical;
//- (void)mustFlattenForAlert:(id)arg1;
//- (void)mustFlattenForNavigationTransition:(id)arg1;
//- (void)mustFlattenForResignActive:(id)arg1;
//- (BOOL)navigationTransitionFlattened;
//- (int)orientation;
//- (void)removeFromSuperview;
//- (void)saveDeactivationReason:(id)arg1;
//- (BOOL)scroller:(id)arg1 fullyContainSelectionRect:(struct CGRect { struct CGPoint { float x_1_1_1; float x_1_1_2; } x1; struct CGSize { float x_2_1_1; float x_2_1_2; } x2; })arg2;
//- (void)setActiveFlattened:(BOOL)arg1;
//- (void)setAlertFlattened:(BOOL)arg1;
//- (void)setAnimating:(BOOL)arg1;
//- (void)setFrame:(struct CGRect { struct CGPoint { float x_1_1_1; float x_1_1_2; } x1; struct CGSize { float x_2_1_1; float x_2_1_2; } x2; })arg1;
//- (void)setHidden:(BOOL)arg1;
//- (void)setIsDotted:(BOOL)arg1;
//- (void)setNavigationTransitionFlattened:(BOOL)arg1;
//- (void)setOrientation:(int)arg1;
//- (void)updateDot;

/*!
 Tests if a given point is inside the caret draggable area
 rectangle
 @discussion
 The draggable rectangle size is an area
 around the caret view frame.
 @param point The point to test.
 @return YES if the draggable rectangle contains the point (CGRectContainsPoint).
 */
- (BOOL)pointCanDrag:(CGPoint)point;

@end

@interface FKSelectionGrabberDot : UIView

@end


text:
package validation

// Warning values thrown by validating webhook
// https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/
const (
	// deprecatedACMEEABKeyAlgorithmField is raised when the deprecated keyAlgorithm field for an ACME issuer's external account binding (EAB) is set.
	deprecatedACMEEABKeyAlgorithmField = "ACME issuer spec field 'externalAccount.keyAlgorithm' is deprecated. The value of this field will be ignored."
)


text:
This module deals with data storage on the bots side. It provides a set of APIs to simplify storing and retrieving data. Why we need a module for this? Because the data for each run need to stay separate. The APIs in this module provide a 'safe sandbox' that allow each run to only access their data. This way developers don't have to think about keeping data separate.

This module provides 4 APIs:

1. `nutella.persist.get_json_collection_store(name)`
1. `nutella.persist.get_json_object_store(name)`
1. `nutella.persist.get_mongo_collection_store(name)`
1. `nutella.persist.get_mongo_object_store(name)`

Each one of these methods returns a "store" which is automatically persisted to a `.json` file in the filesystem (for the first two APIs) or to MongoDB (for the last two). Also, the second and fourth methods provide APIs which are better suited for dealing with a single object that is updated/changed frequently while the first and third method provide APIs to add/remove relatively static objects to/from a collection.

The APIs offered by the "stores" are extremely idiomatic of the language so please refer to the language specific documentation.

## Where is stuff stored?
Depending on the type of "store" used, data is persisted with different methods and in different locations.

- **mongo, collection**: stored as MongoDB collection named `run_id/name` inside the database `app_id`.
- **mongo, object**: stored as MongoDB document with `_id` `run_id/name`, inside the collection `run_persisted_hashes`, inside the database `app_id`.
- **file, collection**: stored as a file in `bot_dir/data/run_id/coll/name.json`
- **file, object**:  stored as a file in `bot_dir/data/run_id/obj/name.json`


text:
from __future__ import unicode_literals

from django.db import models

class People(models.Model):
    name = models.CharField(max_length=255)
    parent = models.ForeignKey('self')

class Message(models.Model):
    from_field = models.ForeignKey(People, db_column='from_id')

class PeopleData(models.Model):
    people_pk = models.ForeignKey(People, primary_key=True)
    ssn = models.CharField(max_length=11)

class PeopleMoreData(models.Model):
    people_unique = models.ForeignKey(People, unique=True)
    license = models.CharField(max_length=255)

class DigitsInColumnName(models.Model):
    all_digits = models.CharField(max_length=11, db_column='123')
    leading_digit = models.CharField(max_length=11, db_column='4extra')
    leading_digits = models.CharField(max_length=11, db_column='45extra')

class SpecialColumnName(models.Model):
    field = models.IntegerField(db_column='field')
    # Underscores
    field_field_0 = models.IntegerField(db_column='Field_')
    field_field_1 = models.IntegerField(db_column='Field__')
    field_field_2 = models.IntegerField(db_column='__field')
    # Other chars
    prc_x = models.IntegerField(db_column='prc(%) x')
    non_ascii = models.IntegerField(db_column='tamaño')

class ColumnTypes(models.Model):
    id = models.AutoField(primary_key=True)
    big_int_field = models.BigIntegerField()
    bool_field = models.BooleanField(default=False)
    null_bool_field = models.NullBooleanField()
    char_field = models.CharField(max_length=10)
    comma_separated_int_field = models.CommaSeparatedIntegerField(max_length=99)
    date_field = models.DateField()
    date_time_field = models.DateTimeField()
    decimal_field = models.DecimalField(max_digits=6, decimal_places=1)
    email_field = models.EmailField()
    file_field = models.FileField(upload_to="unused")
    file_path_field = models.FilePathField()
    float_field = models.FloatField()
    int_field = models.IntegerField()
    ip_address_field = models.IPAddressField()
    gen_ip_adress_field = models.GenericIPAddressField(protocol="ipv4")
    pos_int_field = models.PositiveIntegerField()
    pos_small_int_field = models.PositiveSmallIntegerField()
    slug_field = models.SlugField()
    small_int_field = models.SmallIntegerField()
    text_field = models.TextField()
    time_field = models.TimeField()
    url_field = models.URLField()


text:
package com.wangsong.activiti.controller;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

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

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.wangsong.activiti.service.ActivitiService;
import com.wangsong.common.controller.BaseController;
import com.wangsong.common.model.Page;
import com.wangsong.common.util.ByteToInputStream;

/**
 * 字典controller
 * @author ty
 * @date 2015年1月13日
 */
@Controller
@RequestMapping("activiti/processDefinition")
public class ProcessDefinitionController extends BaseController{

	@Autowired
	private ActivitiService processDefinitionService;

	/**
	 * 默认页面
	 */
	@RequestMapping(value="/toList")
	public String list() {
		return "activiti/processDefinition/list";
	}

	/**
	 * 获取字典json
	 */
	@RequestMapping(value="/list")
	@ResponseBody
	public Map<String, Object> list(HttpServletRequest request) {
		Page<Map<String,Object>> page = getPage(request);
		page= processDefinitionService.findProcessDefinitionList(page);
		return getEasyUIData(page);
	}

	/**
	 * 添加字典跳转
	 *
	 * @param model
	 */
	@RequestMapping(value = "/toViewImage")
	public String toViewImage(String deploymentId,String diagramResourceName,Model model) {
		model.addAttribute("deploymentId", deploymentId);
		model.addAttribute("diagramResourceName",diagramResourceName);
		return "activiti/processDefinition/viewImage";
	}

	/**
	 * 查看流程图
	 * @throws Exception
	 */
	@RequestMapping(value="/viewImage")
	public void viewImage(String deploymentId,String diagramResourceName,HttpServletResponse response) throws Exception{

		//2:获取资源文件表(act_ge_bytearray)中资源图片输入流InputStream
		byte[] bt = processDefinitionService.findImageInputStream(deploymentId,diagramResourceName);
		InputStream in =ByteToInputStream.byte2Input(bt);
		//3:从response对象获取输出流
		OutputStream out = response.getOutputStream();
		//4:将输入流中的数据读取出来,写到输出流中
		for(int b=-1;(b=in.read())!=-1;){
			out.write(b);
		}
		out.close();
		in.close();
		//将图写到页面上,用输出流写
	}

}


text:
require "fileutils"
require "cask/cache"
require "cask/quarantine"

module Cask
  # A download corresponding to a {Cask}.
  #
  # @api private
  class Download
    include Context

    attr_reader :cask

    def initialize(cask, quarantine: nil)
      @cask = cask
      @quarantine = quarantine
    end

    def fetch(verify_download_integrity: true)
      downloaded_path = begin
        downloader.fetch
        downloader.cached_location
      rescue => e
        error = CaskError.new("Download failed on Cask '#{cask}' with message: #{e}")
        error.set_backtrace e.backtrace
        raise error
      end
      quarantine(downloaded_path)
      self.verify_download_integrity(downloaded_path) if verify_download_integrity
      downloaded_path
    end

    def downloader
      @downloader ||= begin
        strategy = DownloadStrategyDetector.detect(cask.url.to_s, cask.url.using)
        strategy.new(cask.url.to_s, cask.token, cask.version, cache: Cache.path, **cask.url.specs)
      end
    end

    def time_file_size
      downloader.resolved_time_file_size
    end

    def clear_cache
      downloader.clear_cache
    end

    def cached_download
      downloader.cached_location
    end

    def basename
      downloader.basename
    end

    def verify_download_integrity(fn)
      if @cask.sha256 == :no_check
        opoo "No checksum defined for cask '#{@cask}', skipping verification."
        return
      end

      begin
        ohai "Verifying checksum for cask '#{@cask}'" if verbose?
        fn.verify_checksum(@cask.sha256)
      rescue ChecksumMissingError
        opoo <<~EOS
          Cannot verify integrity of '#{fn.basename}'.
          No checksum was provided for this cask.
          For your reference, the checksum is:
            sha256 "#{fn.sha256}"
        EOS
      end
    end

    private

    def quarantine(path)
      return if @quarantine.nil?
      return unless Quarantine.available?

      if @quarantine
        Quarantine.cask!(cask: @cask, download_path: path)
      else
        Quarantine.release!(download_path: path)
      end
    end
  end
end


text:
package boofcv.gui.image;

import boofcv.io.image.UtilImageIO;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;

/**
 * Simple JPanel for displaying buffered images.
 *
 * @author Peter Abeles
 */
public class ImagePanel extends JPanel {
	// the image being displayed
	protected BufferedImage img;
	// should it re-size the image based on the panel's size
	protected ScaleOptions scaling = ScaleOptions.DOWN;

	public double scale = 1;

	public static int saveCounter = 0;

	public ImagePanel(BufferedImage img) {
		this(img,ScaleOptions.NONE);
	}

	public ImagePanel(final BufferedImage img , ScaleOptions scaling ) {
		this.img = img;
		this.scaling = scaling;
		autoSetPreferredSize();
	}

	public ImagePanel( int width , int height ) {
		setPreferredSize(new Dimension(width,height));
	}

	public ImagePanel() {
	}

	{
		addMouseSaveImage();
	}

	/**
	 * Adds the ability to save an image using the right mouse button
	 */
	public void addMouseSaveImage() {
		addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if( e.getButton() == 2 ) {
					System.out.println("Image saved "+saveCounter);
					UtilImageIO.saveImage(img, String.format("saved_image%03d.png",saveCounter++));
				}
			}
		});
	}

	@Override
	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		Graphics2D g2 = (Graphics2D)g;

		//draw the image
		BufferedImage img = this.img;
		if (img != null) {
			if( scaling != ScaleOptions.NONE ) {
				double ratioW = (double)getWidth()/(double)img.getWidth();
				double ratioH = (double)getHeight()/(double)img.getHeight();

				scale = Math.min(ratioW,ratioH);
				if( scaling == ScaleOptions.DOWN && scale >= 1 )
					scale = 1;

				if( scale == 1 ) {
					g.drawImage(img, 0, 0, this);
				} else {
					AffineTransform tran = AffineTransform.getScaleInstance(scale, scale);
//					g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
//							RenderingHints.VALUE_ANTIALIAS_ON);
					g2.drawImage(img,tran,null);
				}

			} else {
				scale = 1;
				g2.drawImage(img, 0, 0, this);
			}
		}
	}

	/**
	 * Change the image being displayed. If panel is active then don't call unless inside the GUI thread.  Repaint()
    * is not automatically called.
	 *
	 * @param image The new image which will be displayed.
	 */
	public void setBufferedImage(BufferedImage image) {
		this.img = image;
		this.repaint();
	}

   /**
    * Change the image being displayed. Can be called at any time and automatically called repaint().
    *
    * @param image The new image which will be displayed.
    */
   public void setBufferedImageSafe(final BufferedImage image) {
      SwingUtilities.invokeLater(new Runnable() {
         @Override
         public void run() {
			 setBufferedImage(image);
         }
      });
   }

	public BufferedImage getImage() {
		return img;
	}

	public void setScaling(ScaleOptions scaling) {
		this.scaling = scaling;
	}

	public void autoSetPreferredSize() {
		setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));
	}
}


text:
<?php

class Google_Service_YouTubeAnalytics_BatchReportOutputs extends Google_Model
{
  public $downloadUrl;
  public $format;
  public $type;

  public function setDownloadUrl($downloadUrl)
  {
    $this->downloadUrl = $downloadUrl;
  }
  public function getDownloadUrl()
  {
    return $this->downloadUrl;
  }
  public function setFormat($format)
  {
    $this->format = $format;
  }
  public function getFormat()
  {
    return $this->format;
  }
  public function setType($type)
  {
    $this->type = $type;
  }
  public function getType()
  {
    return $this->type;
  }
}


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

<title>CaptureResult</title>
<meta name="date" content="2014-03-25">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

pagelyzer

Class CaptureResult

java.lang.Object

pagelyzer.CaptureResult

public class CaptureResult
extends java.lang.Object

Data structure to hold capture results

Field Summary

Fields

Modifier and Type
Field and Description

byte[]
debug

Used for debugging.

byte[]
image

byte array to hold an image

java.lang.String
srcHTML

String to hold the rendered source code

java.lang.String
viXML

String to hold the segmentation results

Constructor Summary

Constructors

Constructor and Description

CaptureResult()

Constructor

Method Summary

Methods

Modifier and Type
Method and Description

java.awt.image.BufferedImage
getBufferedImage()

Get bufferImage from byte array

void
saveDebugFile(java.lang.String to)

Writes debug image to disk

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

image

public byte[] image

byte array to hold an image

viXML

public java.lang.String viXML

String to hold the segmentation results

srcHTML

public java.lang.String srcHTML

String to hold the rendered source code

debug

public byte[] debug

Used for debugging. Intermediate images.

Constructor Detail

CaptureResult

public CaptureResult()

Constructor

Method Detail

getBufferedImage

public java.awt.image.BufferedImage getBufferedImage()

Get bufferImage from byte array

Returns:

BufferedImage

saveDebugFile

public void saveDebugFile(java.lang.String to)

Writes debug image to disk

Parameters:

to - file to save to

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
//-------------------------------------------------------------------------------
// Licensed Materials - Property of IBM
// XXXX-XXX (C) Copyright IBM Corp. 2013. All Rights Reserved.
// US Government Users Restricted Rights - Use, duplication or
// disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
//-------------------------------------------------------------------------------
//
//  IBMAbstractTrigger.h
//  IBMLocation iOS SDK

@class IBMTriggerCallback;

/**
 IBMAbstractTrigger is a class that defines methods common to all triggers. When implementing a trigger, subclass IBMAbstractTrigger and override the copyWithZone: method required by NSCopying.

 The IBMAbstractTrigger class is a provisional API.  APIs that are marked provisional are evolving and might change or be removed in future releases.
 */
@interface IBMAbstractTrigger : NSObject <NSCopying>

/**
 * The callback object whose execute() method that will be called when the trigger is activated.
 */
@property (nonatomic) IBMTriggerCallback *callback;

@end


text:
var randHex = require('./randHex');
var choice = require('./choice');

  /**
   * Returns pseudo-random guid (UUID v4)
   * IMPORTANT: it's not totally "safe" since randHex/choice uses Math.random
   * by default and sequences can be predicted in some cases. See the
   * "random/random" documentation for more info about it and how to replace
   * the default PRNG.
   */
  function guid() {
    return (
        randHex(8)+'-'+
        randHex(4)+'-'+
        // v4 UUID always contain "4" at this position to specify it was
        // randomly generated
        '4' + randHex(3) +'-'+
        // v4 UUID always contain chars [a,b,8,9] at this position
        choice(8, 9, 'a', 'b') + randHex(3)+'-'+
        randHex(12)
    );
  }
  module.exports = guid;


text:
Boolean x = true; //na verdade é traduzido para o abaixo
Boolean x = Boolean.valueOf(true);

ArrayList<Boolean> = lista = new ArrayList<>(); //válido
ArrayList<boolean> = lista = new ArrayList<>(); //inválido

void metodo(boolean x) {x = false;} //quando terminar o método, não muda nada no argumento
void metodo(Boolean x) {x = false;} //quando terminar o método, o argumento valerá false

//https://pt.stackoverflow.com/q/160914/101


text:
package org.apache.karaf.jaas.modules.properties;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.security.MessageDigest;
import java.util.HashSet;
import java.util.Map;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.FailedLoginException;
import javax.security.auth.login.LoginException;

import org.apache.commons.codec.binary.Base64;
import org.apache.felix.utils.properties.Properties;
import org.apache.karaf.jaas.boot.principal.GroupPrincipal;
import org.apache.karaf.jaas.boot.principal.RolePrincipal;
import org.apache.karaf.jaas.boot.principal.UserPrincipal;
import org.apache.karaf.jaas.modules.AbstractKarafLoginModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * JAAS Login module for user / password, based on two properties files.
 */
public class  DigestPasswordLoginModule extends AbstractKarafLoginModule {

    private static final transient Logger LOGGER = LoggerFactory.getLogger(DigestPasswordLoginModule.class);

    static final String USER_FILE = "users";

    private MessageDigest digest;

    private String usersFile;

    public void initialize(Subject sub, CallbackHandler handler, Map<String, ?> sharedState, Map<String, ?> options) {
        super.initialize(sub,handler,options);
        usersFile = (String) options.get(USER_FILE);
        if (debug) {
            LOGGER.debug("Initialized debug={} usersFile={}", debug, usersFile);
        }
    }

    public String doPasswordDigest(String nonce, String created, String password) {
        String passwdDigest = null;
        try {
            passwdDigest = doPasswordDigest(nonce, created, password.getBytes("UTF-8"));
        } catch (Exception e) {
                LOGGER.debug(e.getMessage(), e);
        }
        return passwdDigest;
    }

    public String doPasswordDigest(String nonce, String created, byte[] password) {
        String passwdDigest = null;
        try {
            byte[] b1 = nonce != null ? new Base64().decode(nonce) : new byte[0];
            byte[] b2 = created != null ? created.getBytes("UTF-8") : new byte[0];
            byte[] b3 = password;
            byte[] b4 = new byte[b1.length + b2.length + b3.length];
            int offset = 0;
            System.arraycopy(b1, 0, b4, offset, b1.length);
            offset += b1.length;

            System.arraycopy(b2, 0, b4, offset, b2.length);
            offset += b2.length;

            System.arraycopy(b3, 0, b4, offset, b3.length);

            byte[] digestBytes = generateDigest(b4);
            passwdDigest = new String(Base64.encodeBase64(digestBytes));
        } catch (Exception e) {
            LOGGER.debug(e.getMessage(), e);
        }
        return passwdDigest;
    }

    /**
     * Generate a (SHA1) digest of the input bytes. The MessageDigest instance that backs this
     * method is cached for efficiency.
     * @param inputBytes the bytes to digest
     * @return the digest of the input bytes
     */
    public synchronized byte[] generateDigest(byte[] inputBytes) {
        try {
            if (digest == null) {
                digest = MessageDigest.getInstance("SHA-1");
            }
            return digest.digest(inputBytes);
        } catch (Exception e) {
            throw new RuntimeException("Error in generating digest", e);
        }
    }

    public boolean login() throws LoginException {
        if (usersFile == null) {
            throw new LoginException("The property users may not be null");
        }
        File f = new File(usersFile);
        if (!f.exists()) {
            throw new LoginException("Users file not found at " + f);
        }

        Properties users;
        try {
            users = new Properties(f);
        } catch (IOException ioe) {
            throw new LoginException("Unable to load user properties file " + f);
        }

        Callback[] callbacks = new Callback[2];

        callbacks[0] = new NameCallback("Username: ");
        callbacks[1] = new PasswordCallback("Password: ", false);
        if (callbackHandler != null) {
            try {
                callbackHandler.handle(callbacks);
            } catch (IOException ioe) {
                throw new LoginException(ioe.getMessage());
            } catch (UnsupportedCallbackException uce) {
                throw new LoginException(uce.getMessage() + " not available to obtain information from user");
            }
        }
        // user callback get value
        if (((NameCallback) callbacks[0]).getName() == null) {
            throw new LoginException("Username can not be null");
        }
        user = ((NameCallback) callbacks[0]).getName();
        if (user.startsWith(PropertiesBackingEngine.GROUP_PREFIX)) {
            // you can't log in under a group name
            throw new FailedLoginException("login failed");
        }

        // password callback get value
        if (((PasswordCallback) callbacks[1]).getPassword() == null) {
            throw new LoginException("Password can not be null");
        }
        String password = new String(((PasswordCallback) callbacks[1]).getPassword());

        // user infos container read from the users properties file
        String userInfos = null;
        try {
            userInfos = users.get(user);
        } catch (NullPointerException e) {
            //error handled in the next statement
        }
        if (userInfos == null) {
        	if (!this.detailedLoginExcepion) {
        		throw new FailedLoginException("login failed");
        	} else {
        		throw new FailedLoginException("User " + user + " does not exist");
        	}
        }

        // the password is in the first position
        String[] infos = userInfos.split(",");
        String storedPassword = infos[0];

        CallbackHandler myCallbackHandler = null;

        try {
            Field field = callbackHandler.getClass().getDeclaredField("ch");
            field.setAccessible(true);
            myCallbackHandler = (CallbackHandler) field.get(callbackHandler);
        } catch (Exception e) {
            throw new LoginException("Unable to load underlying callback handler");
        }

        if (myCallbackHandler instanceof NameDigestPasswordCallbackHandler) {
            NameDigestPasswordCallbackHandler digestCallbackHandler = (NameDigestPasswordCallbackHandler)myCallbackHandler;
            storedPassword = doPasswordDigest(digestCallbackHandler.getNonce(),
                                                            digestCallbackHandler.getCreatedTime(),
                                                            storedPassword);
        }

        // check the provided password
        if (!checkPassword(password, storedPassword)) {
        	if (!this.detailedLoginExcepion) {
        		throw new FailedLoginException("login failed");
        	} else {
        		throw new FailedLoginException("Password for " + user + " does not match");
        	}
        }

        principals = new HashSet<>();
        principals.add(new UserPrincipal(user));
        for (int i = 1; i < infos.length; i++) {
            if (infos[i].trim().startsWith(PropertiesBackingEngine.GROUP_PREFIX)) {
                // it's a group reference
                principals.add(new GroupPrincipal(infos[i].trim().substring(PropertiesBackingEngine.GROUP_PREFIX.length())));
                String groupInfo = users.get(infos[i].trim());
                if (groupInfo != null) {
                    String[] roles = groupInfo.split(",");
                    for (int j = 1; j < roles.length; j++) {
                        principals.add(new RolePrincipal(roles[j].trim()));
                    }
                }
            } else {
                // it's an user reference
                principals.add(new RolePrincipal(infos[i].trim()));
            }
        }

        users.clear();

        if (debug) {
            LOGGER.debug("Successfully logged in {}", user);
        }
        return true;
    }

    public boolean abort() throws LoginException {
        clear();
        if (debug) {
            LOGGER.debug("abort");
        }
        return true;
    }

    public boolean logout() throws LoginException {
        subject.getPrincipals().removeAll(principals);
        principals.clear();
        if (debug) {
            LOGGER.debug("logout");
        }
        return true;
    }

}


text:
<!doctype html>

<meta charset="utf-8">
<link rel="help" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1740702">
<link rel="match" href="../reference/ref-filled-green-100px-square-only.html">

Test passes if there is a filled green square.


text:
package main

import (
	"os"
	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/docker/infrakit/pkg/cli"
	"github.com/docker/infrakit/pkg/discovery/local"
	"github.com/docker/infrakit/pkg/plugin"
	"github.com/docker/infrakit/pkg/plugin/group"
	metadata_plugin "github.com/docker/infrakit/pkg/plugin/metadata"
	flavor_client "github.com/docker/infrakit/pkg/rpc/flavor"
	group_server "github.com/docker/infrakit/pkg/rpc/group"
	instance_client "github.com/docker/infrakit/pkg/rpc/instance"
	metadata_rpc "github.com/docker/infrakit/pkg/rpc/metadata"
	"github.com/docker/infrakit/pkg/spi/flavor"
	"github.com/docker/infrakit/pkg/spi/instance"
	"github.com/docker/infrakit/pkg/types"
	"github.com/spf13/cobra"
)

func main() {

	cmd := &cobra.Command{
		Use:   os.Args[0],
		Short: "Group server",
	}
	name := cmd.Flags().String("name", "group", "Plugin name to advertise for discovery")
	logLevel := cmd.Flags().Int("log", cli.DefaultLogLevel, "Logging level. 0 is least verbose. Max is 5")
	pollInterval := cmd.Flags().Duration("poll-interval", 10*time.Second, "Group polling interval")
	maxParallelNum := cmd.Flags().Uint("max-parallel", 0, "Max number of parallel instance operation (create, delete). (Default: 0 = no limit)")
	cmd.RunE = func(c *cobra.Command, args []string) error {

		cli.SetLogLevel(*logLevel)

		plugins, err := local.NewPluginDiscovery()
		if err != nil {
			return err
		}

		instancePluginLookup := func(n plugin.Name) (instance.Plugin, error) {
			endpoint, err := plugins.Find(n)
			if err != nil {
				return nil, err
			}
			return instance_client.NewClient(n, endpoint.Address)
		}

		flavorPluginLookup := func(n plugin.Name) (flavor.Plugin, error) {
			endpoint, err := plugins.Find(n)
			if err != nil {
				return nil, err
			}
			return flavor_client.NewClient(n, endpoint.Address)
		}

		groupPlugin := group.NewGroupPlugin(instancePluginLookup, flavorPluginLookup, *pollInterval, *maxParallelNum)

		// Start a poller to load the snapshot and make that available as metadata
		updateSnapshot := make(chan func(map[string]interface{}))
		stopSnapshot := make(chan struct{})
		go func() {
			tick := time.Tick(1 * time.Second)
			tick30 := time.Tick(30 * time.Second)
			for {
				select {
				case <-tick:
					// load the specs for the groups
					snapshot := map[string]interface{}{}
					if specs, err := groupPlugin.InspectGroups(); err == nil {
						for _, spec := range specs {
							snapshot[string(spec.ID)] = spec
						}
					} else {
						snapshot["err"] = err
					}

					updateSnapshot <- func(view map[string]interface{}) {
						types.Put([]string{"specs"}, snapshot, view)
					}

				case <-tick30:
					snapshot := map[string]interface{}{}
					// describe the groups and expose info as metadata
					if specs, err := groupPlugin.InspectGroups(); err == nil {
						for _, spec := range specs {
							if description, err := groupPlugin.DescribeGroup(spec.ID); err == nil {
								snapshot[string(spec.ID)] = description
							} else {
								snapshot[string(spec.ID)] = err
							}
						}
					} else {
						snapshot["err"] = err
					}

					updateSnapshot <- func(view map[string]interface{}) {
						types.Put([]string{"groups"}, snapshot, view)
					}

				case <-stopSnapshot:
					log.Infoln("Snapshot updater stopped")
					return
				}
			}
		}()

		cli.RunPlugin(*name,
			metadata_rpc.PluginServer(metadata_plugin.NewPluginFromChannel(updateSnapshot)),
			group_server.PluginServer(groupPlugin))

		close(stopSnapshot)

		return nil
	}

	cmd.AddCommand(cli.VersionCommand())

	err := cmd.Execute()
	if err != nil {
		log.Error(err)
		os.Exit(1)
	}
}


text:
<add>
<doc>
<field name="uid">doi:10.1371/journal.pntd.0001551</field>
<field name="doi">10.1371/journal.pntd.0001551</field>
<field name="data_source">PLoS Open Access XML</field>
<field name="authors">Karina M. Monteiro, Mateus B. Cardoso, Cristian Follmer, Nádya P. da Silveira, Daiani M. Vargas, Elliot W. Kitajima, Arnaldo Zaha, Henrique B. Ferreira</field>
<field name="title">Echinococcus granulosus Antigen B Structure: Subunit Composition and Oligomeric States</field>
<field name="journal">PLoS Neglected Tropical Diseases</field>
<field name="year">2012</field>
<field name="volume">6</field>
<field name="number">3</field>
<field name="pages">e1551</field>
<field name="license">Creative Commons Attribution (CC BY)</field>
<field name="license_url">http://creativecommons.org/licenses/by/3.0/</field>
<field name="fulltext">
Abstract

Background

Antigen B (AgB) is the major protein secreted by the Echinococcus granulosus
metacestode and is involved in key host-parasite interactions during
infection. The full comprehension of AgB functions depends on the elucidation
of several structural aspects that remain unknown, such as its subunit
composition and oligomeric states.

Methodology/Principal Findings

The subunit composition of E. granulosus AgB oligomers from individual bovine
and human cysts was assessed by mass spectrometry associated with
electrophoretic analysis. AgB8/1, AgB8/2, AgB8/3 and AgB8/4 subunits were
identified in all samples analyzed, and an AgB8/2 variant (AgB8/2v8) was found
in one bovine sample. The exponentially modified protein abundance index
(emPAI) was used to estimate the relative abundance of the AgB subunits,
revealing that AgB8/1 subunit was relatively overrepresented in all samples.
The abundance of AgB8/3 subunit varied between bovine and human cysts. The
oligomeric states formed by E. granulosus AgB and recombinant subunits
available, rAgB8/1, rAgB8/2 and rAgB8/3, were characterized by native PAGE,
light scattering and microscopy. Recombinant subunits showed markedly distinct
oligomerization behaviors, forming oligomers with a maximum size relation of
rAgB8/3>rAgB8/2>rAgB8/1. Moreover, the oligomeric states formed by rAgB8/3
subunit were more similar to those observed for AgB purified from hydatid
fluid. Pressure-induced dissociation experiments demonstrated that the
molecular assemblies formed by the more aggregative subunits, rAgB8/2 and
rAgB8/3, also display higher structural stability.

Conclusions/Significance

For the first time, AgB subunit composition was analyzed in samples from
single hydatid cysts, revealing qualitative and quantitative differences
between samples. We showed that AgB oligomers are formed by different
subunits, which have distinct abundances and oligomerization properties.
Overall, our findings have significantly contributed to increase the current
knowledge on AgB expression and structure, highlighting issues that may help
to understand the parasite adaptive response during chronic infection.

Author Summary

Antigen B (AgB) is the major secretory protein of the Echinococcus granulosus
hydatid cyst, the causative agent of cystic hydatid disease. Structurally, AgB
is a multisubunit protein formed by 8-kDa subunits, but it is not known which
subunits are secreted by a single parasite (cyst) and how they interact in the
formation of distinct AgB oligomeric states. Here, we investigated AgB subunit
composition and oligomeric states in individual samples from bovine and human
cysts. We identified AgB8/1, AgB8/2, AgB8/3 and AgB8/4 subunits in AgB
oligomers of all samples analyzed. Quantitative and qualitative differences in
the expression of AgB subunits were observed within and between samples. Using
recombinant subunits as models, we showed that AgB subunits form distinct
oligomeric states, with a rAgB8/3>rAgB8/2>rAgB8/1 maximum size relation. We
also demonstrated by different experimental approaches that rAgB8/3 oligomers
are more similar, both in size and morphology, to those observed for E.
granulosus AgB. Overall, we provided experimental evidences that </field></doc>
</add>


text:
package jetbrains.buildserver.sonarplugin.manager.projectsettings;

import jetbrains.buildserver.sonarplugin.manager.SQSInfo;
import org.jetbrains.annotations.Nullable;

import java.util.UUID;

/**
 * Created by Andrey Titov on 7/10/14.
 */
public class XMLBasedSQSInfoHelper {
    private XMLBasedSQSInfoHelper() {
    }

    public static SQSInfo createServerInfo(@Nullable final String id,
                                           @Nullable final String name,
                                           @Nullable final String url,
                                           @Nullable final String login,
                                           @Nullable final String password,
                                           @Nullable final String dbUrl,
                                           @Nullable final String dbUsername,
                                           @Nullable final String dbPassword) {
        return new XMLBasedSQSInfo(id == null ? UUID.randomUUID().toString() : id, name, url, login, password, dbUrl, dbUsername, dbPassword);
    }

    public static SQSInfo createServerInfo(@Nullable final String id) {
        return new XMLBasedSQSInfo(id == null ? UUID.randomUUID().toString() : id, null, null, null, null, null, null, null);
    }
}


text:
export interface Organization {
    Name: string;
    DisplayName: string; // DEPRECATED
    PlanName: string;
    VPNPlanName: string;
    TwoFactorGracePeriod: number; // If non-null, number of seconds until 2FA setup enforced
    Theme: string;
    ToMigrate: 0 | 1;
    BrokenSKL: 0 | 1;
    Email: string;
    MaxDomains: number;
    MaxAddresses: number;
    MaxCalendars: number;
    MaxSpace: number;
    MaxMembers: number;
    MaxVPN: number;
    Features: number; // bits: 1 = catch-all addresses
    Flags: number; // bits: 1 = loyalty, 2 = covid, 64 = dissident, 128 = proton
    UsedDomains: number;
    UsedCalendars: number;
    UsedAddresses: number;
    UsedSpace: number;
    AssignedSpace: number;
    UsedMembers: number;
    UsedVPN: number;
    HasKeys: number;
    CreateTime: number;
    LoyaltyCounter: number;
    LoyaltyIncrementTime: number;
    BonusDomains: number;
    BonusAddresses: number;
    BonusSpace: number;
    BonusMembers: number;
    BonusVPN: number;
}


text:
package toberefactored.parser;

import java.util.Map;

import org.neo4art.domain.Coordinates;
import org.neo4art.domain.ReligiousBuilding;
import org.neo4art.importer.wikipedia.parser.util.WikipediaInfoboxParserUtils;

import toberefactored.parser.util.InfoboxNameParser;
import toberefactored.parser.util.InfoboxUrlParser;

/**
 *
 * @author Mattia Zaratin
 * @since 30 Apr 2015
 */
public class WikipediaReligiousBuildingShintoShrineInfobox
{

  public static final String NAME   = "name";
  public static final String LATD   = "latd";
  public static final String LATM   = "latm";
  public static final String LATS   = "lats";
  public static final String LATNS  = "latNS";
  public static final String LONGD  = "longd";
  public static final String LONGM  = "longm";
  public static final String LONGS  = "longs";
  public static final String LONGEW = "longEW";
  public static final String IMAGE  = "image";
  public static final String STYLE  = "infobox";

  /**
   *
   * @param text
   * @return
   */
  public static ReligiousBuilding parse(String text)
  {
    ReligiousBuilding shintoShrine = new ReligiousBuilding();
    Coordinates coordinates = new Coordinates();

    Map<String, String> map = WikipediaInfoboxParserUtils.asMap(text);

    for (String key : map.keySet())
    {
      switch (key)
      {
        case NAME:
          shintoShrine.setName(InfoboxNameParser.infoboxBuildingName(map.get(key)));
          break;
        case IMAGE:
          shintoShrine.setImage(InfoboxUrlParser.infoboxUrl(map.get(key)));
          break;
        case LATD:
          coordinates.setLatD(Double.parseDouble(map.get(key)));
          break;
        case LATM:
          coordinates.setLatM(Double.parseDouble(map.get(key)));
          break;
        case LATS:
          coordinates.setLatS(Double.parseDouble(map.get(key)));
          break;
        case LATNS:
          coordinates.setLatNS(map.get(key));
          break;
        case LONGD:
          coordinates.setLongD(Double.parseDouble(map.get(key)));
          break;
        case LONGM:
          coordinates.setLongM(Double.parseDouble(map.get(key)));
          break;
        case LONGS:
          coordinates.setLongS(Double.parseDouble(map.get(key)));
          break;
        case LONGEW:
          coordinates.setLongEW(map.get(key));
          break;
      }

      shintoShrine.setCoordinates(coordinates);
    }

    return shintoShrine;
  }
}