text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <base data-ice="baseUrl" href="../../../">
  <title data-ice="title">src/lib/rtree.js | Gisplay API Documentation API Document</title>
  <link type="text/css" rel="stylesheet" href="css/style.css">
  <link type="text/css" rel="stylesheet" href="css/prettify-tomorrow.css">

  Home

  Reference
  Source
  Test

    <input class="search-input">

Gisplay
CAesthetic

CFeature

CGisplay

CGisplayOptions

CLegend

Gisplay/Helpers
CColorBrewer

CWebGLUtils

Gisplay/Maps
CChangeMap

CChoropleth

CDotMap

CMap

CProportionalSymbolsMap

Gisplay/Maps/Background Maps
CBGMapBingMaps

CBGMapGoogleMaps

CBGMapHereMaps

CBGMapMapBox

CBGMapWrapper

src/lib/rtree.js

/**
 * Exports a `PolygonLookup` constructor, which constructs a data-structure for
 * quickly finding the polygon that a point intersects in a (potentially very
 * large) set.
 */

var pointInPolygon = function (point, vs) {
    // ray-casting algorithm based on
    // http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html

    var x = point[0], y = point[1];

    var inside = false;
    for (var i = 0, j = vs.length - 1; i < vs.length; j = i++) {
        var xi = vs[i][0], yi = vs[i][1];
        var xj = vs[j][0], yj = vs[j][1];

        var intersect = ((yi > y) != (yj > y))
            && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
        if (intersect) inside = !inside;
    }

    return inside;
};

/**
 * @property {rbush} rtree A spatial index for `this.polygons`.
 * @property {object} polgons A GeoJSON feature collection.
 *
 * @param {object} [featureCollection] An optional GeoJSON feature collection
 *    to pass to `loadFeatureCollection()`.
 */
