<commit_before>(function(d3, _, helpers, extensions) {
  var property = helpers.property;

  /**
    Configurable chart

    Configure chart based on given options, including adding charts, axes, legend, and other properties

    @example
    ```javascript
    var chart = d3.select('#chart')
      .append('svg')
      .chart('Configurable', {
        type: 'Values'
        charts: [
          {type: 'Bars', dataKey: 'participation', itemPadding: 20},
          {type: 'Line', dataKey: 'results', labels: {position: 'top'}}
        ],
        axes: {
          y: {scale: {domain: [0, 20000]}},
          secondaryY: {dataKey: 'results', scale: {domain: [0, 70]}}
        }
      })
      .width(600)
      .height(400)
      .chartMargins({top: 10});
    ```

    @param {Object} options
    - charts: {Array} of chart definitions
      - type: Matches Chart name (Line, LineValues, Bars)
      - dataKey: Key for extracting chart data from data object
      - other chart properties (e.g. xScale/yScale: {type, domain}, itemPadding, labelPosition, etc.)
    - axes: {Array} of axis definitions
      - type: [Axis] Matches Axis name (Axis, AxisValues)
      - dataKey: Key for extracting axis data from data object
      - other axis properties
    - legend: {Object} of legend properties
      - dataKey: Key for extracting legend data from data object
      - position: top, right, bottom, left
      - other legend properties
  */
  d3.chart('Container').extend('Configurable', {
    initialize: function() {
      this.redrawFor('title', 'charts', 'axes', 'legend');
    },

    options: property('options', {
      defaultValue: {},
      set: function(options) {
        this.type(options.type, {silent: true});

        this.axes(options.axes, {silent: true});
        this.charts(options.charts, {silent: true});
        this.legend(options.legend, {silent: true});
        this.title(options.title, {silent: true});

        // To avoid changing underlying and then redraw failing due to no "change"
        // store cloned options
        return {
          override: _.clone(options)
        };
      }
    }),

    type: property('type', {
      defaultValue: 'XY'
    }),

    title: property('title', {
      set: function(options, title) {
        var changed = false;

        if (!options || _.isEmpty(options)) {
          // Remove title if no options are given
          this.detachComponent('title');

          return {
            override: undefined
          };
        }

        // Title may be set directly
        if (_.isString(options))
          options = {title: options};

        // Load defaults
        options = _.defaults({}, options, d3.chart('Configurable').defaults.title);

        if (!title) {
          // Create title
          var Title = helpers.resolveChart(options.type, 'Title', this.type());
          title = new Title(this.componentLayer({zIndex: helpers.zIndex.title}), options);

          this.attachComponent('title', title);
          changed = true;
        }
        else if (!_.isEqual(title.options(), options)) {
          // Update existing title options
          title.options(options/*, {silent: true}*/);
          changed = true;
        }

        return {
          override: title,

          // Updating existing object causes change determination to always be false,
          // so keep track explicitly
          changed: changed
        };
      }
    }),

    charts: property('charts', {
      set: function(options, charts) {
        options = options || {};
        charts = charts || {};
        var removeIds = _.difference(_.keys(charts), _.keys(options));
        var changed = removeIds.length > 0;

        _.each(removeIds, function(removeId) {
          this.detachChart(removeId);
          delete charts[removeId];
        });

        _.each(options, function(chartOptions, chartId) {
          var chart = charts[chartId];
          chartOptions = _.defaults({}, chartOptions, d3.chart('Configurable').defaults.charts);

          if (!chart) {
            // Create chart
            var Chart = helpers.resolveChart(chartOptions.type, 'Chart', this.type());
            chart = new Chart(this.chartLayer(), chartOptions);

            this.attachChart(chartId, chart);
            charts[chartId] = chart;
            changed = true;
          }
          else if (!_.isEqual(chart.options(), chartOptions)) {
            // Update chart
            chart.options(chartOptions/*, {silent: true}*/);
            changed = true;
          }
        }, this);

        return {
          override: charts,
          changed: changed,
          after: function() {
            this.bindChartScales();
          }
        };
      },
      defaultValue: {}
    }),

    axes: property('axes', {
      set: function(options, axes) {
        options = options || {};
        axes = axes || {};
        var axisIds = _.uniq(['x', 'y'].concat(_.keys(options)));
        var removeIds = _.difference(_.keys(axes), axisIds);
        var changed = removeIds.length > 0;

        _.each(removeIds, function(removeId) {
          this.detachComponent('axis.' + removeId);
          this.detachComponent('axis_title.' + removeId);
          delete axes[removeId];
        });

        _.each(axisIds, function(axisId) {
          var axis = axes[axisId];
          var positionById = {
            x: 'bottom',
            y: 'left',
            secondaryX: 'top',
            secondaryY: 'right'
          };
          var axisOptions = {
            position: positionById[axisId]
          };

          if (options[axisId] === false)
            axisOptions = _.defaults({display: false}, axisOptions, d3.chart('Configurable').defaults.axes);
          else
            axisOptions = _.defaults({}, options[axisId], axisOptions, d3.chart('Configurable').defaults.axes);

          if (axisId != 'x' && axisId != 'y' && !axisOptions.dataKey)
            throw new Error('d3.chart.csnw.configurable: dataKey(s) are required for axes other than x and y');

          if (!axis) {
            // Create axis
            var Axis = helpers.resolveChart(axisOptions.type, 'Axis', this.type());
            axis = new Axis(this.chartLayer({zIndex: helpers.zIndex.axis}), axisOptions);

            this.attachComponent('axis.' + axisId, axis);
            axes[axisId] = axis;
            changed = true;
          }
          else {
            // Check for changed from options
            if (!_.isEqual(axis.options(), axisOptions))
              changed = true;

            axis.options(axisOptions/*, {silent: true}*/);
          }

          // Create axis title
          if (axisOptions.title) {
            var id = 'axis_title.' + axisId;
            var title = this.componentsById[id];
            var titleOptions = _.isString(axisOptions.title) ? {title: axisOptions.title} : axisOptions.title;
            titleOptions = _.defaults({}, titleOptions, {position: axisOptions.position, 'class': 'chart-title-axis'});

            if (!title) {
              var Title = helpers.resolveChart(titleOptions.type, 'Title', this.type());
              title = new Title(this.componentLayer({zIndex: helpers.zIndex.title}), titleOptions);

              this.attachComponent(id, title);
            }
            else {
              title.options(titleOptions/*, {silent: true}*/);
            }
          }
        }, this);

        // Setup filter keys for x and y axes
        _.each(['x', 'y'], function(axisId) {
          var axis = axes[axisId];

          // Don't need to filter keys if dataKey already set
          if (axis.options().dataKey)
            return;

          var filterKeys = [];
          _.each(axes, function(filterAxis, filterKey) {
            if ((axisId == 'x' && !filterAxis.isXAxis()) || (axisId == 'y' && !filterAxis.isYAxis()))
              return;

            var dataKey = filterAxis.options().dataKey;
            if (dataKey)
              filterKeys = filterKeys.concat(_.isArray(dataKey) ? dataKey : [dataKey]);
          }, this);

          if (!_.isEqual(axis.options().filterKeys, filterKeys))
            changed = true;

          // Set filterKeys "internally" to avoid change firing
          axis.options().filterKeys = filterKeys;
        }, this);

        return {
          override: axes,
          changed: changed,
          after: function() {
            this.bindChartScales();
          }
        };
      },
      defaultValue: {}
    }),

    legend: property('legend', {
      set: function(options, legend) {
        options = options === false ? {display: false} : (options || {});
        options = _.defaults({}, options, d3.chart('Configurable').defaults.legend);
        var changed = false;

        // Load chart information
        if (options.dataKey) {
          // Load only charts matching dataKey(s)
          var dataKeys = _.isArray(options.dataKey) ? options.dataKey : [options.dataKey];
          options.charts = _.filter(this.charts(), function(chart) {
            return _.contains(dataKeys, chart.options().dataKey);
          });
        }

        // If switching from outside to inset, need to change legend base layer, so remove
        if (legend && legend.options().type != options.type) {
          // TODO Possible alternates for changing base of legend
          this.detachComponent('legend');
          legend = undefined;
        }

        if (!legend) {
          var Legend = helpers.resolveChart(options.type, 'Legend', this.type());
          var base = options.type == 'Inset' || options.type == 'InsetLegend' ? this.chartLayer({zIndex: helpers.zIndex.legend}) : this.componentLayer({zIndex: helpers.zIndex.legend});
          legend = new Legend(base, options);

          this.attachComponent('legend', legend);
          changed = true;
        }
        else {
          if (!_.isEqual(legend.options(), options))
            changed = true;

          legend.options(options);
        }

        return {
          override: legend,
          changed: changed
        };
      }
    }),

    demux: function(name, data) {
      var item = this.chartsById[name] || this.componentsById[name];

      if (item)
        return this.extractData(item, data);
      else
        return data;
    },

    extractData: function(item, data) {
      var dataKey = item.options().dataKey;
      var filterKeys = item.options().filterKeys;

      // Legends need all data (filter by charts)
      if (item && item.isLegend)
        return data;

      // Use dataKey or filterKeys if specified, otherwise use all data
      if (dataKey || filterKeys) {
        var dataKeys = _.isArray(dataKey) ? dataKey : (dataKey ? [dataKey] : []);
        filterKeys = _.isArray(filterKeys) ? filterKeys : (filterKeys ? [filterKeys] : []);

        var filtered = _.reduce(data, function(memo, series, key) {
          var exclude = _.contains(filterKeys, key);
          var include = _.contains(dataKeys, key);
          var includeAll = !dataKeys.length;

          if ((include || includeAll) && !exclude)
            return memo.concat(series);
          else
            return memo;
        }, []);

        return filtered;
      }
      else {
        return data;
      }
    },

    bindChartScales: function() {
      _.each(this.charts(), function(chart) {
        // Get scales for chart
        chart.xScale = this.getScale(chart.options().dataKey, 'x');
        chart.yScale = this.getScale(chart.options().dataKey, 'y');
      }, this);
    },

    getScale: function(dataKey, type) {
      var match = _.find(this.axes(), function(axis) {
        if ((type == 'x' && !axis.isXAxis()) || (type == 'y' && !axis.isYAxis()))
          return false;

        var axisDataKey = axis.options().dataKey;
        return _.isArray(axisDataKey) ? _.contains(axisDataKey, dataKey) : axisDataKey == dataKey;
      });
      var axis = match || this.axes()[type];
      var scaleKey = type == 'x' ? '_xScale' : '_yScale';

      return axis[scaleKey].bind(axis);
    }
  }, {
    defaults: {
      charts: {
        type: 'Line'
      },
      axes: {
        display: true
      },
      legend: {
        position: 'right'
      },
      title: {
        position: 'top',
        'class': 'chart-title-main'
      }
    }
  });

})(d3, _, d3.chart.helpers, d3.chart.extensions);
<commit_msg>Fix legend bug<commit_after>(function(d3, _, helpers, extensions) {
  var property = helpers.property;

  /**
    Configurable chart

    Configure chart based on given options, including adding charts, axes, legend, and other properties

    @example
    ```javascript
    var chart = d3.select('#chart')
      .append('svg')
      .chart('Configurable', {
        type: 'Values'
        charts: [
          {type: 'Bars', dataKey: 'participation', itemPadding: 20},
          {type: 'Line', dataKey: 'results', labels: {position: 'top'}}
        ],
        axes: {
          y: {scale: {domain: [0, 20000]}},
          secondaryY: {dataKey: 'results', scale: {domain: [0, 70]}}
        }
      })
      .width(600)
      .height(400)
      .chartMargins({top: 10});
    ```

    @param {Object} options
    - charts: {Array} of chart definitions
      - type: Matches Chart name (Line, LineValues, Bars)
      - dataKey: Key for extracting chart data from data object
      - other chart properties (e.g. xScale/yScale: {type, domain}, itemPadding, labelPosition, etc.)
    - axes: {Array} of axis definitions
      - type: [Axis] Matches Axis name (Axis, AxisValues)
      - dataKey: Key for extracting axis data from data object
      - other axis properties
    - legend: {Object} of legend properties
      - dataKey: Key for extracting legend data from data object
      - position: top, right, bottom, left
      - other legend properties
  */
  d3.chart('Container').extend('Configurable', {
    initialize: function() {
      this.redrawFor('title', 'charts', 'axes', 'legend');
    },

    options: property('options', {
      defaultValue: {},
      set: function(options) {
        this.type(options.type, {silent: true});

        this.axes(options.axes, {silent: true});
        this.charts(options.charts, {silent: true});
        this.legend(options.legend, {silent: true});
        this.title(options.title, {silent: true});

        // To avoid changing underlying and then redraw failing due to no "change"
        // store cloned options
        return {
          override: _.clone(options)
        };
      }
    }),

    type: property('type', {
      defaultValue: 'XY'
    }),

    title: property('title', {
      set: function(options, title) {
        var changed = false;

        if (!options || _.isEmpty(options)) {
          // Remove title if no options are given
          this.detachComponent('title');

          return {
            override: undefined
          };
        }

        // Title may be set directly
        if (_.isString(options))
          options = {title: options};

        // Load defaults
        options = _.defaults({}, options, d3.chart('Configurable').defaults.title);

        if (!title) {
          // Create title
          var Title = helpers.resolveChart(options.type, 'Title', this.type());
          title = new Title(this.componentLayer({zIndex: helpers.zIndex.title}), options);

          this.attachComponent('title', title);
          changed = true;
        }
        else if (!_.isEqual(title.options(), options)) {
          // Update existing title options
          title.options(options/*, {silent: true}*/);
          changed = true;
        }

        return {
          override: title,

          // Updating existing object causes change determination to always be false,
          // so keep track explicitly
          changed: changed
        };
      }
    }),

    charts: property('charts', {
      set: function(options, charts) {
        options = options || {};
        charts = charts || {};
        var removeIds = _.difference(_.keys(charts), _.keys(options));
        var changed = removeIds.length > 0;

        _.each(removeIds, function(removeId) {
          this.detachChart(removeId);
          delete charts[removeId];
        });

        _.each(options, function(chartOptions, chartId) {
          var chart = charts[chartId];
          chartOptions = _.defaults({}, chartOptions, d3.chart('Configurable').defaults.charts);

          if (!chart) {
            // Create chart
            var Chart = helpers.resolveChart(chartOptions.type, 'Chart', this.type());
            chart = new Chart(this.chartLayer(), chartOptions);

            this.attachChart(chartId, chart);
            charts[chartId] = chart;
            changed = true;
          }
          else if (!_.isEqual(chart.options(), chartOptions)) {
            // Update chart
            chart.options(chartOptions/*, {silent: true}*/);
            changed = true;
          }
        }, this);

        return {
          override: charts,
          changed: changed,
          after: function() {
            this.bindChartScales();
          }
        };
      },
      defaultValue: {}
    }),

    axes: property('axes', {
      set: function(options, axes) {
        options = options || {};
        axes = axes || {};
        var axisIds = _.uniq(['x', 'y'].concat(_.keys(options)));
        var removeIds = _.difference(_.keys(axes), axisIds);
        var changed = removeIds.length > 0;

        _.each(removeIds, function(removeId) {
          this.detachComponent('axis.' + removeId);
          this.detachComponent('axis_title.' + removeId);
          delete axes[removeId];
        });

        _.each(axisIds, function(axisId) {
          var axis = axes[axisId];
          var positionById = {
            x: 'bottom',
            y: 'left',
            secondaryX: 'top',
            secondaryY: 'right'
          };
          var axisOptions = {
            position: positionById[axisId]
          };

          if (options[axisId] === false)
            axisOptions = _.defaults({display: false}, axisOptions, d3.chart('Configurable').defaults.axes);
          else
            axisOptions = _.defaults({}, options[axisId], axisOptions, d3.chart('Configurable').defaults.axes);

          if (axisId != 'x' && axisId != 'y' && !axisOptions.dataKey)
            throw new Error('d3.chart.csnw.configurable: dataKey(s) are required for axes other than x and y');

          if (!axis) {
            // Create axis
            var Axis = helpers.resolveChart(axisOptions.type, 'Axis', this.type());
            axis = new Axis(this.chartLayer({zIndex: helpers.zIndex.axis}), axisOptions);

            this.attachComponent('axis.' + axisId, axis);
            axes[axisId] = axis;
            changed = true;
          }
          else {
            // Check for changed from options
            if (!_.isEqual(axis.options(), axisOptions))
              changed = true;

            axis.options(axisOptions/*, {silent: true}*/);
          }

          // Create axis title
          if (axisOptions.title) {
            var id = 'axis_title.' + axisId;
            var title = this.componentsById[id];
            var titleOptions = _.isString(axisOptions.title) ? {title: axisOptions.title} : axisOptions.title;
            titleOptions = _.defaults({}, titleOptions, {position: axisOptions.position, 'class': 'chart-title-axis'});

            if (!title) {
              var Title = helpers.resolveChart(titleOptions.type, 'Title', this.type());
              title = new Title(this.componentLayer({zIndex: helpers.zIndex.title}), titleOptions);

              this.attachComponent(id, title);
            }
            else {
              title.options(titleOptions/*, {silent: true}*/);
            }
          }
        }, this);

        // Setup filter keys for x and y axes
        _.each(['x', 'y'], function(axisId) {
          var axis = axes[axisId];

          // Don't need to filter keys if dataKey already set
          if (axis.options().dataKey)
            return;

          var filterKeys = [];
          _.each(axes, function(filterAxis, filterKey) {
            if ((axisId == 'x' && !filterAxis.isXAxis()) || (axisId == 'y' && !filterAxis.isYAxis()))
              return;

            var dataKey = filterAxis.options().dataKey;
            if (dataKey)
              filterKeys = filterKeys.concat(_.isArray(dataKey) ? dataKey : [dataKey]);
          }, this);

          if (!_.isEqual(axis.options().filterKeys, filterKeys))
            changed = true;

          // Set filterKeys "internally" to avoid change firing
          axis.options().filterKeys = filterKeys;
        }, this);

        return {
          override: axes,
          changed: changed,
          after: function() {
            this.bindChartScales();
          }
        };
      },
      defaultValue: {}
    }),

    legend: property('legend', {
      set: function(options, legend) {
        options = options === false ? {display: false} : (options || {});
        options = _.defaults({}, options, d3.chart('Configurable').defaults.legend);
        var changed = false;

        // Load chart information
        if (options.dataKey) {
          // Load only charts matching dataKey(s)
          var dataKeys = _.isArray(options.dataKey) ? options.dataKey : [options.dataKey];
          options.charts = _.filter(this.charts(), function(chart) {
            return _.contains(dataKeys, chart.options().dataKey);
          });
        }
        else {
          options.charts = this.charts();
        }

        // If switching from outside to inset, need to change legend base layer, so remove
        if (legend && legend.options().type != options.type) {
          // TODO Possible alternates for changing base of legend
          this.detachComponent('legend');
          legend = undefined;
        }

        if (!legend) {
          var Legend = helpers.resolveChart(options.type, 'Legend', this.type());
          var base = options.type == 'Inset' || options.type == 'InsetLegend' ? this.chartLayer({zIndex: helpers.zIndex.legend}) : this.componentLayer({zIndex: helpers.zIndex.legend});
          legend = new Legend(base, options);

          this.attachComponent('legend', legend);
          changed = true;
        }
        else {
          if (!_.isEqual(legend.options(), options))
            changed = true;

          legend.options(options);
        }

        return {
          override: legend,
          changed: changed
        };
      }
    }),

    demux: function(name, data) {
      var item = this.chartsById[name] || this.componentsById[name];

      if (item)
        return this.extractData(item, data);
      else
        return data;
    },

    extractData: function(item, data) {
      var dataKey = item.options().dataKey;
      var filterKeys = item.options().filterKeys;

      // Legends need all data (filter by charts)
      if (item && item.isLegend)
        return data;

      // Use dataKey or filterKeys if specified, otherwise use all data
      if (dataKey || filterKeys) {
        var dataKeys = _.isArray(dataKey) ? dataKey : (dataKey ? [dataKey] : []);
        filterKeys = _.isArray(filterKeys) ? filterKeys : (filterKeys ? [filterKeys] : []);

        var filtered = _.reduce(data, function(memo, series, key) {
          var exclude = _.contains(filterKeys, key);
          var include = _.contains(dataKeys, key);
          var includeAll = !dataKeys.length;

          if ((include || includeAll) && !exclude)
            return memo.concat(series);
          else
            return memo;
        }, []);

        return filtered;
      }
      else {
        return data;
      }
    },

    bindChartScales: function() {
      _.each(this.charts(), function(chart) {
        // Get scales for chart
        chart.xScale = this.getScale(chart.options().dataKey, 'x');
        chart.yScale = this.getScale(chart.options().dataKey, 'y');
      }, this);
    },

    getScale: function(dataKey, type) {
      var match = _.find(this.axes(), function(axis) {
        if ((type == 'x' && !axis.isXAxis()) || (type == 'y' && !axis.isYAxis()))
          return false;

        var axisDataKey = axis.options().dataKey;
        return _.isArray(axisDataKey) ? _.contains(axisDataKey, dataKey) : axisDataKey == dataKey;
      });
      var axis = match || this.axes()[type];
      var scaleKey = type == 'x' ? '_xScale' : '_yScale';

      return axis[scaleKey].bind(axis);
    }
  }, {
    defaults: {
      charts: {
        type: 'Line'
      },
      axes: {
        display: true
      },
      legend: {
        display: true,
        position: 'right'
      },
      title: {
        position: 'top',
        'class': 'chart-title-main'
      }
    }
  });

})(d3, _, d3.chart.helpers, d3.chart.extensions);
<|endoftext|>


