<commit_before>goog.provide('ol.geom.LineString');

goog.require('goog.asserts');
goog.require('ol.Extent');
goog.require('ol.geom.Geometry');
goog.require('ol.geom.GeometryType');
goog.require('ol.geom.SharedVertices');
goog.require('ol.geom.VertexArray');

/**
 * @constructor
 * @extends {ol.geom.Geometry}
 * @param {ol.geom.VertexArray} coordinates Vertex array (e.g.
 *    [[x0, y0], [x1, y1]]).
 * @param {ol.geom.SharedVertices=} opt_shared Shared vertices.
 */
ol.geom.LineString = function(coordinates, opt_shared) {
  goog.base(this);
  goog.asserts.assert(goog.isArray(coordinates[0]));

  var vertices = opt_shared,
      dimension;

  if (!goog.isDef(vertices)) {
    dimension = coordinates[0].length;
    vertices = new ol.geom.SharedVertices({dimension: dimension});
  }

  /**
   * @type {ol.geom.SharedVertices}
   */
  this.vertices = vertices;

  /**
   * @type {string}
   * @private
   */
  this.sharedId_ = vertices.add(coordinates);

  /**
   * @type {number}
   */
  this.dimension = vertices.getDimension();
  goog.asserts.assert(this.dimension >= 2);

  /**
   * @type {ol.Extent}
   * @private
   */
  this.bounds_ = null;

};
goog.inherits(ol.geom.LineString, ol.geom.Geometry);

/**
 * Get a vertex coordinate value for the given dimension.
 * @param {number} index Vertex index.
 * @param {number} dim Coordinate dimension.
 * @return {number} The vertex coordinate value.
 */
ol.geom.LineString.prototype.get = function(index, dim) {
  return this.vertices.get(this.sharedId_, index, dim);
};

/**
 * @inheritDoc
 * @return {ol.geom.VertexArray} Coordinates array.
 */
ol.geom.LineString.prototype.getCoordinates = function() {
  var count = this.getCount();
  var coordinates = new Array(count);
  var vertex;
  for (var i = 0; i < count; ++i) {
    vertex = new Array(this.dimension);
    for (var j = 0; j < this.dimension; ++j) {
      vertex[j] = this.get(i, j);
    }
    coordinates[i] = vertex;
  }
  return coordinates;
};

/**
 * Get the count of vertices in this linestring.
 * @return {number} The vertex count.
 */
ol.geom.LineString.prototype.getCount = function() {
  return this.vertices.getCount(this.sharedId_);
};

/**
 * @inheritDoc
 */
ol.geom.LineString.prototype.getBounds = function() {
  if (goog.isNull(this.bounds_)) {
    var minX, minY = minX = Number.POSITIVE_INFINITY,
        maxX, maxY = maxX = Number.NEGATIVE_INFINITY,
        dimension = this.dimension,
        vertices = this.vertices,
        id = this.sharedId_,
        count = vertices.getCount(id),
        start = vertices.getStart(id),
        end = start + (count * dimension),
        coordinates = vertices.coordinates,
        x, y, i;

    for (i = start; i < end; i += dimension) {
      x = coordinates[i];
      y = coordinates[i + 1];
      if (x < minX) {
        minX = x;
      } else if (x > maxX) {
        maxX = x;
      }
      if (y < minY) {
        minY = y;
      } else if (y > maxY) {
        maxY = y;
      }
    }
    this.bounds_ = new ol.Extent(minX, minY, maxX, maxY);
  }
  return this.bounds_;
};

/**
 * @inheritDoc
 */
ol.geom.LineString.prototype.getType = function() {
  return ol.geom.GeometryType.LINESTRING;
};

/**
 * Get the identifier used to mark this line in the shared vertices structure.
 * @return {string} The identifier.
 */
ol.geom.LineString.prototype.getSharedId = function() {
  return this.sharedId_;
};
<commit_msg>Proper bounds<commit_after>goog.provide('ol.geom.LineString');

goog.require('goog.asserts');
goog.require('ol.Extent');
goog.require('ol.geom.Geometry');
goog.require('ol.geom.GeometryType');
goog.require('ol.geom.SharedVertices');
goog.require('ol.geom.VertexArray');

/**
 * @constructor
 * @extends {ol.geom.Geometry}
 * @param {ol.geom.VertexArray} coordinates Vertex array (e.g.
 *    [[x0, y0], [x1, y1]]).
 * @param {ol.geom.SharedVertices=} opt_shared Shared vertices.
 */
ol.geom.LineString = function(coordinates, opt_shared) {
  goog.base(this);
  goog.asserts.assert(goog.isArray(coordinates[0]));

  var vertices = opt_shared,
      dimension;

  if (!goog.isDef(vertices)) {
    dimension = coordinates[0].length;
    vertices = new ol.geom.SharedVertices({dimension: dimension});
  }

  /**
   * @type {ol.geom.SharedVertices}
   */
  this.vertices = vertices;

  /**
   * @type {string}
   * @private
   */
  this.sharedId_ = vertices.add(coordinates);

  /**
   * @type {number}
   */
  this.dimension = vertices.getDimension();
  goog.asserts.assert(this.dimension >= 2);

  /**
   * @type {ol.Extent}
   * @private
   */
  this.bounds_ = null;

};
goog.inherits(ol.geom.LineString, ol.geom.Geometry);

/**
 * Get a vertex coordinate value for the given dimension.
 * @param {number} index Vertex index.
 * @param {number} dim Coordinate dimension.
 * @return {number} The vertex coordinate value.
 */
ol.geom.LineString.prototype.get = function(index, dim) {
  return this.vertices.get(this.sharedId_, index, dim);
};

/**
 * @inheritDoc
 * @return {ol.geom.VertexArray} Coordinates array.
 */
ol.geom.LineString.prototype.getCoordinates = function() {
  var count = this.getCount();
  var coordinates = new Array(count);
  var vertex;
  for (var i = 0; i < count; ++i) {
    vertex = new Array(this.dimension);
    for (var j = 0; j < this.dimension; ++j) {
      vertex[j] = this.get(i, j);
    }
    coordinates[i] = vertex;
  }
  return coordinates;
};

/**
 * Get the count of vertices in this linestring.
 * @return {number} The vertex count.
 */
ol.geom.LineString.prototype.getCount = function() {
  return this.vertices.getCount(this.sharedId_);
};

/**
 * @inheritDoc
 */
ol.geom.LineString.prototype.getBounds = function() {
  if (goog.isNull(this.bounds_)) {
    var dimension = this.dimension,
        vertices = this.vertices,
        id = this.sharedId_,
        count = vertices.getCount(id),
        start = vertices.getStart(id),
        end = start + (count * dimension),
        coordinates = vertices.coordinates,
        minX, maxX,
        minY, maxY,
        x, y, i;

    minX = maxX = coordinates[start];
    minY = maxY = coordinates[start + 1];
    for (i = start + dimension; i < end; i += dimension) {
      x = coordinates[i];
      y = coordinates[i + 1];
      if (x < minX) {
        minX = x;
      } else if (x > maxX) {
        maxX = x;
      }
      if (y < minY) {
        minY = y;
      } else if (y > maxY) {
        maxY = y;
      }
    }
    this.bounds_ = new ol.Extent(minX, minY, maxX, maxY);
  }
  return this.bounds_;
};

/**
 * @inheritDoc
 */
ol.geom.LineString.prototype.getType = function() {
  return ol.geom.GeometryType.LINESTRING;
};

/**
 * Get the identifier used to mark this line in the shared vertices structure.
 * @return {string} The identifier.
 */
ol.geom.LineString.prototype.getSharedId = function() {
  return this.sharedId_;
};
<|endoftext|>


<commit_before>/**
 *  url.js JavaScript library
 *  =========================
 *  A lightweight JavaScript library to manipulate the page url.
 *  Check out the documentation at: https://github.com/jillix/url.js
 *
 *  Created with <3 by the jillix develeopers.
 */
(function(window) {

    var Url = window.Url = {};

    /**
     * queryString
     * Finds the value of parameter passed in first argument.
     *
     * @name queryString
     * @function
     * @param {String} name The parameter name
     * @param {Boolean} notDecoded If true, the result will be encoded.
     * @return {String} The value of the parameter name (`name` parameter)
     */
    function queryString(name, notDecoded) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
        var results = regex.exec(location.search);
        if (results === null) {
            return "";
        } else {
            var encoded = results[1].replace(/\+/g, " ");
            if (notDecoded) {
                return encoded;
            }
            return decodeURIComponent(encoded);
        }
    }

    /**
     * parseQuery
     * Parses the string from `search` parameter or the location search
     *
     * @name parseQuery
     * @function
     * @param {String} search Optional string that should be parsed
     * @return {Object} The parsed search query
     */
    function parseQuery(search) {
        var query = {};
        search = search || window.location.search;
        if (search[0] === "?") {
            search = search.substring(1);
        }
        if (!search) {
            return {};
        }
        var a = search.split('&');
        for (var i in a) {
            var b = a[i].split('=');
            query[decodeURIComponent(b[0])] = decodeURIComponent(b[1]);
        }

        return query;
    }

    /**
     * queryToString
     * Stringifies a query object
     *
     * @name queryToString
     * @function
     * @param {Object} queryObj The object that should be stringified
     * @return {String} The stringified value of `queryObj` object
     */
    function queryToString(queryObj) {
        if (!queryObj || queryObj.constructor !== Object) {
            throw new Error("Query object should be an object.");
        }
        var stringified = "";
        for (var param in queryObj) {
            if (!queryObj.hasOwnProperty(param)) continue;
            stringified +=
                param + "=" + encodeURIComponent(queryObj[param]) + "&";
        }
        stringified = stringified.substring(0, stringified.length - 1);
        return stringified;
    }

    /**
     * updateSearchParam
     * Adds a parameter=value to the url (without page refresh)
     *
     * @name updateSearchParam
     * @function
     * @param {String} param The parameter name
     * @param {String|undefined} value The parameter value. If undefined, the parameter will be removed.
     * @return undefined
     */
    function updateSearchParam(param, value) {

        var searchParsed = parseQuery();

        // No value, we will delete param
        if (value === undefined) {
            delete searchParsed[param];
        } else {

            // Same value, no fun
            value = encodeURIComponent(value);
            if (searchParsed[param] === value) {
                return;
            }

            // Update value in search object
            searchParsed[param] = value;
        }

        // Stringify the search object
        var newSearch = "?" + queryToString(searchParsed);

        // Finally, replace the state
        window.history.replaceState(null, "", newSearch + location.hash);
    }

    /**
     * getLocation
     * Returns the page url, but not including the domain name
     *
     * @name getLocation
     * @function
     * @return {String} The page url (without domain)
     */
    function getLocation() {
        return window.location.pathname + window.location.search + window.location.hash;
    }

    // Append the methods
    Url.getLocation = getLocation;
    Url.updateSearchParam = updateSearchParam;
    Url.queryString = queryString;
    Url.parseSearchQuery = parseQuery;

    // Version
    Url.version = "1.0.0";
})(window);
<commit_msg>Fixes in JSDoc comments.<commit_after>/**
 *  url.js JavaScript library
 *  =========================
 *  A lightweight JavaScript library to manipulate the page url.
 *  Check out the documentation at: https://github.com/jillix/url.js
 *
 *  Created with <3 by the jillix develeopers.
 */