function PolygonLookup(featureCollection) {
    this.search = function search(x, y) {
        var bboxes = this.rtree.search([x, y, x, y]);
        var pt = [x, y];
        for (var ind = 0; ind < bboxes.length; ind++) {
            var polyObj = this.polygons[bboxes[ind].polyId];
            var polyCoords = polyObj.geometry.coordinates[0];
            if (pointInPolygon(pt, polyCoords)) {
                var inHole = false;
                for (var subPolyInd = 1; subPolyInd < polyObj.geometry.coordinates.length; subPolyInd++) {
                    if (pointInPolygon(pt, polyObj.geometry.coordinates[subPolyInd])) {
                        inHole = true;
                        break;
                    }
                }

                if (!inHole) {
                    return polyObj;
                }
            }
        }
    };

    this.loadFeatureCollection = function loadFeatureCollection(collection) {
        var bboxes = [];
        var polygons = [];
        var polyId = 0;

        function getBoundingBox(poly) {
            var firstPt = poly[0];
            var bbox = [
                firstPt[0], firstPt[1],
                firstPt[0], firstPt[1]
            ];

            for (var ind = 1; ind < poly.length; ind++) {
                var pt = poly[ind];

                var x = pt[0];
                if (x < bbox[0]) {
                    bbox[0] = x;
                }
                else if (x > bbox[2]) {
                    bbox[2] = x;
                }

                var y = pt[1];
                if (y < bbox[1]) {
                    bbox[1] = y;
                }
                else if (y > bbox[3]) {
                    bbox[3] = y;
                }
            }

            return bbox;
        }

        function indexPolygon(poly) {
            polygons.push(poly);
            var bbox = getBoundingBox(poly.geometry.coordinates[0]);
            bbox.polyId = polyId++;
            bboxes.push(bbox);
        }

        function indexFeature(poly) {
            if (poly.geometry.coordinates[0] !== undefined &&
                poly.geometry.coordinates[0].length > 0) {
                switch (poly.geometry.type) {
                    case 'Polygon':
                        indexPolygon(poly);
                        break;

                    case 'MultiPolygon':
                        var childPolys = poly.geometry.coordinates;
                        for (var ind = 0; ind < childPolys.length; ind++) {
                            var childPoly = {
                                type: 'Feature',
                                properties: poly.properties,
                                geometry: {
                                    type: 'Polygon',
                                    coordinates: childPolys[ind]
                                }
                            };
                            indexPolygon(childPoly);
                        }
                        break;
                }
            }
        }

        var rBush = (function rbush() {

            this.RBush = function (maxEntries, format) {

                // jshint newcap: false, validthis: true
                if (!(this instanceof RBush)) return new RBush(maxEntries, format);

                // max entries in a node is 9 by default; min node fill is 40% for best performance
                this._maxEntries = Math.max(4, maxEntries || 9);
                this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4));

                if (format) {
                    this._initFormat(format);
                }

                this.clear();
            }

            RBush.prototype = {

                all: function () {
                    return this._all(this.data, []);
                },

                search: function (bbox) {

                    var node = this.data,
                        result = [],
                        toBBox = this.toBBox;

                    if (!intersects(bbox, node.bbox)) return result;

                    var nodesToSearch = [],
                        i, len, child, childBBox;

                    while (node) {
                        for (i = 0, len = node.children.length; i < len; i++) {

                            child = node.children[i];
                            childBBox = node.leaf ? toBBox(child) : child.bbox;

                            if (intersects(bbox, childBBox)) {
                                if (node.leaf) result.push(child);
                                else if (contains(bbox, childBBox)) this._all(child, result);
                                else nodesToSearch.push(child);
                            }
                        }
                        node = nodesToSearch.pop();
                    }

                    return result;
                },

                load: function (data) {
                    if (!(data && data.length)) return this;

                    if (data.length < this._minEntries) {
                        for (var i = 0, len = data.length; i < len; i++) {
                            this.insert(data[i]);
                        }
                        return this;
                    }

                    // recursively build the tree with the given data from stratch using OMT algorithm
                    var node = this._build(data.slice(), 0, data.length - 1, 0);

                    if (!this.data.children.length) {
                        // save as is if tree is empty
                        this.data = node;

                    } else if (this.data.height === node.height) {
                        // split root if trees have the same height
                        this._splitRoot(this.data, node);

                    } else {
                        if (this.data.height < node.height) {
                            // swap trees if inserted one is bigger
                            var tmpNode = this.data;
                            this.data = node;
                            node = tmpNode;
                        }

                        // insert the small tree into the large tree at appropriate level
                        this._insert(node, this.data.height - node.height - 1, true);
                    }

                    return this;
                },

                insert: function (item) {
                    if (item) this._insert(item, this.data.height - 1);
                    return this;
                },

                clear: function () {
                    this.data = {
                        children: [],
                        height: 1,
                        bbox: empty(),
                        leaf: true
                    };
                    return this;
                },

                remove: function (item) {
                    if (!item) return this;

                    var node = this.data,
                        bbox = this.toBBox(item),
                        path = [],
                        indexes = [],
                        i, parent, index, goingUp;

                    // depth-first iterative tree traversal
                    while (node || path.length) {

                        if (!node) { // go up
                            node = path.pop();
                            parent = path[path.length - 1];
                            i = indexes.pop();
                            goingUp = true;
                        }

                        if (node.leaf) { // check current node
                            index = node.children.indexOf(item);

                            if (index !== -1) {
                                // item found, remove the item and condense tree upwards
                                node.children.splice(index, 1);
                                path.push(node);
                                this._condense(path);
                                return this;
                            }
                        }

                        if (!goingUp && !node.leaf && contains(node.bbox, bbox)) { // go down
                            path.push(node);
                            indexes.push(i);
                            i = 0;
                            parent = node;
                            node = node.children[0];

                        } else if (parent) { // go right
                            i++;
                            node = parent.children[i];
                            goingUp = false;

                        } else node = null; // nothing found
                    }

                    return this;
                },

                toBBox: function (item) { return item; },

                compareMinX: function (a, b) { return a[0] - b[0]; },
                compareMinY: function (a, b) { return a[1] - b[1]; },

                toJSON: function () { return this.data; },

                fromJSON: function (data) {
                    this.data = data;
                    return this;
                },

                _all: function (node, result) {
                    var nodesToSearch = [];
                    while (node) {
                        if (node.leaf) result.push.apply(result, node.children);
                        else nodesToSearch.push.apply(nodesToSearch, node.children);

                        node = nodesToSearch.pop();
                    }
                    return result;
                },

                _build: function (items, left, right, height) {

                    var N = right - left + 1,
                        M = this._maxEntries,
                        node;

                    if (N <= M) {
                        // reached leaf level; return leaf
                        node = {
                            children: items.slice(left, right + 1),
                            height: 1,
                            bbox: null,
                            leaf: true
                        };
                        calcBBox(node, this.toBBox);
                        return node;
                    }

                    if (!height) {
                        // target height of the bulk-loaded tree
                        height = Math.ceil(Math.log(N) / Math.log(M));

                        // target number of root entries to maximize storage utilization
                        M = Math.ceil(N / Math.pow(M, height - 1));
                    }

                    // TODO eliminate recursion?

                    node = {
                        children: [],
                        height: height,
                        bbox: null
                    };

                    // split the items into M mostly square tiles

                    var N2 = Math.ceil(N / M),
                        N1 = N2 * Math.ceil(Math.sqrt(M)),
                        i, j, right2, right3;

                    multiSelect(items, left, right, N1, this.compareMinX);

                    for (i = left; i <= right; i += N1) {

                        right2 = Math.min(i + N1 - 1, right);

                        multiSelect(items, i, right2, N2, this.compareMinY);

                        for (j = i; j <= right2; j += N2) {

                            right3 = Math.min(j + N2 - 1, right2);

                            // pack each entry recursively
                            node.children.push(this._build(items, j, right3, height - 1));
                        }
                    }

                    calcBBox(node, this.toBBox);

                    return node;
                },

                _chooseSubtree: function (bbox, node, level, path) {

                    var i, len, child, targetNode, area, enlargement, minArea, minEnlargement;

                    while (true) {
                        path.push(node);

                        if (node.leaf || path.length - 1 === level) break;

                        minArea = minEnlargement = Infinity;

                        for (i = 0, len = node.children.length; i < len; i++) {
                            child = node.children[i];
                            area = bboxArea(child.bbox);
                            enlargement = enlargedArea(bbox, child.bbox) - area;

                            // choose entry with the least area enlargement
                            if (enlargement < minEnlargement) {
                                minEnlargement = enlargement;
                                minArea = area < minArea ? area : minArea;
                                targetNode = child;

                            } else if (enlargement === minEnlargement) {
                                // otherwise choose one with the smallest area
                                if (area < minArea) {
                                    minArea = area;
                                    targetNode = child;
                                }
                            }
                        }

                        node = targetNode;
                    }

                    return node;
                },

                _insert: function (item, level, isNode) {

                    var toBBox = this.toBBox,
                        bbox = isNode ? item.bbox : toBBox(item),
                        insertPath = [];

                    // find the best node for accommodating the item, saving all nodes along the path too
                    var node = this._chooseSubtree(bbox, this.data, level, insertPath);

                    // put the item into the node
                    node.children.push(item);
                    extend(node.bbox, bbox);

                    // split on node overflow; propagate upwards if necessary
                    while (level >= 0) {
                        if (insertPath[level].children.length > this._maxEntries) {
                            this._split(insertPath, level);
                            level--;
                        } else break;
                    }

                    // adjust bboxes along the insertion path
                    this._adjustParentBBoxes(bbox, insertPath, level);
                },

                // split overflowed node into two
                _split: function (insertPath, level) {

                    var node = insertPath[level],
                        M = node.children.length,
                        m = this._minEntries;

                    this._chooseSplitAxis(node, m, M);

                    var newNode = {
                        children: node.children.splice(this._chooseSplitIndex(node, m, M)),
                        height: node.height
                    };

                    if (node.leaf) newNode.leaf = true;

                    calcBBox(node, this.toBBox);
                    calcBBox(newNode, this.toBBox);

                    if (level) insertPath[level - 1].children.push(newNode);
                    else this._splitRoot(node, newNode);
                },

                _splitRoot: function (node, newNode) {
                    // split root node
                    this.data = {
                        children: [node, newNode],
                        height: node.height + 1
                    };
                    calcBBox(this.data, this.toBBox);
                },

                _chooseSplitIndex: function (node, m, M) {

                    var i, bbox1, bbox2, overlap, area, minOverlap, minArea, index;

                    minOverlap = minArea = Infinity;

                    for (i = m; i <= M - m; i++) {
                        bbox1 = distBBox(node, 0, i, this.toBBox);
                        bbox2 = distBBox(node, i, M, this.toBBox);

                        overlap = intersectionArea(bbox1, bbox2);
                        area = bboxArea(bbox1) + bboxArea(bbox2);

                        // choose distribution with minimum overlap
                        if (overlap < minOverlap) {
                            minOverlap = overlap;
                            index = i;

                            minArea = area < minArea ? area : minArea;

                        } else if (overlap === minOverlap) {
                            // otherwise choose distribution with minimum area
                            if (area < minArea) {
                                minArea = area;
                                index = i;
                            }
                        }
                    }

                    return index;
                },

                // sorts node children by the best axis for split
                _chooseSplitAxis: function (node, m, M) {

                    var compareMinX = node.leaf ? this.compareMinX : compareNodeMinX,
                        compareMinY = node.leaf ? this.compareMinY : compareNodeMinY,
                        xMargin = this._allDistMargin(node, m, M, compareMinX),
                        yMargin = this._allDistMargin(node, m, M, compareMinY);

                    // if total distributions margin value is minimal for x, sort by minX,
                    // otherwise it's already sorted by minY
                    if (xMargin < yMargin) node.children.sort(compareMinX);
                },

                // total margin of all possible split distributions where each node is at least m full
                _allDistMargin: function (node, m, M, compare) {

                    node.children.sort(compare);

                    var toBBox = this.toBBox,
                        leftBBox = distBBox(node, 0, m, toBBox),
                        rightBBox = distBBox(node, M - m, M, toBBox),
                        margin = bboxMargin(leftBBox) + bboxMargin(rightBBox),
                        i, child;

                    for (i = m; i < M - m; i++) {
                        child = node.children[i];
                        extend(leftBBox, node.leaf ? toBBox(child) : child.bbox);
                        margin += bboxMargin(leftBBox);
                    }

                    for (i = M - m - 1; i >= m; i--) {
                        child = node.children[i];
                        extend(rightBBox, node.leaf ? toBBox(child) : child.bbox);
                        margin += bboxMargin(rightBBox);
                    }

                    return margin;
                },

                _adjustParentBBoxes: function (bbox, path, level) {
                    // adjust bboxes along the given tree path
                    for (var i = level; i >= 0; i--) {
                        extend(path[i].bbox, bbox);
                    }
                },

                _condense: function (path) {
                    // go through the path, removing empty nodes and updating bboxes
                    for (var i = path.length - 1, siblings; i >= 0; i--) {
                        if (path[i].children.length === 0) {
                            if (i > 0) {
                                siblings = path[i - 1].children;
                                siblings.splice(siblings.indexOf(path[i]), 1);

                            } else this.clear();

                        } else calcBBox(path[i], this.toBBox);
                    }
                },

                _initFormat: function (format) {
                    // data format (minX, minY, maxX, maxY accessors)

                    // uses eval-type function compilation instead of just accepting a toBBox function
                    // because the algorithms are very sensitive to sorting functions performance,
                    // so they should be dead simple and without inner calls

                    // jshint evil: true

                    var compareArr = ['return a', ' - b', ';'];

                    this.compareMinX = new Function('a', 'b', compareArr.join(format[0]));
                    this.compareMinY = new Function('a', 'b', compareArr.join(format[1]));

                    this.toBBox = new Function('a', 'return [a' + format.join(', a') + '];');
                }
            };

            // calculate node's bbox from bboxes of its children
            function calcBBox(node, toBBox) {
                node.bbox = distBBox(node, 0, node.children.length, toBBox);
            }

            // min bounding rectangle of node children from k to p-1
            function distBBox(node, k, p, toBBox) {
                var bbox = empty();

                for (var i = k, child; i < p; i++) {
                    child = node.children[i];
                    extend(bbox, node.leaf ? toBBox(child) : child.bbox);
                }

                return bbox;
            }

            function empty() { return [Infinity, Infinity, -Infinity, -Infinity]; }

            function extend(a, b) {
                a[0] = Math.min(a[0], b[0]);
                a[1] = Math.min(a[1], b[1]);
                a[2] = Math.max(a[2], b[2]);
                a[3] = Math.max(a[3], b[3]);
                return a;
            }

            function compareNodeMinX(a, b) { return a.bbox[0] - b.bbox[0]; }
            function compareNodeMinY(a, b) { return a.bbox[1] - b.bbox[1]; }

            function bboxArea(a) { return (a[2] - a[0]) * (a[3] - a[1]); }
            function bboxMargin(a) { return (a[2] - a[0]) + (a[3] - a[1]); }

            function enlargedArea(a, b) {
                return (Math.max(b[2], a[2]) - Math.min(b[0], a[0])) *
                    (Math.max(b[3], a[3]) - Math.min(b[1], a[1]));
            }

            function intersectionArea(a, b) {
                var minX = Math.max(a[0], b[0]),
                    minY = Math.max(a[1], b[1]),
                    maxX = Math.min(a[2], b[2]),
                    maxY = Math.min(a[3], b[3]);

                return Math.max(0, maxX - minX) *
                    Math.max(0, maxY - minY);
            }

            function contains(a, b) {
                return a[0] <= b[0] &&
                    a[1] <= b[1] &&
                    b[2] <= a[2] &&
                    b[3] <= a[3];
            }

            function intersects(a, b) {
                return b[0] <= a[2] &&
                    b[1] <= a[3] &&
                    b[2] >= a[0] &&
                    b[3] >= a[1];
            }

            // sort an array so that items come in groups of n unsorted items, with groups sorted between each other;
            // combines selection algorithm with binary divide & conquer approach

            function multiSelect(arr, left, right, n, compare) {
                var stack = [left, right],
                    mid;

                while (stack.length) {
                    right = stack.pop();
                    left = stack.pop();

                    if (right - left <= n) continue;

                    mid = left + Math.ceil((right - left) / n / 2) * n;
                    select(arr, left, right, mid, compare);

                    stack.push(left, mid, mid, right);
                }
            }

            // sort array between left and right (inclusive) so that the smallest k elements come first (unordered)
            function select(arr, left, right, k, compare) {
                var n, i, z, s, sd, newLeft, newRight, t, j;

                while (right > left) {
                    if (right - left > 600) {
                        n = right - left + 1;
                        i = k - left + 1;
                        z = Math.log(n);
                        s = 0.5 * Math.exp(2 * z / 3);
                        sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (i - n / 2 < 0 ? -1 : 1);
                        newLeft = Math.max(left, Math.floor(k - i * s / n + sd));
                        newRight = Math.min(right, Math.floor(k + (n - i) * s / n + sd));
                        select(arr, newLeft, newRight, k, compare);
                    }

                    t = arr[k];
                    i = left;
                    j = right;

                    swap(arr, left, k);
                    if (compare(arr[right], t) > 0) swap(arr, left, right);

                    while (i < j) {
                        swap(arr, i, j);
                        i++;
                        j--;
                        while (compare(arr[i], t) < 0) i++;
                        while (compare(arr[j], t) > 0) j--;
                    }

                    if (compare(arr[left], t) === 0) swap(arr, left, j);
                    else {
                        j++;
                        swap(arr, j, right);
                    }

                    if (j <= k) left = j + 1;
                    if (k <= j) right = j - 1;
                }
            }

            function swap(arr, i, j) {
                var tmp = arr[i];
                arr[i] = arr[j];
                arr[j] = tmp;
            }

            // export as AMD/CommonJS module or global variable
            if (typeof define === 'function' && define.amd) define(function () { return rbush; });
            else if (typeof module !== 'undefined') module.exports = rbush;
            else if (typeof self !== 'undefined') self.rbush = rbush;
            else window.rbush = rbush;

        })();

        collection.features.forEach(indexFeature);
        this.rtree = (new rbush()).RBush().load(bboxes);
        this.polygons = polygons;
    };

    if (featureCollection !== undefined) {
        this.loadFeatureCollection(featureCollection);
    }
}