<commit_before>goog.provide('ol.TileStore');

goog.require('ol.Store');
goog.require('ol.Tile');
goog.require('ol.TileCoord');
goog.require('ol.TileGrid');
goog.require('ol.TileUrlFunctionType');

/**
 * @constructor
 * @extends {ol.Store}
 * @param {ol.Projection} projection Projection.
 * @param {ol.TileGrid} tileGrid Tile grid.
 * @param {ol.TileUrlFunctionType} tileUrlFunction Tile URL.
 * @param {ol.Extent=} opt_extent Extent.
 * @param {?string=} opt_crossOrigin Cross origin.
 */
ol.TileStore = function(
    projection, tileGrid, tileUrlFunction, opt_extent, opt_crossOrigin) {

  goog.base(this, projection, opt_extent);

  /**
   * @private
   * @type {ol.TileGrid}
   */
  this.tileGrid_ = tileGrid;

  /**
   * @private
   * @type {ol.TileUrlFunctionType}
   */
  this.tileUrlFunction_ = tileUrlFunction;

  /**
   * @private
   * @type {?string}
   */
  this.crossOrigin_ =
      goog.isDef(opt_crossOrigin) ? opt_crossOrigin : 'anonymous';

  /**
   * @private
   * @type {Object.<string, ol.Tile>}
   * FIXME will need to expire elements from this cache
   * FIXME see elemoine's work with goog.structs.LinkedMap
   */
  this.tileCache_ = {};

};
goog.inherits(ol.TileStore, ol.Store);