(function(window) {

    var Url = window.Url = {};

    /**
     * queryString
     * Finds the value of parameter passed in first argument.
     *
     * @name queryString
     * @function
     * @param {String} name The parameter name.
     * @param {Boolean} notDecoded If `true`, the result will be encoded.
     * @return {String} The parameter value.
     */
    function queryString(name, notDecoded) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");

        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
        var results = regex.exec(location.search);
        var encoded = null;

        if (results === null) {
            return "";
        } else {
            encoded = results[1].replace(/\+/g, " ");
            if (notDecoded) {
                return encoded;
            }
            return decodeURIComponent(encoded);
        }
    }

    /**
     * parseQuery
     * Parses a string as querystring.
     *
     * @name parseQuery
     * @function
     * @param {String} search An optional string that should be parsed (default: `window.location.search`).
     * @return {Object} The parsed querystring.
     */
    function parseQuery(search) {
        var query = {};

        if (typeof search !== "string") {
            search = window.location.search;
        }

        search = search.replace(/^\?/g, "");

        if (!search) {
            return {};
        }

        var a = search.split("&");
        var b = null;
        var i = 0;
        for (; i < a.length; ++i) {
            b = a[i].split("=");
            query[decodeURIComponent(b[0])] = decodeURIComponent(b[1]);
        }

        return query;
    }

    /**
     * stringify
     * Stringifies a query object.
     *
     * @name stringify
     * @function
     * @param {Object} queryObj The object that should be stringified.
     * @return {String} The stringified value of `queryObj` object.
     */
    function stringify(queryObj) {

        if (!queryObj || queryObj.constructor !== Object) {
            throw new Error("Query object should be an object.");
        }

        var stringified = "";
        Object.keys(queryObj).forEach(function(c) {
            stringified += c + "=" + encodeURIComponent(queryObj[c]) + "&";
        });

        stringified = stringified.replace(/\&$/g, "");
        return stringified;
    }

    /**
     * updateSearchParam
     * Adds, updates or deletes a parameter (without page refresh).
     *
     * @name updateSearchParam
     * @function
     * @param {String} param The parameter name.
     * @param {String|undefined} value The parameter value. If `undefined`, the parameter will be removed.
     * @return {Url} The `Url` object.
     */
    function updateSearchParam(param, value) {

        var searchParsed = parseQuery();

        // Delete the parameter
        if (value === undefined) {
            delete searchParsed[param];
        } else {
            // Update or add
            value = encodeURIComponent(value);
            if (searchParsed[param] === value) {
                return Url;
            }
            searchParsed[param] = value;
        }

        var newSearch = "?" + stringify(searchParsed);
        window.history.replaceState(null, "", newSearch + location.hash);

        return Url;
    }

    /**
     * getLocation
     * Returns the page url, but not including the domain name.
     *
     * @name getLocation
     * @function
     * @return {String} The page url (without domain).
     */
    function getLocation() {
        return window.location.pathname + window.location.search + window.location.hash;
    }

    // Append the methods
    Url.getLocation = getLocation;
    Url.updateSearchParam = updateSearchParam;
    Url.queryString = queryString;
    Url.parseSearchQuery = parseQuery;

    // Version
    Url.version = "1.0.0";
})(window);
<|endoftext|>


<commit_before>import { ADD_ACTIVITY } from 'src/screens/ActivityAdd/actions/types';

const initialState = {
  activityList: [],
}

export default function reducer(state = initialState, action) {

  switch(action.type) {

    case ADD_ACTIVITY:
      return {...state, activityList: state.activityList.concat(action.activity)};

    default:
      return state;
  }
}
<commit_msg>Remove residual files<commit_after><|endoftext|>


<commit_before>/* eslint-disable no-unused-vars */
var profile = {
    basePath: '../src',
    action: 'release',
    cssOptimize: 'comments',
    mini: true,
    optimize: false,
    layerOptimize: false,
    selectorEngine: 'acme',
    layers: {
        'dojo/dojo': {
            include: [
                'dojo/i18n',
                'dojo/domReady',
                'app/packages',
                'app/run',
                'app/App',
                'esri/layers/VectorTileLayerImpl',
                'dojox/gfx/filters',
                'dojox/gfx/path',
                'dojox/gfx/svg',
                'dojox/gfx/svgext',
                'dojox/gfx/shape'
            ],
            includeLocales: ['en-us'],
            customBase: true,
            boot: true
        },
        'ijit/widgets/authentication/UserAdmin': {
            exclude: ['dojo/dojo']
        }
    },
    packages: [{
        name: 'proj4',
        trees: [
          // don't bother with .hidden, tests, min, src, and templates
          ['.', '.', /(\/\.)|(~$)|(test|txt|src|min|html)/]
        ],
        resourceTags: {
            amd: function amd() {
                return true;
            },
            copyOnly: function copyOnly() {
                return false;
            }
        }
    }, {
        name: 'moment',
        location: 'moment',
        main: 'moment',
        trees: [
          // don't bother with .hidden, tests, min, src, and templates
          ['.', '.', /(\/\.)|(~$)|(test|txt|src|min|templates)/]
        ],
        resourceTags: {
            amd: function amd(filename, mid) {
                return /\.js$/.test(filename);
            }
        }
    }],
    staticHasFeatures: {
        // The trace & log APIs are used for debugging the loader, so we don’t need them in the build
        'dojo-trace-api': 0,
        'dojo-log-api': 0,

        // This causes normally private loader data to be exposed for debugging, so we don’t need that either
        'dojo-publish-privates': 0,

        // We’re fully async, so get rid of the legacy loader
        'dojo-sync-loader': 0,

        // dojo-xhr-factory relies on dojo-sync-loader
        'dojo-xhr-factory': 0,

        // We aren’t loading tests in production
        'dojo-test-sniff': 0
    },
    userConfig: {
        packages: ['app', 'dijit', 'dojox', 'agrc', 'ijit', 'esri', 'layer-selector', 'sherlock']
    }
};
<commit_msg>add ie 11 support<commit_after>/* eslint-disable no-unused-vars */
var profile = {
    basePath: '../src',
    action: 'release',
    cssOptimize: 'comments',
    mini: true,
    optimize: false,
    layerOptimize: false,
    selectorEngine: 'acme',
    layers: {
        'dojo/dojo': {
            include: [
                'dojo/i18n',
                'dojo/domReady',
                'app/packages',
                'app/run',
                'app/App',
                'esri/layers/VectorTileLayerImpl',
                'dojox/gfx/filters',
                'dojox/gfx/path',
                'dojox/gfx/svg',
                'dojox/gfx/svgext',
                'dojox/gfx/shape'
            ],
            includeLocales: ['en-us'],
            customBase: true,
            boot: true
        },
        'ijit/widgets/authentication/UserAdmin': {
            exclude: ['dojo/dojo']
        }
    },
    packages: [{
        name: 'proj4',
        trees: [
          // don't bother with .hidden, tests, min, src, and templates
          ['.', '.', /(\/\.)|(~$)|(test|txt|src|min|html)/]
        ],
        resourceTags: {
            amd: function amd() {
                return true;
            },
            copyOnly: function copyOnly() {
                return false;
            }
        }
    }, {
        name: 'moment',
        location: 'moment',
        main: 'moment',
        trees: [
          // don't bother with .hidden, tests, min, src, and templates
          ['.', '.', /(\/\.)|(~$)|(test|txt|src|min|templates)/]
        ],
        resourceTags: {
            amd: function amd(filename, mid) {
                return /\.js$/.test(filename);
            }
        }
    }],
    staticHasFeatures: {
        // The trace & log APIs are used for debugging the loader, so we don’t need them in the build
        'dojo-trace-api': 0,
        'dojo-log-api': 0,

        // This causes normally private loader data to be exposed for debugging, so we don’t need that either
        'dojo-publish-privates': 0,

        // We’re fully async, so get rid of the legacy loader
        'dojo-sync-loader': 0,

        // dojo-xhr-factory relies on dojo-sync-loader
        'dojo-xhr-factory': 0,

        // We aren’t loading tests in production
        'dojo-test-sniff': 0,

        // ie 11 support
        'dojo-guarantee-console': 1,
        'console-as-object': 0
    },
    userConfig: {
        packages: ['app', 'dijit', 'dojox', 'agrc', 'ijit', 'esri', 'layer-selector', 'sherlock']
    }
};
<|endoftext|>


