<commit_before>var _ = require('lodash'),
    cheerio = require('cheerio'),
    chalk = require('chalk'),
    Table = require('cli-table'),
    Utility = require('../utility'),
    Model = require('../model');

Model.prototype.options = {
  string_truncate_length: 50,
  show_table: true
};

Model.prototype.parse = function(html){
  var $ = cheerio.load(html),
      self = this,
      definition = this.definition,
      collection,
      iteration,
      table;

  if (definition.type === 'collection') {
    collection = self._parseCollection(definition.validate, definition.format, definition.iterate, definition.elements, $);
    iteration = self._parseIteration(definition.iterate, $);

    console.log(chalk.yellow(iteration.length) + chalk.gray(' items matching the iterator, ' + chalk.green(collection.length)) + chalk.gray(' items valid.') );

    if (self.options.show_table) {
      table = new Table({
        head: _.keys(definition.elements),
        style: {
          head: ['white']
        }
      });

      _.map(iteration, function($){
        if (_.isNull(self._applyFilters(definition.validate, definition.format, self._parseItem(definition.elements, $)))){
          table.push(_.map(_.values(self._parseItem(definition.elements, $)), _.compose(chalk.gray, Utility.truncateString(self.string_truncate_length))))
        } else {
          table.push(_.map(_.values(self._parseItem(definition.elements, $)), _.compose(chalk.white, Utility.truncateString(self.string_truncate_length))))
        }
      });

      console.log(table.toString());
    }

    return collection;
  }

  if (definition.type === 'item')
    return this._parseItem(definition.elements, $);
};

module.exports = Model;<commit_msg>Fixed string truncating on ignite-model Added table row limit<commit_after>var _ = require('lodash'),
    cheerio = require('cheerio'),
    chalk = require('chalk'),
    Table = require('cli-table'),
    Utility = require('../utility'),
    Model = require('../model');

Model.prototype.options = {
  string_truncate_length: 50,
  show_table: true,
  table_rows: 10
};

Model.prototype.parse = function(html){
  var $ = cheerio.load(html),
      self = this,
      definition = this.definition,
      collection,
      iteration,
      table;

  if (definition.type === 'collection') {
    collection = self._parseCollection(definition.validate, definition.format, definition.iterate, definition.elements, $);
    iteration = self._parseIteration(definition.iterate, $);

    console.log(chalk.yellow(iteration.length) + chalk.gray(' items matching the iterator, ' + chalk.green(collection.length)) + chalk.gray(' items valid.') );

    if (self.options.show_table) {
      table = new Table({
        head: _.keys(definition.elements),
        style: {
          head: ['white']
        }
      });

      _.map(_.first(iteration, self.options.table_rows), function($){
        if (_.isNull(self._applyFilters(definition.validate, definition.format, self._parseItem(definition.elements, $)))){
          table.push(_.map(_.values(self._parseItem(definition.elements, $)), _.compose(chalk.gray, Utility.truncateString(self.options.string_truncate_length))))
        } else {
          table.push(_.map(_.values(self._parseItem(definition.elements, $)), _.compose(chalk.white, Utility.truncateString(self.options.string_truncate_length))))
        }
      });

      console.log(table.toString());
    }

    return collection;
  }

  if (definition.type === 'item')
    return this._parseItem(definition.elements, $);
};

module.exports = Model;<|endoftext|>


<commit_before>import '../add-layers/vector/add-layers-vector.module';
import 'angular-socialshare';
import ImageLayer from 'ol/layer/Image';
import SparqlJson from '../layers/hs.source.SparqlJson';
import VectorLayer from 'ol/layer/Vector';
import {Attribution} from 'ol/control';
import {Circle, Fill, Icon, Stroke, Style} from 'ol/style';
import {ImageArcGISRest, ImageStatic, TileArcGISRest, TileWMS} from 'ol/source';
import {ImageWMS, XYZ} from 'ol/source';
import {Tile} from 'ol/layer';
import {Vector as VectorSource} from 'ol/source';

/**
 * @param HsMapService
 * @param HsAddLayersVectorService
 */
export default function (HsMapService, HsAddLayersVectorService) {
  'ngInject';
  const me = {
    /**
     * @ngdoc method
     * @name hs.compositions.config_parsers.service#createWmsLayer
     * @public
     * @param {object} lyr_def Layer definition object
     * @returns {object} Ol Image or Tile layer
     * @description Parse definition object to create WMS Ol.layer  (source = ol.source.ImageWMS / ol.source.TileWMS)
     */
    createWmsLayer: function (lyr_def) {
      const source_class = lyr_def.singleTile ? ImageWMS : TileWMS;
      const layer_class = lyr_def.singleTile ? ImageLayer : Tile;
      const params = lyr_def.params;
      const legends = [];
      delete params.REQUEST;
      //delete params.FORMAT; Commented, because otherwise when loading from cookie or store, it displays jpeg
      if (angular.isDefined(lyr_def.legends)) {
        for (let idx_leg = 0; idx_leg < lyr_def.legends.length; idx_leg++) {
          legends.push(decodeURIComponent(lyr_def.legends[idx_leg]));
        }
      }
      const source = new source_class({
        url: decodeURIComponent(lyr_def.url),
        attributions: lyr_def.attribution
          ? [
              new Attribution({
                html:
                  '' +
                  lyr_def.attribution.Title +
                  '',
              }),
            ]
          : undefined,
        styles: angular.isDefined(lyr_def.metadata)
          ? lyr_def.metadata.styles
          : undefined,
        params: params,
        crossOrigin: 'anonymous',
        projection: lyr_def.projection,
        ratio: lyr_def.ratio,
      });
      const new_layer = new layer_class({
        title: lyr_def.title,
        from_composition: true,
        maxResolution: lyr_def.maxResolution || Number.Infinity,
        minResolution: lyr_def.minResolution || 0,
        minScale: lyr_def.minScale || Number.Infinity,
        maxScale: lyr_def.maxScale || 0,
        show_in_manager: lyr_def.displayInLayerSwitcher,
        abstract: lyr_def.name || lyr_def.abstract,
        base: lyr_def.base,
        metadata: lyr_def.metadata,
        dimensions: lyr_def.dimensions,
        legends: legends,
        saveState: true,
        path: lyr_def.path,
        opacity: lyr_def.opacity || 1,
        source,
        subLayers: lyr_def.subLayers,
      });

      new_layer.setVisible(lyr_def.visibility);
      HsMapService.proxifyLayerLoader(new_layer, !lyr_def.singleTile);
      return new_layer;
    },
    /**
     * @ngdoc method
     * @name hs.compositions.config_parsers.service#createArcGISLayer
     * @public
     * @param {object} lyr_def Layer definition object
     * @returns {object} Ol Image or Tile layer
     * @description Parse definition object to create ArcGIS Ol.layer  (source = ol.source.ImageArcGISRest / ol.source.TileArcGISRest)
     */
    createArcGISLayer: function (lyr_def) {
      const source_class = lyr_def.singleTile
        ? ImageArcGISRest
        : TileArcGISRest;
      const layer_class = lyr_def.singleTile ? ImageLayer : Tile;
      const params = lyr_def.params;
      const legends = [];
      if (angular.isDefined(params)) {
        delete params.REQUEST;
      }
      //delete params.FORMAT; Commented, because otherwise when loading from cookie or store, it displays jpeg
      if (angular.isDefined(lyr_def.legends)) {
        for (let idx_leg = 0; idx_leg < lyr_def.legends.length; idx_leg++) {
          legends.push(decodeURIComponent(lyr_def.legends[idx_leg]));
        }
      }
      const source = new source_class({
        url: decodeURIComponent(lyr_def.url),
        attributions: lyr_def.attribution
          ? [
              new Attribution({
                html:
                  '' +
                  lyr_def.attribution.Title +
                  '',
              }),
            ]
          : undefined,
        params: params,
        crossOrigin: 'anonymous',
        projection: lyr_def.projection,
        ratio: lyr_def.ratio,
      });
      const new_layer = new layer_class({
        title: lyr_def.title,
        from_composition: true,
        maxResolution: lyr_def.maxResolution || Number.Infinity,
        minResolution: lyr_def.minResolution || 0,
        minScale: lyr_def.minScale || Number.Infinity,
        maxScale: lyr_def.maxScale || 0,
        show_in_manager: lyr_def.displayInLayerSwitcher,
        abstract: lyr_def.name || lyr_def.abstract,
        base: lyr_def.base,
        metadata: lyr_def.metadata,
        dimensions: lyr_def.dimensions,
        legends: legends,
        saveState: true,
        path: lyr_def.path,
        opacity: lyr_def.opacity || 1,
        source,
      });

      new_layer.setVisible(lyr_def.visibility);
      //TODO Proxify
      //OlMap.proxifyLayerLoader(new_layer, !lyr_def.singleTile);
      return new_layer;
    },
    /**
     * @ngdoc method
     * @name hs.compositions.config_parsers.service#createXYZLayer
     * @public
     * @param {object} lyr_def Layer definition object
     * @returns {object} Ol Image or Tile layer
     * @description Parse definition object to create XYZ Ol.layer
     */
    createXYZLayer: function (lyr_def) {
      const source_class = XYZ;
      const layer_class = Tile;
      const legends = [];
      if (angular.isDefined(lyr_def.legends)) {
        for (let idx_leg = 0; idx_leg < lyr_def.legends.length; idx_leg++) {
          legends.push(decodeURIComponent(lyr_def.legends[idx_leg]));
        }
      }
      const source = new source_class({
        url: decodeURIComponent(lyr_def.url),
        attributions: lyr_def.attribution
          ? [
              new Attribution({
                html:
                  '' +
                  lyr_def.attribution.Title +
                  '',
              }),
            ]
          : undefined,
        crossOrigin: 'anonymous',
        projection: lyr_def.projection,
        wrapX: lyr_def.wrapX,
        //TODO Add the rest of parameters and describe in the composition schema
      });
      const new_layer = new layer_class({
        title: lyr_def.title,
        from_composition: true,
        maxResolution: lyr_def.maxResolution || Number.Infinity,
        minResolution: lyr_def.minResolution || 0,
        minScale: lyr_def.minScale || Number.Infinity,
        maxScale: lyr_def.maxScale || 0,
        show_in_manager: lyr_def.displayInLayerSwitcher,
        abstract: lyr_def.name || lyr_def.abstract,
        base: lyr_def.base,
        metadata: lyr_def.metadata,
        dimensions: lyr_def.dimensions,
        legends: legends,
        saveState: true,
        path: lyr_def.path,
        opacity: lyr_def.opacity || 1,
        source,
      });

      new_layer.setVisible(lyr_def.visibility);
      //TODO Proxify
      //OlMap.proxifyLayerLoader(new_layer, !lyr_def.singleTile);
      return new_layer;
    },
    /**
     * @ngdoc method
     * @name hs.compositions.config_parsers.service#createStaticImageLayer
     * @public
     * @param {object} lyr_def Layer definition object
     * @returns {object} Ol Image or Tile layer
     * @description Parse definition object to create ImageStatic Ol.layer
     */
    createStaticImageLayer: function (lyr_def) {
      const source_class = ImageStatic;
      const layer_class = ImageLayer;
      const legends = [];
      if (angular.isDefined(lyr_def.legends)) {
        for (let idx_leg = 0; idx_leg < lyr_def.legends.length; idx_leg++) {
          legends.push(decodeURIComponent(lyr_def.legends[idx_leg]));
        }
      }
      const source = new source_class({
        url: decodeURIComponent(lyr_def.url),
        attributions: lyr_def.attribution
          ? [
              new Attribution({
                html:
                  '' +
                  lyr_def.attribution.Title +
                  '',
              }),
            ]
          : undefined,
        imageExtent: lyr_def.extent,
        crossOrigin: 'anonymous',
        projection: lyr_def.projection,
        wrapX: lyr_def.wrapX,
        //TODO Add the rest of parameters and describe in the composition schema
      });
      const new_layer = new layer_class({
        title: lyr_def.title,
        from_composition: true,
        maxResolution: lyr_def.maxResolution || Number.Infinity,
        minResolution: lyr_def.minResolution || 0,
        minScale: lyr_def.minScale || Number.Infinity,
        maxScale: lyr_def.maxScale || 0,
        show_in_manager: lyr_def.displayInLayerSwitcher,
        abstract: lyr_def.name || lyr_def.abstract,
        base: lyr_def.base,
        metadata: lyr_def.metadata,
        dimensions: lyr_def.dimensions,
        legends: legends,
        saveState: true,
        path: lyr_def.path,
        opacity: lyr_def.opacity || 1,
        source,
      });

      new_layer.setVisible(lyr_def.visibility);
      return new_layer;
    },
    /**
     * @ngdoc method
     * @name hs.compositions.config_parsers.service#createSparqlLayer
     * @public
     * @param {object} lyr_def Layer definition object
     * @description  Parse definition object to create Sparql layer
     */
    createSparqlLayer: function (lyr_def) {
      const url = decodeURIComponent(lyr_def.protocol.url);
      const definition = {};
      definition.url = url;
      definition.format = 'hs.format.Sparql';

      let style = null;
      if (angular.isDefined(lyr_def.style)) {
        style = me.parseStyle(lyr_def.style);
      }

      const src = new SparqlJson({
        geom_attribute: '?geom',
        url: url,
        category_field: 'http://www.openvoc.eu/poi#categoryWaze',
        projection: 'EPSG:3857',
      });

      const lyr = new VectorLayer({
        from_composition: true,
        definition: definition,
        source: src,
        opacity: lyr_def.opacity || 1,
        style: style,
        title: lyr_def.title,
      });
      lyr.setVisible(lyr_def.visibility);
    },
    /**
     * @ngdoc method
     * @name hs.compositions.config_parsers.service#parseStyle
     * @public
     * @param {object} j Style definition object
     * @returns {ol.style.Style} Valid Ol style object
     * @description Parse style definition object to create valid Style
     */
    parseStyle: function (j) {
      const style_json = {};
      if (angular.isDefined(j.fill)) {
        style_json.fill = new Fill({
          color: j.fill,
        });
      }
      if (angular.isDefined(j.stroke)) {
        style_json.stroke = new Stroke({
          color: j.stroke.color,
          width: j.stroke.width,
        });
      }
      if (angular.isDefined(j.image)) {
        if (j.image.type == 'circle') {
          const circle_json = {};

          if (angular.isDefined(j.image.radius)) {
            circle_json.radius = j.image.radius;
          }

          if (angular.isDefined(j.image.fill)) {
            circle_json.fill = new Fill({
              color: j.image.fill,
            });
          }
          if (angular.isDefined(j.image.stroke)) {
            circle_json.stroke = new Stroke({
              color: j.image.stroke.color,
              width: j.image.stroke.width,
            });
          }
          style_json.image = new Circle(circle_json);
        }
        if (j.image.type == 'icon') {
          const img = new Image();
          img.src = j.image.src;
          if (img.width == 0) {
            img.width = 43;
          }
          if (img.height == 0) {
            img.height = 41;
          }
          const icon_json = {
            img: img,
            imgSize: [img.width, img.height],
            crossOrigin: 'anonymous',
          };
          style_json.image = new Icon(icon_json);
        }
      }
      return new Style(style_json);
    },
    /**
     * @ngdoc method
     * @name hs.compositions.config_parsers.service#createVectorLayer
     * @public
     * @param {object} lyr_def Layer definition object
     * @returns {ol.layer.Vector|Function} Either valid vector layer or function for creation of other supported vector file types)
     * @description Parse definition object to create Vector layer (classic Ol.vector, KML, GeoJSON, WFS, Sparql)
     */
    createVectorLayer: function (lyr_def) {
      let format = '';
      if (angular.isDefined(lyr_def.protocol)) {
        format = lyr_def.protocol.format;
      }
      const options = {};
      options.opacity = lyr_def.opacity || 1;
      options.from_composition = true;

      let extractStyles = true;
      if (angular.isDefined(lyr_def.style)) {
        options.style = me.parseStyle(lyr_def.style);
        extractStyles = false;
      }
      let layer;
      switch (format) {
        case 'ol.format.KML':
          layer = HsAddLayersVectorService.createVectorLayer(
            'kml',
            decodeURIComponent(lyr_def.protocol.url),
            lyr_def.title || 'Layer',
            lyr_def.abstract,
            lyr_def.projection.toUpperCase(),
            Object.assign(options, {extractStyles})
          );
          break;
        case 'ol.format.GeoJSON':
          layer = HsAddLayersVectorService.createVectorLayer(
            'geojson',
            decodeURIComponent(lyr_def.protocol.url),
            lyr_def.title || 'Layer',
            lyr_def.abstract,
            lyr_def.projection.toUpperCase(),
            options
          );
          break;
        case 'hs.format.WFS':
          options.defOptions = lyr_def.defOptions;
          layer = HsAddLayersVectorService.createVectorLayer(
            'wfs',
            decodeURIComponent(lyr_def.protocol.url),
            lyr_def.title || 'Layer',
            lyr_def.abstract,
            lyr_def.projection.toUpperCase(),
            options
          );
          break;
        case 'hs.format.LaymanWfs':
          layer = new VectorLayer({
            title: lyr_def.title,
            name: lyr_def.title,
            visibility: lyr_def.visibility,
            synchronize: true,
            editor: {
              editable: true,
              defaultAttributes: {},
            },
            saveState: true,
            source: new VectorSource({}),
          });
          break;
        case 'hs.format.Sparql':
          layer = me.createSparqlLayer(lyr_def);
          break;
        default:
          if (angular.isDefined(lyr_def.features)) {
            layer = HsAddLayersVectorService.createVectorLayer(
              '',
              undefined,
              lyr_def.title || 'Layer',
              lyr_def.abstract,
              lyr_def.projection.toUpperCase(),
              lyr_def
            );
          }
      }
      return layer;
    },
  };
  return me;
}
<commit_msg>Osm layers should be base layers always refs #710<commit_after>import '../add-layers/vector/add-layers-vector.module';
import 'angular-socialshare';
import ImageLayer from 'ol/layer/Image';
import SparqlJson from '../layers/hs.source.SparqlJson';
import VectorLayer from 'ol/layer/Vector';
import {Attribution} from 'ol/control';
import {Circle, Fill, Icon, Stroke, Style} from 'ol/style';
import {ImageArcGISRest, ImageStatic, TileArcGISRest, TileWMS} from 'ol/source';
import {ImageWMS, XYZ} from 'ol/source';
import {Tile} from 'ol/layer';
import {Vector as VectorSource} from 'ol/source';