/**
 * Find the polygon that a point intersects. Execute a bounding-box search to
 * narrow down the candidate polygons to a small subset, and then perform
 * additional point-in-polygon intersections to resolve any ambiguities.
 *
 * @param {number} x The x-coordinate of the point.
 * @param {number} y The y-coordinate of the point.
 * @return {undefined|object} If one or more bounding box intersections are
 *    found, return the first polygon that intersects (`x`, `y`); otherwise,
 *    `undefined`.
 *
PolygonLookup.prototype.search = function search( x, y ){
  var bboxes = this.rtree.search( [ x, y, x, y ] );
  var pt = [ x, y ];
  for( var ind = 0; ind < bboxes.length; ind++ ){
    var polyObj = this.polygons[ bboxes[ ind ].polyId ];
    var polyCoords = polyObj.geometry.coordinates[ 0 ];
    if( pointInPolygon( pt, polyCoords ) ){
      var inHole = false;
      for( var subPolyInd = 1; subPolyInd < polyObj.geometry.coordinates.length; subPolyInd++ ){
        if( pointInPolygon( pt, polyObj.geometry.coordinates[ subPolyInd ] ) ){
          inHole = true;
          break;
        }
      }

      if( !inHole ){
        return polyObj;
      }
    }
  }
};

*/
/**
 * Build a spatial index for a set of polygons, and store both the polygons and
 * the index in this `PolygonLookup`.
 *
 * @param {object} collection A GeoJSON-formatted FeatureCollection.
 *
PolygonLookup.prototype.loadFeatureCollection = function loadFeatureCollection( collection ){
  var bboxes = [];
  var polygons = [];
  var polyId = 0;

  function indexPolygon( poly ){
    polygons.push(poly);
    var bbox = getBoundingBox( poly.geometry.coordinates[ 0 ] );
    bbox.polyId = polyId++;
    bboxes.push(bbox);
  }

  function indexFeature( poly ){
    if( poly.geometry.coordinates[ 0 ] !== undefined &&
        poly.geometry.coordinates[ 0 ].length > 0){
      switch( poly.geometry.type ){
        case 'Polygon':
          indexPolygon( poly );
          break;

        case 'MultiPolygon':
          var childPolys = poly.geometry.coordinates;
          for( var ind = 0; ind < childPolys.length; ind++ ){
            var childPoly = {
              type: 'Feature',
              properties: poly.properties,
              geometry: {
                type: 'Polygon',
                coordinates: childPolys[ ind ]
              }
            };
            indexPolygon( childPoly );
          }
          break;
      }
    }
  }

  collection.features.forEach( indexFeature );
  this.rtree = new RBush().load( bboxes );
  this.polygons = polygons;
};

*/

  Generated by ESDoc(0.5.2)


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">FreeOTP</string>
    <string name="invalid_token">A megadott jelsor érvénytelen volt!</string>
    <string name="delete">Törlés</string>
    <string name="edit">Szerkesztés</string>
    <string name="restore_defaults">Alapértékek visszaállítása</string>
    <string name="no_keys">Nincsenek OTP kulcsok telepítve.</string>
    <string name="add_token">Jelsor hozzáadása</string>
    <string name="scan_qr_code">QR-kód beolvasása</string>
    <string name="interval">Időköz</string>
    <string name="counter">Számláló</string>
    <string name="secret">Titok</string>
    <string name="type">Típus</string>
    <string name="algorithm">Algoritmus</string>
    <string name="digits">Számjegyek</string>
    <string name="save">Mentés</string>
    <string name="code_copied">Kód vágólapra másolva.</string>

    <string name="about_freeotp">A FreeOTP névjegye</string>
    <string name="about_version">FreeOTP verzió: %1$s (%2$d)</string>
    <string name="about_copyright">© 2013 - Red Hat, Inc., et al.</string>
    <string name="about_license">A FreeOTP %1$s licenc szerint érhető el.</string>
    <string name="about_website">További információkért nézze meg a %s.</string>
    <string name="about_icons">Az alkalmazásban használt néhány ikon az Android nyílt forráskódú projekt által létrehozott és megosztott munkából származik, és a Creative Commons 2.5 Nevezd meg! licencben leírtak szerint használható.</string>

    <string name="link_website">weboldalunkat</string>
    <string name="link_apache2">Apache 2.0</string>

    <string name="error_camera_open">Hiba a kamera megnyitásakor!</string>
    <string name="error_permission_camera_open">Nincs jogosultság a kamera megnyitásához</string>
    <string name="error_image_open">Hiba a kép megnyitásakor!</string>

    <string name="delete_summary">Ez az utolsó esélye: ha törli ezt a jelsort, akkor örökre eltűnik. Nem lesz letiltva a kiszolgálón.</string>
    <string name="delete_question">Törli ezt a jelsort?</string>

    <string-array name="algorithms">
        <item>MD5</item>
        <item>SHA1</item>
        <item>SHA256</item>
        <item>SHA512</item>
    </string-array>