<commit_before>/* eslint-disable no-unused-vars */
var profile = {
    basePath: '../src',
    action: 'release',
    cssOptimize: 'comments',
    mini: true,
    optimize: false,
    layerOptimize: false,
    selectorEngine: 'acme',
    layers: {
        'dojo/dojo': {
            include: [
                'dojo/i18n',
                'dojo/domReady',
                'app/packages',
                'app/run',
                'app/App',
                'esri/layers/VectorTileLayerImpl',
                'dojox/gfx/filters',
                'dojox/gfx/path',
                'dojox/gfx/svg',
                'dojox/gfx/svgext',
                'dojox/gfx/shape'
            ],
            includeLocales: ['en-us'],
            customBase: true,
            boot: true
        },
        'ijit/widgets/authentication/UserAdmin': {
            exclude: ['dojo/dojo']
        }
    },
    packages: [{
        name: 'proj4',
        trees: [
          // don't bother with .hidden, tests, min, src, and templates
          ['.', '.', /(\/\.)|(~$)|(test|txt|src|min|html)/]
        ],
        resourceTags: {
            amd: function amd() {
                return true;
            },
            copyOnly: function copyOnly() {
                return false;
            }
        }
    }, {
        name: 'moment',
        location: 'moment',
        main: 'moment',
        trees: [
          // don't bother with .hidden, tests, min, src, and templates
          ['.', '.', /(\/\.)|(~$)|(test|txt|src|min|templates)/]
        ],
        resourceTags: {
            amd: function amd(filename, mid) {
                return /\.js$/.test(filename);
            }
        }
    }],
    staticHasFeatures: {
        // The trace & log APIs are used for debugging the loader, so we don’t need them in the build
        'dojo-trace-api': 0,
        'dojo-log-api': 0,

        // This causes normally private loader data to be exposed for debugging, so we don’t need that either
        'dojo-publish-privates': 0,

        // We’re fully async, so get rid of the legacy loader
        'dojo-sync-loader': 0,

        // dojo-xhr-factory relies on dojo-sync-loader
        'dojo-xhr-factory': 0,

        // We aren’t loading tests in production
        'dojo-test-sniff': 0,

        // ie 11 support
        'dojo-guarantee-console': 1,
        'console-as-object': 0
    },
    userConfig: {
        packages: ['app', 'dijit', 'dojox', 'agrc', 'ijit', 'esri', 'layer-selector', 'sherlock']
    }
};
<commit_msg>organize and add attribution<commit_after>/* eslint-disable no-unused-vars */
var profile = {
    basePath: '../src',
    action: 'release',
    cssOptimize: 'comments',
    mini: true,
    optimize: false,
    layerOptimize: false,
    selectorEngine: 'acme',
    layers: {
        'dojo/dojo': {
            include: [
                'app/App',
                'app/packages',
                'app/run',
                'dojo/domReady',
                'dojo/i18n',
                'dojox/gfx/filters',
                'dojox/gfx/path',
                'dojox/gfx/shape',
                'dojox/gfx/svg',
                'dojox/gfx/svgext',
                'esri/dijit/Attribution',
                'esri/layers/VectorTileLayerImpl'
            ],
            includeLocales: ['en-us'],
            customBase: true,
            boot: true
        },
        'ijit/widgets/authentication/UserAdmin': {
            exclude: ['dojo/dojo']
        }
    },
    packages: [{
        name: 'proj4',
        trees: [
          // don't bother with .hidden, tests, min, src, and templates
          ['.', '.', /(\/\.)|(~$)|(test|txt|src|min|html)/]
        ],
        resourceTags: {
            amd: function amd() {
                return true;
            },
            copyOnly: function copyOnly() {
                return false;
            }
        }
    }, {
        name: 'moment',
        location: 'moment',
        main: 'moment',
        trees: [
          // don't bother with .hidden, tests, min, src, and templates
          ['.', '.', /(\/\.)|(~$)|(test|txt|src|min|templates)/]
        ],
        resourceTags: {
            amd: function amd(filename, mid) {
                return /\.js$/.test(filename);
            }
        }
    }],
    staticHasFeatures: {
        // The trace & log APIs are used for debugging the loader, so we don’t need them in the build
        'dojo-trace-api': 0,
        'dojo-log-api': 0,

        // This causes normally private loader data to be exposed for debugging, so we don’t need that either
        'dojo-publish-privates': 0,

        // We’re fully async, so get rid of the legacy loader
        'dojo-sync-loader': 0,

        // dojo-xhr-factory relies on dojo-sync-loader
        'dojo-xhr-factory': 0,

        // We aren’t loading tests in production
        'dojo-test-sniff': 0,

        // ie 11 support
        'dojo-guarantee-console': 1,
        'console-as-object': 0
    },
    userConfig: {
        packages: ['app', 'dijit', 'dojox', 'agrc', 'ijit', 'esri', 'layer-selector', 'sherlock']
    }
};
<|endoftext|>


<commit_before>/*
 * Copyright 2011 Pablo Mendes, Max Jakob
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  Check our project website for information on how to acknowledge the authors and how to contribute to the project: http://spotlight.dbpedia.org
 */

/**
 * If you use this script, please give credit to DBpedia Spotlight by:
 * - adding "powered by DBpedia Spotlight" somewhere in the page.
 * - add a link to http://spotlight.dbpedia.org.
 *
 * TODO people can also want to change the boundaries of the spotting
 * TODO showScores = [ list of score names to display ]
 *
 * @author pablomendes
 *
 */