/**
 * @param HsMapService
 * @param HsAddLayersVectorService
 */
export default function (HsMapService, HsAddLayersVectorService) {
  'ngInject';
  const me = {
    /**
     * @ngdoc method
     * @name hs.compositions.config_parsers.service#createWmsLayer
     * @public
     * @param {object} lyr_def Layer definition object
     * @returns {object} Ol Image or Tile layer
     * @description Parse definition object to create WMS Ol.layer  (source = ol.source.ImageWMS / ol.source.TileWMS)
     */
    createWmsLayer: function (lyr_def) {
      const source_class = lyr_def.singleTile ? ImageWMS : TileWMS;
      const layer_class = lyr_def.singleTile ? ImageLayer : Tile;
      const params = lyr_def.params;
      const legends = [];
      delete params.REQUEST;
      //delete params.FORMAT; Commented, because otherwise when loading from cookie or store, it displays jpeg
      if (angular.isDefined(lyr_def.legends)) {
        for (let idx_leg = 0; idx_leg < lyr_def.legends.length; idx_leg++) {
          legends.push(decodeURIComponent(lyr_def.legends[idx_leg]));
        }
      }
      const source = new source_class({
        url: decodeURIComponent(lyr_def.url),
        attributions: lyr_def.attribution
          ? [
              new Attribution({
                html:
                  '' +
                  lyr_def.attribution.Title +
                  '',
              }),
            ]
          : undefined,
        styles: angular.isDefined(lyr_def.metadata)
          ? lyr_def.metadata.styles
          : undefined,
        params: params,
        crossOrigin: 'anonymous',
        projection: lyr_def.projection,
        ratio: lyr_def.ratio,
      });
      const new_layer = new layer_class({
        title: lyr_def.title,
        from_composition: true,
        maxResolution: lyr_def.maxResolution || Number.Infinity,
        minResolution: lyr_def.minResolution || 0,
        minScale: lyr_def.minScale || Number.Infinity,
        maxScale: lyr_def.maxScale || 0,
        show_in_manager: lyr_def.displayInLayerSwitcher,
        abstract: lyr_def.name || lyr_def.abstract,
        base: lyr_def.base,
        metadata: lyr_def.metadata,
        dimensions: lyr_def.dimensions,
        legends: legends,
        saveState: true,
        path: lyr_def.path,
        opacity: lyr_def.opacity || 1,
        source,
        subLayers: lyr_def.subLayers,
      });

      new_layer.setVisible(lyr_def.visibility);
      HsMapService.proxifyLayerLoader(new_layer, !lyr_def.singleTile);
      return new_layer;
    },
    /**
     * @ngdoc method
     * @name hs.compositions.config_parsers.service#createArcGISLayer
     * @public
     * @param {object} lyr_def Layer definition object
     * @returns {object} Ol Image or Tile layer
     * @description Parse definition object to create ArcGIS Ol.layer  (source = ol.source.ImageArcGISRest / ol.source.TileArcGISRest)
     */
    createArcGISLayer: function (lyr_def) {
      const source_class = lyr_def.singleTile
        ? ImageArcGISRest
        : TileArcGISRest;
      const layer_class = lyr_def.singleTile ? ImageLayer : Tile;
      const params = lyr_def.params;
      const legends = [];
      if (angular.isDefined(params)) {
        delete params.REQUEST;
      }
      //delete params.FORMAT; Commented, because otherwise when loading from cookie or store, it displays jpeg
      if (angular.isDefined(lyr_def.legends)) {
        for (let idx_leg = 0; idx_leg < lyr_def.legends.length; idx_leg++) {
          legends.push(decodeURIComponent(lyr_def.legends[idx_leg]));
        }
      }
      const source = new source_class({
        url: decodeURIComponent(lyr_def.url),
        attributions: lyr_def.attribution
          ? [
              new Attribution({
                html:
                  '' +
                  lyr_def.attribution.Title +
                  '',
              }),
            ]
          : undefined,
        params: params,
        crossOrigin: 'anonymous',
        projection: lyr_def.projection,
        ratio: lyr_def.ratio,
      });
      const new_layer = new layer_class({
        title: lyr_def.title,
        from_composition: true,
        maxResolution: lyr_def.maxResolution || Number.Infinity,
        minResolution: lyr_def.minResolution || 0,
        minScale: lyr_def.minScale || Number.Infinity,
        maxScale: lyr_def.maxScale || 0,
        show_in_manager: lyr_def.displayInLayerSwitcher,
        abstract: lyr_def.name || lyr_def.abstract,
        base: lyr_def.base,
        metadata: lyr_def.metadata,
        dimensions: lyr_def.dimensions,
        legends: legends,
        saveState: true,
        path: lyr_def.path,
        opacity: lyr_def.opacity || 1,
        source,
      });

      new_layer.setVisible(lyr_def.visibility);
      //TODO Proxify
      //OlMap.proxifyLayerLoader(new_layer, !lyr_def.singleTile);
      return new_layer;
    },
    /**
     * @ngdoc method
     * @name hs.compositions.config_parsers.service#createXYZLayer
     * @public
     * @param {object} lyr_def Layer definition object
     * @returns {object} Ol Image or Tile layer
     * @description Parse definition object to create XYZ Ol.layer
     */
    createXYZLayer: function (lyr_def) {
      const source_class = XYZ;
      const layer_class = Tile;
      const legends = [];
      if (angular.isDefined(lyr_def.legends)) {
        for (let idx_leg = 0; idx_leg < lyr_def.legends.length; idx_leg++) {
          legends.push(decodeURIComponent(lyr_def.legends[idx_leg]));
        }
      }
      const source = new source_class({
        url: decodeURIComponent(lyr_def.url),
        attributions: lyr_def.attribution
          ? [
              new Attribution({
                html:
                  '' +
                  lyr_def.attribution.Title +
                  '',
              }),
            ]
          : undefined,
        crossOrigin: 'anonymous',
        projection: lyr_def.projection,
        wrapX: lyr_def.wrapX,
        //TODO Add the rest of parameters and describe in the composition schema
      });
      const new_layer = new layer_class({
        title: lyr_def.title,
        from_composition: true,
        maxResolution: lyr_def.maxResolution || Number.Infinity,
        minResolution: lyr_def.minResolution || 0,
        minScale: lyr_def.minScale || Number.Infinity,
        maxScale: lyr_def.maxScale || 0,
        show_in_manager: lyr_def.displayInLayerSwitcher,
        abstract: lyr_def.name || lyr_def.abstract,
        base: lyr_def.base || lyr_def.url.indexOf('openstreetmap') > -1,
        metadata: lyr_def.metadata,
        dimensions: lyr_def.dimensions,
        legends: legends,
        saveState: true,
        path: lyr_def.path,
        opacity: lyr_def.opacity || 1,
        source,
      });

      new_layer.setVisible(lyr_def.visibility);
      //TODO Proxify
      //OlMap.proxifyLayerLoader(new_layer, !lyr_def.singleTile);
      return new_layer;
    },
    /**
     * @ngdoc method
     * @name hs.compositions.config_parsers.service#createStaticImageLayer
     * @public
     * @param {object} lyr_def Layer definition object
     * @returns {object} Ol Image or Tile layer
     * @description Parse definition object to create ImageStatic Ol.layer
     */
    createStaticImageLayer: function (lyr_def) {
      const source_class = ImageStatic;
      const layer_class = ImageLayer;
      const legends = [];
      if (angular.isDefined(lyr_def.legends)) {
        for (let idx_leg = 0; idx_leg < lyr_def.legends.length; idx_leg++) {
          legends.push(decodeURIComponent(lyr_def.legends[idx_leg]));
        }
      }
      const source = new source_class({
        url: decodeURIComponent(lyr_def.url),
        attributions: lyr_def.attribution
          ? [
              new Attribution({
                html:
                  '' +
                  lyr_def.attribution.Title +
                  '',
              }),
            ]
          : undefined,
        imageExtent: lyr_def.extent,
        crossOrigin: 'anonymous',
        projection: lyr_def.projection,
        wrapX: lyr_def.wrapX,
        //TODO Add the rest of parameters and describe in the composition schema
      });
      const new_layer = new layer_class({
        title: lyr_def.title,
        from_composition: true,
        maxResolution: lyr_def.maxResolution || Number.Infinity,
        minResolution: lyr_def.minResolution || 0,
        minScale: lyr_def.minScale || Number.Infinity,
        maxScale: lyr_def.maxScale || 0,
        show_in_manager: lyr_def.displayInLayerSwitcher,
        abstract: lyr_def.name || lyr_def.abstract,
        base: lyr_def.base,
        metadata: lyr_def.metadata,
        dimensions: lyr_def.dimensions,
        legends: legends,
        saveState: true,
        path: lyr_def.path,
        opacity: lyr_def.opacity || 1,
        source,
      });

      new_layer.setVisible(lyr_def.visibility);
      return new_layer;
    },
    /**
     * @ngdoc method
     * @name hs.compositions.config_parsers.service#createSparqlLayer
     * @public
     * @param {object} lyr_def Layer definition object
     * @description  Parse definition object to create Sparql layer
     */
    createSparqlLayer: function (lyr_def) {
      const url = decodeURIComponent(lyr_def.protocol.url);
      const definition = {};
      definition.url = url;
      definition.format = 'hs.format.Sparql';

      let style = null;
      if (angular.isDefined(lyr_def.style)) {
        style = me.parseStyle(lyr_def.style);
      }

      const src = new SparqlJson({
        geom_attribute: '?geom',
        url: url,
        category_field: 'http://www.openvoc.eu/poi#categoryWaze',
        projection: 'EPSG:3857',
      });

      const lyr = new VectorLayer({
        from_composition: true,
        definition: definition,
        source: src,
        opacity: lyr_def.opacity || 1,
        style: style,
        title: lyr_def.title,
      });
      lyr.setVisible(lyr_def.visibility);
    },
    /**
     * @ngdoc method
     * @name hs.compositions.config_parsers.service#parseStyle
     * @public
     * @param {object} j Style definition object
     * @returns {ol.style.Style} Valid Ol style object
     * @description Parse style definition object to create valid Style
     */
    parseStyle: function (j) {
      const style_json = {};
      if (angular.isDefined(j.fill)) {
        style_json.fill = new Fill({
          color: j.fill,
        });
      }
      if (angular.isDefined(j.stroke)) {
        style_json.stroke = new Stroke({
          color: j.stroke.color,
          width: j.stroke.width,
        });
      }
      if (angular.isDefined(j.image)) {
        if (j.image.type == 'circle') {
          const circle_json = {};

          if (angular.isDefined(j.image.radius)) {
            circle_json.radius = j.image.radius;
          }

          if (angular.isDefined(j.image.fill)) {
            circle_json.fill = new Fill({
              color: j.image.fill,
            });
          }
          if (angular.isDefined(j.image.stroke)) {
            circle_json.stroke = new Stroke({
              color: j.image.stroke.color,
              width: j.image.stroke.width,
            });
          }
          style_json.image = new Circle(circle_json);
        }
        if (j.image.type == 'icon') {
          const img = new Image();
          img.src = j.image.src;
          if (img.width == 0) {
            img.width = 43;
          }
          if (img.height == 0) {
            img.height = 41;
          }
          const icon_json = {
            img: img,
            imgSize: [img.width, img.height],
            crossOrigin: 'anonymous',
          };
          style_json.image = new Icon(icon_json);
        }
      }
      return new Style(style_json);
    },
    /**
     * @ngdoc method
     * @name hs.compositions.config_parsers.service#createVectorLayer
     * @public
     * @param {object} lyr_def Layer definition object
     * @returns {ol.layer.Vector|Function} Either valid vector layer or function for creation of other supported vector file types)
     * @description Parse definition object to create Vector layer (classic Ol.vector, KML, GeoJSON, WFS, Sparql)
     */
    createVectorLayer: function (lyr_def) {
      let format = '';
      if (angular.isDefined(lyr_def.protocol)) {
        format = lyr_def.protocol.format;
      }
      const options = {};
      options.opacity = lyr_def.opacity || 1;
      options.from_composition = true;

      let extractStyles = true;
      if (angular.isDefined(lyr_def.style)) {
        options.style = me.parseStyle(lyr_def.style);
        extractStyles = false;
      }
      let layer;
      switch (format) {
        case 'ol.format.KML':
          layer = HsAddLayersVectorService.createVectorLayer(
            'kml',
            decodeURIComponent(lyr_def.protocol.url),
            lyr_def.title || 'Layer',
            lyr_def.abstract,
            lyr_def.projection.toUpperCase(),
            Object.assign(options, {extractStyles})
          );
          break;
        case 'ol.format.GeoJSON':
          layer = HsAddLayersVectorService.createVectorLayer(
            'geojson',
            decodeURIComponent(lyr_def.protocol.url),
            lyr_def.title || 'Layer',
            lyr_def.abstract,
            lyr_def.projection.toUpperCase(),
            options
          );
          break;
        case 'hs.format.WFS':
          options.defOptions = lyr_def.defOptions;
          layer = HsAddLayersVectorService.createVectorLayer(
            'wfs',
            decodeURIComponent(lyr_def.protocol.url),
            lyr_def.title || 'Layer',
            lyr_def.abstract,
            lyr_def.projection.toUpperCase(),
            options
          );
          break;
        case 'hs.format.LaymanWfs':
          layer = new VectorLayer({
            title: lyr_def.title,
            name: lyr_def.title,
            visibility: lyr_def.visibility,
            synchronize: true,
            editor: {
              editable: true,
              defaultAttributes: {},
            },
            saveState: true,
            source: new VectorSource({}),
          });
          break;
        case 'hs.format.Sparql':
          layer = me.createSparqlLayer(lyr_def);
          break;
        default:
          if (angular.isDefined(lyr_def.features)) {
            layer = HsAddLayersVectorService.createVectorLayer(
              '',
              undefined,
              lyr_def.title || 'Layer',
              lyr_def.abstract,
              lyr_def.projection.toUpperCase(),
              lyr_def
            );
          }
      }
      return layer;
    },
  };
  return me;
}
<|endoftext|>