</resources>

redpajama_set_name: RedPajamaGithub


text:
"""Fiona command line interface"""

import code
from functools import partial
import json
import logging
import pprint
import sys
import warnings

import click
import six.moves

import fiona
import fiona.crs
from fiona.transform import transform_geom
from fiona.fio.cli import cli
from fiona.fio.cat import cat, collect, dump, distrib
from fiona.fio.bounds import bounds

FIELD_TYPES_MAP_REV = dict([(v, k) for k, v in fiona.FIELD_TYPES_MAP.items()])

warnings.simplefilter('default')

# Commands are below.

@cli.command(short_help="Print information about the fio environment.")
@click.option('--formats', 'key', flag_value='formats', default=True,
              help="Enumerate the available formats.")
@click.pass_context
def env(ctx, key):
    """Print information about the Fiona environment: available
    formats, etc.
    """
    verbosity = (ctx.obj and ctx.obj.get('verbosity')) or 1
    logger = logging.getLogger('fio')
    stdout = click.get_text_stream('stdout')
    with fiona.drivers(CPL_DEBUG=(verbosity > 2)) as env:
        if key == 'formats':
            for k, v in sorted(fiona.supported_drivers.items()):
                modes = ', '.join("'" + m + "'" for m in v)
                stdout.write("%s (modes %s)\n" % (k, modes))
            stdout.write('\n')