/**
 * @inheritDoc
 */
ol.TileStore.prototype.getResolutions = function() {
  return this.tileGrid_.getResolutions();
};

/**
 * @param {ol.TileCoord} tileCoord Tile coordinate.
 * @return {ol.Tile} Tile.
 */
ol.TileStore.prototype.getTile = function(tileCoord) {
  var key = tileCoord.toString();
  if (goog.object.containsKey(this.tileCache_, key)) {
    return this.tileCache_[key];
  } else {
    var tileUrl = this.getTileCoordUrl(tileCoord);
    var tile;
    if (goog.isDef(tileUrl)) {
      tile = new ol.Tile(tileCoord, tileUrl, this.crossOrigin_);
    } else {
      tile = null;
    }
    this.tileCache_[key] = tile;
    return tile;
  }
};

/**
 * @param {ol.TileCoord} tileCoord Tile coordinate.
 * @return {string|undefined} Tile URL.
 */
ol.TileStore.prototype.getTileCoordUrl = function(tileCoord) {
  return this.tileUrlFunction_(tileCoord);
};

/**
 * @return {ol.TileGrid} Tile grid.
 */
ol.TileStore.prototype.getTileGrid = function() {
  return this.tileGrid_;
};
<commit_msg>Make ol.TileStore.tileGrid and tileUrlFunction protected<commit_after>goog.provide('ol.TileStore');

goog.require('ol.Store');
goog.require('ol.Tile');
goog.require('ol.TileCoord');
goog.require('ol.TileGrid');
goog.require('ol.TileUrlFunctionType');

/**
 * @constructor
 * @extends {ol.Store}
 * @param {ol.Projection} projection Projection.
 * @param {ol.TileGrid} tileGrid Tile grid.
 * @param {ol.TileUrlFunctionType} tileUrlFunction Tile URL.
 * @param {ol.Extent=} opt_extent Extent.
 * @param {?string=} opt_crossOrigin Cross origin.
 */
ol.TileStore = function(
    projection, tileGrid, tileUrlFunction, opt_extent, opt_crossOrigin) {

  goog.base(this, projection, opt_extent);

  /**
   * @protected
   * @type {ol.TileGrid}
   */
  this.tileGrid = tileGrid;

  /**
   * @protected
   * @type {ol.TileUrlFunctionType}
   */
  this.tileUrlFunction = tileUrlFunction;

  /**
   * @private
   * @type {?string}
   */
  this.crossOrigin_ =
      goog.isDef(opt_crossOrigin) ? opt_crossOrigin : 'anonymous';

  /**
   * @private
   * @type {Object.<string, ol.Tile>}
   * FIXME will need to expire elements from this cache
   * FIXME see elemoine's work with goog.structs.LinkedMap
   */
  this.tileCache_ = {};

};
goog.inherits(ol.TileStore, ol.Store);

/**
 * @inheritDoc
 */
ol.TileStore.prototype.getResolutions = function() {
  return this.tileGrid.getResolutions();
};

/**
 * @param {ol.TileCoord} tileCoord Tile coordinate.
 * @return {ol.Tile} Tile.
 */
ol.TileStore.prototype.getTile = function(tileCoord) {
  var key = tileCoord.toString();
  if (goog.object.containsKey(this.tileCache_, key)) {
    return this.tileCache_[key];
  } else {
    var tileUrl = this.getTileCoordUrl(tileCoord);
    var tile;
    if (goog.isDef(tileUrl)) {
      tile = new ol.Tile(tileCoord, tileUrl, this.crossOrigin_);
    } else {
      tile = null;
    }
    this.tileCache_[key] = tile;
    return tile;
  }
};

/**
 * @param {ol.TileCoord} tileCoord Tile coordinate.
 * @return {string|undefined} Tile URL.
 */
ol.TileStore.prototype.getTileCoordUrl = function(tileCoord) {
  return this.tileUrlFunction(tileCoord);
};

/**
 * @return {ol.TileGrid} Tile grid.
 */
ol.TileStore.prototype.getTileGrid = function() {
  return this.tileGrid;
};
<|endoftext|>


<commit_before>/**
 * Bootstrap Table French (France) translation
 * Author: Dennis Hernández
 *         Tidalf (https://github.com/TidalfFR)
 *         Nevets82 <Nevets82@gmail.com>
 */

$.fn.bootstrapTable.locales['fr-FR'] = $.fn.bootstrapTable.locales['fr'] = {
  formatCopyRows () {
    return 'Copier les lignes'
  },
  formatPrint () {
    return 'Imprimer'
  },
  formatLoadingMessage () {
    return 'Chargement en cours'
  },
  formatRecordsPerPage (pageNumber) {
    return `${pageNumber} lignes par page`
  },
  formatShowingRows (pageFrom, pageTo, totalRows, totalNotFiltered) {
    if (totalNotFiltered !== undefined && totalNotFiltered > 0 && totalNotFiltered > totalRows) {
      return `Affiche de ${pageFrom} à ${pageTo} sur ${totalRows} lignes (filtrés à partir de ${totalNotFiltered} lignes)`
    }

    return `Affiche de ${pageFrom} à ${pageTo} sur ${totalRows} lignes`
  },
  formatSRPaginationPreText () {
    return 'page précédente'
  },
  formatSRPaginationPageText (page) {
    return `vers la page ${page}`
  },
  formatSRPaginationNextText () {
    return 'page suivante'
  },
  formatDetailPagination (totalRows) {
    return `Affiche ${totalRows} lignes`
  },
  formatClearSearch () {
    return 'Effacer la recherche'
  },
  formatSearch () {
    return 'Recherche'
  },
  formatNoMatches () {
    return 'Aucun résultat'
  },
  formatPaginationSwitch () {
    return 'Masquer/Afficher la pagination'
  },
  formatPaginationSwitchDown () {
    return 'Afficher la pagination'
  },
  formatPaginationSwitchUp () {
    return 'Masquer la pagination'
  },
  formatRefresh () {
    return 'Actualiser'
  },
  formatToggleOn () {
    return 'Afficher la vue carte'
  },
  formatToggleOff () {
    return 'Masquer la vue carte'
  },
  formatColumns () {
    return 'Colonnes'
  },
  formatColumnsToggleAll () {
    return 'Tout basculer'
  },
  formatFullscreen () {
    return 'Plein écran'
  },
  formatAllRows () {
    return 'Tout'
  },
  formatAutoRefresh () {
    return 'Actualisation automatique'
  },
  formatExport () {
    return 'Exporter les données'
  },
  formatJumpTo () {
    return 'ALLER'
  },
  formatAdvancedSearch () {
    return 'Recherche avancée'
  },
  formatAdvancedCloseButton () {
    return 'Fermer'
  },
  formatFilterControlSwitch () {
    return 'Masquer/Afficher les contrôles'
  },
  formatFilterControlSwitchHide () {
    return 'Masquer les contrôles'
  },
  formatFilterControlSwitchShow () {
    return 'Afficher les contrôles'
  }
}

$.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales['fr-FR'])
<commit_msg>Typo error<commit_after>/**
 * Bootstrap Table French (France) translation
 * Author: Dennis Hernández
 *         Tidalf (https://github.com/TidalfFR)
 *         Nevets82 <Nevets82@gmail.com>
 */