<commit_before>/*jshint maxdepth:6*/

// # can/route/pushstate/pushstate.js
//
// Plugin for `can.route` which uses browser `history.pushState` support
// to update window's pathname instead of the `hash`.
//
// It registers itself as binding on `can.route`, intercepts `click` events
// on `<a>` elements across document and accordingly updates `can.route` state
// and window's pathname.

steal('can/util', 'can/route', function (can) {
	"use strict";

	// Initialize plugin only if browser supports pushstate.
	if (window.history && history.pushState) {

		// Registers itself within `can.route.bindings`.
		can.route.bindings.pushstate = {
			/**
			 * @property {String} can.route.pushstate.root
			 * @parent can.route.pushstate
			 *
			 * @description Configure the base url that will not be modified.
			 *
			 * @option {String} Represents the base url that pushstate will prepend to all
			 * routes.  `root` defaults to: `"/"`.
			 *
			 * @body
			 *
			 * ## Use
			 *
			 * By default, a route like:
			 *
			 *     can.route(":type/:id")
			 *
			 * Matches urls like:
			 *
			 *     http://domain.com/contact/5
			 *
			 * But sometimes, you only want to match pages within a certain directory.  For
			 * example, an application that is a filemanager.  You might want to
			 * specify root and routes like:
			 *
			 *     can.route.pushstate.root = "/filemanager/"
			 *     can.route("file-:fileId");
			 *     can.route("folder-:fileId")
			 *
			 * Which matches urls like:
			 *
			 *     http://domain.com/filemanager/file-34234
			 *
			 */

			// Start of `location.pathname` is the root.
			// (Can be configured via `can.route.bindings.pushstate.root`)
			root: "/",
			paramsMatcher: /^\?(?:[^=]+=[^&]*&)*[^=]+=[^&]*/,
			querySeparator: '?',

			// Intercepts clicks on `<a>` elements and rewrites original `history` methods.
			bind: function () {
				// Intercept routable links.
				can.delegate.call(can.$(document.documentElement), 'a', 'click', anchorClickHandler);

				// Rewrites original `pushState`/`replaceState` methods on `history` and keeps pointer to original methods
				can.each(methodsToOverride, function (method) {
					originalMethods[method] = window.history[method];
					window.history[method] = function (state, title, url) {
						// Avoid doubled history states (with pushState).
						var absolute = url.indexOf("http") === 0;
						var searchHash = window.location.search + window.location.hash;
						// If url differs from current call original histoy method and update `can.route` state.
						if ((!absolute && url !== window.location.pathname + searchHash) || (absolute && url !== window.location.href + searchHash)) {
							originalMethods[method].apply(window.history, arguments);
							can.route.setState();
						}
					};
				});

				// Bind to `popstate` event, fires on back/forward.
				can.bind.call(window, 'popstate', can.route.setState);
			},

			// Unbinds and restores original `history` methods
			unbind: function () {
				can.undelegate.call(can.$(document.documentElement), 'click', 'a', anchorClickHandler);

				can.each(methodsToOverride, function (method) {
					window.history[method] = originalMethods[method];
				});
				can.unbind.call(window, 'popstate', can.route.setState);
			},

			// Returns matching part of url without root.
			matchingPartOfURL: function () {
				var root = cleanRoot(),
					loc = (location.pathname + location.search),
					index = loc.indexOf(root);

				return loc.substr(index + root.length);
			},

			// Updates URL by calling `pushState`.
			setURL: function (path) {
				// Keeps hash if not in path.
				if (includeHash && path.indexOf("#") === -1 && window.location.hash) {
					path += window.location.hash;
				}
				window.history.pushState(null, null, can.route._call("root") + path);
			}
		};

		// Handler function for `click` events.
		var anchorClickHandler = function (e) {
			if (!(e.isDefaultPrevented ? e.isDefaultPrevented() : e.defaultPrevented === true)) {
				// YUI calls back events triggered with this as a wrapped object.
				var node = this._node || this;
				// Fix for IE showing blank host, but blank host means current host.
				var linksHost = node.host || window.location.host;

				// If link is within the same domain and descendant of `root`
				if (window.location.host === linksHost) {
					var root = can.route._call("root");
					if (node.pathname.indexOf(root) === 0) {

						// Removes root from url.
						var url = (node.pathname + node.search).substr(root.length);
						// If a route matches update the data.
						var curParams = can.route.deparam(url);
						if (curParams.hasOwnProperty('route')) {
							// Makes it possible to have a link with a hash.
							includeHash = true;
							window.history.pushState(null, null, node.href);

							// Test if you can preventDefault
							// our tests can't call .click() b/c this
							// freezes phantom.
							if (e.preventDefault) {
								e.preventDefault();
							}
						}
					}
				}
			}
		},
			// Always returns clean root, without domain.
			cleanRoot = function () {
				var domain = location.protocol + "//" + location.host,
					root = can.route._call("root"),
					index = root.indexOf(domain);
				if (index === 0) {
					return can.route.root.substr(domain.length);
				}
				return root;
			},
			// Original methods on `history` that will be overwritten
			methodsToOverwrite = ['pushState', 'replaceState'],
			// A place to store pointers to original `history` methods.
			originalMethods = {},
			// Used to tell setURL to include the hash because we clicked on a link.
			includeHash = false;

		// Enables plugin, by default `hashchange` binding is used.
		can.route.defaultBinding = "pushstate";
	}

	return can;
});
<commit_msg>Function headings added, jshint directive moved from top.<commit_after>// # can/route/pushstate/pushstate.js
//
// Plugin for `can.route` which uses browser `history.pushState` support
// to update window's pathname instead of the `hash`.
//
// It registers itself as binding on `can.route`, intercepts `click` events
// on `<a>` elements across document and accordingly updates `can.route` state
// and window's pathname.