# Info command.
@cli.command(short_help="Print information about a dataset.")
# One or more files.
@click.argument('input', type=click.Path(exists=True))
@click.option('--indent', default=None, type=int,
              help="Indentation level for pretty printed output.")
# Options to pick out a single metadata item and print it as
# a string.
@click.option('--count', 'meta_member', flag_value='count',
              help="Print the count of features.")
@click.option('-f', '--format', '--driver', 'meta_member', flag_value='driver',
              help="Print the format driver.")
@click.option('--crs', 'meta_member', flag_value='crs',
              help="Print the CRS as a PROJ.4 string.")
@click.option('--bounds', 'meta_member', flag_value='bounds',
              help="Print the nodata value.")
@click.pass_context
def info(ctx, input, indent, meta_member):
    verbosity = ctx.obj['verbosity']
    logger = logging.getLogger('rio')

    stdout = click.get_text_stream('stdout')
    try:
        with fiona.drivers(CPL_DEBUG=verbosity>2):
            with fiona.open(input) as src:
                info = src.meta
                info.update(bounds=src.bounds, count=len(src))
                proj4 = fiona.crs.to_string(src.crs)
                if proj4.startswith('+init=epsg'):
                    proj4 = proj4.split('=')[1].upper()
                info['crs'] = proj4
                if meta_member:
                    if isinstance(info[meta_member], (list, tuple)):
                        print(" ".join(map(str, info[meta_member])))
                    else:
                        print(info[meta_member])
                else:
                    stdout.write(json.dumps(info, indent=indent))
                    stdout.write("\n")
        sys.exit(0)
    except Exception:
        logger.exception("Failed. Exception caught")
        sys.exit(1)