$.fn.bootstrapTable.locales['fr-FR'] = $.fn.bootstrapTable.locales['fr'] = {
  formatCopyRows () {
    return 'Copier les lignes'
  },
  formatPrint () {
    return 'Imprimer'
  },
  formatLoadingMessage () {
    return 'Chargement en cours'
  },
  formatRecordsPerPage (pageNumber) {
    return '${pageNumber} lignes par page'
  },
  formatShowingRows (pageFrom, pageTo, totalRows, totalNotFiltered) {
    if (totalNotFiltered !== undefined && totalNotFiltered > 0 && totalNotFiltered > totalRows) {
      return 'Affichage de ${pageFrom} à ${pageTo} sur ${totalRows} lignes (filtrées à partir de ${totalNotFiltered} lignes)'
    }

    return 'Affichage de ${pageFrom} à ${pageTo} sur ${totalRows} lignes'
  },
  formatSRPaginationPreText () {
    return 'page précédente'
  },
  formatSRPaginationPageText (page) {
    return 'vers la page ${page}'
  },
  formatSRPaginationNextText () {
    return 'page suivante'
  },
  formatDetailPagination (totalRows) {
    return 'Affichage de ${totalRows} lignes'
  },
  formatClearSearch () {
    return 'Effacer la recherche'
  },
  formatSearch () {
    return 'Recherche'
  },
  formatNoMatches () {
    return 'Aucun résultat'
  },
  formatPaginationSwitch () {
    return 'Masquer/Afficher la pagination'
  },
  formatPaginationSwitchDown () {
    return 'Afficher la pagination'
  },
  formatPaginationSwitchUp () {
    return 'Masquer la pagination'
  },
  formatRefresh () {
    return 'Actualiser'
  },
  formatToggleOn () {
    return 'Afficher la vue carte'
  },
  formatToggleOff () {
    return 'Masquer la vue carte'
  },
  formatColumns () {
    return 'Colonnes'
  },
  formatColumnsToggleAll () {
    return 'Tout basculer'
  },
  formatFullscreen () {
    return 'Plein écran'
  },
  formatAllRows () {
    return 'Tout'
  },
  formatAutoRefresh () {
    return 'Actualisation automatique'
  },
  formatExport () {
    return 'Exporter les données'
  },
  formatJumpTo () {
    return 'ALLER'
  },
  formatAdvancedSearch () {
    return 'Recherche avancée'
  },
  formatAdvancedCloseButton () {
    return 'Fermer'
  },
  formatFilterControlSwitch () {
    return 'Masquer/Afficher les contrôles'
  },
  formatFilterControlSwitchHide () {
    return 'Masquer les contrôles'
  },
  formatFilterControlSwitchShow () {
    return 'Afficher les contrôles'
  }
}

$.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales['fr-FR'])
<|endoftext|>


<commit_before>define([
  'dojo/_base/declare',
  'dojo/_base/lang',
  'dojo/Stateful',
  'dojo/Evented',
  'dojo/Deferred',
  'dojo/promise/all',
  'require'
], function(declare, lang, Stateful, Evented, Deferred, all, require) {

  function isClass(item) {
		return typeof item === 'function';
  }

  return declare('dcomponent.core.Factory', [Stateful, Evented], {

    _loadDeferred: null,

    loaded: null,

    // Setters and Getters

    /**
     * The registry setter.
     *
     * @param registry
     */
    _registrySetter: function(registry) {
      if(!registry) {
        registry = lang.mixin({}, registry);
      }
      this._setLoaded(new Deferred());
      this._load(registry);
    },

    /**
     * The private loaded setter.
     *
     * @param loadDeferred
     */
    _setLoaded: function(loadDeferred) {
      if(!this.isLoaded() && this.loaded) {
        this._loadDeferred.cancel('reloading');
      }

      this._loadDeferred = loadDeferred;
      this.loaded = this._loadDeferred.promise;
    },

    /**
     * Load the registy.
     */
    _load: function(registry) {
      var promiseList = [];

      if(registry) {
        this._registry = {};
        for (var id in registry) {
          promiseList.push(this.register(id, registry[id]));
        }

        all(promiseList).then(this._loadDeferred.resolve);
      }
      return this.loaded;
    },

    /**
     * Indicates if the factory is loaded or not.
     *
     * @returns {Boolean}
     */
    isLoaded: function() {
      return this.loaded && this.loaded.isResolved();
    },

    /**
     * Checks if an item is registered under a certain id or not.
     *
     * @param {String} id - A possibly registerd id.
     * @returns {Boolean}
     */
    isRegistered: function(/*string*/ id) {
      return this._registry[id] !== undefined;
    },

    /**
     * Search for a class in the registry by it's id.
     *
     * @param {String} id - A registerd id.
     * @returns {dijit._WidgetBase|undefined}
     */
    byId: function(/*string*/ id) {
      var clazz = this._registry[id];
      var keys = Object.keys(this._registry);
      if(!clazz) {
        var errMsg = 'dcomponent/Registry::byId() - Module id "' + id + '" was not found in registry.!';
        var evt = { error: new Error(errMsg) };
        this.emit('error', evt);
      }
      return clazz;
    },

    /**
     * Registers a class and connect it to the given id.
     *
     * @param id - A id related to the moduleId.
     * @param moduleId - A module id as string or a dijit._WidgetBase module created through a dojo.declare.
     */
    register: function(/*string*/ id, /*string|dijit._WidgetBase*/ moduleId) {
      var deferred = new Deferred();
      if(isClass(moduleId)) {
        var ModuleRef = moduleId;
        this._register(id, ModuleRef);
        deferred.resolve(id);
      } else {
        try {
          var self = this;
          require([moduleId], function(ModuleRef) {
            self._register(id, ModuleRef);
            deferred.resolve(id);
          });
        } catch(e) {
          deferred.reject(e);
          this.emit('error', { error: e });
        }
      }
      return deferred.promise;
    },

    _register: function(id, ModuleRef) {
      if (!this.isRegistered(id)) {
        this._registry[id] = ModuleRef;
        this.emit('register', { id: id });
      }
    },

    /**
     * Deregisters a class by it's connected id.
     *
     * @param {String} id
     */
    deregister: function(id) {
      var deferred = new Deferred();

      this.loaded.then((function() {
        if(this.isRegistered(id)) {
          delete this._registry[id];
          deferred.resolve(id);
          this.emit('deregister', { id: id });
        } else {
          var errMsg = 'dcomponent/Registery::deregister() - Can not deregister unknow module with id: "' + id + '"!';
          var evt = { error: new Error(errMsg) };
          deferred.reject(evt);
          this.emit('error', evt);
        }
      }).bind(this));

      return deferred.promise;
    },

    /**
     * This method creates a widget.
     *
     * @param {String} id - The id of the widget to be generated.
     * @param {Object} props - The params for the widget to be generated.
     * @param {HTMLElement} node - The node where the widget will be placed.
     * @returns {dijit._WidgetBase}
     */

    create: function(id, props, node) {
      var ModuleRef = this.byId(id);
      var args = [ lang.mixin({}, props) ];
      if(node) {
        args.push(node);
      }
      return ModuleRef.apply(null, args)
    }
  });
});<commit_msg>Add Semicolon and remove unuesed.<commit_after>define([
  'dojo/_base/declare',
  'dojo/_base/lang',
  'dojo/Stateful',
  'dojo/Evented',
  'dojo/Deferred',
  'dojo/promise/all',
  'require'
], function(declare, lang, Stateful, Evented, Deferred, all, require) {

  function isClass(item) {
		return typeof item === 'function';
  }

  return declare('dcomponent.core.Factory', [Stateful, Evented], {

    _loadDeferred: null,

    loaded: null,

    // Setters and Getters

    /**
     * The registry setter.
     *
     * @param registry
     */
    _registrySetter: function(registry) {
      if(!registry) {
        registry = lang.mixin({}, registry);
      }
      this._setLoaded(new Deferred());
      this._load(registry);
    },

    /**
     * The private loaded setter.
     *
     * @param loadDeferred
     */
    _setLoaded: function(loadDeferred) {
      if(!this.isLoaded() && this.loaded) {
        this._loadDeferred.cancel('reloading');
      }

      this._loadDeferred = loadDeferred;
      this.loaded = this._loadDeferred.promise;
    },

    /**
     * Load the registy.
     */
    _load: function(registry) {
      var promiseList = [];

      if(registry) {
        this._registry = {};
        for (var id in registry) {
          promiseList.push(this.register(id, registry[id]));
        }

        all(promiseList).then(this._loadDeferred.resolve);
      }
      return this.loaded;
    },

    /**
     * Indicates if the factory is loaded or not.
     *
     * @returns {Boolean}
     */
    isLoaded: function() {
      return this.loaded && this.loaded.isResolved();
    },

    /**
     * Checks if an item is registered under a certain id or not.
     *
     * @param {String} id - A possibly registerd id.
     * @returns {Boolean}
     */
    isRegistered: function(/*string*/ id) {
      return this._registry[id] !== undefined;
    },

    /**
     * Search for a class in the registry by it's id.
     *
     * @param {String} id - A registerd id.
     * @returns {dijit._WidgetBase|undefined}
     */
    byId: function(/*string*/ id) {
      var clazz = this._registry[id];
      if(!clazz) {
        var errMsg = 'dcomponent/Registry::byId() - Module id "' + id + '" was not found in registry.!';
        var evt = { error: new Error(errMsg) };
        this.emit('error', evt);
      }
      return clazz;
    },

    /**
     * Registers a class and connect it to the given id.
     *
     * @param id - A id related to the moduleId.
     * @param moduleId - A module id as string or a dijit._WidgetBase module created through a dojo.declare.
     */
    register: function(/*string*/ id, /*string|dijit._WidgetBase*/ moduleId) {
      var deferred = new Deferred();
      if(isClass(moduleId)) {
        var ModuleRef = moduleId;
        this._register(id, ModuleRef);
        deferred.resolve(id);
      } else {
        try {
          var self = this;
          require([moduleId], function(ModuleRef) {
            self._register(id, ModuleRef);
            deferred.resolve(id);
          });
        } catch(e) {
          deferred.reject(e);
          this.emit('error', { error: e });
        }
      }
      return deferred.promise;
    },

    _register: function(id, ModuleRef) {
      if (!this.isRegistered(id)) {
        this._registry[id] = ModuleRef;
        this.emit('register', { id: id });
      }
    },

    /**
     * Deregisters a class by it's connected id.
     *
     * @param {String} id
     */
    deregister: function(id) {
      var deferred = new Deferred();

      this.loaded.then((function() {
        if(this.isRegistered(id)) {
          delete this._registry[id];
          deferred.resolve(id);
          this.emit('deregister', { id: id });
        } else {
          var errMsg = 'dcomponent/Registery::deregister() - Can not deregister unknow module with id: "' + id + '"!';
          var evt = { error: new Error(errMsg) };
          deferred.reject(evt);
          this.emit('error', evt);
        }
      }).bind(this));

      return deferred.promise;
    },

    /**
     * This method creates a widget.
     *
     * @param {String} id - The id of the widget to be generated.
     * @param {Object} props - The params for the widget to be generated.
     * @param {HTMLElement} node - The node where the widget will be placed.
     * @returns {dijit._WidgetBase}
     */

    create: function(id, props, node) {
      var ModuleRef = this.byId(id);
      var args = [ lang.mixin({}, props) ];
      if(node) {
        args.push(node);
      }
      return ModuleRef.apply(null, args);
    }
  });
});<|endoftext|>