/*jshint maxdepth:6*/

steal('can/util', 'can/route', function (can) {
	"use strict";

	// Initialize plugin only if browser supports pushstate.
	if (window.history && history.pushState) {

		// Registers itself within `can.route.bindings`.
		can.route.bindings.pushstate = {
			/**
			 * @property {String} can.route.pushstate.root
			 * @parent can.route.pushstate
			 *
			 * @description Configure the base url that will not be modified.
			 *
			 * @option {String} Represents the base url that pushstate will prepend to all
			 * routes.  `root` defaults to: `"/"`.
			 *
			 * @body
			 *
			 * ## Use
			 *
			 * By default, a route like:
			 *
			 *     can.route(":type/:id")
			 *
			 * Matches urls like:
			 *
			 *     http://domain.com/contact/5
			 *
			 * But sometimes, you only want to match pages within a certain directory.  For
			 * example, an application that is a filemanager.  You might want to
			 * specify root and routes like:
			 *
			 *     can.route.pushstate.root = "/filemanager/"
			 *     can.route("file-:fileId");
			 *     can.route("folder-:fileId")
			 *
			 * Which matches urls like:
			 *
			 *     http://domain.com/filemanager/file-34234
			 *
			 */

			// Start of `location.pathname` is the root.
			// (Can be configured via `can.route.bindings.pushstate.root`)
			root: "/",
			paramsMatcher: /^\?(?:[^=]+=[^&]*&)*[^=]+=[^&]*/,
			querySeparator: '?',

			// ## bind

			// Intercepts clicks on `<a>` elements and rewrites original `history` methods.
			bind: function () {
				// Intercept routable links.
				can.delegate.call(can.$(document.documentElement), 'a', 'click', anchorClickHandler);

				// Rewrites original `pushState`/`replaceState` methods on `history` and keeps pointer to original methods
				can.each(methodsToOverwrite, function (method) {
					originalMethods[method] = window.history[method];
					window.history[method] = function (state, title, url) {
						// Avoid doubled history states (with pushState).
						var absolute = url.indexOf("http") === 0;
						var searchHash = window.location.search + window.location.hash;
						// If url differs from current call original histoy method and update `can.route` state.
						if ((!absolute && url !== window.location.pathname + searchHash) || (absolute && url !== window.location.href + searchHash)) {
							originalMethods[method].apply(window.history, arguments);
							can.route.setState();
						}
					};
				});

				// Bind to `popstate` event, fires on back/forward.
				can.bind.call(window, 'popstate', can.route.setState);
			},

			// ## unbind

			// Unbinds and restores original `history` methods
			unbind: function () {
				can.undelegate.call(can.$(document.documentElement), 'click', 'a', anchorClickHandler);

				can.each(methodsToOverwrite, function (method) {
					window.history[method] = originalMethods[method];
				});
				can.unbind.call(window, 'popstate', can.route.setState);
			},

			// ## matchingPartOfURL

			// Returns matching part of url without root.
			matchingPartOfURL: function () {
				var root = cleanRoot(),
					loc = (location.pathname + location.search),
					index = loc.indexOf(root);

				return loc.substr(index + root.length);
			},

			// ## setURL

			// Updates URL by calling `pushState`.
			setURL: function (path) {
				// Keeps hash if not in path.
				if (includeHash && path.indexOf("#") === -1 && window.location.hash) {
					path += window.location.hash;
				}
				window.history.pushState(null, null, can.route._call("root") + path);
			}
		};

		// ## anchorClickHandler

		// Handler function for `click` events.
		var anchorClickHandler = function (e) {
			if (!(e.isDefaultPrevented ? e.isDefaultPrevented() : e.defaultPrevented === true)) {
				// YUI calls back events triggered with this as a wrapped object.
				var node = this._node || this;
				// Fix for IE showing blank host, but blank host means current host.
				var linksHost = node.host || window.location.host;

				// If link is within the same domain and descendant of `root`
				if (window.location.host === linksHost) {
					var root = can.route._call("root");
					if (node.pathname.indexOf(root) === 0) {

						// Removes root from url.
						var url = (node.pathname + node.search).substr(root.length);
						// If a route matches update the data.
						var curParams = can.route.deparam(url);
						if (curParams.hasOwnProperty('route')) {
							// Makes it possible to have a link with a hash.
							includeHash = true;
							window.history.pushState(null, null, node.href);

							// Test if you can preventDefault
							// our tests can't call .click() b/c this
							// freezes phantom.
							if (e.preventDefault) {
								e.preventDefault();
							}
						}
					}
				}
			}
		},

			// ## cleanRoot

			// Always returns clean root, without domain.
			cleanRoot = function () {
				var domain = location.protocol + "//" + location.host,
					root = can.route._call("root"),
					index = root.indexOf(domain);
				if (index === 0) {
					return can.route.root.substr(domain.length);
				}
				return root;
			},
			// Original methods on `history` that will be overwritten
			methodsToOverwrite = ['pushState', 'replaceState'],
			// A place to store pointers to original `history` methods.
			originalMethods = {},
			// Used to tell setURL to include the hash because we clicked on a link.
			includeHash = false;

		// Enables plugin, by default `hashchange` binding is used.
		can.route.defaultBinding = "pushstate";
	}

	return can;
});
<|endoftext|>


<commit_before>/**
 * General-purpose jQuery wrapper. Simply pass the plugin name as the expression.
 *
 * It is possible to specify a default set of parameters for each jQuery plugin.
 * Under the jq key, namespace each plugin by that which will be passed to ui-jq.
 * Unfortunately, at this time you can only pre-define the first parameter.
 * @example { jq : { datepicker : { showOn:'click', uiDefer: true } } }
 *
 * @param ui-jq {string} The $elm.[pluginName]() to call.
 * @param [ui-options] {mixed} Expression to be evaluated and passed as options to the function
 *     Multiple parameters can be separated by commas
 * @param [ui-refresh] {expression} Watch expression and refire plugin on changes
 *
 * @example <input ui-jq="datepicker" ui-options="{showOn:'click'},secondParameter,thirdParameter" ui-refresh="iChange">
 */