# Insp command.
@cli.command(short_help="Open a dataset and start an interpreter.")
@click.argument('src_path', type=click.Path(exists=True))
@click.pass_context
def insp(ctx, src_path):
    verbosity = ctx.obj['verbosity']
    logger = logging.getLogger('fio')
    try:
        with fiona.drivers(CPL_DEBUG=verbosity>2):
            with fiona.open(src_path) as src:
                code.interact(
                    'Fiona %s Interactive Inspector (Python %s)\n'
                    'Type "src.schema", "next(src)", or "help(src)" '
                    'for more information.' %  (
                        fiona.__version__, '.'.join(
                            map(str, sys.version_info[:3]))),
                    local=locals())
            sys.exit(0)
    except Exception:
        logger.exception("Failed. Exception caught")
        sys.exit(1)

# Load command.
@cli.command(short_help="Load GeoJSON to a dataset in another format.")
@click.argument('output', type=click.Path(), required=True)
@click.option('-f', '--format', '--driver', required=True,
              help="Output format driver name.")
@click.option('--src_crs', default=None, help="Source CRS.")
@click.option('--dst_crs', default=None, help="Destination CRS.")
@click.option('--x-json-seq/--x-json-obj', default=False,
              help="Read a LF-delimited JSON sequence (default is object). Experimental.")
@click.pass_context

def load(ctx, output, driver, src_crs, dst_crs, x_json_seq):
    """Load features from JSON to a file in another format.

    The input is a GeoJSON feature collection or optionally a sequence of
    GeoJSON feature objects."""
    verbosity = ctx.obj['verbosity']
    logger = logging.getLogger('fio')
    stdin = click.get_text_stream('stdin')

    if src_crs and dst_crs:
        transformer = partial(transform_geom, src_crs, dst_crs,
                              antimeridian_cutting=True, precision=-1)
    else:
        transformer = lambda x: x

    first_line = next(stdin)

    # If input is RS-delimited JSON sequence.
    if first_line.startswith(u'\x1e'):
        def feature_gen():
            buffer = first_line.strip(u'\x1e')
            for line in stdin:
                if line.startswith(u'\x1e'):
                    if buffer:
                        feat = json.loads(buffer)
                        feat['geometry'] = transformer(feat['geometry'])
                        yield feat
                    buffer = line.strip(u'\x1e')
                else:
                    buffer += line
            else:
                feat = json.loads(buffer)
                feat['geometry'] = transformer(feat['geometry'])
                yield feat
    elif x_json_seq:
        def feature_gen():
            yield json.loads(first_line)
            for line in stdin:
                feat = json.loads(line)
                feat['geometry'] = transformer(feat['geometry'])
                yield feat
    else:
        def feature_gen():
            for feat in json.load(input)['features']:
                feat['geometry'] = transformer(feat['geometry'])
                yield feat

    try:
        source = feature_gen()

        # Use schema of first feature as a template.
        # TODO: schema specified on command line?
        first = next(source)
        schema = {'geometry': first['geometry']['type']}
        schema['properties'] = dict([
            (k, FIELD_TYPES_MAP_REV[type(v)])
            for k, v in first['properties'].items()])

        with fiona.drivers(CPL_DEBUG=verbosity>2):
            with fiona.open(
                    output, 'w',
                    driver=driver,
                    crs=dst_crs,
                    schema=schema) as dst:
                dst.write(first)
                dst.writerecords(source)
        sys.exit(0)
    except IOError:
        logger.info("IOError caught")
        sys.exit(0)
    except Exception:
        logger.exception("Failed. Exception caught")
        sys.exit(1)

if __name__ == '__main__':
    cli()


text:
package org.waveprotocol.wave.model.supplement;

import org.waveprotocol.wave.model.adt.ObservableMonotonicMap;
import org.waveprotocol.wave.model.adt.ObservableMonotonicValue;
import org.waveprotocol.wave.model.adt.docbased.DocumentBasedMonotonicMap;
import org.waveprotocol.wave.model.adt.docbased.DocumentBasedMonotonicValue;
import org.waveprotocol.wave.model.document.util.DocumentEventRouter;
import org.waveprotocol.wave.model.id.WaveletId;
import org.waveprotocol.wave.model.supplement.ObservablePrimitiveSupplement.Listener;
import org.waveprotocol.wave.model.util.Serializer;

/**
 * Implements the per-wavelet read state, using the
 * {@link DocumentBasedMonotonicValue} embedding for the participants and
 * wavelet-override last-read versions, and the
 * {@link DocumentBasedMonotonicMap} embedding for per-blip last-read versions.
 *
 * @param <E> element type of the document implementation
 */
class DocumentBasedWaveletReadState<E> implements WaveletReadState {
  private final ObservableMonotonicMap<String, Integer> blips;
  private final ObservableMonotonicValue<Integer> participants;
  private final ObservableMonotonicValue<Integer> tags;
  private final ObservableMonotonicValue<Integer> wavelet;
  private final DocumentEventRouter<? super E, E, ?> router;
  private final E container;