<commit_before>wa.ui.Dialog = (function($){
    var me = {};

    me.showImpl = function() {
        $("#mor_dialog_content").modal({
            overlayId: 'mor_dialog_overlay',
            containerId: 'mor_dialog_container',
            closeHTML: null,
            minHeight: 80,
            opacity: 65,
            position: ['100',],
            overlayClose: true
        });
    	me.adjustHeight();
    };

    me.adjustHeight = function () {
    	setTimeout(function() {
	        var container = $("#mor_dialog_container");
	        var h = $("#mor_dialog_data", container).height()
	            +   $("#mor_dialog_title", container).height()
	            + 20; // padding

	        container.css( { height: h, top: "100px" } );
    	}, 20);
    };

    return {
        show : function(title, body, cb) {
            me.cb = cb;
            $("#mor_dialog_title").html(title);
            $("#mor_dialog_data").html(body);
            me.showImpl();
        },

        showUsingTemplate : function( title, templateUrl, templateContext, cb ) {
            cb = typeof(templateContext) === "function" ? templateContext : cb;
            me.cb = cb;
            $("#mor_dialog_title").html(title);
            $("#mor_dialog_data").setTemplateURL(templateUrl);
            $("#mor_dialog_data").processTemplate(templateContext || {});
            me.showImpl();
        },

        updateTemplateContext : function(templateContext) {
        	$("#mor_dialog_data").processTemplate(templateContext || {});
        	me.adjustHeight();
        },

        close : function() {
            $.modal.close();
        }
    };
})(jQuery);
<commit_msg>Fixed bug in dialog resizing<commit_after>wa.ui.Dialog = (function($){
    var me = {};

    me.showImpl = function() {
        $("#mor_dialog_content").modal({
            overlayId: 'mor_dialog_overlay',
            containerId: 'mor_dialog_container',
            closeHTML: null,
            minHeight: 80,
            opacity: 65,
            position: ['100',],
            overlayClose: true
        });
    	me.adjustHeight();
    };

    me.adjustHeight = function () {
    	setTimeout(function() {
	        var container = $("#mor_dialog_container");
	        var h = $("#mor_dialog_data", container).height()
	            +   $("#mor_dialog_title", container).height()
	            + 30; // padding

	        container.css( { height: h, top: "100px" } );
    	}, 10);
    };

    return {
        show : function(title, body, cb) {
            me.cb = cb;
            $("#mor_dialog_title").html(title);
            $("#mor_dialog_data").html(body);
            me.showImpl();
        },

        showUsingTemplate : function( title, templateUrl, templateContext, cb ) {
            cb = typeof(templateContext) === "function" ? templateContext : cb;
            me.cb = cb;
            $("#mor_dialog_title").html(title);
            $("#mor_dialog_data").setTemplateURL(templateUrl);
            $("#mor_dialog_data").processTemplate(templateContext || {});
            me.showImpl();
        },

        updateTemplateContext : function(templateContext) {
        	$("#mor_dialog_data").processTemplate(templateContext || {});
        	me.adjustHeight();
        },

        close : function() {
            $.modal.close();
        }
    };
})(jQuery);
<|endoftext|>


<commit_before>const AV = require('./av');
const request = require('./request');

/**
 * Call this method first to set up authentication tokens for AV.
 * This method is for AV's own private use.
 * @param {String} applicationId Your AV Application ID.
 * @param {String} applicationKey Your AV Application Key
 */
const initialize = (appId, appKey, masterKey) => {
  if (AV.applicationId && appId !== AV.applicationId && appKey !== AV.applicationKey && masterKey !== AV.masterKey) {
    console.warn('LeanCloud SDK is already initialized, please do not reinitialize it.');
  }
  AV.applicationId = appId;
  AV.applicationKey = appKey;
  AV.masterKey = masterKey;
  AV._useMasterKey = false;
};

const masterKeyWarn = () => {
  console.warn('MasterKey is not supposed to be used in browser.');
};

/**
  * Call this method first to set up your authentication tokens for AV.
  * You can get your app keys from the LeanCloud dashboard on http://leancloud.cn .
  * @function AV.init
  * @param {Object} options
  * @param {String} options.appId application id
  * @param {String} options.appKey application key
  * @param {String} options.masterKey application master key
*/

AV.init = (...args) => {
  switch (args.length) {
    case 1:
      const options = args[0];
      if (typeof options === 'object') {
        if (!AV._config.isNode && options.masterKey) {
          masterKeyWarn();
        }
        initialize(options.appId, options.appKey, options.masterKey);
        request.setServerUrlByRegion(options.region);
        AV._config.disableCurrentUser = options.disableCurrentUser;
      } else {
        throw new Error('AV.init(): Parameter is not correct.');
      }
    break;
    // 兼容旧版本的初始化方法
    case 2:
    case 3:
      console.warn('Please use AV.init() to replace AV.initialize(), ' +
       'AV.init() need an Object param, like { appId: \'YOUR_APP_ID\', appKey: \'YOUR_APP_KEY\' } . ' +
       'Docs: https://leancloud.cn/docs/sdk_setup-js.html');
      if (!AV._config.isNode && args.length === 3) {
        masterKeyWarn();
      }
      initialize(...args);
      request.setServerUrlByRegion('cn');
    break;
  }
};

// If we're running in node.js, allow using the master key.
if (AV._config.isNode) {
  AV.Cloud = AV.Cloud || {};
  /**
   * Switches the LeanCloud SDK to using the Master key.  The Master key grants
   * priveleged access to the data in LeanCloud and can be used to bypass ACLs and
   * other restrictions that are applied to the client SDKs.
   *
Available in Cloud Code and Node.js only.
   *

   */
  AV.Cloud.useMasterKey = function() {
    AV._useMasterKey = true;
  };
}