angular.module('ui.directives').directive('uiJq', ['ui.config', '$timeout', function (uiConfig, $timeout) {
  return {
    restrict: 'A',
    compile: function (tElm, tAttrs) {
      if (!angular.isFunction(tElm[tAttrs.uiJq])) {
        throw new Error('ui-jq: The "' + tAttrs.uiJq + '" function does not exist');
      }
      var options = uiConfig.jq && uiConfig.jq[tAttrs.uiJq] || {};
      return function (scope, elm, attrs) {
        var linkOptions = [], uiDefer = false;

        // If ui-options are passed, merge (or override) them onto global defaults and pass to the jQuery method
        if (attrs.uiOptions) {
          linkOptions = scope.$eval('[' + attrs.uiOptions + ']');
          if (angular.isObject(options) && angular.isObject(linkOptions[0])) {
            linkOptions[0] = angular.extend({}, options, linkOptions[0]);
          }
        } else if (options) {
          linkOptions = [options];
        }
        // If change compatibility is enabled, the form input's "change" event will trigger an "input" event
        if (attrs.ngModel && elm.is('select,input,textarea')) {
          elm.on('change', function () {
            elm.trigger('input');
          });
        }

        // Call jQuery method and pass relevant options
        function callPlugin() {
          $timeout(function(){
            elm[attrs.uiJq].apply(elm, linkOptions);
          }, 0, false);
        }

        // If ui-refresh is used, re-fire the the method upon every change
        if (attrs.uiRefresh) {
          scope.$watch(attrs.uiRefresh, function(newVal){
            callPlugin();
          });
        }
        callPlugin();
      };
    }
  };
}]);
<commit_msg>fix(jq): Removed uiDefer remnants and default opts<commit_after>/**
 * General-purpose jQuery wrapper. Simply pass the plugin name as the expression.
 *
 * It is possible to specify a default set of parameters for each jQuery plugin.
 * Under the jq key, namespace each plugin by that which will be passed to ui-jq.
 * Unfortunately, at this time you can only pre-define the first parameter.
 * @example { jq : { datepicker : { showOn:'click' } } }
 *
 * @param ui-jq {string} The $elm.[pluginName]() to call.
 * @param [ui-options] {mixed} Expression to be evaluated and passed as options to the function
 *     Multiple parameters can be separated by commas
 * @param [ui-refresh] {expression} Watch expression and refire plugin on changes
 *
 * @example <input ui-jq="datepicker" ui-options="{showOn:'click'},secondParameter,thirdParameter" ui-refresh="iChange">
 */
angular.module('ui.directives').directive('uiJq', ['ui.config', '$timeout', function(uiConfig, $timeout) {
  return {
    restrict: 'A',
    compile: function(tElm, tAttrs) {
      if (!angular.isFunction(tElm[tAttrs.uiJq])) {
        throw new Error('ui-jq: The "' + tAttrs.uiJq + '" function does not exist');
      }
      var options = uiConfig.jq && uiConfig.jq[tAttrs.uiJq];
      return function(scope, elm, attrs) {
        var linkOptions = [];

        // If ui-options are passed, merge (or override) them onto global defaults and pass to the jQuery method
        if (attrs.uiOptions) {
          linkOptions = scope.$eval('[' + attrs.uiOptions + ']');
          if (angular.isObject(options) && angular.isObject(linkOptions[0])) {
            linkOptions[0] = angular.extend({}, options, linkOptions[0]);
          }
        } else if (options) {
          linkOptions = [options];
        }
        // If change compatibility is enabled, the form input's "change" event will trigger an "input" event
        if (attrs.ngModel && elm.is('select,input,textarea')) {
          elm.on('change', function() {
            elm.trigger('input');
          });
        }

        // Call jQuery method and pass relevant options
        function callPlugin() {
          $timeout(function() {
            console.log(attrs.uiJq, elm[attrs.uiJq], elm);
            elm[attrs.uiJq].apply(elm, linkOptions);
          }, 0, false);
        }

        // If ui-refresh is used, re-fire the the method upon every change
        if (attrs.uiRefresh) {
          scope.$watch(attrs.uiRefresh, function(newVal) {
            callPlugin();
          });
        }
        callPlugin();
      };
    }
  };
}]);
<|endoftext|>


<commit_before>'use strict';

const Benchmark = require('benchmark');
Benchmark.options.minSamples = 200;

let fileWriter = null;