  DocumentBasedWaveletReadState(DocumentEventRouter<? super E, E, ?> router, E container) {
    this.router = router;
    this.container = container;
    blips =
        DocumentBasedMonotonicMap.create(router, container,
            Serializer.STRING, Serializer.INTEGER, WaveletBasedSupplement.BLIP_READ_TAG,
            WaveletBasedSupplement.ID_ATTR, WaveletBasedSupplement.VERSION_ATTR);
    participants =
        DocumentBasedMonotonicValue.create(router, container, Serializer.INTEGER,
            WaveletBasedSupplement.PARTICIPANTS_READ_TAG, WaveletBasedSupplement.VERSION_ATTR);
    tags =
        DocumentBasedMonotonicValue.create(router, container, Serializer.INTEGER,
            WaveletBasedSupplement.TAGS_READ_TAG, WaveletBasedSupplement.VERSION_ATTR);
    wavelet =
        DocumentBasedMonotonicValue.create(router, container, Serializer.INTEGER,
            WaveletBasedSupplement.WAVELET_READ_TAG, WaveletBasedSupplement.VERSION_ATTR);
  }

  /**
   * Creates
   *
   * @param router     router
   * @param container  element in which the read state is contained
   * @param id         wavelet id being tracked
   * @param listener   listener for read-state changes
   * @return a new read-state tracker.
   */
  public static <E> DocumentBasedWaveletReadState<E> create(
      DocumentEventRouter<? super E, E, ?> router, E container, WaveletId id,
      Listener listener) {
    DocumentBasedWaveletReadState<E> x = new DocumentBasedWaveletReadState<E>(router, container);
    x.installListeners(id, listener);
    return x;
  }

  /**
   * Injects listeners into the underlying ADTs that translate their events
   * into primitive-supplement events.
   *
   * @param wid
   * @param listener
   */
  private void installListeners(final WaveletId wid, final Listener listener) {
    blips.addListener(new ObservableMonotonicMap.Listener<String, Integer>() {
      @Override
      public void onEntrySet(String key, Integer oldValue, Integer newValue) {
        listener.onLastReadBlipVersionChanged(wid, key, valueOf(oldValue), valueOf(newValue));
      }
    });
    participants.addListener(new ObservableMonotonicValue.Listener<Integer>() {
      @Override
      public void onSet(Integer oldValue, Integer newValue) {
        listener.onLastReadParticipantsVersionChanged(wid, valueOf(oldValue), valueOf(newValue));
      }
    });
    tags.addListener(new ObservableMonotonicValue.Listener<Integer>() {
      @Override
      public void onSet(Integer oldValue, Integer newValue) {
        listener.onLastReadTagsVersionChanged(wid, valueOf(oldValue), valueOf(newValue));
      }
    });
    wavelet.addListener(new ObservableMonotonicValue.Listener<Integer>() {
      @Override
      public void onSet(Integer oldValue, Integer newValue) {
        listener.onLastReadWaveletVersionChanged(wid, valueOf(oldValue), valueOf(newValue));
      }
    });
  }

  private static int valueOf(Integer version) {
    return version != null ? version : PrimitiveSupplement.NO_VERSION;
  }

  @Override
  public void setBlipLastReadVersion(String blipId, int version) {
    blips.put(blipId, version);
  }

  @Override
  public int getBlipLastReadVersion(String id) {
    return valueOf(blips.get(id));
  }

  @Override
  public void setParticipantsLastReadVersion(int version) {
    participants.set(version);
  }

  @Override
  public int getParticipantsLastReadVersion() {
    return valueOf(participants.get());
  }

  @Override
  public int getTagsLastReadVersion() {
    return valueOf(tags.get());
  }

  @Override
  public void setTagsLastReadVersion(int version) {
    tags.set(version);
  }

  @Override
  public void setWaveletLastReadVersion(int version) {
    wavelet.set(version);
  }

  @Override
  public int getWaveletLastReadVersion() {
    return valueOf(wavelet.get());
  }

  @Override
  public Iterable<String> getReadBlips() {
    return blips.keySet();
  }

  @Override
  public void remove() {
    router.getDocument().deleteNode(container);
  }

  @Override
  public void clearBlipReadState(String blipId) {
    blips.remove(blipId);
  }
}


text:
"""Test deprecation and future warnings.

"""
from __future__ import division, absolute_import, print_function

import numpy as np
from numpy.testing import assert_warns

def test_qr_mode_full_future_warning():
    """Check mode='full' FutureWarning.

    In numpy 1.8 the mode options 'full' and 'economic' in linalg.qr were
    deprecated. The release date will probably be sometime in the summer
    of 2013.

    """
    a = np.eye(2)
    assert_warns(DeprecationWarning, np.linalg.qr, a, mode='full')
    assert_warns(DeprecationWarning, np.linalg.qr, a, mode='f')
    assert_warns(DeprecationWarning, np.linalg.qr, a, mode='economic')
    assert_warns(DeprecationWarning, np.linalg.qr, a, mode='e')


text:
import {NgModule} from "@angular/core";
import {CommonModule} from "@angular/common";
import {JigsawFloatModule, JigsawMovableModule, JigsawSelectModule} from "jigsaw/public_api";
import {JigsawDemoDescriptionModule} from "app/for-internal/description/demo-description";
import {FloatPosReviserDemo} from "./demo.component";