(function( $ ){

   var powered_by = "
Powered by DBpedia Spotlight
";

   var settings = {
      'endpoint' : 'http://localhost:2223/rest',
      'confidence' : 0.4,          //
      'support' : 20,
      'powered_by': 'yes',         // yes or no
      'showScores': 'yes',         // yes or no
      'types': '',
      'policy' : 'whitelist',
      'spotter': 'LingPipeSpotter' // one of: LingPipeSpotter,AtLeastOneNounSelector,CoOccurrenceBasedSelector
    };

   function getScoreDOMElements(data) {
        var li = ""
        for (var key in data)
            li  += "" + data[key] +"";
        return li;
   }

   var Parser = {
	getSelectBox: function(resources, className) {
             var ul =  $("

");
             $.each(resources, function(i, r) {
                 var li = "
" + r["@label"] + "";
                 //TODO settings.showScores = ["finalScore"] foreach showscores, add k=v

                 if (settings.showScores == 'yes') {
                    li += " (" + parseFloat(r["@finalScore"]).toPrecision(3) +")";
                 }

                 li += getScoreDOMElements({
                                     "finalScore": parseFloat(r["@finalScore"]).toPrecision(3),
                                     "contextualScore": parseFloat(r["@contextualScore"]),
                                     "percentageOfSecondRank": parseFloat(r["@percentageOfSecondRank"]),
                                     "support": parseFloat(r["@support"]),
                                     "priorScore": parseFloat(r["@priorScore"])
                                    });

                 li += "
";
                 var opt = $(li);
                 $.data(opt,"testProp","testValue");
                 //console.log($.data(opt,"testProp"));
                 $(ul).append(opt);
             });
             return ul;
        },
	getAnnotatedText: function(response) {
             var json = $.parseJSON(response);
	     if (json==null) json = response; // when it comes already parsed

             var text = json["annotation"]["@text"];

             var start = 0;
             var annotatedText = text;

             if (json.annotation['surfaceForm']!=undefined)
                  //console.log(json.annotation['surfaceForm']);
                  var annotations = new Array().concat(json.annotation.surfaceForm) // deals with the case of only one surfaceFrom returned (ends up not being an array)
                  annotatedText = annotations.map(function(e) {
                  if (e==undefined) return "";
		  //console.log(e);
                  var sfName = e["@name"];
                  var offset = parseInt(e["@offset"]);
                  var sfLength = parseInt(sfName.length);
                  var snippet = text.substring(start, offset)
                  var surfaceForm = text.substring(offset,offset+sfLength);
                  start = offset+sfLength;

                  var classes = "annotation";

                  snippet += "
" + sfName + "";
                  //TODO instead of showing directly the select box, it would be cuter to just show a span, and onClick on that span, build the select box.
                  var ul = Parser.getSelectBox($(e.resource),'candidate');
                  //ul.children().each(function() { console.log($.data($(this),"testProp")); });
                  snippet += "
"+ul.html()+"
"; //FIXME this wrapper is a repeat from getSelectBox
                  snippet += "
";

                  return snippet;
			    }).join("");
             //snippet after last surface form
             annotatedText += text.substring(start, text.length);
             //console.log(annotatedText);
             return annotatedText.replace(/\n/g, "
\n");
        },
        getAnnotatedTextFirstBest: function(response) {
                     var json = $.parseJSON(response);
        	     if (json==null) json = response; // when it comes already parsed

                     var text = json["@text"];

                     var start = 0;
                     var annotatedText = text;

                     if (json['Resources']!=undefined)
                          var annotations = new Array().concat(json.Resources) // deals with the case of only one surfaceFrom returned (ends up not being an array)

                          annotatedText = annotations.map(function(e) {
                          if (e==undefined) return "";

                          var sfName = e["@surfaceForm"];
                          var offset = parseInt(e["@offset"]);
                          var uri = e["@URI"];

                          var sfLength = parseInt(sfName.length);
                          var snippet = text.substring(start, offset)
                          var surfaceForm = text.substring(offset,offset+sfLength);
                          start = offset+sfLength;

                          var support = parseInt(e["@support"]);
                          var confidence = 0.0;

                          var classes = "annotation"
                          snippet += "" + sfName

                          snippet += getScoreDOMElements({
                                     "finalScore": parseFloat(e["@similarityScore"]).toPrecision(3),
                                     "percentageOfSecondRank": parseFloat(e["@percentageOfSecondRank"]),
                                     "support": parseFloat(e["@support"]),
                                    });

                          snippet += "";

                          return snippet;
        			    }).join("");
                     //snippet after last surface form
                     annotatedText += text.substring(start, text.length);
                     //console.log(annotatedText);
                     return annotatedText.replace(/\n/g, "
\n");
                },

	getSuggestions: function(response, targetSurfaceForm) {
             var json = $.parseJSON(response);
	     if (json==null) json = response; // when it comes already parsed
             var suggestions = "";
	     if (json.annotation['surfaceForm']!=undefined) {
                  var annotations = new Array().concat(json.annotation.surfaceForm) // deals with the case of only one surfaceFrom returned (ends up not being an array)
                  suggestions = annotations.filter(function(e) {
			return (e["@name"]==$.trim(targetSurfaceForm));
		  }).map(function(e) {
                  	return Parser.getSelectBox($(e.resource),'none');
		  }).join("");
            }
            return suggestions;
        }
   };

   var ajaxRequest;
   var methods = {
      init : function( options ) {
          // If options exist, lets merge them with our default settings
          if ( options ) {
              $.extend( settings, options );
          }
      },
      best: function( options ) {
          //init(options);
          function update(response) {

                   var content = "
" + Parser.getAnnotatedTextFirstBest(response) + "
";
                   if (settings.powered_by == 'yes') {
                       $(content).append($(powered_by));
                   };
                   $(this).html(content);

               if(settings.callback != undefined) {
                   settings.callback(response);
               }
          }

               return this.each(function() {
                 //console.log($.quoteString($(this).text()));
                 var params = {'text': $(this).text(), 'confidence': settings.confidence, 'support': settings.support, 'spotter': settings.spotter, 'policy': settings.policy };
                 if("types" in settings && settings["types"] != undefined)
                   params["types"] = settings.types;
                 if("sparql" in settings && settings["sparql"] != undefined)
                   params["sparql"] = settings.sparql;

                 ajaxRequest = $.ajax({ 'url': settings.endpoint+"/annotate",
                      'data': params,
                      'context': this,
                      'headers': {'Accept': 'application/json'},
                      'success': update
                    });
                 });
       },
       candidates: function( options ) {
		//init(options);
               function update(response) {
                   var content = "
" + Parser.getAnnotatedText(response) + "
";
                   if (settings.powered_by == 'yes') {
                       $(content).append($(powered_by));
                   };
                   $(this).html(content);

                   if(settings.callback != undefined) {
                    settings.callback(response);
                   }
               }

               return this.each(function() {
                 var params = {'text': $(this).text(), 'confidence': settings.confidence, 'support': settings.support, 'spotter': settings.spotter, 'policy': settings.policy };
                 if("types" in settings && settings["types"] != undefined)
                   params['types'] = settings.types;
                 if("sparql" in settings && settings["sparql"] != undefined)
                   params["sparql"] = settings.sparql;

                 ajaxRequest = $.ajax({ 'url': settings.endpoint+"/candidates",
                      'data': params,
                      'context': this,
                      'headers': {'Accept': 'application/json'},
                      'success': update
                    });
               });
       },
       suggest: function( options ) {
	       //init(options);
               function update(response) {
                   var keywords = Kolich.Selector.getSelected();
                   var suggestion = Parser.getSuggestions(response, keywords);
			console.log('keywords:'+keywords);
			console.log('suggestion:'+suggestion);
                   var content = "
" + suggestion + "
";
                   if (settings.powered_by == 'yes') {
                       $(content).append($(powered_by));
                   };
                   $(this).html(content);
               }

               return this.each(function() {
                 console.log('suggest');
                 var keywords = $.trim("" + Kolich.Selector.getSelected());
		 var params = {'text': $(this).text(), 'confidence': settings.confidence, 'support': settings.support, 'spotter': settings.spotter, 'surfaceForm': keywords };
                 if("types" in settings && settings["types"] != undefined){
                   params['types'] = settings.types;
                 }

                 ajaxRequest = $.ajax({ 'url': settings.endpoint+"/candidates",
                      'data': params,
                      'context': this,
                      'headers': {'Accept': 'application/json'},
                      'success': update
                    });
               });
       }

  };

  $.fn.annotate = function(method) {

	//console.log('method:',method);

      // Method calling logic
      if ( methods[method] ) {
        return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
      } else if ( typeof method === 'object' || ! method ) {
        return methods.init.apply( this, arguments );
      } else {
        $.error( 'Method ' +  method + ' does not exist on jQuery.spotlight' );
      }
  };

    $.fn.cancelAnnotation = function() {
        ajaxRequest.abort();
    }

})( jQuery );
<commit_msg>fixed bug with ordering of spots, added new config parameter names to server.conf<commit_after>/*
 * Copyright 2011 Pablo Mendes, Max Jakob
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  Check our project website for information on how to acknowledge the authors and how to contribute to the project: http://spotlight.dbpedia.org
 */

/**
 * If you use this script, please give credit to DBpedia Spotlight by:
 * - adding "powered by DBpedia Spotlight" somewhere in the page.
 * - add a link to http://spotlight.dbpedia.org.
 *
 * TODO people can also want to change the boundaries of the spotting
 * TODO showScores = [ list of score names to display ]
 *
 * @author pablomendes
 *
 */

jQuery.fn.sort = function() {
    return this.pushStack( [].sort.apply( this, arguments ), []);
};

 function sortOffset(a,b){
     if (a["@offset"] == b["@offset"]){
         console.log("equal")
       return 0;
     }

     console.log("a>b="+parseInt(a["@offset"])>parseInt(b["@offset"]))
     return parseInt(a["@offset"]) > parseInt(b["@offset"]) ? 1 : -1;
 };

(function( $ ){

   var powered_by = "
Powered by DBpedia Spotlight
";

   var settings = {
      'endpoint' : 'http://localhost:2223/rest',
      'confidence' : 0.4,          //
      'support' : 20,
      'powered_by': 'yes',         // yes or no
      'showScores': 'yes',         // yes or no
      'types': '',
      'policy' : 'whitelist',
      'spotter': 'LingPipeSpotter' // one of: LingPipeSpotter,AtLeastOneNounSelector,CoOccurrenceBasedSelector
    };

   function getScoreDOMElements(data) {
        var li = ""
        for (var key in data)
            li  += "" + data[key] +"";
        return li;
   }

   var Parser = {
	getSelectBox: function(resources, className) {
             var ul =  $("

");
             $.each(resources, function(i, r) {
                 var li = "
" + r["@label"] + "";

                 //TODO settings.showScores = ["finalScore"] foreach showscores, add k=v
                 if (settings.showScores == 'yes') {
                    li += " (" + parseFloat(r["@finalScore"]).toPrecision(3) +")";
                 }

                 li += getScoreDOMElements({
                                     "finalScore": parseFloat(r["@finalScore"]).toPrecision(3),
                                     "contextualScore": parseFloat(r["@contextualScore"]),
                                     "percentageOfSecondRank": parseFloat(r["@percentageOfSecondRank"]),
                                     "support": parseFloat(r["@support"]),
                                     "priorScore": parseFloat(r["@priorScore"])
                                    });

                 li += "
";
                 var opt = $(li);
                 $(ul).append(opt);
             });
             return ul;
        },
	getAnnotatedText: function(response) {
             var json = $.parseJSON(response);
	     if (json==null) json = response; // when it comes already parsed

             var text = json["annotation"]["@text"];

             var start = 0;
             var annotatedText = text;

             if (json.annotation['surfaceForm']!=undefined)
                  //console.log(json.annotation['surfaceForm']);
                  var annotations = new Array().concat(json.annotation.surfaceForm).sort(sortOffset) // deals with the case of only one surfaceFrom returned (ends up not being an array)
                  console.log(annotations)
                  annotatedText = annotations.map(function(e) {
                  if (e==undefined) return "";
		  //console.log(e);
                  var sfName = e["@name"];
                  var offset = parseInt(e["@offset"]);
                  var sfLength = parseInt(sfName.length);
                  var snippet = text.substring(start, offset)
                  var surfaceForm = text.substring(offset,offset+sfLength);
                  start = offset+sfLength;

                  var classes = "annotation";

                  snippet += "
" + sfName + "";
                  var ul = Parser.getSelectBox($(e.resource),'candidate');
                  //ul.children().each(function() { console.log($.data($(this),"testProp")); });
                  snippet += "
"+ul.html()+"
"; //FIXME this wrapper is a repeat from getSelectBox
                  snippet += "
";

                  return snippet;
			    }).join("");
             //snippet after last surface form
             annotatedText += text.substring(start, text.length);
             //console.log(annotatedText);
             return annotatedText.replace(/\n/g, "
\n");
        },
        getAnnotatedTextFirstBest: function(response) {
                     var json = $.parseJSON(response);
        	     if (json==null) json = response; // when it comes already parsed

                     var text = json["@text"];

                     var start = 0;
                     var annotatedText = text;

                     if (json['Resources']!=undefined)
                          var annotations = new Array().concat(json.Resources) // deals with the case of only one surfaceFrom returned (ends up not being an array)

                          annotatedText = annotations.map(function(e) {
                          if (e==undefined) return "";

                          var sfName = e["@surfaceForm"];
                          var offset = parseInt(e["@offset"]);
                          var uri = e["@URI"];

                          var sfLength = parseInt(sfName.length);
                          var snippet = text.substring(start, offset)
                          var surfaceForm = text.substring(offset,offset+sfLength);
                          start = offset+sfLength;

                          var support = parseInt(e["@support"]);
                          var confidence = 0.0;

                          var classes = "annotation"
                          snippet += "" + sfName

                          snippet += getScoreDOMElements({
                                     "finalScore": parseFloat(e["@similarityScore"]).toPrecision(3),
                                     "percentageOfSecondRank": parseFloat(e["@percentageOfSecondRank"]),
                                     "support": parseFloat(e["@support"]),
                                    });

                          snippet += "";

                          return snippet;
        			    }).join("");
                     //snippet after last surface form
                     annotatedText += text.substring(start, text.length);
                     //console.log(annotatedText);
                     return annotatedText.replace(/\n/g, "
\n");
                },

	getSuggestions: function(response, targetSurfaceForm) {
             var json = $.parseJSON(response);
	     if (json==null) json = response; // when it comes already parsed
             var suggestions = "";
	     if (json.annotation['surfaceForm']!=undefined) {
                  var annotations = new Array().concat(json.annotation.surfaceForm) // deals with the case of only one surfaceFrom returned (ends up not being an array)
                  suggestions = annotations.filter(function(e) {
			return (e["@name"]==$.trim(targetSurfaceForm));
		  }).map(function(e) {
                  	return Parser.getSelectBox($(e.resource),'none');
		  }).join("");
            }
            return suggestions;
        }
   };

   var ajaxRequest;
   var methods = {
      init : function( options ) {
          // If options exist, lets merge them with our default settings
          if ( options ) {
              $.extend( settings, options );
          }
      },
      best: function( options ) {
          //init(options);
          function update(response) {

                   var content = "
" + Parser.getAnnotatedTextFirstBest(response) + "
";
                   if (settings.powered_by == 'yes') {
                       $(content).append($(powered_by));
                   };
                   $(this).html(content);

               if(settings.callback != undefined) {
                   settings.callback(response);
               }
          }

               return this.each(function() {
                 //console.log($.quoteString($(this).text()));
                 var params = {'text': $(this).text(), 'confidence': settings.confidence, 'support': settings.support, 'spotter': settings.spotter, 'policy': settings.policy };
                 if("types" in settings && settings["types"] != undefined)
                   params["types"] = settings.types;
                 if("sparql" in settings && settings["sparql"] != undefined)
                   params["sparql"] = settings.sparql;

                 ajaxRequest = $.ajax({ 'url': settings.endpoint+"/annotate",
                      'data': params,
                      'context': this,
                      'headers': {'Accept': 'application/json'},
                      'success': update
                    });
                 });
       },
       candidates: function( options ) {
		//init(options);
               function update(response) {
                   var content = "
" + Parser.getAnnotatedText(response) + "
";
                   if (settings.powered_by == 'yes') {
                       $(content).append($(powered_by));
                   };
                   $(this).html(content);

                   if(settings.callback != undefined) {
                    settings.callback(response);
                   }
               }

               return this.each(function() {
                 var params = {'text': $(this).text(), 'confidence': settings.confidence, 'support': settings.support, 'spotter': settings.spotter, 'policy': settings.policy };
                 if("types" in settings && settings["types"] != undefined)
                   params['types'] = settings.types;
                 if("sparql" in settings && settings["sparql"] != undefined)
                   params["sparql"] = settings.sparql;

                 ajaxRequest = $.ajax({ 'url': settings.endpoint+"/candidates",
                      'data': params,
                      'context': this,
                      'headers': {'Accept': 'application/json'},
                      'success': update
                    });
               });
       },
       suggest: function( options ) {
	       //init(options);
               function update(response) {
                   var keywords = Kolich.Selector.getSelected();
                   var suggestion = Parser.getSuggestions(response, keywords);
			console.log('keywords:'+keywords);
			console.log('suggestion:'+suggestion);
                   var content = "
" + suggestion + "
";
                   if (settings.powered_by == 'yes') {
                       $(content).append($(powered_by));
                   };
                   $(this).html(content);
               }

               return this.each(function() {
                 console.log('suggest');
                 var keywords = $.trim("" + Kolich.Selector.getSelected());
		 var params = {'text': $(this).text(), 'confidence': settings.confidence, 'support': settings.support, 'spotter': settings.spotter, 'surfaceForm': keywords };
                 if("types" in settings && settings["types"] != undefined){
                   params['types'] = settings.types;
                 }

                 ajaxRequest = $.ajax({ 'url': settings.endpoint+"/candidates",
                      'data': params,
                      'context': this,
                      'headers': {'Accept': 'application/json'},
                      'success': update
                    });
               });
       }

  };

  $.fn.annotate = function(method) {

	//console.log('method:',method);

      // Method calling logic
      if ( methods[method] ) {
        return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
      } else if ( typeof method === 'object' || ! method ) {
        return methods.init.apply( this, arguments );
      } else {
        $.error( 'Method ' +  method + ' does not exist on jQuery.spotlight' );
      }
  };

    $.fn.cancelAnnotation = function() {
        ajaxRequest.abort();
    }

})( jQuery );
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import './vms.css'
import {selectVmDetail, closeVmDetail, shutdownVm, restartVm, startVm, getConsole} from './actions'
import {canRestart, canShutdown, canStart, canConsole, logDebug} from './helpers'

class NoVm extends Component {
  render () {// TODO
    return (

          No VM available

          No VM can be retrieved for the logged user.

          Learn more about this on the documentation.

          <button className="btn btn-primary btn-lg"> Main Action </button>

          <button className="btn btn-default"> Secondary Action </button> <button className="btn btn-default"> Secondary Action </button> <button className="btn btn-default"> Secondary Action </button>

  )}
}
class VmActions extends Component {
  button ({className, tooltip='', onClick}) {
    return (

  )}
  render () {
    const {vm, dispatch} = this.props

    const onShutdown = () => dispatch(shutdownVm({vm, force: false}))
    const onRestart = () => dispatch(restartVm({vm, force: false}))
    const onStart = () => dispatch(startVm({vm}))

    return (

      {canShutdown(vm.status) ? this.button({className: 'fa fa-power-off', tooltip: 'Click to shut down the VM', onClick: onShutdown}): ''}
      {canRestart(vm.status) ? this.button({className: 'fa fa-refresh', tooltip: 'Click to reboot the VM', onClick: onRestart}) : ''}
      {canStart(vm.status) ? this.button({className: 'fa fa-angle-double-right', tooltip: 'Click to start the VM', onClick: onStart}) : ''}

  )}
}
VmActions.propTypes = {
  vm: React.PropTypes.object.isRequired,
  dispatch: React.PropTypes.func.isRequired
}

class VmStatusInfo extends Component {
  statusIcon ({state}) {
    function iconElement ({className, tooltip}) {
      return (

    )}

    switch (state) { // TODO: review
      case 'up':
        return iconElement({className: 'pficon pficon-ok icon-1x-vms', tooltip: 'The VM is running.'});
      case 'powering_up':
        return iconElement({className: 'fa fa-angle-double-right icon-1x-vms', tooltip: 'The VM is powering up.'});
      case 'down':
        return iconElement({className: 'fa fa-arrow-circle-o-down icon-1x-vms', tooltip: 'The VM is down.'});
      case 'paused':
        return iconElement({className: 'pficon pficon-pause icon-1x-vms', tooltip: 'The VM is paused.'});
      case 'suspended':
        return iconElement({className: 'fa fa-shield icon-1x-vms', tooltip: 'The VM is suspended.'});
      case 'powering_down':
        return iconElement({className: 'glyphicon glyphicon-wrench icon-1x-vms', tooltip: 'The VM is going down.'});
      case 'not_responding':
        return iconElement({className: 'pficon pficon-warning-triangle-o icon-1x-vms', tooltip: 'The VM is not responding.'});
      case 'unknown':
        return iconElement({className: 'pficon pficon-help icon-1x-vms', tooltip: 'The VM status is unknown.'});
      case 'unassigned':
        return iconElement({className: 'pficon pficon-help icon-1x-vms', tooltip: 'The VM status is unassigned.'});
      case 'migrating':
        return iconElement({className: 'pficon pficon-service icon-1x-vms', tooltip: 'The VM is being migrated.'});
      case 'wait_for_launch':
        return iconElement({className: 'pficon pficon-service icon-1x-vms', tooltip: 'The VM is scheduled for launch.'});
      case 'reboot_in_progress':
        return iconElement({className: 'fa fa-refresh icon-1x-vms', tooltip: 'The VM is being rebooted.'});
      case 'saving_state':
        return iconElement({className: 'pficon pficon-export icon-1x-vms', tooltip: 'The VM is saving its state.'});
      case 'restoring_state':
        return iconElement({className: 'pficon pficon-import icon-1x-vms', tooltip: 'The VM is restoring its state.'});
      case 'image_locked':
        return iconElement({className: 'pficon pficon-volume icon-1x-vms', tooltip: 'The VM\'s image is locked'});

      case undefined: // better not to happen ...
        logDebug(`-- VmStatusInfo component: VM state is undefined`);
        return (
)
      default: // better not to happen ...
        logDebug(`-- VmStatusInfo component: unrecognized VM state '${state}'`);
        return iconElement({className: 'pficon pficon-zone', tooltip: `The VM state is '${state}'`})
    }
  }
  consoleIcon ({vm, dispatch}) {
    const onGetConsole = () => dispatch(getConsole({vm}))
    return (

  )}
  render () {
    const {vm, dispatch} = this.props

    return (// fa fa-check

          {this.statusIcon({state: vm.status})}

        {canConsole({vm}) ? this.consoleIcon({vm, dispatch}) : ''}

    )
  }
}
VmStatusInfo.propTypes = {
  vm: React.PropTypes.object.isRequired,
  dispatch: React.PropTypes.func.isRequired
}

class VmStatusText extends Component {
  render () {
    const {vm} = this.props

    switch (vm.status) {// TODO: review
      case 'up':
      case 'powering_up':
      case 'paused':
      case 'migrating':
        return (
Started On{vm['startTime']}
)
      default:
        return (
Stopped On: {vm['stopTime']}
)
    }
  }
}
VmStatusText.propTypes = {
  vm: React.PropTypes.object.isRequired
}

class VmIcon extends Component {
  render () {
    const {vmIcon, className, missingIconClassName} = this.props

    if (vmIcon.content) {
      const src = `data:${vmIcon.mediaType};base64,${vmIcon.content}`
      return ()
    }

    return ()
  }
}
VmIcon.propTypes = {
  vmIcon: React.PropTypes.object.isRequired, // either vm.icons.large or vm.icons.small
  className: React.PropTypes.string.isRequired, // either card-pf-icon or vm-detail-icon
  missingIconClassName: React.PropTypes.string.isRequired
}

class Vm extends Component {
  render () {
    const {vm, dispatch} = this.props

    const onSelectVm = () => dispatch(selectVmDetail({vm}))

    // TODO: improve the card flip:
    // TODO: https://davidwalsh.name/css-flip
    // TODO: http://tympanus.net/codrops/2013/12/18/perspective-page-view-navigation/
    // TODO: https://desandro.github.io/3dtransforms/docs/card-flip.html
    return (

              <VmIcon vmIcon={vm.icons.large} className="card-pf-icon" missingIconClassName="fa fa-birthday-cake card-pf-icon-circle"/>

              {vm.name}

            <VmStatusInfo vm={vm} dispatch={dispatch}/>
            <VmActions vm={vm} dispatch={dispatch}/>
            <VmStatusText vm={vm} />

    )
  }
}
Vm.propTypes = {
  vm: React.PropTypes.object.isRequired,
  dispatch: React.PropTypes.func.isRequired
}

class VmDetail extends Component {
  render () {
    const vm = this.props['vm'] // optional

    if (vm) {
      const dispatch = this.props.dispatch
      const onClose = () => dispatch(closeVmDetail())

      return (

           Close

<VmIcon vmIcon={vm.icons.small} missingIconClassName="pficon pficon-virtual-machine" className="vm-detail-icon"/> {vm.name}

Operating System

{vm.os['type']}

State

{vm.status}

ID

{vm.id}

Created On

{vm['creationTime']}

Started On

{vm['startTime']}

Stopped On

{vm['stopTime']}

Address

{vm['fqdn']}

      )
    } else {
      return (
)
    }
  }
}
Vm.propTypes = {
  vm: React.PropTypes.object,
  dispatch: React.PropTypes.func
}

class Vms extends Component {
  renderVms ({vms, dispatch}) {
    const containerClass = 'container-fluid container-cards-pf ' + (vms.selected ? 'move-left' : 'move-left-remove')

    return (

          {vms.vms.map(vm => <Vm vm={vm} key={vm.id} dispatch={dispatch}/>)}

      <VmDetail vm={vms.selected} dispatch={dispatch}/>

  )}
  render () {
    const {vms, dispatch} = this.props
    if (vms.vms && vms.vms.length > 0) {
      return (this.renderVms({vms, dispatch}))
    } else {
      return (

        <NoVm />

)
    }
  }
}
Vms.propTypes = {
  vms: React.PropTypes.object.isRequired,
  dispatch: React.PropTypes.func.isRequired
}

export default Vms
<commit_msg>Bind the ESC key to close the VM detail<commit_after>import React, { Component } from 'react'
import './vms.css'
import {selectVmDetail, closeVmDetail, shutdownVm, restartVm, startVm, getConsole} from './actions'
import {canRestart, canShutdown, canStart, canConsole, logDebug} from './helpers'

class NoVm extends Component {
  render () {// TODO
    return (

          No VM available

          No VM can be retrieved for the logged user.

          Learn more about this on the documentation.

          <button className="btn btn-primary btn-lg"> Main Action </button>

          <button className="btn btn-default"> Secondary Action </button> <button className="btn btn-default"> Secondary Action </button> <button className="btn btn-default"> Secondary Action </button>

  )}
}
class VmActions extends Component {
  button ({className, tooltip='', onClick}) {
    return (

  )}
  render () {
    const {vm, dispatch} = this.props

    const onShutdown = () => dispatch(shutdownVm({vm, force: false}))
    const onRestart = () => dispatch(restartVm({vm, force: false}))
    const onStart = () => dispatch(startVm({vm}))

    return (

      {canShutdown(vm.status) ? this.button({className: 'fa fa-power-off', tooltip: 'Click to shut down the VM', onClick: onShutdown}): ''}
      {canRestart(vm.status) ? this.button({className: 'fa fa-refresh', tooltip: 'Click to reboot the VM', onClick: onRestart}) : ''}
      {canStart(vm.status) ? this.button({className: 'fa fa-angle-double-right', tooltip: 'Click to start the VM', onClick: onStart}) : ''}

  )}
}
VmActions.propTypes = {
  vm: React.PropTypes.object.isRequired,
  dispatch: React.PropTypes.func.isRequired
}

class VmStatusInfo extends Component {
  statusIcon ({state}) {
    function iconElement ({className, tooltip}) {
      return (

    )}

    switch (state) { // TODO: review
      case 'up':
        return iconElement({className: 'pficon pficon-ok icon-1x-vms', tooltip: 'The VM is running.'});
      case 'powering_up':
        return iconElement({className: 'fa fa-angle-double-right icon-1x-vms', tooltip: 'The VM is powering up.'});
      case 'down':
        return iconElement({className: 'fa fa-arrow-circle-o-down icon-1x-vms', tooltip: 'The VM is down.'});
      case 'paused':
        return iconElement({className: 'pficon pficon-pause icon-1x-vms', tooltip: 'The VM is paused.'});
      case 'suspended':
        return iconElement({className: 'fa fa-shield icon-1x-vms', tooltip: 'The VM is suspended.'});
      case 'powering_down':
        return iconElement({className: 'glyphicon glyphicon-wrench icon-1x-vms', tooltip: 'The VM is going down.'});
      case 'not_responding':
        return iconElement({className: 'pficon pficon-warning-triangle-o icon-1x-vms', tooltip: 'The VM is not responding.'});
      case 'unknown':
        return iconElement({className: 'pficon pficon-help icon-1x-vms', tooltip: 'The VM status is unknown.'});
      case 'unassigned':
        return iconElement({className: 'pficon pficon-help icon-1x-vms', tooltip: 'The VM status is unassigned.'});
      case 'migrating':
        return iconElement({className: 'pficon pficon-service icon-1x-vms', tooltip: 'The VM is being migrated.'});
      case 'wait_for_launch':
        return iconElement({className: 'pficon pficon-service icon-1x-vms', tooltip: 'The VM is scheduled for launch.'});
      case 'reboot_in_progress':
        return iconElement({className: 'fa fa-refresh icon-1x-vms', tooltip: 'The VM is being rebooted.'});
      case 'saving_state':
        return iconElement({className: 'pficon pficon-export icon-1x-vms', tooltip: 'The VM is saving its state.'});
      case 'restoring_state':
        return iconElement({className: 'pficon pficon-import icon-1x-vms', tooltip: 'The VM is restoring its state.'});
      case 'image_locked':
        return iconElement({className: 'pficon pficon-volume icon-1x-vms', tooltip: 'The VM\'s image is locked'});

      case undefined: // better not to happen ...
        logDebug(`-- VmStatusInfo component: VM state is undefined`);
        return (
)
      default: // better not to happen ...
        logDebug(`-- VmStatusInfo component: unrecognized VM state '${state}'`);
        return iconElement({className: 'pficon pficon-zone', tooltip: `The VM state is '${state}'`})
    }
  }
  consoleIcon ({vm, dispatch}) {
    const onGetConsole = () => dispatch(getConsole({vm}))
    return (

  )}
  render () {
    const {vm, dispatch} = this.props

    return (// fa fa-check

          {this.statusIcon({state: vm.status})}

        {canConsole({vm}) ? this.consoleIcon({vm, dispatch}) : ''}

    )
  }
}
VmStatusInfo.propTypes = {
  vm: React.PropTypes.object.isRequired,
  dispatch: React.PropTypes.func.isRequired
}

class VmStatusText extends Component {
  render () {
    const {vm} = this.props

    switch (vm.status) {// TODO: review
      case 'up':
      case 'powering_up':
      case 'paused':
      case 'migrating':
        return (
Started On{vm['startTime']}
)
      default:
        return (
Stopped On: {vm['stopTime']}
)
    }
  }
}
VmStatusText.propTypes = {
  vm: React.PropTypes.object.isRequired
}

class VmIcon extends Component {
  render () {
    const {vmIcon, className, missingIconClassName} = this.props

    if (vmIcon.content) {
      const src = `data:${vmIcon.mediaType};base64,${vmIcon.content}`
      return ()
    }

    return ()
  }
}
VmIcon.propTypes = {
  vmIcon: React.PropTypes.object.isRequired, // either vm.icons.large or vm.icons.small
  className: React.PropTypes.string.isRequired, // either card-pf-icon or vm-detail-icon
  missingIconClassName: React.PropTypes.string.isRequired
}

class Vm extends Component {
  render () {
    const {vm, dispatch} = this.props

    const onSelectVm = () => dispatch(selectVmDetail({vm}))

    // TODO: improve the card flip:
    // TODO: https://davidwalsh.name/css-flip
    // TODO: http://tympanus.net/codrops/2013/12/18/perspective-page-view-navigation/
    // TODO: https://desandro.github.io/3dtransforms/docs/card-flip.html
    return (

              <VmIcon vmIcon={vm.icons.large} className="card-pf-icon" missingIconClassName="fa fa-birthday-cake card-pf-icon-circle"/>

              {vm.name}

            <VmStatusInfo vm={vm} dispatch={dispatch}/>
            <VmActions vm={vm} dispatch={dispatch}/>
            <VmStatusText vm={vm} />

    )
  }
}
Vm.propTypes = {
  vm: React.PropTypes.object.isRequired,
  dispatch: React.PropTypes.func.isRequired
}

class VmDetail extends Component {
  componentDidMount () {
    this.onKeyDown = (event) => {
      if (event.keyCode === 27) { // ESC
        this.onClose()
      }
    }
    this.onClose = () => {
      this.props.dispatch(closeVmDetail())
    }

    window.addEventListener('keydown', this.onKeyDown);
  }
  componentWillUnmount () {
    window.removeEventListener('keydown', this.onKeyDown);
  }
  render () {
    const vm = this.props['vm'] // optional

    if (vm) {
      return (

           Close

<VmIcon vmIcon={vm.icons.small} missingIconClassName="pficon pficon-virtual-machine" className="vm-detail-icon"/> {vm.name}

Operating System

{vm.os['type']}

State

{vm.status}

ID

{vm.id}

Created On

{vm['creationTime']}

Started On

{vm['startTime']}

Stopped On

{vm['stopTime']}

Address

{vm['fqdn']}

      )
    } else {
      return (
)
    }
  }
}
Vm.propTypes = {
  vm: React.PropTypes.object,
  dispatch: React.PropTypes.func
}

class Vms extends Component {
  renderVms ({vms, dispatch}) {
    const containerClass = 'container-fluid container-cards-pf ' + (vms.selected ? 'move-left' : 'move-left-remove')

    return (

          {vms.vms.map(vm => <Vm vm={vm} key={vm.id} dispatch={dispatch}/>)}

      <VmDetail vm={vms.selected} dispatch={dispatch}/>

  )}
  render () {
    const {vms, dispatch} = this.props
    if (vms.vms && vms.vms.length > 0) {
      return (this.renderVms({vms, dispatch}))
    } else {
      return (

        <NoVm />

)
    }
  }
}
Vms.propTypes = {
  vms: React.PropTypes.object.isRequired,
  dispatch: React.PropTypes.func.isRequired
}

export default Vms
<|endoftext|>


<commit_before>/*
 * Copyright 2011 Pablo Mendes, Max Jakob
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  Check our project website for information on how to acknowledge the authors and how to contribute to the project: http://spotlight.dbpedia.org
 */

/**
 * If you use this script, please give credit to DBpedia Spotlight by:
 * - adding "powered by DBpedia Spotlight" somewhere in the page.
 * - add a link to http://spotlight.dbpedia.org.
 *
 * TODO people can also want to change the boundaries of the spotting
 * TODO showScores = [ list of score names to display ]
 *
 * @author pablomendes
 *
 */

//from http://www.wrichards.com/blog/2009/02/jquery-sorting-elements/
jQuery.fn.sort = function() {
    return this.pushStack( [].sort.apply( this, arguments ), []);
};
function sortOffset(a,b){
     if (a["@offset"] == b["@offset"]){
       return 0;
     }
     return parseInt(a["@offset"]) > parseInt(b["@offset"]) ? 1 : -1;
};

(function( $ ){

   var powered_by = "
Powered by DBpedia Spotlight
";

   var settings = {
      'endpoint' : 'http://localhost:2223/rest',
      'confidence' : 0.4,          //
      'support' : 20,
      'powered_by': 'yes',         // yes or no
      'showScores': 'yes',         // yes or no
      'types': '',
      'policy' : 'whitelist',
      'spotter': 'LingPipeSpotter' // one of: LingPipeSpotter,AtLeastOneNounSelector,CoOccurrenceBasedSelector
    };

   function getScoreDOMElements(data) {
        var li = ""
        for (var key in data)
            li  += "" + data[key] +"";
        return li;
   }

   var Parser = {
	getSelectBox: function(resources, className) {
             var ul =  $("

");
             $.each(resources, function(i, r) {
                 var li = "
" + r["@label"] + "";

                 //TODO settings.showScores = ["finalScore"] foreach showscores, add k=v
                 if (settings.showScores == 'yes') {
                    li += " (" + parseFloat(r["@finalScore"]).toPrecision(3) +")";
                 }

                 li += getScoreDOMElements({
                                     "finalScore": parseFloat(r["@finalScore"]).toPrecision(3),
                                     "contextualScore": parseFloat(r["@contextualScore"]),
                                     "percentageOfSecondRank": parseFloat(r["@percentageOfSecondRank"]),
                                     "support": parseFloat(r["@support"]),
                                     "priorScore": parseFloat(r["@priorScore"])
                                    });

                 li += "
";
                 var opt = $(li);
                 $(ul).append(opt);
             });
             return ul;
        },
	getAnnotatedText: function(response) {
             var json = $.parseJSON(response);
	     if (json==null) json = response; // when it comes already parsed

             var text = json["annotation"]["@text"];

             var start = 0;
             var annotatedText = text;

             if (json.annotation['surfaceForm']!=undefined)
                  //console.log(json.annotation['surfaceForm']);
                  var annotations = new Array().concat(json.annotation.surfaceForm).sort(sortOffset) // deals with the case of only one surfaceFrom returned (ends up not being an array)
                  console.log(annotations)
                  annotatedText = annotations.map(function(e) {
                  if (e==undefined) return "";
		  //console.log(e);
                  var sfName = e["@name"];
                  var offset = parseInt(e["@offset"]);
                  var sfLength = parseInt(sfName.length);
                  var snippet = text.substring(start, offset)
                  var surfaceForm = text.substring(offset,offset+sfLength);
                  start = offset+sfLength;

                  var classes = "annotation";

                  snippet += "
" + sfName + "";
                  var ul = Parser.getSelectBox($(e.resource),'candidate');
                  //ul.children().each(function() { console.log($.data($(this),"testProp")); });
                  snippet += "
"+ul.html()+"
"; //FIXME this wrapper is a repeat from getSelectBox
                  snippet += "
";

                  return snippet;
			    }).join("");
             //snippet after last surface form
             annotatedText += text.substring(start, text.length);
             //console.log(annotatedText);
             return annotatedText.replace(/\n/g, "
\n");
        },
        getAnnotatedTextFirstBest: function(response) {
                     var json = $.parseJSON(response);
        	     if (json==null) json = response; // when it comes already parsed

                     var text = json["@text"];

                     var start = 0;
                     var annotatedText = text;

                     if (json['Resources']!=undefined)
                          var annotations = new Array().concat(json.Resources) // deals with the case of only one surfaceFrom returned (ends up not being an array)

                          annotatedText = annotations.map(function(e) {
                          if (e==undefined) return "";

                          var sfName = e["@surfaceForm"];
                          var offset = parseInt(e["@offset"]);
                          var uri = e["@URI"];

                          var sfLength = parseInt(sfName.length);
                          var snippet = text.substring(start, offset)
                          var surfaceForm = text.substring(offset,offset+sfLength);
                          start = offset+sfLength;

                          var support = parseInt(e["@support"]);
                          var confidence = 0.0;

                          var classes = "annotation"
                          snippet += "" + sfName

                          snippet += getScoreDOMElements({
                                     "finalScore": parseFloat(e["@similarityScore"]).toPrecision(3),
                                     "percentageOfSecondRank": parseFloat(e["@percentageOfSecondRank"]),
                                     "support": parseFloat(e["@support"]),
                                    });

                          snippet += "";

                          return snippet;
        			    }).join("");
                     //snippet after last surface form
                     annotatedText += text.substring(start, text.length);
                     //console.log(annotatedText);
                     return annotatedText.replace(/\n/g, "
\n");
                },

	getSuggestions: function(response, targetSurfaceForm) {
             var json = $.parseJSON(response);
	     if (json==null) json = response; // when it comes already parsed
             var suggestions = "";
	     if (json.annotation['surfaceForm']!=undefined) {
                  var annotations = new Array().concat(json.annotation.surfaceForm) // deals with the case of only one surfaceFrom returned (ends up not being an array)
                  suggestions = annotations.filter(function(e) {
			return (e["@name"]==$.trim(targetSurfaceForm));
		  }).map(function(e) {
                  	return Parser.getSelectBox($(e.resource),'none');
		  }).join("");
            }
            return suggestions;
        }
   };

   var ajaxRequest;
   var methods = {
      init : function( options ) {
          // If options exist, lets merge them with our default settings
          if ( options ) {
              $.extend( settings, options );
          }
      },
      best: function( options ) {
          //init(options);
          function update(response) {

                   var content = "
" + Parser.getAnnotatedTextFirstBest(response) + "
";
                   if (settings.powered_by == 'yes') {
                       $(content).append($(powered_by));
                   };
                   $(this).html(content);

               if(settings.callback != undefined) {
                   settings.callback(response);
               }
          }

               return this.each(function() {
                 //console.log($.quoteString($(this).text()));
                 var params = {'text': $(this).text(), 'confidence': settings.confidence, 'support': settings.support, 'spotter': settings.spotter, 'policy': settings.policy };
                 if("types" in settings && settings["types"] != undefined)
                   params["types"] = settings.types;
                 if("sparql" in settings && settings["sparql"] != undefined)
                   params["sparql"] = settings.sparql;

                 ajaxRequest = $.ajax({ 'url': settings.endpoint+"/annotate",
                      'data': params,
                      'context': this,
                      'headers': {'Accept': 'application/json'},
                      'success': update
                    });
                 });
       },
       candidates: function( options ) {
		//init(options);
               function update(response) {
                   var content = "
" + Parser.getAnnotatedText(response) + "
";
                   if (settings.powered_by == 'yes') {
                       $(content).append($(powered_by));
                   };
                   $(this).html(content);

                   if(settings.callback != undefined) {
                    settings.callback(response);
                   }
               }

               return this.each(function() {
                 var params = {'text': $(this).text(), 'confidence': settings.confidence, 'support': settings.support, 'spotter': settings.spotter, 'policy': settings.policy };
                 if("types" in settings && settings["types"] != undefined)
                   params['types'] = settings.types;
                 if("sparql" in settings && settings["sparql"] != undefined)
                   params["sparql"] = settings.sparql;

                 ajaxRequest = $.ajax({ 'url': settings.endpoint+"/candidates",
                      'data': params,
                      'context': this,
                      'headers': {'Accept': 'application/json'},
                      'success': update
                    });
               });
       },
       suggest: function( options ) {
           //init(options);
           function update(response) {
               var keywords = Kolich.Selector.getSelected();
               var suggestion = Parser.getSuggestions(response, keywords);
               console.log('keywords:'+keywords);
               console.log('suggestion:'+suggestion);
               var content = "
" + suggestion + "
";
               if (settings.powered_by == 'yes') {
                   $(content).append($(powered_by));
               };
               $(this).html(content);
           }

           return this.each(function() {
               console.log('suggest');
               var keywords = $.trim("" + Kolich.Selector.getSelected());
               var params = {'text': $(this).text(), 'confidence': settings.confidence, 'support': settings.support, 'spotter': settings.spotter, 'surfaceForm': keywords };
               if("types" in settings && settings["types"] != undefined){
                   params['types'] = settings.types;
               }

               ajaxRequest = $.ajax({ 'url': settings.endpoint+"/candidates",
                   'data': params,
                   'context': this,
                   'headers': {'Accept': 'application/json'},
                   'success': update
               });
           });
       }

  };

  $.fn.annotate = function(method) {

	//console.log('method:',method);

      // Method calling logic
      if ( methods[method] ) {
        return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
      } else if ( typeof method === 'object' || ! method ) {
        return methods.init.apply( this, arguments );
      } else {
        $.error( 'Method ' +  method + ' does not exist on jQuery.spotlight' );
      }
  };

    $.fn.cancelAnnotation = function() {
        ajaxRequest.abort();
    }

})( jQuery );
<commit_msg>fixed bug introduced by last change to FreebaseType object creation; separated factories; added workaround to console.log<commit_after>/*
 * Copyright 2011 Pablo Mendes, Max Jakob
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  Check our project website for information on how to acknowledge the authors and how to contribute to the project: http://spotlight.dbpedia.org
 */

/**
 * If you use this script, please give credit to DBpedia Spotlight by:
 * - adding "powered by DBpedia Spotlight" somewhere in the page.
 * - add a link to http://spotlight.dbpedia.org.
 *
 * TODO people can also want to change the boundaries of the spotting
 * TODO showScores = [ list of score names to display ]
 *
 * @author pablomendes
 *
 */

// adding this in case we forget to remove some console.log statement that would make it break on firefox without firebug.
if (console===undefined) {
    console = { "log": function() {} }
}

//from http://www.wrichards.com/blog/2009/02/jquery-sorting-elements/
jQuery.fn.sort = function() {
    return this.pushStack( [].sort.apply( this, arguments ), []);
};
function sortOffset(a,b){
     if (a["@offset"] == b["@offset"]){
       return 0;
     }
     return parseInt(a["@offset"]) > parseInt(b["@offset"]) ? 1 : -1;
};

(function( $ ){

   var powered_by = "
Powered by DBpedia Spotlight
";

   var settings = {
      'endpoint' : 'http://localhost:2223/rest',
      'confidence' : 0.4,          //
      'support' : 20,
      'powered_by': 'yes',         // yes or no
      'showScores': 'yes',         // yes or no
      'types': '',
      'policy' : 'whitelist',
      'spotter': 'LingPipeSpotter' // one of: LingPipeSpotter,AtLeastOneNounSelector,CoOccurrenceBasedSelector
    };

   function getScoreDOMElements(data) {
        var li = ""
        for (var key in data)
            li  += "" + data[key] +"";
        return li;
   }

   var Parser = {
	getSelectBox: function(resources, className) {
             var ul =  $("

");
             $.each(resources, function(i, r) {
                 var li = "
" + r["@label"] + "";

                 //TODO settings.showScores = ["finalScore"] foreach showscores, add k=v
                 if (settings.showScores == 'yes') {
                    li += " (" + parseFloat(r["@finalScore"]).toPrecision(3) +")";
                 }

                 li += getScoreDOMElements({
                                     "finalScore": parseFloat(r["@finalScore"]).toPrecision(3),
                                     "contextualScore": parseFloat(r["@contextualScore"]),
                                     "percentageOfSecondRank": parseFloat(r["@percentageOfSecondRank"]),
                                     "support": parseFloat(r["@support"]),
                                     "priorScore": parseFloat(r["@priorScore"])
                                    });

                 li += "
";
                 var opt = $(li);
                 $(ul).append(opt);
             });
             return ul;
        },
	getAnnotatedText: function(response) {
             var json = $.parseJSON(response);
	     if (json==null) json = response; // when it comes already parsed

             var text = json["annotation"]["@text"];

             var start = 0;
             var annotatedText = text;

             if (json.annotation['surfaceForm']!=undefined)
                  //console.log(json.annotation['surfaceForm']);
                  var annotations = new Array().concat(json.annotation.surfaceForm).sort(sortOffset) // deals with the case of only one surfaceFrom returned (ends up not being an array)
                  console.log(annotations)
                  annotatedText = annotations.map(function(e) {
                  if (e==undefined) return "";
		  //console.log(e);
                  var sfName = e["@name"];
                  var offset = parseInt(e["@offset"]);
                  var sfLength = parseInt(sfName.length);
                  var snippet = text.substring(start, offset)
                  var surfaceForm = text.substring(offset,offset+sfLength);
                  start = offset+sfLength;

                  var classes = "annotation";

                  snippet += "
" + sfName + "";
                  var ul = Parser.getSelectBox($(e.resource),'candidate');
                  //ul.children().each(function() { console.log($.data($(this),"testProp")); });
                  snippet += "
"+ul.html()+"
"; //FIXME this wrapper is a repeat from getSelectBox
                  snippet += "
";

                  return snippet;
			    }).join("");
             //snippet after last surface form
             annotatedText += text.substring(start, text.length);
             //console.log(annotatedText);
             return annotatedText.replace(/\n/g, "
\n");
        },
        getAnnotatedTextFirstBest: function(response) {
                     var json = $.parseJSON(response);
        	     if (json==null) json = response; // when it comes already parsed

                     var text = json["@text"];

                     var start = 0;
                     var annotatedText = text;

                     if (json['Resources']!=undefined)
                          var annotations = new Array().concat(json.Resources) // deals with the case of only one surfaceFrom returned (ends up not being an array)

                          annotatedText = annotations.map(function(e) {
                          if (e==undefined) return "";

                          var sfName = e["@surfaceForm"];
                          var offset = parseInt(e["@offset"]);
                          var uri = e["@URI"];

                          var sfLength = parseInt(sfName.length);
                          var snippet = text.substring(start, offset)
                          var surfaceForm = text.substring(offset,offset+sfLength);
                          start = offset+sfLength;

                          var support = parseInt(e["@support"]);
                          var confidence = 0.0;

                          var classes = "annotation"
                          snippet += "" + sfName

                          snippet += getScoreDOMElements({
                                     "finalScore": parseFloat(e["@similarityScore"]).toPrecision(3),
                                     "percentageOfSecondRank": parseFloat(e["@percentageOfSecondRank"]),
                                     "support": parseFloat(e["@support"]),
                                    });

                          snippet += "";

                          return snippet;
        			    }).join("");
                     //snippet after last surface form
                     annotatedText += text.substring(start, text.length);
                     //console.log(annotatedText);
                     return annotatedText.replace(/\n/g, "
\n");
                },

	getSuggestions: function(response, targetSurfaceForm) {
             var json = $.parseJSON(response);
	     if (json==null) json = response; // when it comes already parsed
             var suggestions = "";
	     if (json.annotation['surfaceForm']!=undefined) {
                  var annotations = new Array().concat(json.annotation.surfaceForm) // deals with the case of only one surfaceFrom returned (ends up not being an array)
                  suggestions = annotations.filter(function(e) {
			return (e["@name"]==$.trim(targetSurfaceForm));
		  }).map(function(e) {
                  	return Parser.getSelectBox($(e.resource),'none');
		  }).join("");
            }
            return suggestions;
        }
   };

   var ajaxRequest;
   var methods = {
      init : function( options ) {
          // If options exist, lets merge them with our default settings
          if ( options ) {
              $.extend( settings, options );
          }
      },
      best: function( options ) {
          //init(options);
          function update(response) {

                   var content = "
" + Parser.getAnnotatedTextFirstBest(response) + "
";
                   if (settings.powered_by == 'yes') {
                       $(content).append($(powered_by));
                   };
                   $(this).html(content);

               if(settings.callback != undefined) {
                   settings.callback(response);
               }
          }

               return this.each(function() {
                 //console.log($.quoteString($(this).text()));
                 var params = {'text': $(this).text(), 'confidence': settings.confidence, 'support': settings.support, 'spotter': settings.spotter, 'policy': settings.policy };
                 if("types" in settings && settings["types"] != undefined)
                   params["types"] = settings.types;
                 if("sparql" in settings && settings["sparql"] != undefined)
                   params["sparql"] = settings.sparql;

                 ajaxRequest = $.ajax({ 'url': settings.endpoint+"/annotate",
                      'data': params,
                      'context': this,
                      'headers': {'Accept': 'application/json'},
                      'success': update
                    });
                 });
       },
       candidates: function( options ) {
		//init(options);
               function update(response) {
                   var content = "
" + Parser.getAnnotatedText(response) + "
";
                   if (settings.powered_by == 'yes') {
                       $(content).append($(powered_by));
                   };
                   $(this).html(content);

                   if(settings.callback != undefined) {
                    settings.callback(response);
                   }
               }

               return this.each(function() {
                 var params = {'text': $(this).text(), 'confidence': settings.confidence, 'support': settings.support, 'spotter': settings.spotter, 'policy': settings.policy };
                 if("types" in settings && settings["types"] != undefined)
                   params['types'] = settings.types;
                 if("sparql" in settings && settings["sparql"] != undefined)
                   params["sparql"] = settings.sparql;

                 ajaxRequest = $.ajax({ 'url': settings.endpoint+"/candidates",
                      'data': params,
                      'context': this,
                      'headers': {'Accept': 'application/json'},
                      'success': update
                    });
               });
       },
       suggest: function( options ) {
           //init(options);
           function update(response) {
               var keywords = Kolich.Selector.getSelected();
               var suggestion = Parser.getSuggestions(response, keywords);
               console.log('keywords:'+keywords);
               console.log('suggestion:'+suggestion);
               var content = "
" + suggestion + "
";
               if (settings.powered_by == 'yes') {
                   $(content).append($(powered_by));
               };
               $(this).html(content);
           }

           return this.each(function() {
               console.log('suggest');
               var keywords = $.trim("" + Kolich.Selector.getSelected());
               var params = {'text': $(this).text(), 'confidence': settings.confidence, 'support': settings.support, 'spotter': settings.spotter, 'surfaceForm': keywords };
               if("types" in settings && settings["types"] != undefined){
                   params['types'] = settings.types;
               }

               ajaxRequest = $.ajax({ 'url': settings.endpoint+"/candidates",
                   'data': params,
                   'context': this,
                   'headers': {'Accept': 'application/json'},
                   'success': update
               });
           });
       }

  };

  $.fn.annotate = function(method) {

	//console.log('method:',method);

      // Method calling logic
      if ( methods[method] ) {
        return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
      } else if ( typeof method === 'object' || ! method ) {
        return methods.init.apply( this, arguments );
      } else {
        $.error( 'Method ' +  method + ' does not exist on jQuery.spotlight' );
      }
  };

    $.fn.cancelAnnotation = function() {
        ajaxRequest.abort();
    }

})( jQuery );
<|endoftext|>