if (process.argv.some((e) => e === "writeFile")) {
    const BenchFileCreator = require('../benchFileCreator');
    fileWriter = new BenchFileCreator();
    fileWriter.addInformations(Benchmark.options.minSamples);
    fileWriter.writeTableHeader(['Elements', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13']);
}

function computeNumber(nb) {
    if (nb > 1000000){
        return `${Math.round(nb / 10000)/100}m`;
    } else if (nb > 1000){
        return `${Math.round(nb / 10)/100}k`;
    } else {
        return `${Math.round(nb*100)/100}`;
    }
}

function doSuite(arrayLength) {
    console.log(`# Array.length : ${arrayLength}`);
    const Suite = new Benchmark.Suite();

    const array = new Array(arrayLength).fill(0);

    Suite
        .add('for (let i = 0; i < array.length; i++)', function () {
            for (let i = 0; i < array.length; i++) {
                array[i] * array[i];
            }
        })
        .add('for (let i = 0, iMax = array.length; i < iMax; i++)', function () {
            for (let i = 0, iMax = array.length; i < iMax; i++) {
                array[i] * array[i];
            }
        })
        .add('let i = 0; const iMax = array.length; for (; i++ < iMax;)', function () {
            let i = 0;
            const iMax = array.length;

            for (; i++ < iMax;) {
                array[i] * array[i];
            }
        })
        .add('let i = 0; const iMax = array.length; for (; i < iMax; i++)', function () {
            let i = 0;
            const iMax = array.length;

            for (; i < iMax; i++) {
                array[i] * array[i];
            }
        })
        .add('let i = 0; for (; i < array.length; i++)', function () {
            let i = 0;

            for (; i < array.length; i++) {
                array[i] * array[i];
            }
        })
        .add('let i = 0; const iMax = array.length; for (; iMax - i; i++)', function () {
            let i = 0;
            const iMax = array.length;

            for (; iMax - i; i++) {
                array[i] * array[i];
            }
        })
        .add('let i = 0; for (; array[i] !== undefined; i++)', function () {
            let i = 0;

            for (; array[i] !== undefined; i++) {
                array[i] * array[i];
            }
        })
        .add('let i = 0; for (; array[i++] !== undefined;)', function () {
            let i = 0;

            for (; array[i++] !== undefined;) {
                array[i] * array[i];
            }
        })
        .add('let i = 0; while (array[i++] !== undefined)', function () {
            let i = 0;

            while (array[i++] !== undefined) {
                array[i] * array[i];
            }
        })
        .add('let i = array.length; while (i--)', function () {
            let i = array.length;

            while (i--) {
                array[i] * array[i];
            }
        })
        .add('let i = 0, iMax = array.length; while (i++ < iMax)', function () {
            let i = 0, iMax = array.length;

            while (i++ < iMax) {
                array[i] * array[i];
            }
        })
        .add('let i = 0, iMax = array.length; while (iMax - (i++))', function () {
            let i = 0, iMax = array.length;

            while (iMax - i++) {
                array[i] * array[i];
            }
        })
        .add('let i = -array.length; while (i++)', function () {
            let i = -array.length;

            while (i++) {
                array[i + array.length] * array[i + array.length];
            }
        })
        .on('cycle', function (event) {
            console.log(String(event.target));
            if (fileWriter) {
                fileWriter.writeTableElement(computeNumber(event.target.hz));
            }
        })
        .on('complete', function () {
            console.log('Fastest is ' + this.filter('fastest').map('name'));
        })
        .run({ async: false });
}

for (let i = 10; i < 10000000; i *= 10) {
    if (fileWriter) {
        fileWriter.writeTableElement(i);
    }

    doSuite(i);

    if (fileWriter) {
        fileWriter.newLine();
    }
}

if (fileWriter) {
    fileWriter.end();
}
<commit_msg>feat(loopBench): Add recursive iterations<commit_after>'use strict';

const Benchmark = require('benchmark');
Benchmark.options.minSamples = 200;

let fileWriter = null;

if (process.argv.some((e) => e === "writeFile")) {
    const BenchFileCreator = require('../benchFileCreator');
    fileWriter = new BenchFileCreator();
    fileWriter.addInformations(Benchmark.options.minSamples);
    fileWriter.writeTableHeader(['Elements', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13']);
}

function computeNumber(nb) {
    if (nb > 1000000){
        return `${Math.round(nb / 10000)/100}m`;
    } else if (nb > 1000){
        return `${Math.round(nb / 10)/100}k`;
    } else {
        return `${Math.round(nb*100)/100}`;
    }
}

function simpleRecursiveIteration(array, i = 0){
    if (i < array.length) {
        array[i] * array[i];

        return simpleRecursiveIteration(array, i+1);
    }
}

function recursiveClosureIteration(array){
    let i = 0;

    function rec(array){
        if (i < array.length){
            array[i] * array[i];

            i++;

            return rec(array);
        }
    }

    return rec(array);
}

function doSuite(arrayLength) {
    console.log(`# Array.length : ${arrayLength}`);
    const Suite = new Benchmark.Suite();
    const array = new Array(arrayLength).fill(0);

    Suite
        .add('Simple recursion', function() {
            simpleRecursiveIteration(array);
        })
        .add('Simple recursion with i in closure', function() {
            recursiveClosureIteration(array);
        })
        .add('for (let i = 0; i < array.length; i++)', function () {
            for (let i = 0; i < array.length; i++) {
                array[i] * array[i];
            }
        })
        .add('for (let i = 0, iMax = array.length; i < iMax; i++)', function () {
            for (let i = 0, iMax = array.length; i < iMax; i++) {
                array[i] * array[i];
            }
        })
        .add('let i = 0; const iMax = array.length; for (; i++ < iMax;)', function () {
            let i = 0;
            const iMax = array.length;

            for (; i++ < iMax;) {
                array[i] * array[i];
            }
        })
        .add('let i = 0; const iMax = array.length; for (; i < iMax; i++)', function () {
            let i = 0;
            const iMax = array.length;

            for (; i < iMax; i++) {
                array[i] * array[i];
            }
        })
        .add('let i = 0; for (; i < array.length; i++)', function () {
            let i = 0;

            for (; i < array.length; i++) {
                array[i] * array[i];
            }
        })
        .add('let i = 0; const iMax = array.length; for (; iMax - i; i++)', function () {
            let i = 0;
            const iMax = array.length;

            for (; iMax - i; i++) {
                array[i] * array[i];
            }
        })
        .add('let i = 0; for (; array[i] !== undefined; i++)', function () {
            let i = 0;

            for (; array[i] !== undefined; i++) {
                array[i] * array[i];
            }
        })
        .add('let i = 0; for (; array[i++] !== undefined;)', function () {
            let i = 0;

            for (; array[i++] !== undefined;) {
                array[i] * array[i];
            }
        })
        .add('let i = 0; while (array[i++] !== undefined)', function () {
            let i = 0;

            while (array[i++] !== undefined) {
                array[i] * array[i];
            }
        })
        .add('let i = array.length; while (i--)', function () {
            let i = array.length;

            while (i--) {
                array[i] * array[i];
            }
        })
        .add('let i = 0, iMax = array.length; while (i++ < iMax)', function () {
            let i = 0, iMax = array.length;

            while (i++ < iMax) {
                array[i] * array[i];
            }
        })
        .add('let i = 0, iMax = array.length; while (iMax - (i++))', function () {
            let i = 0, iMax = array.length;

            while (iMax - i++) {
                array[i] * array[i];
            }
        })
        .add('let i = -array.length; while (i++)', function () {
            let i = -array.length;

            while (i++) {
                array[i + array.length] * array[i + array.length];
            }
        })
        .on('cycle', function (event) {
            console.log(String(event.target));
            if (fileWriter) {
                fileWriter.writeTableElement(computeNumber(event.target.hz));
            }
        })
        .on('complete', function () {
            console.log('Fastest is ' + this.filter('fastest').map('name'));
        })
        .run({ async: false });
}

for (let i = 10; i < 10000000; i *= 10) {
    if (fileWriter) {
        fileWriter.writeTableElement(i);
    }

    doSuite(i);

    if (fileWriter) {
        fileWriter.newLine();
    }
}

if (fileWriter) {
    fileWriter.end();
}
<|endoftext|>


<commit_before>this["Selector"] = this["Selector"] || {};
this["Selector"]["templates"] = this["Selector"]["templates"] || {};

this["Selector"]["templates"]["messages"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
    var helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;

  return "                <div childName=\""
    + alias4(((helper = (helper = helpers["component-name"] || (depth0 != null ? depth0["component-name"] : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"component-name","hash":{},"data":data}) : helper)))
    + "-"
    + alias4(((helper = (helper = helpers.key || (data && data.key)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"key","hash":{},"data":data}) : helper)))
    + "\"\n                     class=\"tab-name\">"
    + alias4(container.lambda((depth0 != null ? depth0.title : depth0), depth0))
    + "
\n";
},"3":function(container,depth0,helpers,partials,data,blockParams,depths) {
    var stack1, helper, alias1=container.lambda, alias2=container.escapeExpression, alias3=depth0 != null ? depth0 : (container.nullContext || {});

  return "
\n
\n
"
    + alias2(alias1((depth0 != null ? depth0.title : depth0), depth0))
    + "
\n
\n"
    + ((stack1 = helpers.each.call(alias3,(depth0 != null ? depth0.items : depth0),{"name":"each","hash":{},"fn":container.program(4, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "")
    + "
\n
\n
\n";
},"4":function(container,depth0,helpers,partials,data,blockParams,depths) {
    var alias1=container.lambda, alias2=container.escapeExpression;

  return "
"
    + alias2(alias1((depth0 != null ? depth0.name : depth0), depth0))
    + "
\n";
},"6":function(container,depth0,helpers,partials,data,blockParams,depths) {
    var stack1;

  return "
\n
"
    + container.escapeExpression(container.lambda((depth0 != null ? depth0.title : depth0), depth0))
    + "
\n
\n"
    + ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.items : depth0),{"name":"each","hash":{},"fn":container.program(4, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "")
    + "
\n
\n";
},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data,blockParams,depths) {
    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;

  return "
\n
\n
"
    + alias4(((helper = (helper = helpers["display-title"] || (depth0 != null ? depth0["display-title"] : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"display-title","hash":{},"data":data}) : helper)))
    + "
\n        add skills\n\n
\n

\n
\n\n\n
\n
\n
\n
All\n                Categories
\n"
    + ((stack1 = helpers.each.call(alias1,(depth0 != null ? depth0.itemsBySection : depth0),{"name":"each","hash":{},"fn":container.program(1, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "")
    + "
\n"
    + ((stack1 = helpers.each.call(alias1,(depth0 != null ? depth0.itemsBySection : depth0),{"name":"each","hash":{},"fn":container.program(3, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "")
    + "\n
\n"
    + ((stack1 = helpers.each.call(alias1,(depth0 != null ? depth0.itemsBySection : depth0),{"name":"each","hash":{},"fn":container.program(6, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "")
    + "
\n
\n
\n
Close
\n
\n
\n\n\n";
},"useData":true,"useDepths":true});<commit_msg>Selector UI: removed a file created by Grunt (now renamed to selector).<commit_after><|endoftext|>


<commit_before>/*jshint maxdepth:6*/
steal('can/util', 'can/route', function (can) {
	"use strict";

	if (window.history && history.pushState) {
		can.route.bindings.pushstate = {
			/**
			 * @property {String} can.route.pushstate.root
			 * @parent can.route.pushstate
			 *
			 * @description Configure the base url that will not be modified.
			 *
			 * @option {String} Represents the base url that pushstate will prepend to all
			 * routes.  `root` defaults to: `"/"`.
			 *
			 * @body
			 *
			 * ## Use
			 *
			 * By default, a route like:
			 *
			 *     can.route(":type/:id")
			 *
			 * Matches urls like:
			 *
			 *     http://domain.com/contact/5
			 *
			 * But sometimes, you only want to match pages within a certain directory.  For
			 * example, an application that is a filemanager.  You might want to
			 * specify root and routes like:
			 *
			 *     can.route.pushstate.root = "/filemanager/"
			 *     can.route("file-:fileId");
			 *     can.route("folder-:fileId")
			 *
			 * Which matches urls like:
			 *
			 *     http://domain.com/filemanager/file-34234
			 *
			 */
			root: "/",
			paramsMatcher: /^\?(?:[^=]+=[^&]*&)*[^=]+=[^&]*/,
			querySeparator: '?',
			bind: function () {
				// intercept routable links
				can.delegate.call(can.$(document.documentElement), 'a', 'click', anchorClickFix);

				// popstate only fires on back/forward.
				// To detect when someone calls push/replaceState, we need to wrap each method.
				can.each(['pushState', 'replaceState'], function (method) {
					originalMethods[method] = window.history[method];
					window.history[method] = function (state, title, url) {
						// avoid doubled history states (with pushState)
						var absolute = url.indexOf("http") === 0;
						var searchHash = window.location.search + window.location.hash;
						if ((!absolute && url !== window.location.pathname + searchHash) || (absolute && url !== window.location.href + searchHash)) {
							originalMethods[method].apply(window.history, arguments);
							can.route.setState();
						}
					};
				});

				// Bind to popstate for back/forward
				can.bind.call(window, 'popstate', can.route.setState);
			},
			unbind: function () {
				can.undelegate.call(can.$(document.documentElement), 'click', 'a', anchorClickFix);

				can.each(['pushState', 'replaceState'], function (method) {
					window.history[method] = originalMethods[method];
				});
				can.unbind.call(window, 'popstate', can.route.setState);
			},
			matchingPartOfURL: function () {
				var root = cleanRoot(),
					loc = (location.pathname + location.search),
					index = loc.indexOf(root);

				return loc.substr(index + root.length);
			},
			setURL: function (path) {
				// keep hash if not in path, but in
				if (includeHash && path.indexOf("#") === -1 && window.location.hash) {
					path += window.location.hash;
				}
				window.history.pushState(null, null, can.route._call("root") + path);
			}
		};

		var anchorClickFix = function (e) {
			if (!(e.isDefaultPrevented ? e.isDefaultPrevented() : e.defaultPrevented === true)) {
				// YUI calls back events triggered with this as a wrapped object
				var node = this._node || this;
				// Fix for ie showing blank host, but blank host means current host.
				var linksHost = node.host || window.location.host;
				// if link is within the same domain
				if (window.location.host === linksHost) {
					// if link is a descendant of `root`
					var root = can.route._call("root");
					if (node.pathname.indexOf(root) === 0) {
						// remove `root` from url
						var url = (node.pathname + node.search)
							.substr(root.length);
						var curParams = can.route.deparam(url);
						// if a route matches
						if (curParams.hasOwnProperty('route')) {
							// make it possible to have a link with a hash
							includeHash = true;
							// update the data
							window.history.pushState(null, null, node.href);
							// test if you can preventDefault
							// our tests can't call .click() b/c this
							// freezes phantom
							if (e.preventDefault) {
								e.preventDefault();
							}
						}
					}
				}
			}
		},
			cleanRoot = function () {
				var domain = location.protocol + "//" + location.host,
					root = can.route._call("root"),
					index = root.indexOf(domain);
				if (index === 0) {
					return can.route.root.substr(domain.length);
				}
				return root;
			},
			// a collection of methods on history that we are overwriting
			originalMethods = {},
			// used to tell setURL to include the hash because
			// we clicked on a link
			includeHash = false;

		can.route.defaultBinding = "pushstate";

	}

	return can;
});
<commit_msg>Inline docs for can/route/pushstate, #838<commit_after>// # can/route/pushstate/pushstate.js
//
// Plugin for `can.route` which uses browser `history.pushState` support
// to update window's pathname instead of the `hash`.
//
// Registers itself as handler on `can.route`, intercepts `click` events
// on `<a>` elements across document and accordingly updates `can.route` state
// and window's pathname.

steal('can/util', 'can/route', function (can) {
	"use strict";

	// Initialize plugin only if browser supports pushstate.
	if (window.history && history.pushState) {

		// Registers itself within `can.route.bindings`.
		can.route.bindings.pushstate = {
			/**
			 * @property {String} can.route.pushstate.root
			 * @parent can.route.pushstate
			 *
			 * @description Configure the base url that will not be modified.
			 *
			 * @option {String} Represents the base url that pushstate will prepend to all
			 * routes.  `root` defaults to: `"/"`.
			 *
			 * @body
			 *
			 * ## Use
			 *
			 * By default, a route like:
			 *
			 *     can.route(":type/:id")
			 *
			 * Matches urls like:
			 *
			 *     http://domain.com/contact/5
			 *
			 * But sometimes, you only want to match pages within a certain directory.  For
			 * example, an application that is a filemanager.  You might want to
			 * specify root and routes like:
			 *
			 *     can.route.pushstate.root = "/filemanager/"
			 *     can.route("file-:fileId");
			 *     can.route("folder-:fileId")
			 *
			 * Which matches urls like:
			 *
			 *     http://domain.com/filemanager/file-34234
			 *
			 */

			// Start of `location.pathname` is the root.
			// (Can be configured via `can.route.bindings.pushstate.root`)
			root: "/",
			paramsMatcher: /^\?(?:[^=]+=[^&]*&)*[^=]+=[^&]*/,
			querySeparator: '?',

			// Intercepts clicks on `<a>` elements and rewrites original `history` methods.
			bind: function () {
				// Intercept routable links.
				can.delegate.call(can.$(document.documentElement), 'a', 'click', anchorClickHandler);

				// Rewrites original `pushState`/`replaceState` methods on `history` and keeps pointer to original methods
				can.each(methodsToOverride, function (method) {
					originalMethods[method] = window.history[method];
					window.history[method] = function (state, title, url) {
						// Avoid doubled history states (with pushState).
						var absolute = url.indexOf("http") === 0;
						var searchHash = window.location.search + window.location.hash;
						// If url differs from current call original histoy method and update `can.route` state.
						if ((!absolute && url !== window.location.pathname + searchHash) || (absolute && url !== window.location.href + searchHash)) {
							originalMethods[method].apply(window.history, arguments);
							can.route.setState();
						}
					};
				});

				// Bind to `popstate` event, fires on back/forward.
				can.bind.call(window, 'popstate', can.route.setState);
			},

			// Unbinds and restores original `history` methods
			unbind: function () {
				can.undelegate.call(can.$(document.documentElement), 'click', 'a', anchorClickHandler);

				can.each(methodsToOverride, function (method) {
					window.history[method] = originalMethods[method];
				});
				can.unbind.call(window, 'popstate', can.route.setState);
			},

			// Returns matching part of url without root.
			matchingPartOfURL: function () {
				var root = cleanRoot(),
					loc = (location.pathname + location.search),
					index = loc.indexOf(root);

				return loc.substr(index + root.length);
			},

			// Updates URL by calling `pushState`.
			setURL: function (path) {
				// Keeps hash if not in path.
				if (includeHash && path.indexOf("#") === -1 && window.location.hash) {
					path += window.location.hash;
				}
				window.history.pushState(null, null, can.route._call("root") + path);
			}
		};

		// Handler function for `click` events.
		var anchorClickHandler = function (e) {
			if (!(e.isDefaultPrevented ? e.isDefaultPrevented() : e.defaultPrevented === true)) {
				// YUI calls back events triggered with this as a wrapped object.
				var node = this._node || this;
				// Fix for IE showing blank host, but blank host means current host.
				var linksHost = node.host || window.location.host;

				// If link is within the same domain and descendant of `root`
				if (window.location.host === linksHost) {
					var root = can.route._call("root");
					if (node.pathname.indexOf(root) === 0) {

						// Removes root from url.
						var url = (node.pathname + node.search).substr(root.length);
						// If a route matches update the data.
						var curParams = can.route.deparam(url);
						if (curParams.hasOwnProperty('route')) {
							// Makes it possible to have a link with a hash.
							includeHash = true;
							window.history.pushState(null, null, node.href);

							// Test if you can preventDefault
							// our tests can't call .click() b/c this
							// freezes phantom.
							if (e.preventDefault) {
								e.preventDefault();
							}
						}
					}
				}
			}
		},
			// Always returns clean root, without domain.
			cleanRoot = function () {
				var domain = location.protocol + "//" + location.host,
					root = can.route._call("root"),
					index = root.indexOf(domain);
				if (index === 0) {
					return can.route.root.substr(domain.length);
				}
				return root;
			},
			// Original methods on `history` that will be overwritten
			methodsToOverride = ['pushState', 'replaceState'],
			// A place to store pointers to original `history` methods.
			originalMethods = {},
			// Used to tell setURL to include the hash because we clicked on a link
			includeHash = false;

		// Enables plugin, by default `hashchange` binding is used.
		can.route.defaultBinding = "pushstate";
	}

	return can;
});
<|endoftext|>


<commit_before>/*
** Module dependencies
*/
var mongoose = require('mongoose');
var utils = require('../utils');
var openfisca = require('../simulation/openfisca');

var Schema = mongoose.Schema;

var ressourceTypes = [
    'revenusSalarie',
    'stage',
    'revenusStageFormationPro',
    'allocationsChomage',
    'allocationSecurisationPro',
    'primeRepriseActivite',
    'allocationLogement',
    'rsa',
    'asf',
    'aspa',
    'ass',
    'aah',
    'indJourMaternite',
    'indJourMaladie',
    'indJourMaladieProf',
    'indJourAccidentDuTravail',
    'indChomagePartiel',
    'indVolontariat',
    'dedommagementAmiante',
    'pensionsAlimentaires',
    'prestationCompensatoire',
    'pensionsRetraitesRentes',
    'retraiteCombattant',
    'pensionsInvalidite',
    'bourseEnseignementSup',
    'bourseRecherche',
    'gainsExceptionnels',
    'revenusLocatifs',
    'revenusDuCapital',

    // rnc
    'rncRevenusActivite',
    'rncAutresRevenus',
    'rncPensionsRetraitesRentes',
    'rncPensionsAlimentaires',
    'rncPensionsAlimentairesVersees'
];

var RessourceSchema = new Schema({
    periode: { type: String },
    type: { type: String, enum: ressourceTypes },
    montant: { type: Number, required: true }
});

var situationsPro = [
    'sans_activite',
    'salarie',
    'auto_entrepreneur',
    'apprenti',
    'travailleur_saisonnier',
    'stagiaire',
    'independant',
    'gerant_salarie',
    'demandeur_emploi',
    'etudiant',
    'retraite',
    'handicap',
    'boursier',
    'inapte_travail',
    'autre'
];

var SituationPro = new Schema({
    situation: { type: String, enum: situationsPro },
    since: String,
    volontairementSansActivite: Boolean,
    contractType: { type: String, enum: ['cdi', 'cdd', 'interim'] },
    isRemunere: Boolean,
    gerantSalarieAffiliation: String,
    isIndemnise: Boolean,
    indemniseSince: String
});

var statutsMaritaux = [
    'mariage',
    'pacs',
    'relation_libre',
    'celibataire',
    'separe',
    'divorce',
    'veuf',
    'pacs_rompu',
    'concubinage_rompu'
];

var situationsEnfants = [
    'scolarise',
    'apprenti',
    'salarie',
    'formation_pro',
    'demandeur_emploi',
    'chomage_indemnise',
    'sans_activite',
    'autre'
];

var IndividuDef = {
    civilite: { type: String, enum: ['f', 'h'] },
    firstName: String,
    lastName: String,
    nomUsage: String,
    nir: String,
    enceinte: Boolean,
    boursier: Boolean,
    statutMarital: { type: String, enum: statutsMaritaux },
    dateSituationFamiliale: Date,
    dateDeNaissance: Date,
    villeNaissance: String,
    departementNaissance: String,
    paysNaissance: String,
    situation: { type: String, enum: situationsEnfants },
    situationsPro: [SituationPro],
    scolarite: { type: String, enum: ['inconnue', 'college', 'lycee'] },
    nationalite: { type: String, enum: ['fr', 'ue', 'autre'] },
    dateArriveeFoyer: Date,
    inscritCaf: Boolean,
    gardeAlternee: Boolean,
    assPreconditionRemplie: Boolean,
    numeroAllocataire: String,
    lienParente: { type: String, enum: ['fils', 'neveu', 'aucun', 'autre'] },
    residenceAlternee: Boolean,
    role: { type: String, enum: ['demandeur', 'conjoint', 'enfant', 'personneACharge', 'personneSousMemeToit'] },
    ressources: [RessourceSchema],
    interruptedRessources: [{ type: String, enum: ressourceTypes }],
    caMicroEntreprise: Number,
    autresRevenusTns: Number,
    tauxInvalidite: { type: String, enum: ['nul', 'moins50', 'moins80', 'plus80'] },
    tnsStructureType: { type: String, enum: ['auto_entrepreneur', 'micro_entreprise'] },
    tnsActiviteType: { type: String, enum: ['achat_revente', 'bic', 'bnc'] }
};

var IndividuSchema = new Schema(IndividuDef);

var AdresseDef = {
    adresse: String,
    codePostal: String,
    codeInsee: String,
    ville: String,
    pays: String
};

var LogementDef = {
    primoAccedant: Boolean,
    pretConventionne: Boolean,
    membreFamilleProprietaire: Boolean,
    conjointMemeAdresse: Boolean,
    loyer: Number,
    adresse: AdresseDef,
    type: { type: String, enum: ['locataire', 'proprietaire', 'gratuit', 'payant'] },
    colocation: Boolean,
    locationType: { type: String, enum: ['foyer', 'nonmeuble', 'meublehotel', 'hlm'] },
    isChambre: Boolean,
    dateArrivee: Date,
    adresseConjoint: AdresseDef
};

var SituationSchema = new Schema({
    _updated: Date,
    status: { type: String, default: 'new' },
    dateDeValeur: { type: Date, default: Date.now },
    logement: LogementDef,
    individus: [IndividuSchema],
    patrimoine: {
        captured: Boolean,
        revenusLocatifs: [RessourceSchema],
        valeurLocativeImmoNonLoue: Number,
        valeurLocativeTerrainNonLoue: Number,
        revenusDuCapital: [RessourceSchema],
        epargneSurLivret: Number,
        epargneSansRevenus: Number
    },
    ressourcesYearMoins2Captured: { type: Boolean, default: false },
    rfr: Number,
    phoneNumber: String,
    email: String,
    token: String
});

SituationSchema.methods = {

    submit: function(done) {
        if (this.status !== 'new') done(new Error('Not a new situation. Cannot be submitted.'));
        this.set('status', 'pending').save(done);
    },

    simulate: function(done) {
        openfisca.simulate(this, done);
    }

};

SituationSchema.pre('save', function(next) {
    if (!this.isNew) next();
    var situation = this;
    utils.generateToken(function(err, generatedToken) {
        if (err) return next(err);
        situation.token = generatedToken;
        next();
    });
});

mongoose.model('Situation', SituationSchema);
<commit_msg>suppression champ residence alternee sur entité individu<commit_after>/*
** Module dependencies
*/
var mongoose = require('mongoose');
var utils = require('../utils');
var openfisca = require('../simulation/openfisca');

var Schema = mongoose.Schema;

var ressourceTypes = [
    'revenusSalarie',
    'stage',
    'revenusStageFormationPro',
    'allocationsChomage',
    'allocationSecurisationPro',
    'primeRepriseActivite',
    'allocationLogement',
    'rsa',
    'asf',
    'aspa',
    'ass',
    'aah',
    'indJourMaternite',
    'indJourMaladie',
    'indJourMaladieProf',
    'indJourAccidentDuTravail',
    'indChomagePartiel',
    'indVolontariat',
    'dedommagementAmiante',
    'pensionsAlimentaires',
    'prestationCompensatoire',
    'pensionsRetraitesRentes',
    'retraiteCombattant',
    'pensionsInvalidite',
    'bourseEnseignementSup',
    'bourseRecherche',
    'gainsExceptionnels',
    'revenusLocatifs',
    'revenusDuCapital',

    // rnc
    'rncRevenusActivite',
    'rncAutresRevenus',
    'rncPensionsRetraitesRentes',
    'rncPensionsAlimentaires',
    'rncPensionsAlimentairesVersees'
];

var RessourceSchema = new Schema({
    periode: { type: String },
    type: { type: String, enum: ressourceTypes },
    montant: { type: Number, required: true }
});

var situationsPro = [
    'sans_activite',
    'salarie',
    'auto_entrepreneur',
    'apprenti',
    'travailleur_saisonnier',
    'stagiaire',
    'independant',
    'gerant_salarie',
    'demandeur_emploi',
    'etudiant',
    'retraite',
    'handicap',
    'boursier',
    'inapte_travail',
    'autre'
];

var SituationPro = new Schema({
    situation: { type: String, enum: situationsPro },
    since: String,
    volontairementSansActivite: Boolean,
    contractType: { type: String, enum: ['cdi', 'cdd', 'interim'] },
    isRemunere: Boolean,
    gerantSalarieAffiliation: String,
    isIndemnise: Boolean,
    indemniseSince: String
});

var statutsMaritaux = [
    'mariage',
    'pacs',
    'relation_libre',
    'celibataire',
    'separe',
    'divorce',
    'veuf',
    'pacs_rompu',
    'concubinage_rompu'
];

var situationsEnfants = [
    'scolarise',
    'apprenti',
    'salarie',
    'formation_pro',
    'demandeur_emploi',
    'chomage_indemnise',
    'sans_activite',
    'autre'
];

var IndividuDef = {
    civilite: { type: String, enum: ['f', 'h'] },
    firstName: String,
    lastName: String,
    nomUsage: String,
    nir: String,
    enceinte: Boolean,
    boursier: Boolean,
    statutMarital: { type: String, enum: statutsMaritaux },
    dateSituationFamiliale: Date,
    dateDeNaissance: Date,
    villeNaissance: String,
    departementNaissance: String,
    paysNaissance: String,
    situation: { type: String, enum: situationsEnfants },
    situationsPro: [SituationPro],
    scolarite: { type: String, enum: ['inconnue', 'college', 'lycee'] },
    nationalite: { type: String, enum: ['fr', 'ue', 'autre'] },
    dateArriveeFoyer: Date,
    inscritCaf: Boolean,
    gardeAlternee: Boolean,
    assPreconditionRemplie: Boolean,
    numeroAllocataire: String,
    lienParente: { type: String, enum: ['fils', 'neveu', 'aucun', 'autre'] },
    role: { type: String, enum: ['demandeur', 'conjoint', 'enfant', 'personneACharge', 'personneSousMemeToit'] },
    ressources: [RessourceSchema],
    interruptedRessources: [{ type: String, enum: ressourceTypes }],
    caMicroEntreprise: Number,
    autresRevenusTns: Number,
    tauxInvalidite: { type: String, enum: ['nul', 'moins50', 'moins80', 'plus80'] },
    tnsStructureType: { type: String, enum: ['auto_entrepreneur', 'micro_entreprise'] },
    tnsActiviteType: { type: String, enum: ['achat_revente', 'bic', 'bnc'] }
};

var IndividuSchema = new Schema(IndividuDef);

var AdresseDef = {
    adresse: String,
    codePostal: String,
    codeInsee: String,
    ville: String,
    pays: String
};

var LogementDef = {
    primoAccedant: Boolean,
    pretConventionne: Boolean,
    membreFamilleProprietaire: Boolean,
    conjointMemeAdresse: Boolean,
    loyer: Number,
    adresse: AdresseDef,
    type: { type: String, enum: ['locataire', 'proprietaire', 'gratuit', 'payant'] },
    colocation: Boolean,
    locationType: { type: String, enum: ['foyer', 'nonmeuble', 'meublehotel', 'hlm'] },
    isChambre: Boolean,
    dateArrivee: Date,
    adresseConjoint: AdresseDef
};

var SituationSchema = new Schema({
    _updated: Date,
    status: { type: String, default: 'new' },
    dateDeValeur: { type: Date, default: Date.now },
    logement: LogementDef,
    individus: [IndividuSchema],
    patrimoine: {
        captured: Boolean,
        revenusLocatifs: [RessourceSchema],
        valeurLocativeImmoNonLoue: Number,
        valeurLocativeTerrainNonLoue: Number,
        revenusDuCapital: [RessourceSchema],
        epargneSurLivret: Number,
        epargneSansRevenus: Number
    },
    ressourcesYearMoins2Captured: { type: Boolean, default: false },
    rfr: Number,
    phoneNumber: String,
    email: String,
    token: String
});

SituationSchema.methods = {

    submit: function(done) {
        if (this.status !== 'new') done(new Error('Not a new situation. Cannot be submitted.'));
        this.set('status', 'pending').save(done);
    },

    simulate: function(done) {
        openfisca.simulate(this, done);
    }

};

SituationSchema.pre('save', function(next) {
    if (!this.isNew) next();
    var situation = this;
    utils.generateToken(function(err, generatedToken) {
        if (err) return next(err);
        situation.token = generatedToken;
        next();
    });
});

mongoose.model('Situation', SituationSchema);
<|endoftext|>


<commit_before>/*
 * inject-dependencies.js
 * https://github.com/stephenplusplus/wiredep
 *
 * Copyright (c) 2013 Stephen Sawchuk
 * Licensed under the MIT license.
 */

'use strict';

var fs = require('fs');
var path = require('path');
var _ = require('lodash');

var globalDependenciesSorted;
var ignorePath;
var fileTypes;

var fileTypesDefault = {
  html: {
    block: /(([\s\t]*)<!--\s*bower:*(\S*)\s*-->)(\n|\r|.)*?(<!--\s*endbower\s*-->)/gi,
    detect: {
      js: /<script.*src=['"](.+)['"]>/gi,
      css: /<link.*href=['"](.+)['"]/gi
    },
    replace: {
      js: '<script src="{{filePath}}"></script>',
      css: '<link rel="stylesheet" href="{{filePath}}" />'
    }
  },

  yaml: {
    block: /(([\s\t]*)#\s*bower:*(\S*))(\n|\r|.)*?(#\s*endbower)/gi,
    detect: {
      js: /-\s(.+)/gi,
      css: /-\s(.+)/gi
    },
    replace: {
      js: '- {{filePath}}',
      css: '- {{filePath}}'
    }
  }
};

fileTypesDefault.yml = fileTypesDefault.yaml;
fileTypesDefault.htm = fileTypesDefault.html;

/**
 * Find references already on the page, not in a Bower block.
 */
var filesCaught = [];
var findReferences = function (match, reference) {
  filesCaught.push(reference);
  return match;
};

var replaceIncludes = function (fileType, returnType) {
  /**
   * Callback function after matching our regex from the source file.
   *
   * @param  {array}  match       strings that were matched
   * @param  {string} startBlock  the opening <!-- bower:xxx --> comment
   * @param  {string} spacing     the type and size of indentation
   * @param  {string} blockType   the type of block (js/css)
   * @param  {string} oldScripts  the old block of scripts we'll remove
   * @param  {string} endBlock    the closing <!-- endbower --> comment
   * @return {string} the new file contents
   */
  return function (match, startBlock, spacing, blockType, oldScripts, endBlock, offset, string) {
    blockType = blockType || 'js';

    var newFileContents = startBlock;
    var dependencies = globalDependenciesSorted[blockType] || [];

    string = string.substr(0, offset) + string.substr(offset + match.length);

    string.
      replace(oldScripts, '').
      replace(fileTypes[fileType].detect[blockType], findReferences);

    spacing = returnType + spacing.replace(/\r|\n/g, '');

    dependencies.
      map(function (path) {
        return path.replace(/\\/g, '/').replace(ignorePath, '');
      }).
      filter(function (path) {
        return filesCaught.indexOf(path) === -1;
      }).
      forEach(function (path) {
        newFileContents += spacing + fileTypes[fileType].replace[blockType].replace('{{filePath}}', path);
      });

    return newFileContents + spacing + endBlock;
  };
};

/**
 * Take a file path, read its contents, inject the Bower packages, then write
 * the new file to disk.
 *
 * @param  {string} file  path to the source file
 */
var injectScripts = function (file) {
  var contents = String(fs.readFileSync(file));
  var fileType = path.extname(file).substr(1);
  var returnType = /\r\n/.test(contents) ? '\r\n' : '\n';

  fs.writeFileSync(file, contents.replace(
    fileTypes[fileType].block,
    replaceIncludes(fileType, returnType)
  ));
};

/**
 * Injects dependencies into the specified HTML file.
 *
 * @param  {object} config  the global configuration object.
 * @return {object} config
 */
module.exports = function inject(config) {
  globalDependenciesSorted = config.get('global-dependencies-sorted');
  ignorePath = config.get('ignore-path');
  fileTypes = _.clone(fileTypesDefault, true);

  _(config.get('file-types')).each(function (fileTypeConfig, fileType) {
    fileTypes[fileType] = fileTypes[fileType] || {};
    _.each(fileTypeConfig, function (config, configKey) {
      if (_.isObject(fileTypes[fileType][configKey])) {
        fileTypes[fileType][configKey] =
          _.assign(fileTypes[fileType][configKey], config);
      } else {
        fileTypes[fileType][configKey] = config;
      }
    });
  });

  config.get('src').forEach(injectScripts);

  return config;
};
<commit_msg>Fix override issue of default Block values<commit_after>/*
 * inject-dependencies.js
 * https://github.com/stephenplusplus/wiredep
 *
 * Copyright (c) 2013 Stephen Sawchuk
 * Licensed under the MIT license.
 */

'use strict';

var fs = require('fs');
var path = require('path');
var _ = require('lodash');

var globalDependenciesSorted;
var ignorePath;
var fileTypes;

var fileTypesDefault = {
  html: {
    block: /(([\s\t]*)<!--\s*bower:*(\S*)\s*-->)(\n|\r|.)*?(<!--\s*endbower\s*-->)/gi,
    detect: {
      js: /<script.*src=['"](.+)['"]>/gi,
      css: /<link.*href=['"](.+)['"]/gi
    },
    replace: {
      js: '<script src="{{filePath}}"></script>',
      css: '<link rel="stylesheet" href="{{filePath}}" />'
    }
  },

  yaml: {
    block: /(([\s\t]*)#\s*bower:*(\S*))(\n|\r|.)*?(#\s*endbower)/gi,
    detect: {
      js: /-\s(.+)/gi,
      css: /-\s(.+)/gi
    },
    replace: {
      js: '- {{filePath}}',
      css: '- {{filePath}}'
    }
  }
};

fileTypesDefault.yml = fileTypesDefault.yaml;
fileTypesDefault.htm = fileTypesDefault.html;

/**
 * Find references already on the page, not in a Bower block.
 */
var filesCaught = [];
var findReferences = function (match, reference) {
  filesCaught.push(reference);
  return match;
};

var replaceIncludes = function (fileType, returnType) {
  /**
   * Callback function after matching our regex from the source file.
   *
   * @param  {array}  match       strings that were matched
   * @param  {string} startBlock  the opening <!-- bower:xxx --> comment
   * @param  {string} spacing     the type and size of indentation
   * @param  {string} blockType   the type of block (js/css)
   * @param  {string} oldScripts  the old block of scripts we'll remove
   * @param  {string} endBlock    the closing <!-- endbower --> comment
   * @return {string} the new file contents
   */
  return function (match, startBlock, spacing, blockType, oldScripts, endBlock, offset, string) {
    blockType = blockType || 'js';

    var newFileContents = startBlock;
    var dependencies = globalDependenciesSorted[blockType] || [];

    string = string.substr(0, offset) + string.substr(offset + match.length);

    string.
      replace(oldScripts, '').
      replace(fileTypes[fileType].detect[blockType], findReferences);

    spacing = returnType + spacing.replace(/\r|\n/g, '');

    dependencies.
      map(function (path) {
        return path.replace(/\\/g, '/').replace(ignorePath, '');
      }).
      filter(function (path) {
        return filesCaught.indexOf(path) === -1;
      }).
      forEach(function (path) {
        newFileContents += spacing + fileTypes[fileType].replace[blockType].replace('{{filePath}}', path);
      });

    return newFileContents + spacing + endBlock;
  };
};

/**
 * Take a file path, read its contents, inject the Bower packages, then write
 * the new file to disk.
 *
 * @param  {string} file  path to the source file
 */
var injectScripts = function (file) {
  var contents = String(fs.readFileSync(file));
  var fileType = path.extname(file).substr(1);
  var returnType = /\r\n/.test(contents) ? '\r\n' : '\n';

  fs.writeFileSync(file, contents.replace(
    fileTypes[fileType].block,
    replaceIncludes(fileType, returnType)
  ));
};

/**
 * Injects dependencies into the specified HTML file.
 *
 * @param  {object} config  the global configuration object.
 * @return {object} config
 */
module.exports = function inject(config) {
  globalDependenciesSorted = config.get('global-dependencies-sorted');
  ignorePath = config.get('ignore-path');
  fileTypes = _.clone(fileTypesDefault, true);

  _(config.get('file-types')).each(function (fileTypeConfig, fileType) {
    fileTypes[fileType] = fileTypes[fileType] || {};
    _.each(fileTypeConfig, function (config, configKey) {
      if (_.isPlainObject(fileTypes[fileType][configKey])) {
        fileTypes[fileType][configKey] =
          _.assign(fileTypes[fileType][configKey], config);
      } else {
        fileTypes[fileType][configKey] = config;
      }
    });
  });

  config.get('src').forEach(injectScripts);

  return config;
};
<|endoftext|>