@NgModule({
    imports: [
        CommonModule, JigsawDemoDescriptionModule, JigsawFloatModule, JigsawMovableModule,
        JigsawSelectModule
    ],
    declarations: [FloatPosReviserDemo],
    exports: [FloatPosReviserDemo]
})
export class FloatPosReviserModule {
}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_submit_data"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="teamawesome.cs180frontend.Activities.Application.SubmitDataActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="@dimen/activity_vertical_margin">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="4dp"
                android:text="@string/enter_school_blurb" />

            <android.support.design.widget.TextInputLayout
                android:id="@+id/data_school_TIL"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="4dp">

                <AutoCompleteTextView
                    android:id="@+id/data_school_ac"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="@string/enter_school_name"
                    android:imeOptions="actionDone"
                    android:inputType="text"
                    android:maxLines="1"
                    android:textSize="18sp"/>

            </android.support.design.widget.TextInputLayout>

            <TextView
                android:id="@+id/new_school_tv"
                android:visibility="gone"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="4dp"
                android:text="@string/enter_system_type" />

            <Spinner
                android:id="@+id/system_type_spinner"
                android:visibility="gone"
                android:background="@drawable/black_rounded_rectangle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="4dp">
            </Spinner>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="4dp"
                android:text="@string/subjects" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:layout_marginBottom="4dp"
                android:id="@+id/subject_data">
            </LinearLayout>

            <include
                android:id="@+id/add_subjects"
                layout="@layout/add_data_widget" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="4dp"
                android:text="@string/classes" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:layout_marginBottom="4dp"
                android:id="@+id/class_data">
            </LinearLayout>

            <include
                android:id="@+id/add_classes"
                layout="@layout/add_data_widget" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="4dp"
                android:text="@string/professors" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:layout_marginBottom="4dp"
                android:id="@+id/prof_data">
            </LinearLayout>

            <include
                android:id="@+id/add_profs"
                layout="@layout/add_data_widget" />

            <Button
                android:id="@+id/submit_data_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="12dp"
                android:layout_gravity="center_horizontal"
                android:text="@string/submit_data"/>

        </LinearLayout>

    </ScrollView>

</android.support.design.widget.CoordinatorLayout>


text:
#ifndef LIBFFI_TARGET_H
#define LIBFFI_TARGET_H

#ifndef LIBFFI_H
#error "Please do not include ffitarget.h directly into your source.  Use ffi.h instead."
#endif

#ifndef LIBFFI_ASM
#ifdef __ILP32__
#define FFI_SIZEOF_ARG 8
typedef unsigned long long ffi_arg;
typedef signed long long ffi_sarg;
#else
typedef unsigned long ffi_arg;
typedef signed long ffi_sarg;
#endif

typedef enum ffi_abi
  {
    FFI_FIRST_ABI = 0,
    FFI_SYSV,
    FFI_LAST_ABI,
    FFI_DEFAULT_ABI = FFI_SYSV
  } ffi_abi;
#endif

/* ---- Definitions for closures ----------------------------------------- */

#define FFI_CLOSURES 1
#if defined (__APPLE__)
#define FFI_TRAMPOLINE_SIZE 20
#define FFI_TRAMPOLINE_CLOSURE_OFFSET 16
#else
#define FFI_TRAMPOLINE_SIZE 24
#define FFI_TRAMPOLINE_CLOSURE_OFFSET FFI_TRAMPOLINE_SIZE
#endif
#define FFI_NATIVE_RAW_API 0

/* ---- Internal ---- */

#if defined (__APPLE__)
#define FFI_TARGET_SPECIFIC_VARIADIC
#define FFI_EXTRA_CIF_FIELDS unsigned aarch64_nfixedargs
#else
/* iOS reserves x18 for the system.  Disable Go closures until
   a new static chain is chosen.  */
#define FFI_GO_CLOSURES 1
#endif

#define FFI_TARGET_HAS_COMPLEX_TYPE

#endif


text:
/**
 * $Id: QueueData.java 1835 2013-05-16 02:00:50Z shijia.wxr $
 */
package com.alibaba.rocketmq.common.protocol.route;

public class QueueData implements Comparable<QueueData> {
    private String brokerName;
    private int readQueueNums;
    private int writeQueueNums;
    private int perm;
    private int topicSynFlag;

    public String getBrokerName() {
        return brokerName;
    }

    public void setBrokerName(String brokerName) {
        this.brokerName = brokerName;
    }

    public int getReadQueueNums() {
        return readQueueNums;
    }

    public void setReadQueueNums(int readQueueNums) {
        this.readQueueNums = readQueueNums;
    }

    public int getWriteQueueNums() {
        return writeQueueNums;
    }

    public void setWriteQueueNums(int writeQueueNums) {
        this.writeQueueNums = writeQueueNums;
    }

    public int getPerm() {
        return perm;
    }

    public void setPerm(int perm) {
        this.perm = perm;
    }

    public int getTopicSynFlag() {
        return topicSynFlag;
    }

    public void setTopicSynFlag(int topicSynFlag) {
        this.topicSynFlag = topicSynFlag;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((brokerName == null) ? 0 : brokerName.hashCode());
        result = prime * result + perm;
        result = prime * result + readQueueNums;
        result = prime * result + writeQueueNums;
        result = prime * result + topicSynFlag;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        QueueData other = (QueueData) obj;
        if (brokerName == null) {
            if (other.brokerName != null)
                return false;
        } else if (!brokerName.equals(other.brokerName))
            return false;
        if (perm != other.perm)
            return false;
        if (readQueueNums != other.readQueueNums)
            return false;
        if (writeQueueNums != other.writeQueueNums)
            return false;
        if (topicSynFlag != other.topicSynFlag)
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "QueueData [brokerName=" + brokerName + ", readQueueNums=" + readQueueNums
                + ", writeQueueNums=" + writeQueueNums + ", perm=" + perm + ", topicSynFlag=" + topicSynFlag
                + "]";
    }

    @Override
    public int compareTo(QueueData o) {
        return this.brokerName.compareTo(o.getBrokerName());
    }
}