// 兼容老版本的初始化方法
AV.initialize = AV.init;
<commit_msg>docs: remove AV.initialize (#387)<commit_after>const AV = require('./av');
const request = require('./request');

const initialize = (appId, appKey, masterKey) => {
  if (AV.applicationId && appId !== AV.applicationId && appKey !== AV.applicationKey && masterKey !== AV.masterKey) {
    console.warn('LeanCloud SDK is already initialized, please do not reinitialize it.');
  }
  AV.applicationId = appId;
  AV.applicationKey = appKey;
  AV.masterKey = masterKey;
  AV._useMasterKey = false;
};

const masterKeyWarn = () => {
  console.warn('MasterKey is not supposed to be used in browser.');
};

/**
  * Call this method first to set up your authentication tokens for AV.
  * You can get your app keys from the LeanCloud dashboard on http://leancloud.cn .
  * @function AV.init
  * @param {Object} options
  * @param {String} options.appId application id
  * @param {String} options.appKey application key
  * @param {String} options.masterKey application master key
*/

AV.init = (...args) => {
  switch (args.length) {
    case 1:
      const options = args[0];
      if (typeof options === 'object') {
        if (!AV._config.isNode && options.masterKey) {
          masterKeyWarn();
        }
        initialize(options.appId, options.appKey, options.masterKey);
        request.setServerUrlByRegion(options.region);
        AV._config.disableCurrentUser = options.disableCurrentUser;
      } else {
        throw new Error('AV.init(): Parameter is not correct.');
      }
    break;
    // 兼容旧版本的初始化方法
    case 2:
    case 3:
      console.warn('Please use AV.init() to replace AV.initialize(), ' +
       'AV.init() need an Object param, like { appId: \'YOUR_APP_ID\', appKey: \'YOUR_APP_KEY\' } . ' +
       'Docs: https://leancloud.cn/docs/sdk_setup-js.html');
      if (!AV._config.isNode && args.length === 3) {
        masterKeyWarn();
      }
      initialize(...args);
      request.setServerUrlByRegion('cn');
    break;
  }
};

// If we're running in node.js, allow using the master key.
if (AV._config.isNode) {
  AV.Cloud = AV.Cloud || {};
  /**
   * Switches the LeanCloud SDK to using the Master key.  The Master key grants
   * priveleged access to the data in LeanCloud and can be used to bypass ACLs and
   * other restrictions that are applied to the client SDKs.
   *
Available in Cloud Code and Node.js only.
   *

   */
  AV.Cloud.useMasterKey = function() {
    AV._useMasterKey = true;
  };
}

// 兼容老版本的初始化方法
AV.initialize = AV.init;
<|endoftext|>


<commit_before>var util = require("util");
var fs = require("fs");
var path = require("path");
var fsCopy = require("./util/fsCopy.js")

module.exports = function (appName) {
    fsCopy.mkdir(appName);
    var templatePath = path.resolve(__dirname, "../template/0/webapp")
    fsCopy.copyDir(templatePath, appName);
    // fs.unlinkSync('/tmp/hello');

}<commit_msg>update template path<commit_after>var util = require("util");
var fs = require("fs");
var path = require("path");
var fsCopy = require("./util/fsCopy.js")

module.exports = function (appName) {
    fsCopy.mkdir(appName);
    var templatePath = path.resolve(__dirname, "../template/0");
    fsCopy.copyDir(templatePath, appName);
    // fs.unlinkSync('/tmp/hello');

}<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { defineMessages } from 'react-intl';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import { get, pick } from 'lodash';

import { Router } from '../server/pages';

import ErrorPage from '../components/ErrorPage';
import Header from '../components/Header';
import Body from '../components/Body';
import Footer from '../components/Footer';
import OrderForm from '../components/OrderForm';
import CollectiveCover from '../components/CollectiveCover';

import { addCreateOrderMutation } from '../graphql/mutations';

import storage from '../lib/storage';
import withData from '../lib/withData';
import withIntl from '../lib/withIntl';
import withLoggedInUser from '../lib/withLoggedInUser';
import { isValidUrl, getDomain } from '../lib/utils';

class CreateOrderPage extends React.Component {
  static getInitialProps({
    query: {
      collectiveSlug,
      eventSlug,
      TierId,
      amount,
      quantity,
      totalAmount,
      interval,
      description,
      verb,
      redeem,
      redirect,
    },
  }) {
    return {
      slug: eventSlug || collectiveSlug,
      TierId,
      quantity,
      totalAmount: totalAmount || amount * 100,
      interval,
      description,
      verb,
      redeem,
      redirect,
    };
  }

  static propTypes = {
    slug: PropTypes.string, // for addData
    TierId: PropTypes.string,
    quantity: PropTypes.number,
    totalAmount: PropTypes.number,
    interval: PropTypes.string,
    description: PropTypes.string,
    verb: PropTypes.string,
    redirect: PropTypes.string,
    redeem: PropTypes.bool,
    createOrder: PropTypes.func.isRequired, // from addCreateOrderMutation
    data: PropTypes.object.isRequired, // from withData
    intl: PropTypes.object.isRequired, // from withIntl
    getLoggedInUser: PropTypes.func.isRequired, // from withLoggedInUser
  };

  constructor(props) {
    super(props);
    this.state = { result: {}, loading: false };
    const interval = (props.interval || '').toLowerCase().replace(/ly$/, '');
    this.order = {
      quantity: parseInt(props.quantity, 10) || 1,
      interval: ['month', 'year'].indexOf(interval) !== -1 ? interval : null,
      totalAmount: parseInt(props.totalAmount, 10) || null,
    };

    switch (props.verb) {
      case 'pay':
        this.defaultType = 'PAYMENT';
        break;
      case 'donate':
        this.defaultType = 'DONATION';
        break;
      case 'contribute':
      default:
        this.defaultType = 'CONTRIBUTION';
        break;
    }

    this.messages = defineMessages({
      'ticket.title': { id: 'tier.order.ticket.title', defaultMessage: 'RSVP' },
      'tier.title': {
        id: 'tier.order.backer.title',
        defaultMessage: 'Become a {name}',
      },
      'donation.title': {
        id: 'tier.order.donation.title',
        defaultMessage: 'Contribute',
      },
      'membership.title': {
        id: 'tier.order.membership.title',
        defaultMessage: 'Become a member',
      },
      'service.title': {
        id: 'tier.order.service.title',
        defaultMessage: 'Order',
      },
      'product.title': {
        id: 'tier.order.product.title',
        defaultMessage: 'Order',
      },
      'contribution.title': {
        id: 'tier.name.contribution',
        defaultMessage: 'contribution',
      },
      'payment.title': { id: 'tier.name.payment', defaultMessage: 'payment' },
      'order.success': {
        id: 'tier.order.success',
        defaultMessage: 'Order processed successfully',
      },
      'order.successRedirect': {
        id: 'tier.order.successRedirect',
        defaultMessage: 'Order processed successfully. Redirecting you to {domain}...',
      },
      'order.error': {
        id: 'tier.order.error',
        defaultMessage: "An error occured 😳. The order didn't go through. Please try again in a few.",
      },
      'tier.donation.button': {
        id: 'tier.donation.button',
        defaultMessage: 'donate',
      },
      'tier.donation.description': {
        id: 'tier.donation.description',
        defaultMessage: 'Thank you for your kind donation 🙏',
      },
    });
  }

  async componentDidMount() {
    const { getLoggedInUser, data } = this.props;
    const newState = {};
    newState.LoggedInUser = await getLoggedInUser();
    if (!data.Tier && data.fetchData) {
      data.fetchData();
    }
    this.referral = storage.get('referral');
    const matchingFund = storage.get('matchingFund');
    if (matchingFund) {
      newState.matchingFund = matchingFund;
    }
    this.setState(newState);
  }

  UNSAFE_componentWillReceiveProps(newProps) {
    if (this.state.matchingFund) return;
    const matchingFund = get(newProps, 'data.Collective.settings.matchingFund');
    if (matchingFund) {
      this.setState({ matchingFund });
    }
  }

  createOrder = async order => {
    const { intl, data, redirect } = this.props;

    if (this.referral && this.referral > 0) {
      order.referral = { id: this.referral };
    }
    order.paymentMethod = pick(order.paymentMethod, [
      'uuid',
      'service',
      'type',
      'token',
      'customerId',
      'data',
      'name',
      'currency',
      'save',
    ]);
    if (this.state.LoggedInUser) {
      delete order.user;
    }
    try {
      this.setState({ loading: true });
      const res = await this.props.createOrder(order);
      const orderCreated = res.data.createOrder;
      if (redirect && isValidUrl(redirect)) {
        const domain = getDomain(redirect);
        this.setState({
          loading: false,
          order,
          result: {
            success: intl.formatMessage(this.messages['order.successRedirect'], { domain }),
          },
        });
        const redirectTo = `${redirect}?transactionid=${get(orderCreated, 'transactions[0].id')}&status=${
          orderCreated.status
        }`;
        window.location.href = redirectTo;
      } else {
        await Router.pushRoute('collective', {
          slug: orderCreated.fromCollective.slug,
          status: orderCreated.status,
          CollectiveId: order.collective.id,
          collectiveType: data.Collective.type,
          OrderId: orderCreated.id,
          TierId: get(order, 'tier.id'),
          totalAmount: order.totalAmount,
          paymentMethodType: order.paymentMethod.type,
        });
        this.setState({
          loading: false,
          order,
          result: {
            success: intl.formatMessage(this.messages['order.success']),
          },
        });
        window.scrollTo(0, 0);
      }
    } catch (e) {
      console.error('>>> createOrder error: ', e);
      const error = e
        .toString()
        .replace('GraphQL error: ', '')
        .replace('Error:', '');
      this.setState({
        loading: false,
        result: {
          error: error || intl.formatMessage(this.messages['order.error']),
        },
      });
    }
  };

  render() {
    const { intl, data } = this.props;
    const { loading, LoggedInUser } = this.state;

    if (!data.Collective) return <ErrorPage data={data} />;

    const description = decodeURIComponent(this.props.description || '');
    const collective = data.Collective;

    const TierId = parseInt(this.props.TierId);
    let tier;
    if (TierId) {
      tier = collective.tiers.find(t => t.id === TierId);
    }

    tier = tier || {
      name: intl.formatMessage(this.messages[`${this.defaultType.toLowerCase()}.title`]),
      presets: !this.order.totalAmount && [1000, 5000, 10000], // we only offer to customize the contribution if it hasn't been specified in the URL
      type: this.defaultType,
      currency: collective.currency,
      interval: this.order.interval,
      button: intl.formatMessage(this.messages['tier.donation.button']),
      description: description || intl.formatMessage(this.messages['tier.donation.description']),
    };

    this.order.tier = tier;
    this.order.description = description;

    const coverClassName = collective.type === 'EVENT' ? 'small' : '';

    return (

          <CollectiveCover
            key={collective.slug}
            collective={collective}
            href={collective.path}
            LoggedInUser={LoggedInUser}
            className={coverClassName}
          />

            <OrderForm
              collective={collective}
              order={this.order}
              LoggedInUser={this.state.LoggedInUser}
              onSubmit={this.createOrder}
              redeemFlow={this.props.redeem}
              matchingFund={this.state.matchingFund}
            />

{this.state.result.success}

                {this.state.result.error &&
{this.state.result.error}
}

    );
  }
}

const addData = graphql(gql`
  query Collective($slug: String) {
    Collective(slug: $slug) {
      id
      slug
      path
      name
      type
      tags
      description
      twitterHandle
      image
      isActive
      host {
        id
        name
        slug
        image
        settings
      }
      location {
        name
      }
      startsAt
      endsAt
      timezone
      parentCollective {
        id
        slug
        name
        image
        backgroundImage
      }
      stats {
        id
        yearlyBudget
        balance
        backers {
          all
        }
      }
      members {
        id
        role
        createdAt
        description
        member {
          id
          description
          name
          slug
          type
          image
        }
      }
      backgroundImage
      settings
      currency
      tiers {
        id
        type
        name
        slug
        description
        amount
        currency
        interval
        presets
        maxQuantity
        stats {
          id
          availableQuantity
        }
      }
    }
  }
`);

export default withData(withIntl(withLoggedInUser(addData(addCreateOrderMutation(CreateOrderPage)))));
<commit_msg>refactor(pages/createOrder): use new Page, withUser architecture<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { defineMessages } from 'react-intl';
import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag';
import { get, pick } from 'lodash';

import { Router } from '../server/pages';

import ErrorPage from '../components/ErrorPage';
import Page from '../components/Page';
import OrderForm from '../components/OrderForm';
import CollectiveCover from '../components/CollectiveCover';

import { addCreateOrderMutation } from '../graphql/mutations';

import storage from '../lib/storage';
import withIntl from '../lib/withIntl';
import { withUser } from '../components/UserProvider';
import { isValidUrl, getDomain } from '../lib/utils';

class CreateOrderPage extends React.Component {
  static getInitialProps({
    query: {
      collectiveSlug,
      eventSlug,
      TierId,
      amount,
      quantity,
      totalAmount,
      interval,
      description,
      verb,
      redeem,
      redirect,
    },
  }) {
    return {
      slug: eventSlug || collectiveSlug,
      TierId,
      quantity,
      totalAmount: totalAmount || amount * 100,
      interval,
      description,
      verb,
      redeem,
      redirect,
    };
  }

  static propTypes = {
    slug: PropTypes.string, // for addData
    TierId: PropTypes.string,
    quantity: PropTypes.number,
    totalAmount: PropTypes.number,
    interval: PropTypes.string,
    description: PropTypes.string,
    verb: PropTypes.string,
    redirect: PropTypes.string,
    redeem: PropTypes.bool,
    createOrder: PropTypes.func.isRequired, // from addCreateOrderMutation
    data: PropTypes.object.isRequired, // from withData
    intl: PropTypes.object.isRequired, // from withIntl
  };

  constructor(props) {
    super(props);
    this.state = { result: {}, loading: false };
    const interval = (props.interval || '').toLowerCase().replace(/ly$/, '');
    this.order = {
      quantity: parseInt(props.quantity, 10) || 1,
      interval: ['month', 'year'].indexOf(interval) !== -1 ? interval : null,
      totalAmount: parseInt(props.totalAmount, 10) || null,
    };

    switch (props.verb) {
      case 'pay':
        this.defaultType = 'PAYMENT';
        break;
      case 'donate':
        this.defaultType = 'DONATION';
        break;
      case 'contribute':
      default:
        this.defaultType = 'CONTRIBUTION';
        break;
    }

    this.messages = defineMessages({
      'ticket.title': { id: 'tier.order.ticket.title', defaultMessage: 'RSVP' },
      'tier.title': {
        id: 'tier.order.backer.title',
        defaultMessage: 'Become a {name}',
      },
      'donation.title': {
        id: 'tier.order.donation.title',
        defaultMessage: 'Contribute',
      },
      'membership.title': {
        id: 'tier.order.membership.title',
        defaultMessage: 'Become a member',
      },
      'service.title': {
        id: 'tier.order.service.title',
        defaultMessage: 'Order',
      },
      'product.title': {
        id: 'tier.order.product.title',
        defaultMessage: 'Order',
      },
      'contribution.title': {
        id: 'tier.name.contribution',
        defaultMessage: 'contribution',
      },
      'payment.title': { id: 'tier.name.payment', defaultMessage: 'payment' },
      'order.success': {
        id: 'tier.order.success',
        defaultMessage: 'Order processed successfully',
      },
      'order.successRedirect': {
        id: 'tier.order.successRedirect',
        defaultMessage: 'Order processed successfully. Redirecting you to {domain}...',
      },
      'order.error': {
        id: 'tier.order.error',
        defaultMessage: "An error occured 😳. The order didn't go through. Please try again in a few.",
      },
      'tier.donation.button': {
        id: 'tier.donation.button',
        defaultMessage: 'donate',
      },
      'tier.donation.description': {
        id: 'tier.donation.description',
        defaultMessage: 'Thank you for your kind donation 🙏',
      },
    });
  }

  async componentDidMount() {
    const { data } = this.props;
    const newState = {};
    if (!data.Tier && data.fetchData) {
      data.fetchData();
    }
    this.referral = storage.get('referral');
    const matchingFund = storage.get('matchingFund');
    if (matchingFund) {
      newState.matchingFund = matchingFund;
    }
    this.setState(newState);
  }

  UNSAFE_componentWillReceiveProps(newProps) {
    if (this.state.matchingFund) return;
    const matchingFund = get(newProps, 'data.Collective.settings.matchingFund');
    if (matchingFund) {
      this.setState({ matchingFund });
    }
  }

  createOrder = async order => {
    const { intl, data, redirect } = this.props;

    if (this.referral && this.referral > 0) {
      order.referral = { id: this.referral };
    }
    order.paymentMethod = pick(order.paymentMethod, [
      'uuid',
      'service',
      'type',
      'token',
      'customerId',
      'data',
      'name',
      'currency',
      'save',
    ]);
    if (this.props.LoggedInUser) {
      delete order.user;
    }
    try {
      this.setState({ loading: true });
      const res = await this.props.createOrder(order);
      const orderCreated = res.data.createOrder;
      if (redirect && isValidUrl(redirect)) {
        const domain = getDomain(redirect);
        this.setState({
          loading: false,
          order,
          result: {
            success: intl.formatMessage(this.messages['order.successRedirect'], { domain }),
          },
        });
        const redirectTo = `${redirect}?transactionid=${get(orderCreated, 'transactions[0].id')}&status=${
          orderCreated.status
        }`;
        window.location.href = redirectTo;
      } else {
        await Router.pushRoute('collective', {
          slug: orderCreated.fromCollective.slug,
          status: orderCreated.status,
          CollectiveId: order.collective.id,
          collectiveType: data.Collective.type,
          OrderId: orderCreated.id,
          TierId: get(order, 'tier.id'),
          totalAmount: order.totalAmount,
          paymentMethodType: order.paymentMethod.type,
        });
        this.setState({
          loading: false,
          order,
          result: {
            success: intl.formatMessage(this.messages['order.success']),
          },
        });
        window.scrollTo(0, 0);
      }
    } catch (e) {
      console.error('>>> createOrder error: ', e);
      const error = e
        .toString()
        .replace('GraphQL error: ', '')
        .replace('Error:', '');
      this.setState({
        loading: false,
        result: {
          error: error || intl.formatMessage(this.messages['order.error']),
        },
      });
    }
  };

  render() {
    const { intl, data, LoggedInUser } = this.props;

    if (!data.Collective) return <ErrorPage data={data} />;

    const description = decodeURIComponent(this.props.description || '');
    const collective = data.Collective;

    const TierId = parseInt(this.props.TierId);
    let tier;
    if (TierId) {
      tier = collective.tiers.find(t => t.id === TierId);
    }

    tier = tier || {
      name: intl.formatMessage(this.messages[`${this.defaultType.toLowerCase()}.title`]),
      presets: !this.order.totalAmount && [1000, 5000, 10000], // we only offer to customize the contribution if it hasn't been specified in the URL
      type: this.defaultType,
      currency: collective.currency,
      interval: this.order.interval,
      button: intl.formatMessage(this.messages['tier.donation.button']),
      description: description || intl.formatMessage(this.messages['tier.donation.description']),
    };

    this.order.tier = tier;
    this.order.description = description;

    const coverClassName = collective.type === 'EVENT' ? 'small' : '';

    return (
      <Page
        title={`Contribute - ${collective.name}`}
        description={collective.description}
        twitterHandle={collective.twitterHandle}
        image={collective.image || collective.backgroundImage}
      >

        <CollectiveCover
          key={collective.slug}
          collective={collective}
          href={collective.path}
          className={coverClassName}
        />

          <OrderForm
            collective={collective}
            order={this.order}
            LoggedInUser={LoggedInUser}
            onSubmit={this.createOrder}
            redeemFlow={this.props.redeem}
            matchingFund={this.state.matchingFund}
          />

{this.state.result.success}

              {this.state.result.error &&
{this.state.result.error}
}

      </Page>
    );
  }
}

const addData = graphql(gql`
  query Collective($slug: String) {
    Collective(slug: $slug) {
      id
      slug
      path
      name
      type
      tags
      description
      twitterHandle
      image
      isActive
      host {
        id
        name
        slug
        image
        settings
      }
      location {
        name
      }
      startsAt
      endsAt
      timezone
      parentCollective {
        id
        slug
        name
        image
        backgroundImage
      }
      stats {
        id
        yearlyBudget
        balance
        backers {
          all
        }
      }
      members {
        id
        role
        createdAt
        description
        member {
          id
          description
          name
          slug
          type
          image
        }
      }
      backgroundImage
      settings
      currency
      tiers {
        id
        type
        name
        slug
        description
        amount
        currency
        interval
        presets
        maxQuantity
        stats {
          id
          availableQuantity
        }
      }
    }
  }
`);

const addGraphQL = compose(
  addData,
  addCreateOrderMutation,
);

export default withIntl(addGraphQL(withUser(CreateOrderPage)));
<|endoftext|>


<commit_before>// Entry point of the application

var parser = require('./parser');
var Renderer = require('./renderer');
var Interpreter = require('./interpreter');
var Predictor = require('./predictor');
var Monitor = require('./monitor');
var ToolBox = require('./toolbox');
var Viewport = require('./viewport');
var ContextMenu = require('./contextmenu');
var Playback = require('./playback');

var interpreter;
var renderer;
var predictor;
var monitor;
var toolbox;
var viewport;
var contextmenu;
var playback;
var initialized = false;

function repredict(initial) {
  // Clear all paths and reset
  if (!initial && renderer) {
    for (var y = 0; y < interpreter.map.height; ++y) {
      for (var x = 0; x < interpreter.map.width; ++x) {
        var tile = interpreter.map.get(x, y);
        var cacheTile = renderer.cacheMap.get(x, y);
        if (tile) {
          tile.directions = {};
          tile.segments = {};
          cacheTile.directions = {};
        }
      }
    }
  }
  var predictQuota = interpreter.map.width * interpreter.map.height * 2;
  predictor = new Predictor(interpreter.map);
  for (var i = 0; i < predictQuota; ++i) {
    if (!predictor.next()) break;
  }
  if (!initial && renderer) renderer.redraw();
}

function reset(initial) {
  if (!initial) {
    interpreter.reset();
    renderer.reset();
  }
  document.getElementById('codeForm-output').value = '';
  playback.running = false;
}

function initialize() {
  if(initialized) {
    toolbox.renderer = renderer;
    viewport.renderer = renderer;
    playback.renderer = renderer;
    playback.interpreter = interpreter;
    return;
  }
  playback = new Playback(interpreter, renderer, function() {
    document.getElementById('codeForm-output').value += interpreter.shift();
    document.getElementById('codeForm-debug').value = monitor.getStatus();
  }, reset.bind(this, false));
  toolbox = new ToolBox(renderer);
  contextmenu = new ContextMenu(document.getElementById('context-bg'),
    document.getElementById('context-push'));
  viewport = new Viewport(document.getElementById('viewport'), toolbox,
    renderer, contextmenu);
  viewport.checkCallback = function() {
    return !playback.running;
  };
  viewport.clickCallback = repredict.bind(this, false);
  initialized = true;
}

window.onload = function() {
  document.getElementById('codeForm').onsubmit = function() {
    var code = document.getElementById('codeForm-code').value;
    interpreter = new Interpreter(code);
    monitor = new Monitor(interpreter);
    repredict(true);
    renderer = new Renderer(document.getElementById('canvas'), interpreter);
    initialize();
    window.interpreter = interpreter;
    window.predictor = predictor;
    reset(true);
    // TODO implement input
    return false;
  };
  /*
  document.getElementById('captureBtn').onclick = function() {
    renderer.canvases.dump(document.getElementById('capture'));
  };
  */
};
<commit_msg>Implement code export<commit_after>// Entry point of the application

var parser = require('./parser');
var Renderer = require('./renderer');
var Interpreter = require('./interpreter');
var Predictor = require('./predictor');
var Monitor = require('./monitor');
var ToolBox = require('./toolbox');
var Viewport = require('./viewport');
var ContextMenu = require('./contextmenu');
var Playback = require('./playback');

var interpreter;
var renderer;
var predictor;
var monitor;
var toolbox;
var viewport;
var contextmenu;
var playback;
var initialized = false;

function repredict(initial) {
  // Clear all paths and reset
  if (!initial && renderer) {
    for (var y = 0; y < interpreter.map.height; ++y) {
      for (var x = 0; x < interpreter.map.width; ++x) {
        var tile = interpreter.map.get(x, y);
        var cacheTile = renderer.cacheMap.get(x, y);
        if (tile) {
          tile.directions = {};
          tile.segments = {};
          cacheTile.directions = {};
        }
      }
    }
  }
  var predictQuota = interpreter.map.width * interpreter.map.height * 2;
  predictor = new Predictor(interpreter.map);
  for (var i = 0; i < predictQuota; ++i) {
    if (!predictor.next()) break;
  }
  if (!initial && renderer) renderer.redraw();
}

function reset(initial) {
  if (!initial) {
    interpreter.reset();
    renderer.reset();
  }
  document.getElementById('codeForm-output').value = '';
  playback.running = false;
}

function initialize() {
  if(initialized) {
    toolbox.renderer = renderer;
    viewport.renderer = renderer;
    playback.renderer = renderer;
    playback.interpreter = interpreter;
    return;
  }
  playback = new Playback(interpreter, renderer, function() {
    document.getElementById('codeForm-output').value += interpreter.shift();
    document.getElementById('codeForm-debug').value = monitor.getStatus();
  }, reset.bind(this, false));
  toolbox = new ToolBox(renderer);
  contextmenu = new ContextMenu(document.getElementById('context-bg'),
    document.getElementById('context-push'));
  viewport = new Viewport(document.getElementById('viewport'), toolbox,
    renderer, contextmenu);
  viewport.checkCallback = function() {
    return !playback.running;
  };
  viewport.clickCallback = repredict.bind(this, false);
  initialized = true;
}

window.onload = function() {
  document.getElementById('codeForm').onsubmit = function() {
    var code = document.getElementById('codeForm-code').value;
    interpreter = new Interpreter(code);
    monitor = new Monitor(interpreter);
    repredict(true);
    renderer = new Renderer(document.getElementById('canvas'), interpreter);
    initialize();
    window.interpreter = interpreter;
    window.predictor = predictor;
    reset(true);
    // TODO implement input
    return false;
  };
  document.getElementById('codeForm-export').onclick = function() {
    document.getElementById('codeForm-code').value = parser.encode(
      interpreter.map);
  };
  /*
  document.getElementById('captureBtn').onclick = function() {
    renderer.canvases.dump(document.getElementById('capture'));
  };
  */
};
<|endoftext|>


<commit_before>var auth = 'Basic WjhlYWYyam1ZOEY1TG90WnJaZHQxbVlKdUVWUStuN1hyckUzL3RTT05tODpaOGVhZjJqbVk4RjVMb3RaclpkdDFtWUp1RVZRK243WHJyRTMvdFNPTm04';

window.disableScroll = true;
$('body').bind('touchmove', function(e) {
  if (window.disableScroll) {
    e.preventDefault();
  }
});

angular.module('hottrade', ['gajus.swing', 'ui.router'])

.config(function($stateProvider, $urlRouterProvider) {

})

.controller('MainCtrl', function($scope, $http) {

  $scope.sectors = ["Consumer, Cyclical", "Financial", "Consumer, Non-cyclical", "Energy", "Technology", "Industrial", "Utilities", "Communications", "Basic Materials", "Diversified"];
  $scope.survey = {
    sector: $scope.sectors[0],
    risk: 'safe'
  };

  $scope.matches = [];

  $scope.matchStocks = function() {
    $http.get('/api/industry/' + $scope.survey.sector).success(function(data) {
      var matches = _.first(data, 20);
      async.eachLimit(matches, 5, function(match, done) {
        var str = encodeURIComponent(match.name + ' Logo');
        var link = 'https://api.datamarket.azure.com/Data.ashx/Bing/Search/Image?$format=json&Query=%27' + str + '%27';

        $http.get(link, {
          headers: {
            Authorization: auth
          }
        }).success(function(data) {
          match.img = data.d.results[0].MediaUrl;
          match.kimono = _.find($scope.kimonoInfo, function(el) {
            return el.symbol.text == match.symbol;
          });
          done();
        });

      }, function() {
        console.log('done loading images');
        setTimeout(function() {
          $scope.matches = matches;
          $scope.$apply();
          $('#workLink').click();
        }, 50);
      });
    });
  };

  $scope.kimonoInfo = [];
  $http.jsonp('https://www.kimonolabs.com/api/27zrivbo?apikey=sNaDL4glHt0HIxcbjOTvflpT3ppp85WI&callback=JSON_CALLBACK').success(function(data) {
    $scope.kimonoInfo = data.results.collection1;
    window.kimonoInfo = $scope.kimonoInfo;
  });

  $scope.passed = [];
  $scope.picked = [];

  $scope.swipeLeft = function(index) {
    console.log(index);
    $scope.passed.push($scope.matches.splice(index, 1)[0]);
    $scope.$apply();
  };

  $scope.swipeRight = function(index) {
    console.log(index);
    $scope.picked.push($scope.matches.splice(index, 1)[0]);
    $scope.$apply();
  };

  $scope.nextWindow = function() {
    if ($scope.matches.length > 0) {
      return;
    }
    $('#nextLink').click();
    window.disableScroll = false;
  };

});
<commit_msg>hide broken images<commit_after>var auth = 'Basic WjhlYWYyam1ZOEY1TG90WnJaZHQxbVlKdUVWUStuN1hyckUzL3RTT05tODpaOGVhZjJqbVk4RjVMb3RaclpkdDFtWUp1RVZRK243WHJyRTMvdFNPTm04';

$("img").error(function() {
  $(this).hide();
});

window.disableScroll = true;
$('body').bind('touchmove', function(e) {
  if (window.disableScroll) {
    e.preventDefault();
  }
});

angular.module('hottrade', ['gajus.swing', 'ui.router'])

.config(function($stateProvider, $urlRouterProvider) {

})

.controller('MainCtrl', function($scope, $http) {

  $scope.sectors = ["Consumer, Cyclical", "Financial", "Consumer, Non-cyclical", "Energy", "Technology", "Industrial", "Utilities", "Communications", "Basic Materials", "Diversified"];
  $scope.survey = {
    sector: $scope.sectors[0],
    risk: 'safe'
  };

  $scope.matches = [];

  $scope.matchStocks = function() {
    $http.get('/api/industry/' + $scope.survey.sector).success(function(data) {
      var matches = _.first(data, 20);
      async.eachLimit(matches, 5, function(match, done) {
        var str = encodeURIComponent(match.name + ' Logo');
        var link = 'https://api.datamarket.azure.com/Data.ashx/Bing/Search/Image?$format=json&Query=%27' + str + '%27';

        $http.get(link, {
          headers: {
            Authorization: auth
          }
        }).success(function(data) {
          match.img = data.d.results[0].MediaUrl;
          match.kimono = _.find($scope.kimonoInfo, function(el) {
            return el.symbol.text == match.symbol;
          });
          done();
        });

      }, function() {
        console.log('done loading images');
        setTimeout(function() {
          $scope.matches = matches;
          $scope.$apply();
          $('#workLink').click();
        }, 50);
      });
    });
  };

  $scope.kimonoInfo = [];
  $http.jsonp('https://www.kimonolabs.com/api/27zrivbo?apikey=sNaDL4glHt0HIxcbjOTvflpT3ppp85WI&callback=JSON_CALLBACK').success(function(data) {
    $scope.kimonoInfo = data.results.collection1;
    window.kimonoInfo = $scope.kimonoInfo;
  });

  $scope.passed = [];
  $scope.picked = [];

  $scope.swipeLeft = function(index) {
    console.log(index);
    $scope.passed.push($scope.matches.splice(index, 1)[0]);
    $scope.$apply();
  };

  $scope.swipeRight = function(index) {
    console.log(index);
    $scope.picked.push($scope.matches.splice(index, 1)[0]);
    $scope.$apply();
  };

  $scope.nextWindow = function() {
    if ($scope.matches.length > 0) {
      return;
    }
    $('#nextLink').click();
    window.disableScroll = false;
  };

});
<|endoftext|>


<commit_before>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * All rights reserved.
 */

/**
 * @name SegmentPoint
 * @class An internal version of Point that notifies its segment of each change
 * Note: This prototype is not exported.
 *
 * @private
 */
var SegmentPoint = Point.extend({
	set: function(x, y) {
		this._x = x;
		this._y = y;
		this._owner._changed(this);
		return this;
	},

	getX: function() {
		return this._x;
	},

	setX: function(x) {
		this._x = x;
		this._owner._changed(this);
	},

	getY: function() {
		return this._y;
	},

	setY: function(y) {
		this._y = y;
		this._owner._changed(this);
	},

	setSelected: function(selected) {
		this._owner._setSelected(this, selected);
	},

	isSelected: function() {
		return this._owner._isSelected(this);
	},

	statics: {
		create: function(segment, key, pt) {
			var point = new SegmentPoint(SegmentPoint.dont),
				x, y, selected;
			if (!pt) {
				x = y = 0;
			} else if (pt.x !== undefined) {
				x = pt.x;
				y = pt.y;
				selected = pt.selected;
			} else {
				x = pt[0];
				y = pt[1];
			}
			point._x = x;
			point._y = y;
			point._owner = segment;
			// We need to set the point on the segment before copying over the
			// selected state, as otherwise this won't actually select it.
			segment[key] = point;
			if (selected)
				point.setSelected(true);
			return point;
		}
	}
});
<commit_msg>Fix problem with passing a Size to the Segment constructor.<commit_after>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * All rights reserved.
 */

/**
 * @name SegmentPoint
 * @class An internal version of Point that notifies its segment of each change
 * Note: This prototype is not exported.
 *
 * @private
 */
var SegmentPoint = Point.extend({
	set: function(x, y) {
		this._x = x;
		this._y = y;
		this._owner._changed(this);
		return this;
	},

	getX: function() {
		return this._x;
	},

	setX: function(x) {
		this._x = x;
		this._owner._changed(this);
	},

	getY: function() {
		return this._y;
	},

	setY: function(y) {
		this._y = y;
		this._owner._changed(this);
	},

	setSelected: function(selected) {
		this._owner._setSelected(this, selected);
	},

	isSelected: function() {
		return this._owner._isSelected(this);
	},

	statics: {
		create: function(segment, key, pt) {
			var point = new SegmentPoint(SegmentPoint.dont),
				x, y, selected;
			if (!pt) {
				x = y = 0;
			} else if (pt.x !== undefined) {
				x = pt.x;
				y = pt.y;
				selected = pt.selected;
			} else if (pt.width !== undefined) {
				x = pt.width;
				y = pt.height;
			} else {
				x = pt[0];
				y = pt[1];
			}
			point._x = x;
			point._y = y;
			point._owner = segment;
			// We need to set the point on the segment before copying over the
			// selected state, as otherwise this won't actually select it.
			segment[key] = point;
			if (selected)
				point.setSelected(true);
			return point;
		}
	}
});
<|endoftext|>


<commit_before>import {CallBuilder} from './call_builder';

/**
* @class PathCallBuilder
*/
export class PathCallBuilder extends CallBuilder {
    /*
    * @constructor
    */
    constructor(url, source, destination, destination_type, destination_amount) {
        super(url);
        this.url.segment('paths');
        this.url.addQuery('destination_account', destination);
        this.url.addQuery('source_account', source);
        this.url.addQuery('destination_amount', destination_amount);

        if (!destination_type.isNative()) {
            this.url.addQuery('destination_asset_type', 'credit_alphanum4');
            this.url.addQuery('destination_asset_code', destination_type.getCode());
            this.url.addQuery('destination_asset_issuer', destination_type.getIssuer());
        } else {
            this.url.addQuery('destination_asset_type', 'native');
        }
    }
}
<commit_msg>Rename destination_type to destination_asset<commit_after>import {CallBuilder} from './call_builder';

/**
* @class PathCallBuilder
*/
export class PathCallBuilder extends CallBuilder {
    /*
    * @constructor
    */
    constructor(url, source, destination, destination_asset, destination_amount) {
        super(url);
        this.url.segment('paths');
        this.url.addQuery('destination_account', destination);
        this.url.addQuery('source_account', source);
        this.url.addQuery('destination_amount', destination_amount);

        if (!destination_asset.isNative()) {
            this.url.addQuery('destination_asset_type', 'credit_alphanum4');
            this.url.addQuery('destination_asset_code', destination_asset.getCode());
            this.url.addQuery('destination_asset_issuer', destination_asset.getIssuer());
        } else {
            this.url.addQuery('destination_asset_type', 'native');
        }
    }
}
<|endoftext|>