<commit_before>/*jshint node:true*/
module.exports = {
  useVersionCompatibility: true,
  scenarios: [
    {
      name: 'default',
      bower: {
        dependencies: {}
      }
    },
    {
      name: 'ember-1.13',
      bower: {
        dependencies: {
          'ember': '~1.13.0'
        },
        resolutions: {
          'ember': '~1.13.0'
        }
      },
      {
      name: 'ember-lts-3.8',
      npm: {
        devDependencies: {
          'ember-source': '~3.8.0'
        }
      }
    },
    {
      name: 'ember-release',
      npm: {
        devDependencies: {
          'ember-source': await getChannelURL('release')
        }
      }
    },
    {
      name: 'ember-beta',
      npm: {
        devDependencies: {
          'ember-source': await getChannelURL('beta')
        }
      }
    },
    {
      name: 'ember-canary',
      npm: {
        devDependencies: {
          'ember-source': await getChannelURL('canary')
        }
      }
    },
    // The default `.travis.yml` runs this scenario via `npm test`,
    // not via `ember try`. It's still included here so that running
    // `ember try:each` manually or from a customized CI config will run it
    // along with all the other scenarios.
    {
      name: 'ember-default',
      npm: {
        devDependencies: {}
      }
    },
    {
      name: 'ember-default-with-jquery',
      env: {
        EMBER_OPTIONAL_FEATURES: JSON.stringify({
          'jquery-integration': true
        })
      },
      npm: {
        devDependencies: {
          '@ember/jquery': '^0.5.1'
        }
      }
    }
  ]
};
<commit_msg>update ember-try config<commit_after>'use strict';

const getChannelURL = require('ember-source-channel-url');

module.exports = async function() {
  return {
    useYarn: true,
    scenarios: [
      {
        name: 'ember-lts-2.18',
        env: {
          EMBER_OPTIONAL_FEATURES: JSON.stringify({ 'jquery-integration': true }),
        },
        npm: {
          devDependencies: {
            '@ember/jquery': '^0.5.1',
            'ember-source': '~2.18.0'
          }
        }
      },
      {
        name: 'ember-lts-3.4',
        env: {
          EMBER_OPTIONAL_FEATURES: JSON.stringify({ 'jquery-integration': true }),
        },
        npm: {
          devDependencies: {
            '@ember/jquery': '^0.5.1',
            'ember-source': '~3.4.0'
          }
        }
      },
      {
        name: 'ember-lts-3.8',
        env: {
          EMBER_OPTIONAL_FEATURES: JSON.stringify({ 'jquery-integration': true }),
        },
        npm: {
          devDependencies: {
            'ember-source': '~3.8.0'
          }
        }
      },
      {
        name: 'ember-release',
        npm: {
          devDependencies: {
            'ember-source': await getChannelURL('release')
          }
        }
      },
      {
        name: 'ember-beta',
        npm: {
          devDependencies: {
            'ember-source': await getChannelURL('beta')
          }
        }
      },
      {
        name: 'ember-canary',
        npm: {
          devDependencies: {
            'ember-source': await getChannelURL('canary')
          }
        }
      },
      // The default `.travis.yml` runs this scenario via `npm test`,
      // not via `ember try`. It's still included here so that running
      // `ember try:each` manually or from a customized CI config will run it
      // along with all the other scenarios.
      {
        name: 'ember-default',
        npm: {
          devDependencies: {}
        }
      },
      {
        name: 'ember-default-with-jquery',
        env: {
          EMBER_OPTIONAL_FEATURES: JSON.stringify({
            'jquery-integration': true
          })
        },
        npm: {
          devDependencies: {
            '@ember/jquery': '^0.5.1'
          }
        }
      }
    ]
  };
};
<|endoftext|>


<commit_before>//
// spawnPointZone.js
//
// Created by Rebecca Stankus on 05/21/2019
// Copyright High Fidelity 2019
//
// Licensed under the Apache 2.0 License
// See accompanying license file or http://apache.org/
//

(function () {
    var _this;

    var DEBUG = 1;
    var HALF = 0.5;
    var DEGREES_ON_AXIS = 360;
    var NUMBER_OF_AXES = 3;

    var SpawnPointZone = function() {
        _this = this;
    };

    SpawnPointZone.prototype = {
        /* This utility handles users falling through the floor when first loading into a domain. When the user
        loads this zone script, they will be moved to random position within a cube whose position and dimensions
        are specified in the `userData` of the  attached zone. */
        preload: function(entityID) {
            _this.entityID = entityID;
            try {
                var userData = JSON.parse(Entities.getEntityProperties(_this.entityID, 'userData').userData);
                var spawnAreaProperties = userData.spawnArea;
                if (DEBUG) {
                    print("SPAWN AREA PROPERTIES: ", JSON.stringify(spawnAreaProperties));
                }
            } catch (err) {
                print("ERROR: COULD NOT GET ZONE USER DATA");
                return;
            }
            if (!spawnAreaProperties.position || spawnAreaProperties.position.length < NUMBER_OF_AXES
                || !spawnAreaProperties.dimensions || spawnAreaProperties.dimensions < NUMBER_OF_AXES) {
                return;
            }
            if (spawnAreaProperties.usernameWhitelist && Array.isArray(spawnAreaProperties.usernameWhitelist)) {
                (spawnAreaProperties.usernameWhitelist).forEach(function (newUsername) {
                    if (DEBUG) {
                        print("USER NAME FROM WHITE LIST IS ", newUsername, " AND MY USERNAME IS ", AccountServices.username);
                    }
                    if (newUsername === AccountServices.username) {
                        return;
                    } else {
                        _this.moveUser(spawnAreaProperties);
                    }
                });
            }
            if (spawnAreaProperties.avatarRotation || spawnAreaProperties.avatarRotation.length < NUMBER_OF_AXES) {
                if (DEBUG) {
                    print("NEW AVATAR ROTATION: ", JSON.stringify(spawnAreaProperties.avatarRotation));
                }
                MyAvatar.orientation = Quat.fromVec3Degrees(spawnAreaProperties.avatarRotation);
            } else {
                var randomYDegrees = Math.random() * DEGREES_ON_AXIS;
                var newOrientation = MyAvatar.orientation = Quat.fromVec3Degrees({x: 0, y: randomYDegrees, z: 0 });
                if (DEBUG) {
                    print("RANDOM AVATAR ROTATION: ", JSON.stringify(newOrientation));
                }
            }
        },

        moveUser: function(spawnAreaProperties) {
            var minX = spawnAreaProperties.position.x - spawnAreaProperties.dimensions.x * HALF;
            var maxX = spawnAreaProperties.position.x + spawnAreaProperties.dimensions.x * HALF;
            if (minX > maxX) {
                var tempX = minX;
                maxX = minX;
                minX = tempX;
            }
            if (DEBUG) {
                print("MIN X: ", minX, "MAX X: ", maxX);
            }
            var minY = spawnAreaProperties.position.y - spawnAreaProperties.dimensions.y * HALF;
            var maxY = spawnAreaProperties.position.y + spawnAreaProperties.dimensions.y * HALF;
            if (minY > maxY) {
                var tempY = minY;
                maxY = minY;
                minY = tempY;
            }
            if (DEBUG) {
                print("MIN Y: ", minY, "MAX Y: ", maxY);
            }
            var minZ = spawnAreaProperties.position.z - spawnAreaProperties.dimensions.z * HALF;
            var maxZ = spawnAreaProperties.position.z + spawnAreaProperties.dimensions.z * HALF;
            if (minZ > maxZ) {
                var tempZ = minZ;
                maxZ = minZ;
                minZ = tempZ;
            }
            if (DEBUG) {
                print("MIN Z: ", minZ, "MAX Z: ", maxZ);
            }
            var spawnX = Math.random() * (maxX - minX) + minX;
            var spawnY = Math.random() * (maxY - minY) + minY;
            var spawnZ = Math.random() * (maxZ - minZ) + minZ;
            var newPosition = { x: spawnX, y: spawnY, z: spawnZ };
            if (DEBUG) {
                print("MOVING TO POSITION: ", JSON.stringify(newPosition));
            }
            MyAvatar.position = newPosition;
        }
    };

    return new SpawnPointZone();
});
<commit_msg>CR Feedback<commit_after>//
// spawnPointZone.js
//
// Created by Rebecca Stankus on 05/21/2019
// Copyright High Fidelity 2019
//
// Licensed under the Apache 2.0 License
// See accompanying license file or http://apache.org/
//

(function () {
    var _this;

    var DEBUG = 0;
    var HALF = 0.5;
    var DEGREES_ON_AXIS = 360;
    var NUMBER_OF_AXES = 3;

    var SpawnPointZone = function() {
        _this = this;
    };

    SpawnPointZone.prototype = {
        /* This utility handles users falling through the floor when first loading into a domain. When the user
        loads this zone script, they will be moved to random position within a cube whose position and dimensions
        are specified in the `userData` of the  attached zone. */
        preload: function(entityID) {
            _this.entityID = entityID;
            try {
                var userData = JSON.parse(Entities.getEntityProperties(_this.entityID, 'userData').userData);
                var spawnAreaProperties = userData.spawnArea;
                if (DEBUG) {
                    print("SPAWN AREA PROPERTIES: ", JSON.stringify(spawnAreaProperties));
                }
            } catch (err) {
                print("ERROR: COULD NOT GET ZONE USER DATA");
                return;
            }
            if (!spawnAreaProperties.position || spawnAreaProperties.position.length < NUMBER_OF_AXES
                || !spawnAreaProperties.dimensions || spawnAreaProperties.dimensions < NUMBER_OF_AXES) {
                return;
            }
            if (spawnAreaProperties.usernameWhitelist && Array.isArray(spawnAreaProperties.usernameWhitelist)) {
                (spawnAreaProperties.usernameWhitelist).forEach(function (newUsername) {
                    if (DEBUG) {
                        print("USER NAME FROM WHITE LIST IS ", newUsername, " AND MY USERNAME IS ", AccountServices.username);
                    }
                    if (newUsername.toLowerCase() === AccountServices.username.toLowerCase()) {
                        return;
                    } else {
                        _this.moveUser(spawnAreaProperties);
                    }
                });
            }
            if (spawnAreaProperties.avatarRotation || spawnAreaProperties.avatarRotation.length < NUMBER_OF_AXES) {
                if (DEBUG) {
                    print("NEW AVATAR ROTATION: ", JSON.stringify(spawnAreaProperties.avatarRotation));
                }
                MyAvatar.orientation = Quat.fromVec3Degrees(spawnAreaProperties.avatarRotation);
            } else {
                var randomYDegrees = Math.random() * DEGREES_ON_AXIS;
                var newOrientation = Quat.fromVec3Degrees({x: 0, y: randomYDegrees, z: 0 });
                MyAvatar.orientation = newOrientation;
                if (DEBUG) {
                    print("RANDOM AVATAR ROTATION: ", JSON.stringify(newOrientation));
                }
            }
        },

        moveUser: function(spawnAreaProperties) {
            var minX = spawnAreaProperties.position.x - spawnAreaProperties.dimensions.x * HALF;
            var maxX = spawnAreaProperties.position.x + spawnAreaProperties.dimensions.x * HALF;
            if (minX > maxX) {
                var tempX = minX;
                maxX = minX;
                minX = tempX;
            }
            if (DEBUG) {
                print("MIN X: ", minX, "MAX X: ", maxX);
            }
            var minY = spawnAreaProperties.position.y - spawnAreaProperties.dimensions.y * HALF;
            var maxY = spawnAreaProperties.position.y + spawnAreaProperties.dimensions.y * HALF;
            if (minY > maxY) {
                var tempY = minY;
                maxY = minY;
                minY = tempY;
            }
            if (DEBUG) {
                print("MIN Y: ", minY, "MAX Y: ", maxY);
            }
            var minZ = spawnAreaProperties.position.z - spawnAreaProperties.dimensions.z * HALF;
            var maxZ = spawnAreaProperties.position.z + spawnAreaProperties.dimensions.z * HALF;
            if (minZ > maxZ) {
                var tempZ = minZ;
                maxZ = minZ;
                minZ = tempZ;
            }
            if (DEBUG) {
                print("MIN Z: ", minZ, "MAX Z: ", maxZ);
            }
            var spawnX = Math.random() * (maxX - minX) + minX;
            var spawnY = Math.random() * (maxY - minY) + minY;
            var spawnZ = Math.random() * (maxZ - minZ) + minZ;
            var newPosition = { x: spawnX, y: spawnY, z: spawnZ };
            if (DEBUG) {
                print("MOVING TO POSITION: ", JSON.stringify(newPosition));
            }
            MyAvatar.position = newPosition;
        }
    };

    return new SpawnPointZone();
});
<|endoftext|>


<commit_before>'use strict';

Crafty.c('TiledMap', {
  setTiledMap: function (tiledMap, done) {
    this.name = name;

    this._tiled = tiledMap;

    this._loadTilesets();
    this._createTileEntities();
    this._createObjectEntities();
    done();
  },

  _loadTilesets: function () {
    var self = this;

    self._tiled.tilesets.forEach(function (tileset) {
      Crafty.sprite(
        tileset.tilewidth,
        tileset.tileheight,
        tileset.image,
        self.arrangeTiles(tileset),
        tileset.spacing,
        tileset.spacing
      );
    });
  },

  arrangeTiles: function (tileset){
    var columns = Math.round(
      tileset.imagewidth / (tileset.tilewidth + tileset.margin)
    );
    var rows = Math.round(
      tileset.imageheight / (tileset.tileheight + tileset.margin)
    );
    var tilesMap = {};

    for (var row = 0; row < rows; row++) {
      for (var column = 0; column < columns; column++) {
        var name =
          "Tile" + ((parseInt(tileset.firstgid) + column) + (columns * row));

        tilesMap[name] = [column, row];
      };
    }

    return tilesMap;
  },

  _createTileEntities: function () {
    var self = this;

    self._tiled.layers.filter(function (layer) {
      return layer.type === 'tilelayer';
    }).forEach(function (layer, layerPosition) {
      layer.data.forEach(function (tileGid, i) {
        var column = i % layer.width;
        var row = Math.floor((i / layer.width));

        Crafty.e('2D, Canvas, Tile' + tileGid)
        .attr({
          x: column * self._tiled.tilewidth,
          y: row * self._tiled.tileheight,
          z: layerPosition
        })
      });
    });
  },

  _createObjectEntities: function () {
    var self = this;

    self._tiled.layers.filter(function (layer) {
      return layer.type === 'objectgroup';
    }).forEach(function (layer, layerPosition) {
      layer.objects.forEach(function (object) {
        if (object.type === 'Player') {
          var x = Math.floor(object.x / Game.map_grid.tile.width);
          var y = Math.floor(object.y / Game.map_grid.tile.height);
          new Player(x, y);
        }
        var objectType = (object.type || 'Block');
        Crafty.e('2D, Canvas, Collision, ' + objectType)
        .attr({
          x: object.x,
          y: object.y,
          w: object.width,
          h: object.height,
          z: layerPosition
        });
      });
    });
  },
});
<commit_msg>Exporting current level<commit_after>'use strict';

Crafty.c('TiledMap', {
  setTiledMap: function (tiledMap, done) {
    this.name = name;

    this._tiled = tiledMap;

    this._loadTilesets();
    this._createTileEntities();
    this._createObjectEntities();
    this._setCurrentLevel();
    done();
  },

  _loadTilesets: function () {
    var self = this;

    self._tiled.tilesets.forEach(function (tileset) {
      Crafty.sprite(
        tileset.tilewidth,
        tileset.tileheight,
        tileset.image,
        self.arrangeTiles(tileset),
        tileset.spacing,
        tileset.spacing
      );
    });
  },

  arrangeTiles: function (tileset){
    var columns = Math.round(
      tileset.imagewidth / (tileset.tilewidth + tileset.margin)
    );
    var rows = Math.round(
      tileset.imageheight / (tileset.tileheight + tileset.margin)
    );
    var tilesMap = {};

    for (var row = 0; row < rows; row++) {
      for (var column = 0; column < columns; column++) {
        var name =
          "Tile" + ((parseInt(tileset.firstgid) + column) + (columns * row));

        tilesMap[name] = [column, row];
      };
    }

    return tilesMap;
  },

  _createTileEntities: function () {
    var self = this;

    self._tiled.layers.filter(function (layer) {
      return layer.type === 'tilelayer';
    }).forEach(function (layer, layerPosition) {
      layer.data.forEach(function (tileGid, i) {
        var column = i % layer.width;
        var row = Math.floor((i / layer.width));

        Crafty.e('2D, Canvas, Tile' + tileGid)
        .attr({
          x: column * self._tiled.tilewidth,
          y: row * self._tiled.tileheight,
          z: layerPosition
        })
      });
    });
  },

  _createObjectEntities: function () {
    var self = this;

    self._tiled.layers.filter(function (layer) {
      return layer.type === 'objectgroup';
    }).forEach(function (layer, layerPosition) {
      layer.objects.forEach(function (object) {
        if (object.type === 'Player') {
          var x = Math.floor(object.x / Game.map_grid.tile.width);
          var y = Math.floor(object.y / Game.map_grid.tile.height);
          new Player(x, y);
        }
        var objectType = (object.type || 'Block');
        Crafty.e('2D, Canvas, Collision, ' + objectType)
        .attr({
          x: object.x,
          y: object.y,
          w: object.width,
          h: object.height,
          z: layerPosition
        });
      });
    });
  },

  _setCurrentLevel: function () {
    Config.currentLevel = this._tiled;
  },
});
<|endoftext|>


<commit_before>import { PureComponent, createElement } from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import PropTypes from 'prop-types';
import qs from 'query-string';
import { handleAnalytics } from 'utils/analytics';
import { isCountryIncluded } from 'app/utils';
import { getLocationParamUpdated } from 'utils/navigation';
import { europeSlug, europeanCountries } from 'app/data/european-countries';

import { actions as fetchActions } from 'pages/ndcs';
import { actions as modalActions } from 'components/modal-metadata';

import Component from './ndcs-map-component';

import {
  getCategories,
  getAgricultureIndicators,
  getSelectedCategory,
  getSelectedIndicator,
  getPathsWithStyles,
  getISOCountries,
  getLinkToDataExplorer,
  MAP_COLORS
} from './ndcs-map-selectors';

const actions = { ...fetchActions, ...modalActions };

const mapStateToProps = (state, { location }) => {
  const { data, loading } = state.ndcs;
  const { countries } = state;
  const search = qs.parse(location.search);
  const ndcsWithSelection = {
    ...data,
    countries: countries.data,
    categorySelected: search.category,
    indicatorSelected: search.indicator,
    search
  };
  return {
    loading,
    paths: getPathsWithStyles(ndcsWithSelection),
    categories: getCategories(ndcsWithSelection),
    isoCountries: getISOCountries(ndcsWithSelection),
    indicators: getAgricultureIndicators(ndcsWithSelection),
    mapColors: MAP_COLORS,
    selectedCategory: getSelectedCategory(ndcsWithSelection),
    selectedIndicator: getSelectedIndicator(ndcsWithSelection),
    downloadLink: getLinkToDataExplorer(ndcsWithSelection)
  };
};

class NDCMapContainer extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      geometryIdHover: null,
      country: null
    };
  }

  componentWillMount() {
    this.props.fetchNDCS();
  }

  getTooltipText() {
    const { geometryIdHover } = this.state;
    const { selectedIndicator } = this.props;
    if (!geometryIdHover || !selectedIndicator) return '';

    const isEuropeanCountry = europeanCountries.includes(geometryIdHover);
    const id = isEuropeanCountry ? europeSlug : geometryIdHover;
    return selectedIndicator.locations && selectedIndicator.locations[id]
      ? selectedIndicator.locations[id].value
      : 'Not Applicable';
  }

  handleCountryClick = geography => {
    const { isoCountries } = this.props;
    const iso = geography.properties && geography.properties.id;
    if (iso && isCountryIncluded(isoCountries, iso)) {
      this.props.history.push(`/ndcs/country/${iso}/sectoral-information`);
      handleAnalytics(
        'NDC Content Map',
        'Use map to find country',
        geography.properties.name
      );
    }
  };

  handleCountryEnter = geography => {
    const iso = geography.properties && geography.properties.id;
    if (iso) this.setState({ geometryIdHover: iso });
    this.setState({ country: geography.properties });
  };

  handleCategoryChange = category => {
    this.updateUrlParam(
      {
        name: 'category',
        value: category.value
      },
      true
    );
    handleAnalytics('NDC Content Map', 'Change category', category.label);
  };

  handleIndicatorChange = indicator => {
    this.updateUrlParam({ name: 'indicator', value: indicator.value });
    handleAnalytics('NDC Content Map', 'Change indicator', indicator.label);
  };

  handleSearchChange = query => {
    this.updateUrlParam({ name: 'search', value: query });
  };

  handleInfoClick = () => {
    this.props.setModalMetadata({
      customTitle: 'NDC Content',
      category: 'NDC Content Map',
      slugs: ['ndc_cw', 'ndc_wb', 'ndc_die'],
      open: true
    });
  };

  updateUrlParam(param, clear) {
    const { history, location } = this.props;
    history.replace(getLocationParamUpdated(location, param, clear));
  }

  render() {
    const tooltipTxt = this.getTooltipText();
    return createElement(Component, {
      ...this.props,
      tooltipTxt,
      handleCountryClick: this.handleCountryClick,
      handleCountryEnter: this.handleCountryEnter,
      handleCategoryChange: this.handleCategoryChange,
      handleIndicatorChange: this.handleIndicatorChange,
      handleInfoClick: this.handleInfoClick,
      countryData: this.state.country
    });
  }
}

NDCMapContainer.propTypes = {
  history: PropTypes.object.isRequired,
  location: PropTypes.object.isRequired,
  isoCountries: PropTypes.array.isRequired,
  selectedIndicator: PropTypes.object,
  setModalMetadata: PropTypes.func.isRequired,
  fetchNDCS: PropTypes.func.isRequired
};

export default withRouter(connect(mapStateToProps, actions)(NDCMapContainer));
<commit_msg>Update analytics tracking text<commit_after>import { PureComponent, createElement } from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import PropTypes from 'prop-types';
import qs from 'query-string';
import { handleAnalytics } from 'utils/analytics';
import { isCountryIncluded } from 'app/utils';
import { getLocationParamUpdated } from 'utils/navigation';
import { europeSlug, europeanCountries } from 'app/data/european-countries';

import { actions as fetchActions } from 'pages/ndcs';
import { actions as modalActions } from 'components/modal-metadata';

import Component from './ndcs-map-component';

import {
  getCategories,
  getAgricultureIndicators,
  getSelectedCategory,
  getSelectedIndicator,
  getPathsWithStyles,
  getISOCountries,
  getLinkToDataExplorer,
  MAP_COLORS
} from './ndcs-map-selectors';

const actions = { ...fetchActions, ...modalActions };

const mapStateToProps = (state, { location }) => {
  const { data, loading } = state.ndcs;
  const { countries } = state;
  const search = qs.parse(location.search);
  const ndcsWithSelection = {
    ...data,
    countries: countries.data,
    categorySelected: search.category,
    indicatorSelected: search.indicator,
    search
  };
  return {
    loading,
    paths: getPathsWithStyles(ndcsWithSelection),
    categories: getCategories(ndcsWithSelection),
    isoCountries: getISOCountries(ndcsWithSelection),
    indicators: getAgricultureIndicators(ndcsWithSelection),
    mapColors: MAP_COLORS,
    selectedCategory: getSelectedCategory(ndcsWithSelection),
    selectedIndicator: getSelectedIndicator(ndcsWithSelection),
    downloadLink: getLinkToDataExplorer(ndcsWithSelection)
  };
};

class NDCMapContainer extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      geometryIdHover: null,
      country: null
    };
  }

  componentWillMount() {
    this.props.fetchNDCS();
  }

  getTooltipText() {
    const { geometryIdHover } = this.state;
    const { selectedIndicator } = this.props;
    if (!geometryIdHover || !selectedIndicator) return '';

    const isEuropeanCountry = europeanCountries.includes(geometryIdHover);
    const id = isEuropeanCountry ? europeSlug : geometryIdHover;
    return selectedIndicator.locations && selectedIndicator.locations[id]
      ? selectedIndicator.locations[id].value
      : 'Not Applicable';
  }

  handleCountryClick = geography => {
    const { isoCountries } = this.props;
    const iso = geography.properties && geography.properties.id;
    if (iso && isCountryIncluded(isoCountries, iso)) {
      this.props.history.push(`/ndcs/country/${iso}/sectoral-information`);
      handleAnalytics(
        'Agriculture Profile - Countries Actions',
        'Use map to find country',
        geography.properties.name
      );
    }
  };

  handleCountryEnter = geography => {
    const iso = geography.properties && geography.properties.id;
    if (iso) this.setState({ geometryIdHover: iso });
    this.setState({ country: geography.properties });
  };

  handleCategoryChange = category => {
    this.updateUrlParam(
      {
        name: 'category',
        value: category.value
      },
      true
    );
    handleAnalytics('NDC Content Map', 'Change category', category.label);
  };

  handleIndicatorChange = indicator => {
    this.updateUrlParam({ name: 'indicator', value: indicator.value });
    handleAnalytics('NDC Content Map', 'Change indicator', indicator.label);
  };

  handleSearchChange = query => {
    this.updateUrlParam({ name: 'search', value: query });
  };

  handleInfoClick = () => {
    this.props.setModalMetadata({
      customTitle: 'NDC Content',
      category: 'NDC Content Map',
      slugs: ['ndc_cw', 'ndc_wb', 'ndc_die'],
      open: true
    });
  };

  updateUrlParam(param, clear) {
    const { history, location } = this.props;
    history.replace(getLocationParamUpdated(location, param, clear));
  }

  render() {
    const tooltipTxt = this.getTooltipText();
    return createElement(Component, {
      ...this.props,
      tooltipTxt,
      handleCountryClick: this.handleCountryClick,
      handleCountryEnter: this.handleCountryEnter,
      handleCategoryChange: this.handleCategoryChange,
      handleIndicatorChange: this.handleIndicatorChange,
      handleInfoClick: this.handleInfoClick,
      countryData: this.state.country
    });
  }
}

NDCMapContainer.propTypes = {
  history: PropTypes.object.isRequired,
  location: PropTypes.object.isRequired,
  isoCountries: PropTypes.array.isRequired,
  selectedIndicator: PropTypes.object,
  setModalMetadata: PropTypes.func.isRequired,
  fetchNDCS: PropTypes.func.isRequired
};

export default withRouter(connect(mapStateToProps, actions)(NDCMapContainer));
<|endoftext|>


<commit_before>/*
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */
import createSolidFromString from '../../../../utils/createSolidFromString';
import useInsertElement from '../../useInsertElement';
import { useStory } from '../../../../app/story';
import { Fixture } from '../../../../karma';

describe('Page Attachment', () => {
  let fixture;
  let frame;
  let safezone;

  const clickOnTarget = async (target) => {
    const { x, y, width, height } = target.getBoundingClientRect();
    await fixture.events.mouse.click(x + width / 2, y + height / 2);
  };

  beforeEach(async () => {
    fixture = new Fixture();
    await fixture.render();
    // Select Page by default.
    safezone = fixture.querySelector('[data-testid="safezone"]');
    await clickOnTarget(safezone);
  });

  afterEach(() => {
    fixture.restore();
  });

  const moveElementToBottom = async () => {
    const safezoneHeight = safezone.getBoundingClientRect().height;
    const frameHeight = frame.getBoundingClientRect().height;
    await fixture.events.mouse.seq(({ moveRel, moveBy, down, up }) => [
      moveRel(frame, 10, 10),
      down(),
      moveBy(0, safezoneHeight - frameHeight, { steps: 10 }),
      up(),
    ]);
  };

  const addElement = async (withLink = true) => {
    const insertElement = await fixture.renderHook(() => useInsertElement());
    const element = await fixture.act(() =>
      insertElement('shape', {
        backgroundColor: createSolidFromString('#ff00ff'),
        mask: { type: 'rectangle' },
        x: 10,
        y: 10,
        width: 50,
        height: 50,
        link: withLink
          ? {
              url: 'https://example.com',
            }
          : null,
      })
    );
    frame = fixture.editor.canvas.framesLayer.frame(element.id).node;
  };

  const setPageAttachmentLink = async (link) => {
    const input = fixture.screen.getByLabelText('Edit: Page Attachment link');
    await fixture.events.click(input, { clickCount: 3 });
    if ('' === link) {
      await fixture.events.keyboard.press('Del');
    } else {
      await fixture.events.keyboard.type(link);
    }
    await input.dispatchEvent(new window.Event('blur'));
  };

  const setCtaText = async (text) => {
    const input = fixture.screen.getByLabelText(
      'Edit: Page Attachment CTA text'
    );
    await fixture.events.click(input, { clickCount: 3 });
    await fixture.events.keyboard.type(text);
    // Wait until the debounced update has taken effect.
    await wait(300);
  };

  describe('CUJ: Creator can Add a Page Attachment: Add Page Attachment', () => {
    it('it should allow adding Page Attachment with custom CTA Text', async () => {
      await setPageAttachmentLink('http://example.com');
      await setCtaText('Click me!');
      const ctaText = fixture.screen.getByText('Click me!');
      expect(ctaText).toBeDefined();
    });

    it('it should display warning for a link in the Page Attachment Area', async () => {
      await addElement();
      await moveElementToBottom();

      await clickOnTarget(safezone);
      await setPageAttachmentLink('');
      const warning = fixture.screen.getByText(
        'Links cannot reside below the dashed line when a page attachment is present. If you add a page attachment, your viewers will not be able to click on the link.'
      );
      expect(warning).toBeDefined();
    });
  });

  describe('CUJ: Creator can Add a Page Attachment: Remove Page Attachment', () => {
    it('it should allow removing a Page Attachment', async () => {
      await setPageAttachmentLink('http://example.com');
      await setCtaText('Click me!');
      const ctaText = fixture.screen.getByText('Click me!');
      expect(ctaText).toBeDefined();

      await setPageAttachmentLink('');
      expect(fixture.screen.queryByText('Click me!')).toBeNull();
    });
  });

  describe('CUJ: Creator can Add a Page Attachment: Adding link to element in Attachment area', () => {
    it('it should not allow adding link to Attachment area', async () => {
      await setPageAttachmentLink('http://example.com');
      await addElement(false);
      await moveElementToBottom();

      const input = fixture.screen.getByLabelText('Edit: Element link');
      await fixture.events.click(input);

      // Verify that the warning is displayed.
      const warning = fixture.screen.getByText(
        'Link can not reside below the dashed line when a page attachment is present'
      );
      expect(warning).toBeDefined();

      await fixture.events.keyboard.type('example.com');
      await input.dispatchEvent(new window.Event('blur'));

      // Verify the link is still null after typing.
      const {
        state: {
          currentPage: {
            elements: [{ link }],
          },
        },
      } = await fixture.renderHook(() => useStory());
      expect(link).toBeUndefined();
    });
  });
});

function wait(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}
<commit_msg>Remove redundant wait function.<commit_after>/*
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */
import createSolidFromString from '../../../../utils/createSolidFromString';
import useInsertElement from '../../useInsertElement';
import { useStory } from '../../../../app/story';
import { Fixture } from '../../../../karma';

describe('Page Attachment', () => {
  let fixture;
  let frame;
  let safezone;

  const clickOnTarget = async (target) => {
    const { x, y, width, height } = target.getBoundingClientRect();
    await fixture.events.mouse.click(x + width / 2, y + height / 2);
  };

  beforeEach(async () => {
    fixture = new Fixture();
    await fixture.render();
    // Select Page by default.
    safezone = fixture.querySelector('[data-testid="safezone"]');
    await clickOnTarget(safezone);
  });

  afterEach(() => {
    fixture.restore();
  });

  const moveElementToBottom = async () => {
    const safezoneHeight = safezone.getBoundingClientRect().height;
    const frameHeight = frame.getBoundingClientRect().height;
    await fixture.events.mouse.seq(({ moveRel, moveBy, down, up }) => [
      moveRel(frame, 10, 10),
      down(),
      moveBy(0, safezoneHeight - frameHeight, { steps: 10 }),
      up(),
    ]);
  };

  const addElement = async (withLink = true) => {
    const insertElement = await fixture.renderHook(() => useInsertElement());
    const element = await fixture.act(() =>
      insertElement('shape', {
        backgroundColor: createSolidFromString('#ff00ff'),
        mask: { type: 'rectangle' },
        x: 10,
        y: 10,
        width: 50,
        height: 50,
        link: withLink
          ? {
              url: 'https://example.com',
            }
          : null,
      })
    );
    frame = fixture.editor.canvas.framesLayer.frame(element.id).node;
  };

  const setPageAttachmentLink = async (link) => {
    const input = fixture.screen.getByLabelText('Edit: Page Attachment link');
    await fixture.events.click(input, { clickCount: 3 });
    if ('' === link) {
      await fixture.events.keyboard.press('Del');
    } else {
      await fixture.events.keyboard.type(link);
    }
    await input.dispatchEvent(new window.Event('blur'));
  };

  const setCtaText = async (text) => {
    const input = fixture.screen.getByLabelText(
      'Edit: Page Attachment CTA text'
    );
    await fixture.events.click(input, { clickCount: 3 });
    await fixture.events.keyboard.type(text);
    // Wait until the debounced update has taken effect.
    await fixture.events.sleep(300);
  };

  describe('CUJ: Creator can Add a Page Attachment: Add Page Attachment', () => {
    it('it should allow adding Page Attachment with custom CTA Text', async () => {
      await setPageAttachmentLink('http://example.com');
      await setCtaText('Click me!');
      const ctaText = fixture.screen.getByText('Click me!');
      expect(ctaText).toBeDefined();
    });

    it('it should display warning for a link in the Page Attachment Area', async () => {
      await addElement();
      await moveElementToBottom();

      await clickOnTarget(safezone);
      await setPageAttachmentLink('');
      const warning = fixture.screen.getByText(
        'Links cannot reside below the dashed line when a page attachment is present. If you add a page attachment, your viewers will not be able to click on the link.'
      );
      expect(warning).toBeDefined();
    });
  });

  describe('CUJ: Creator can Add a Page Attachment: Remove Page Attachment', () => {
    it('it should allow removing a Page Attachment', async () => {
      await setPageAttachmentLink('http://example.com');
      await setCtaText('Click me!');
      const ctaText = fixture.screen.getByText('Click me!');
      expect(ctaText).toBeDefined();

      await setPageAttachmentLink('');
      expect(fixture.screen.queryByText('Click me!')).toBeNull();
    });
  });

  describe('CUJ: Creator can Add a Page Attachment: Adding link to element in Attachment area', () => {
    it('it should not allow adding link to Attachment area', async () => {
      await setPageAttachmentLink('http://example.com');
      await addElement(false);
      await moveElementToBottom();

      const input = fixture.screen.getByLabelText('Edit: Element link');
      await fixture.events.click(input);

      // Verify that the warning is displayed.
      const warning = fixture.screen.getByText(
        'Link can not reside below the dashed line when a page attachment is present'
      );
      expect(warning).toBeDefined();

      await fixture.events.keyboard.type('example.com');
      await input.dispatchEvent(new window.Event('blur'));

      // Verify the link is still null after typing.
      const {
        state: {
          currentPage: {
            elements: [{ link }],
          },
        },
      } = await fixture.renderHook(() => useStory());
      expect(link).toBeUndefined();
    });
  });
});
<|endoftext|>


<commit_before>var Backbone = require('backbone');
var _ = require('underscore');
var RemoveDatasetView = require('builder/components/modals/remove-dataset/remove-dataset-view');
var UserModel = require('builder/data/user-model');
var VisDefinitionModel = require('builder/data/vis-definition-model');
var TableModel = require('builder/data/table-model');
var ConfigModel = require('builder/data/config-model');

describe('modals/remove-dataset-view', function () {
  var modalModel = new Backbone.Model();
  var avatarBase64 = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAACXBIWXMAAAsTAAALEwEAmpwYAAAADElEQVQI12P4//8/AAX+Av7czFnnAAAAAElFTkSuQmCC';
  var configData = {
    base_url: '/u/manolo',
    maps_api_template: 'http://{user}.localhost.lan:8181'
  };
  var userData = {
    id: '8c253a9a-94d8-4042-883c-3aa81285e5e6',
    username: 'cdb',
    organization: {
      display_name: 'Globex Corporation',
      name: 'globex',
      avatar_url: 'https://s3.amazonaws.com/com.cartodb.users-assets.staging/development/cdb/assets/20161028125910fake-company-logo.jpg',
      user_count: 25
    }
  };
  var tableDataWithNoDependentMaps = {
    name: 'NYC Graffiti sights',
    accessible_dependent_derived_maps: [],
    accessible_dependent_derived_maps_count: 0
  };
  var dependentMap = {
    id: '5725afbe-9f51-11e6-af45-080027eb929e',
    name: 'Untitled Map',
    permission: {
      owner: {
        username: 'cdb'
      }
    },
    updated_at: '2016-10-31T10:03:58+00:00'
  };
  var visDataWithNoACL = {
    permission: {
      acl: []
    }
  };
  var visDataWithOrganizationACL = {
    permission: {
      acl: [{
        type: 'org',
        entity: {
          id: 'c210c579-0780-4ccd-83a8-7bf9fee11b34',
          name: 'globex',
          avatar_url: avatarBase64
        }
      }]
    }
  };
  var visDataWithGroupACL = {
    permission: {
      acl: [{
        type: 'group',
        entity: {
          users: [{
            username: 'Meowth',
            avatar_url: avatarBase64
          }]
        }
      }]
    }
  };
  var visModel;
  var configModel;
  var tableModel;
  var userModel;
  var view;

  function createDependantACL (username) {
    return {
      type: 'user',
      entity: {
        username: username || 'pepe' + _.random(99999).toString(),
        avatar_url: avatarBase64
      }
    };
  }

  function createView (options) {
    var opts = options || {};
    var numberOfDependentMaps = opts.numberOfDependentMaps || 0;
    var organizationAffected = opts.organizationAffected || false;
    var numberOfDependentEntities = opts.numberOfDependentEntities || 0;
    var repeatAffectedEntity = opts.repeatAffectedEntity || false;
    var affectedGroup = opts.affectedGroup || false;
    var tableData;
    var visData;

    configModel = new ConfigModel(configData);
    userModel = new UserModel(userData, { configModel: configModel });

    if (numberOfDependentMaps > 0) {
      tableData = _.clone(tableDataWithNoDependentMaps);
      tableData.accessible_dependent_derived_maps_count = numberOfDependentMaps;
      _.times(numberOfDependentMaps, function () {
        tableData.accessible_dependent_derived_maps.push(dependentMap);
      });
    } else {
      tableModel = new TableModel(tableDataWithNoDependentMaps, { parse: true, configModel: configModel });
    }

    if (organizationAffected) {
      visModel = new VisDefinitionModel(visDataWithOrganizationACL, {
        configModel: configModel
      });
    } else if (affectedGroup) {
      visModel = new VisDefinitionModel(visDataWithGroupACL, {
        configModel: configModel
      });
    } else if (numberOfDependentEntities > 0) {
      visData = {
        permission: {
          acl: []
        }
      };
      _.times(numberOfDependentEntities, function () {
        visData.permission.acl.push(createDependantACL());
      });
      visData.permission.acl.push(createDependantACL(userData.username)); // To test if we filter ourselves
      if (repeatAffectedEntity) {
        visData.permission.acl.push(_.clone(visData.permission.acl[0])); // Repeat one user to test if we filter only uniques
      }
      visModel = new VisDefinitionModel(visData, {
        configModel: configModel
      });
    } else {
      visModel = new VisDefinitionModel(visDataWithNoACL, {
        configModel: configModel
      });
    }

    return new RemoveDatasetView({
      modalModel: modalModel,
      userModel: userModel,
      visModel: visModel,
      tableModel: tableModel,
      configModel: configModel
    });
  }

  describe('render', function () {
    it('Nothing affected, visualization and entities sections not shown', function () {
      // Arrange
      view = createView();

      // Act
      view.render();

      // Assert
      expect(view.$('h2')[0].textContent.trim()).toEqual('dataset.delete.title');
      expect(view.$('.MapsList-item').length).toBe(0);
      expect(view.$('.ShareUser').length).toBe(0);
      expect(view.$('button.js-cancel > span')[0].textContent.trim()).toEqual('dataset.delete.cancel');
      expect(view.$('button.js-confirm > span')[0].textContent.trim()).toEqual('dataset.delete.confirm');
    });

    it('1 visualization affected. Visualization gets properly rendered.', function () {
      // Arrange
      view = createView({ numberOfDependentMaps: 1 });

      // Act
      view.render();

      // Assert
      expect(view.$('.js-affectedVis > p')[0].textContent.trim()).toEqual('dataset.delete.affected-vis-count');
      expect(view.$('.js-affectedVis > ul > li').length).toBe(1);
      expect(view.$('.MapCard')[0].dataset['visId']).toEqual(dependentMap.id);
      expect(view.$('.MapCard')[0].dataset['visOwnerName']).toEqual(dependentMap.permission.owner.username);
      expect(view.$('.MapCard > a')[0].href).toBeTruthy();
      expect(view.$('.MapCard > a > img')[0].src).toBeTruthy();
      expect(view.$('.MapCard-content h3 > a')[0].href).toBeTruthy();
      expect(view.$('.MapCard-content h3 > a')[0].title).toEqual(dependentMap.name);
      expect(view.$('.MapCard-contentBodyTimeDiff')[0].textContent.trim()).toBeTruthy();
    });

    it('More vis affected than AFFECTED_VIS_COUNT. Text changed to extended one.', function () {
      // Arrange
      var maxAffectedVisCount = 3; // AFFECTED_VIS_COUNT
      view = createView({ numberOfDependentMaps: 4 });

      // Act
      view.render();

      // Assert
      expect(view.$('.js-affectedVis > p')[0].textContent.trim()).toEqual('dataset.delete.affected-vis-count-extended');
      expect(view.$('.js-affectedVis > ul > li').length).toBe(maxAffectedVisCount);
    });

    it('Organization affected. Proper text and avatar rendered.', function () {
      // Arrange
      var userNode;
      view = createView({ organizationAffected: true });

      // Act
      view.render();

      // Assert
      expect(view.$('.js-affectedEntities > p')[0].textContent.trim()).toEqual('dataset.delete.whole-organization-affected');
      expect(view.$('.js-affectedEntities li').length).toBe(1);
      userNode = view.$('.js-affectedEntities li .Share-user')[0];
      expect(userNode.title).toEqual(userData.organization.display_name);
      expect(userNode.dataset['username']).toEqual(userData.organization.display_name);
      expect(userNode.style.backgroundImage.indexOf(userData.organization.avatar_url) > -1).toBe(true);
    });

    it('1 user affected. Proper text and avatar rendered.', function () {
      // Arrange
      var userNode;
      var affectedEntity;
      view = createView({ numberOfDependentEntities: 1 });
      affectedEntity = view._visModel._permissionModel.get('acl')[0].entity;

      // Act
      view.render();

      // Assert
      expect(view.$('.js-affectedEntities > p')[0].textContent.trim()).toEqual('dataset.delete.affected-entities-count');
      expect(view.$('.js-affectedEntities li').length).toBe(1);
      userNode = view.$('.js-affectedEntities li .Share-user')[0];
      expect(userNode.title).toEqual(affectedEntity.username);
      expect(userNode.dataset['username']).toEqual(affectedEntity.username);
      expect(userNode.style.backgroundImage.indexOf(affectedEntity.avatar_url) > -1).toBe(true);
    });

    it('More user affected than AFFECTED_ENTITIES_SAMPLE_COUNT. Text changed to extended.', function () {
      // Arrange
      var affectedEntitiesSampleCount = 20; // AFFECTED_ENTITIES_SAMPLE_COUNT
      view = createView({ numberOfDependentEntities: affectedEntitiesSampleCount + 1 });

      // Act
      view.render();

      // Assert
      expect(view.$('.js-affectedEntities > p')[0].textContent.trim()).toEqual('dataset.delete.affected-entities-count-extended');
      expect(view.$('.js-affectedEntities li').length).toBe(affectedEntitiesSampleCount);
    });

    it('Affected entity repeated. Repeated entity gets filtered.', function () {
      // Arrange
      view = createView({
        numberOfDependentEntities: 2,
        repeatAffectedEntity: true
      });

      // Act
      view.render();

      // Assert
      expect(view.$('.js-affectedEntities li').length).toBe(2);
    });

    it('Affected group. Users of that group get rendered.', function () {
      // Arrange
      view = createView({
        affectedGroup: true
      });

      // Act
      view.render();

      // Assert
      expect(view.$('.js-affectedEntities li').length).toBe(visDataWithGroupACL.permission.acl[0].entity.users.length);
    });
  });

  describe('_runAction', function () {
    it('Renders loading view and destory has been set to the right success function.', function () {
      // Arrange
      var successFunction;
      view = createView();
      spyOn(view, '_renderLoadingView');
      spyOn(view, '_onSuccessDestroyDataset');
      spyOn(visModel, 'destroy').and.callFake(function (args) {
        successFunction = args.success;
      });

      // Act
      view._runAction();
      successFunction();

      // Assert
      expect(view._renderLoadingView).toHaveBeenCalled();
      expect(view._onSuccessDestroyDataset).toHaveBeenCalled();
    });

    it('Destroy has been set to the right error function.', function () {
      // Arrange
      var errorFunction;
      view = createView();
      spyOn(view, '_onErrorDestroyDataset');
      spyOn(visModel, 'destroy').and.callFake(function (args) {
        errorFunction = args.error;
      });

      // Act
      view._runAction();
      errorFunction(null, {});

      // Assert
      expect(view._onErrorDestroyDataset).toHaveBeenCalled();
    });
  });

  it('_renderLoadingView inserts the right HTML', function () {
    // Arrange
    view = createView();

    // Act
    view._renderLoadingView();

    // Assert
    expect(view.$('.js-loader').length).toBeGreaterThan(0);
  });

  it('_onErrorDestroyDataset inserts the right HTML', function () {
    // Arrange
    view = createView();

    // Act
    view._onErrorDestroyDataset(null, {});

    // Assert
    expect(view.$('i.CDB-IconFont-cockroach').length).toBeGreaterThan(0);
  });
});
<commit_msg>fix spec<commit_after>var Backbone = require('backbone');
var _ = require('underscore');
var RemoveDatasetView = require('builder/components/modals/remove-dataset/remove-dataset-view');
var UserModel = require('builder/data/user-model');
var VisDefinitionModel = require('builder/data/vis-definition-model');
var TableModel = require('builder/data/table-model');
var ConfigModel = require('builder/data/config-model');

describe('modals/remove-dataset-view', function () {
  var modalModel = new Backbone.Model();
  var avatarBase64 = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAACXBIWXMAAAsTAAALEwEAmpwYAAAADElEQVQI12P4//8/AAX+Av7czFnnAAAAAElFTkSuQmCC';
  var configData = {
    base_url: '/u/manolo',
    maps_api_template: 'http://{user}.localhost.lan:8181'
  };
  var userData = {
    id: '8c253a9a-94d8-4042-883c-3aa81285e5e6',
    username: 'cdb',
    organization: {
      display_name: 'Globex Corporation',
      name: 'globex',
      avatar_url: 'https://s3.amazonaws.com/com.cartodb.users-assets.staging/development/cdb/assets/20161028125910fake-company-logo.jpg',
      user_count: 25
    }
  };
  var tableDataWithNoDependentMaps = {
    name: 'NYC Graffiti sights',
    accessible_dependent_derived_maps: [],
    accessible_dependent_derived_maps_count: 0
  };
  var dependentMap = {
    id: '5725afbe-9f51-11e6-af45-080027eb929e',
    name: 'Untitled Map',
    permission: {
      owner: {
        username: 'cdb'
      }
    },
    updated_at: '2016-10-31T10:03:58+00:00'
  };
  var visDataWithNoACL = {
    permission: {
      acl: []
    }
  };
  var visDataWithOrganizationACL = {
    permission: {
      acl: [{
        type: 'org',
        entity: {
          id: 'c210c579-0780-4ccd-83a8-7bf9fee11b34',
          name: 'globex',
          avatar_url: avatarBase64
        }
      }]
    }
  };
  var visDataWithGroupACL = {
    permission: {
      acl: [{
        type: 'group',
        entity: {
          users: [{
            username: 'Meowth',
            avatar_url: avatarBase64
          }]
        }
      }]
    }
  };
  var visModel;
  var configModel;
  var tableModel;
  var userModel;
  var view;

  function createDependantACL (username) {
    return {
      type: 'user',
      entity: {
        username: username || 'pepe' + _.random(99999).toString(),
        avatar_url: avatarBase64
      }
    };
  }

  function createView (options) {
    var opts = options || {};
    var numberOfDependentMaps = opts.numberOfDependentMaps || 0;
    var organizationAffected = opts.organizationAffected || false;
    var numberOfDependentEntities = opts.numberOfDependentEntities || 0;
    var repeatAffectedEntity = opts.repeatAffectedEntity || false;
    var affectedGroup = opts.affectedGroup || false;
    var tableData;
    var visData;

    configModel = new ConfigModel(configData);
    userModel = new UserModel(userData, { configModel: configModel });

    if (numberOfDependentMaps > 0) {
      tableData = _.clone(tableDataWithNoDependentMaps);
      tableData.accessible_dependent_derived_maps_count = numberOfDependentMaps;
      _.times(numberOfDependentMaps, function () {
        tableData.accessible_dependent_derived_maps.push(dependentMap);
      });
      tableModel = new TableModel(tableData, { parse: true, configModel: configModel });
    } else {
      tableModel = new TableModel(tableDataWithNoDependentMaps, { parse: true, configModel: configModel });
    }

    if (organizationAffected) {
      visModel = new VisDefinitionModel(visDataWithOrganizationACL, {
        configModel: configModel
      });
    } else if (affectedGroup) {
      visModel = new VisDefinitionModel(visDataWithGroupACL, {
        configModel: configModel
      });
    } else if (numberOfDependentEntities > 0) {
      visData = {
        permission: {
          acl: []
        }
      };
      _.times(numberOfDependentEntities, function () {
        visData.permission.acl.push(createDependantACL());
      });
      visData.permission.acl.push(createDependantACL(userData.username)); // To test if we filter ourselves
      if (repeatAffectedEntity) {
        visData.permission.acl.push(_.clone(visData.permission.acl[0])); // Repeat one user to test if we filter only uniques
      }
      visModel = new VisDefinitionModel(visData, {
        configModel: configModel
      });
    } else {
      visModel = new VisDefinitionModel(visDataWithNoACL, {
        configModel: configModel
      });
    }

    return new RemoveDatasetView({
      modalModel: modalModel,
      userModel: userModel,
      visModel: visModel,
      tableModel: tableModel,
      configModel: configModel
    });
  }

  describe('render', function () {
    it('Nothing affected, visualization and entities sections not shown', function () {
      // Arrange
      view = createView();

      // Act
      view.render();

      // Assert
      expect(view.$('h2')[0].textContent.trim()).toEqual('dataset.delete.title');
      expect(view.$('.MapsList-item').length).toBe(0);
      expect(view.$('.ShareUser').length).toBe(0);
      expect(view.$('button.js-cancel > span')[0].textContent.trim()).toEqual('dataset.delete.cancel');
      expect(view.$('button.js-confirm > span')[0].textContent.trim()).toEqual('dataset.delete.confirm');
    });

    it('1 visualization affected. Visualization gets properly rendered.', function () {
      // Arrange
      view = createView({ numberOfDependentMaps: 1 });

      // Act
      view.render();

      // Assert
      expect(view.$('.js-affectedVis > p')[0].textContent.trim()).toEqual('dataset.delete.affected-vis-count');
      expect(view.$('.js-affectedVis > ul > li').length).toBe(1);
      expect(view.$('.MapCard')[0].dataset['visId']).toEqual(dependentMap.id);
      expect(view.$('.MapCard')[0].dataset['visOwnerName']).toEqual(dependentMap.permission.owner.username);
      expect(view.$('.MapCard > a')[0].href).toBeTruthy();
      expect(view.$('.MapCard > a > img')[0].src).toBeTruthy();
      expect(view.$('.MapCard-content h3 > a')[0].href).toBeTruthy();
      expect(view.$('.MapCard-content h3 > a')[0].title).toEqual(dependentMap.name);
      expect(view.$('.MapCard-contentBodyTimeDiff')[0].textContent.trim()).toBeTruthy();
    });

    it('More vis affected than AFFECTED_VIS_COUNT. Text changed to extended one.', function () {
      // Arrange
      var maxAffectedVisCount = 3; // AFFECTED_VIS_COUNT
      view = createView({ numberOfDependentMaps: 4 });

      // Act
      view.render();

      // Assert
      expect(view.$('.js-affectedVis > p')[0].textContent.trim()).toEqual('dataset.delete.affected-vis-count-extended');
      expect(view.$('.js-affectedVis > ul > li').length).toBe(maxAffectedVisCount);
    });

    it('Organization affected. Proper text and avatar rendered.', function () {
      // Arrange
      var userNode;
      view = createView({ organizationAffected: true });

      // Act
      view.render();

      // Assert
      expect(view.$('.js-affectedEntities > p')[0].textContent.trim()).toEqual('dataset.delete.whole-organization-affected');
      expect(view.$('.js-affectedEntities li').length).toBe(1);
      userNode = view.$('.js-affectedEntities li .Share-user')[0];
      expect(userNode.title).toEqual(userData.organization.display_name);
      expect(userNode.dataset['username']).toEqual(userData.organization.display_name);
      expect(userNode.style.backgroundImage.indexOf(userData.organization.avatar_url) > -1).toBe(true);
    });

    it('1 user affected. Proper text and avatar rendered.', function () {
      // Arrange
      var userNode;
      var affectedEntity;
      view = createView({ numberOfDependentEntities: 1 });
      affectedEntity = view._visModel._permissionModel.get('acl')[0].entity;

      // Act
      view.render();

      // Assert
      expect(view.$('.js-affectedEntities > p')[0].textContent.trim()).toEqual('dataset.delete.affected-entities-count');
      expect(view.$('.js-affectedEntities li').length).toBe(1);
      userNode = view.$('.js-affectedEntities li .Share-user')[0];
      expect(userNode.title).toEqual(affectedEntity.username);
      expect(userNode.dataset['username']).toEqual(affectedEntity.username);
      expect(userNode.style.backgroundImage.indexOf(affectedEntity.avatar_url) > -1).toBe(true);
    });

    it('More user affected than AFFECTED_ENTITIES_SAMPLE_COUNT. Text changed to extended.', function () {
      // Arrange
      var affectedEntitiesSampleCount = 20; // AFFECTED_ENTITIES_SAMPLE_COUNT
      view = createView({ numberOfDependentEntities: affectedEntitiesSampleCount + 1 });

      // Act
      view.render();

      // Assert
      expect(view.$('.js-affectedEntities > p')[0].textContent.trim()).toEqual('dataset.delete.affected-entities-count-extended');
      expect(view.$('.js-affectedEntities li').length).toBe(affectedEntitiesSampleCount);
    });

    it('Affected entity repeated. Repeated entity gets filtered.', function () {
      // Arrange
      view = createView({
        numberOfDependentEntities: 2,
        repeatAffectedEntity: true
      });

      // Act
      view.render();

      // Assert
      expect(view.$('.js-affectedEntities li').length).toBe(2);
    });

    it('Affected group. Users of that group get rendered.', function () {
      // Arrange
      view = createView({
        affectedGroup: true
      });

      // Act
      view.render();

      // Assert
      expect(view.$('.js-affectedEntities li').length).toBe(visDataWithGroupACL.permission.acl[0].entity.users.length);
    });
  });

  describe('_runAction', function () {
    it('Renders loading view and destory has been set to the right success function.', function () {
      // Arrange
      var successFunction;
      view = createView();
      spyOn(view, '_renderLoadingView');
      spyOn(view, '_onSuccessDestroyDataset');
      spyOn(visModel, 'destroy').and.callFake(function (args) {
        successFunction = args.success;
      });

      // Act
      view._runAction();
      successFunction();

      // Assert
      expect(view._renderLoadingView).toHaveBeenCalled();
      expect(view._onSuccessDestroyDataset).toHaveBeenCalled();
    });

    it('Destroy has been set to the right error function.', function () {
      // Arrange
      var errorFunction;
      view = createView();
      spyOn(view, '_onErrorDestroyDataset');
      spyOn(visModel, 'destroy').and.callFake(function (args) {
        errorFunction = args.error;
      });

      // Act
      view._runAction();
      errorFunction(null, {});

      // Assert
      expect(view._onErrorDestroyDataset).toHaveBeenCalled();
    });
  });

  it('_renderLoadingView inserts the right HTML', function () {
    // Arrange
    view = createView();

    // Act
    view._renderLoadingView();

    // Assert
    expect(view.$('.js-loader').length).toBeGreaterThan(0);
  });

  it('_onErrorDestroyDataset inserts the right HTML', function () {
    // Arrange
    view = createView();

    // Act
    view._onErrorDestroyDataset(null, {});

    // Assert
    expect(view.$('i.CDB-IconFont-cockroach').length).toBeGreaterThan(0);
  });
});
<|endoftext|>


<commit_before>window.vjs = window.vjs || {};

(function(ns) {

    ns.HomeModel = HomeModel;
    var getFunctionName = ns.utils.getFunctionName,
        isObject = ns.utils.isObject,
        isObjectInstance = ns.utils.isObjectInstance,
        isPrimitive = ns.utils.isPrimitive;

    var JS_TYPES = Object.freeze(
        [{
            name: 'number',
            getInstance: function () {
                return 007;
            }
        }, {
            name: 'string',
            getInstance: function () {
                return "Hello World";
            }
        }, {
            name: 'boolean',
            getInstance: function () {
                return true;
            }
        }, {
            name: 'null',
            getInstance: function () {
                return null;
            }
        }, {
            name: 'undefined',
            getInstance: function () {
                return undefined;
            }
        }, {
            name: 'Object',
            isInstanceOf: function(value) {
                return value instanceof Object;
            },
            getInstance: function () {
                return new Object();
            },
            getTypeRef: function() {
                return Object;
            }
        }, {
            name: 'Function',
            isInstanceOf: function(value) {
                return value instanceof Function;
            },
            getInstance: function () {
                return new Function('a','return \'hello world\'');
            },
            getTypeRef: function() {
                return Function;
            }
        }, {
            name: 'Array',
            isInstanceOf: function(value) {
                return value instanceof Array;
            },
            getInstance: function () {
                return new Array();
            },
            getTypeRef: function() {
                return Array;
            }
        },  {
            name: 'Number',
            isInstanceOf: function(value) {
                return value instanceof Number;
            },
            getInstance: function () {
                return new Number();
            },
            getTypeRef: function () {
                return Number;
            }
        },  {
            name: 'String',
            isInstanceOf: function(value) {
                return value instanceof String;
            },
            getInstance: function () {
                return new String();
            },
            getTypeRef: function() {
                return String;
            }
        }, {
            name: 'Boolean',
            isInstanceOf: function(value) {
                return value instanceof Boolean;
            },
            getInstance: function (){
                return new Boolean();
            },
            getTypeRef: function() {
                return Boolean;
            }
        }, {
            name: 'RegExp',
            isInstanceOf: function(value) {
                return value instanceof RegExp;
            },
            getInstance: function() {
                return new RegExp();
            },
            getTypeRef: function() {
                return RegExp;
            }
        }]);

    var RESULT_ENUM = Object.freeze({
            true: 'rgba(0,255,0,0.3)',
            false: 'rgba(255,0,0,0.2)',
            error: 'yellow'
        });

    function HomeModel() {
        this.allTypes = JS_TYPES;
        this._currTypeId = 0;
        this._currDescriptor = new Descriptor();
    }

    Object.defineProperties(HomeModel.prototype, {
        currTypeId: {
            get: function() {
                return this._currTypeId;
            },

            set: function(val) {
                if(typeof val === 'number') {
                    this._currTypeId = val;
                    this.refreshCurrDescriptor();
                }
            }
        },

        currType: {
            get: function() {
            return this.allTypes[this.currTypeId];
            }
        },

        currDescriptor: {
            get: function() {
                return this._currDescriptor;
            }
        }
    });

    var isTypeSupported = function (type) {
        // check if type is supported by app
       var isSupported = false, i = 0;

       while(i < JS_TYPES.length && !isSupported) {
        if(type === JS_TYPES[i].name) {
            isSupported = true;
        }
        i += 1;
       }

       return isSupported;
    };

    var checkInstanceOf = function(src, target){
       // returns if 'src' is instance of 'target' type
       var result = false, inpInstance = src.getInstance();

       if(isTypeSupported(target.name)) {
            // For primitive types instanceof will always be false
            if(!isPrimitive(inpInstance) && !isPrimitive(target.getInstance())) {
                result = target.isInstanceOf(inpInstance)
            }
       } else {
            result = 'error';
       }
       return RESULT_ENUM[result];
    }

    function refreshCurrDescriptor() {
        if(isPrimitive(this.currType.getInstance())) {
            this._currDescriptor.clear();
        } else {
            this._currDescriptor = this.currDescriptor.buildDescriptor(this.currType.getTypeRef());
        }
    }

    function getTypeOf(inp) {
        return typeof inp;
    }

    HomeModel.prototype.checkInstanceOf = checkInstanceOf;
    HomeModel.prototype.getTypeOf = getTypeOf;
    HomeModel.prototype.refreshCurrDescriptor = refreshCurrDescriptor;

    // TODO: Move to different file//
    function Descriptor() {
        this.name = '';
        this.properties = [];
        this.parent = null;
    }

    function buildDescriptor(obj) {
        var newDesc = new Descriptor();
        if(!isPrimitive(obj)) {
            newDesc.name = getFunctionName(obj);
            newDesc.properties = Object.getOwnPropertyNames(obj);
            newDesc.parent = buildDescriptor(Object.getPrototypeOf(obj));
        } else {
            newDesc.name = 'null';
        }
        return newDesc;
    }

    function clear() {
        this.name = '';
        this.properties = '';
        this.parent = null;
    }

    Descriptor.prototype.buildDescriptor = buildDescriptor;
    Descriptor.prototype.clear = clear;
}(window.vjs));<commit_msg>Null parent fixed<commit_after>window.vjs = window.vjs || {};

(function(ns) {

    ns.HomeModel = HomeModel;
    var getFunctionName = ns.utils.getFunctionName,
        isObject = ns.utils.isObject,
        isObjectInstance = ns.utils.isObjectInstance,
        isPrimitive = ns.utils.isPrimitive;

    var JS_TYPES = Object.freeze(
        [{
            name: 'number',
            getInstance: function () {
                return 007;
            }
        }, {
            name: 'string',
            getInstance: function () {
                return "Hello World";
            }
        }, {
            name: 'boolean',
            getInstance: function () {
                return true;
            }
        }, {
            name: 'null',
            getInstance: function () {
                return null;
            }
        }, {
            name: 'undefined',
            getInstance: function () {
                return undefined;
            }
        }, {
            name: 'Object',
            isInstanceOf: function(value) {
                return value instanceof Object;
            },
            getInstance: function () {
                return new Object();
            },
            getTypeRef: function() {
                return Object;
            }
        }, {
            name: 'Function',
            isInstanceOf: function(value) {
                return value instanceof Function;
            },
            getInstance: function () {
                return new Function('a','return \'hello world\'');
            },
            getTypeRef: function() {
                return Function;
            }
        }, {
            name: 'Array',
            isInstanceOf: function(value) {
                return value instanceof Array;
            },
            getInstance: function () {
                return new Array();
            },
            getTypeRef: function() {
                return Array;
            }
        },  {
            name: 'Number',
            isInstanceOf: function(value) {
                return value instanceof Number;
            },
            getInstance: function () {
                return new Number();
            },
            getTypeRef: function () {
                return Number;
            }
        },  {
            name: 'String',
            isInstanceOf: function(value) {
                return value instanceof String;
            },
            getInstance: function () {
                return new String();
            },
            getTypeRef: function() {
                return String;
            }
        }, {
            name: 'Boolean',
            isInstanceOf: function(value) {
                return value instanceof Boolean;
            },
            getInstance: function (){
                return new Boolean();
            },
            getTypeRef: function() {
                return Boolean;
            }
        }, {
            name: 'RegExp',
            isInstanceOf: function(value) {
                return value instanceof RegExp;
            },
            getInstance: function() {
                return new RegExp();
            },
            getTypeRef: function() {
                return RegExp;
            }
        }]);

    var RESULT_ENUM = Object.freeze({
            true: 'rgba(0,255,0,0.3)',
            false: 'rgba(255,0,0,0.2)',
            error: 'yellow'
        });

    function HomeModel() {
        this.allTypes = JS_TYPES;
        this._currTypeId = 0;
        this._currDescriptor = new Descriptor();
    }

    Object.defineProperties(HomeModel.prototype, {
        currTypeId: {
            get: function() {
                return this._currTypeId;
            },

            set: function(val) {
                if(typeof val === 'number') {
                    this._currTypeId = val;
                    this.refreshCurrDescriptor();
                }
            }
        },

        currType: {
            get: function() {
            return this.allTypes[this.currTypeId];
            }
        },

        currDescriptor: {
            get: function() {
                return this._currDescriptor;
            }
        }
    });

    var isTypeSupported = function (type) {
        // check if type is supported by app
       var isSupported = false, i = 0;

       while(i < JS_TYPES.length && !isSupported) {
        if(type === JS_TYPES[i].name) {
            isSupported = true;
        }
        i += 1;
       }

       return isSupported;
    };

    var checkInstanceOf = function(src, target){
       // returns if 'src' is instance of 'target' type
       var result = false, inpInstance = src.getInstance();

       if(isTypeSupported(target.name)) {
            // For primitive types instanceof will always be false
            if(!isPrimitive(inpInstance) && !isPrimitive(target.getInstance())) {
                result = target.isInstanceOf(inpInstance)
            }
       } else {
            result = 'error';
       }
       return RESULT_ENUM[result];
    }

    function refreshCurrDescriptor() {
        if(isPrimitive(this.currType.getInstance())) {
            this._currDescriptor.clear();
        } else {
            this._currDescriptor = this.currDescriptor.buildDescriptor(this.currType.getTypeRef());
        }
    }

    function getTypeOf(inp) {
        return typeof inp;
    }

    HomeModel.prototype.checkInstanceOf = checkInstanceOf;
    HomeModel.prototype.getTypeOf = getTypeOf;
    HomeModel.prototype.refreshCurrDescriptor = refreshCurrDescriptor;

    // TODO: Move to different file//
    function Descriptor() {
        this.name = '';
        this.properties = [];
        this.parent = null;
    }

    function buildDescriptor(obj) {
        var newDesc = new Descriptor();
        if(!isPrimitive(obj)) {
            newDesc.name = getFunctionName(obj);
            newDesc.properties = Object.getOwnPropertyNames(obj);
            newDesc.parent = buildDescriptor(Object.getPrototypeOf(obj));
        } else {
            return null;
        }
        return newDesc;
    }

    function clear() {
        this.name = '';
        this.properties = '';
        this.parent = null;
    }

    Descriptor.prototype.buildDescriptor = buildDescriptor;
    Descriptor.prototype.clear = clear;
}(window.vjs));<|endoftext|>


<commit_before>$(document).ready(function(){

	$('#member_page_controller').hide();
	$('#text_event_name').text("Error: Invalid event name ");
	var eventName = getURLParameter("q");
	if(eventName != null && eventName !== '') {
		$('#text_event_name').text("Event name: " + eventName);
		$('#member_page_controller').show();
	}

});

angular.module('ability-test-app', ['firebase'])
.controller('AbilityTestCtrl', ['$scope', '$firebaseObject', '$firebaseArray',
	function($scope, $firebaseObject, $firebaseArray) {

	firebase.auth().onAuthStateChanged(function(firebaseUser) {
		if(firebaseUser) {
			var user = firebase.auth().currentUser;
	        	$scope.uid = user.uid;
		}
	});

	$scope.quiz = [];
  	$scope.quiz = $firebaseArray(firebase.database().ref("quiz/java"));

	$scope.param = {
		"answer" : []
	};

	$scope.addanswer = function(option){
		$scope.param.answer.push(option);
	};

	$scope.submitFunc = function() {
		var userID = $.trim($scope.uid);
		var newData = {
			'answers': $scope.param.answers
		};
		var refPath = getURLParameter("q") +"/member/" + userID;
		var ref = firebase.database().ref(refPath);
		ref.update({answer: $scope.param.answer})
		window.location.href = "index.html";
	};

}]);
<commit_msg>save the marks of test to the firebase<commit_after>$(document).ready(function(){

	$('#member_page_controller').hide();
	$('#text_event_name').text("Error: Invalid event name ");
	var eventName = getURLParameter("q");
	if(eventName != null && eventName !== '') {
		$('#text_event_name').text("Event name: " + eventName);
		$('#member_page_controller').show();
	}

});

angular.module('ability-test-app', ['firebase'])
.controller('AbilityTestCtrl', ['$scope', '$firebaseObject', '$firebaseArray',
	function($scope, $firebaseObject, $firebaseArray) {
		firebase.auth().onAuthStateChanged(function(firebaseUser) {
	      if(firebaseUser) {
	      	var user = firebase.auth().currentUser;
	        $scope.uid = user.uid;
	      }
	    });

    $scope.quiz = [];
  	$scope.quiz = $firebaseArray(firebase.database().ref("quiz/java"));

		$scope.param = {
			"answer" : []
		};

		$scope.addanswer = function(option){
			$scope.param.answer.push(option);
		};

		$scope.modelanswer = [];

			$scope.quiz.$loaded(function(list){
			var i = 0
			for (; i < $scope.quiz.length; i++){
				$scope.modelanswer.push($scope.quiz[i].answer)
			}

			$scope.submitFunc = function() {
				var correctness = 0
				var userID = $.trim($scope.uid);
				for (var j = 0; j < $scope.modelanswer.length; j++){
					if ($scope.modelanswer[j] == $scope.param.answer[j]){
						correctness += 1
						}
					}
				var mark = correctness / $scope.quiz.length * 100
				var refPath = getURLParameter("q") +"/member/" + userID;
				var ref = firebase.database().ref(refPath);
				ref.update({marks: mark})
				// ref.update({answers:$scope.param.answer})
				var url = "member.html?q=" + getURLParameter("q");
				window.location.href= url
			};
		})
}]);
<|endoftext|>


<commit_before>"use strict";

angular.module("piadinamia").factory("cartService",
    ["$firebase", "Firebase", "FBURL",
    function ($firebase, Firebase, FBURL) {
        var myCart = [],
            myCatalogName = "",
            myUserId;

        return {
            init: function (cart, catalogName, userId) {
                myCart = cart;
                myCatalogName = catalogName;
                myUserId = userId;
            },

            getItems: function () {
                return myCart;
            },

            saveItems: function () {
                var fburl = FBURL + "/users/" + myUserId +
                        "/catalogs/" + myCatalogName + "/cart";

                $firebase(new Firebase(fburl)).$set(myCart);
                if (myCart.length === 0) {
                    $firebase(new Firebase(fburl)).$set("");
                }
            },

            getTotalCount: function () {
                var total = 0;

                myCart.forEach(function (item) {
                    total += item.qty;
                });

                return total;
            },

            getTotalPrice: function () {
                var total = 0;

                myCart.forEach(function (item) {
                    total += item.price * item.qty;
                });

                return total;
            },

            addItem: function (item, price, qty) {
                var self = this,
                    found = false;

                qty = qty || 1;

                myCart.every(function (el, index) {
                    if (el.item === item) {
                        found = true;

                        myCart[index].qty += qty;
                        myCart[index].total = myCart[index].price *
                            myCart[index].qty;

                        if (myCart[index].qty === 0) {
                            self.clearItem(index);
                        }

                        return false;
                    }

                    return true;
                });

                if (!found) {
                    myCart.push({
                        item: item,
                        price: price,
                        qty: 1,
                        total: price
                    });
                }

                this.saveItems();
            },

            clearItem: function (index) {
                myCart.splice(index, 1);
                this.saveItems();
            }
        };

    }]);
<commit_msg>Use firebase ref in saveItems.<commit_after>"use strict";

angular.module("piadinamia").factory("cartService",
    ["$firebase", "Firebase", "FBURL",
    function ($firebase, Firebase, FBURL) {
        var myCart = [],
            myCatalogName = "",
            myUserId;

        return {
            init: function (cart, catalogName, userId) {
                myCart = cart;
                myCatalogName = catalogName;
                myUserId = userId;
            },

            getItems: function () {
                return myCart;
            },

            saveItems: function () {
                var fburl = FBURL + "/users/" + myUserId +
                        "/catalogs/" + myCatalogName + "/cart",
                    cartRef = new Firebase(fburl);

                $firebase(cartRef).$set(myCart);

                if (myCart.length === 0) {
                    $firebase(cartRef).$set("");
                }
            },

            getTotalCount: function () {
                var total = 0;

                myCart.forEach(function (item) {
                    total += item.qty;
                });

                return total;
            },

            getTotalPrice: function () {
                var total = 0;

                myCart.forEach(function (item) {
                    total += item.price * item.qty;
                });

                return total;
            },

            addItem: function (item, price, qty) {
                var self = this,
                    found = false;

                qty = qty || 1;

                myCart.every(function (el, index) {
                    if (el.item === item) {
                        found = true;

                        myCart[index].qty += qty;
                        myCart[index].total = myCart[index].price *
                            myCart[index].qty;

                        if (myCart[index].qty === 0) {
                            self.clearItem(index);
                        }

                        return false;
                    }

                    return true;
                });

                if (!found) {
                    myCart.push({
                        item: item,
                        price: price,
                        qty: 1,
                        total: price
                    });
                }

                this.saveItems();
            },

            clearItem: function (index) {
                myCart.splice(index, 1);
                this.saveItems();
            }
        };

    }]);
<|endoftext|>


<commit_before>'use strict';

/* Controllers */

angular.module('myApp.controllers', [])
    .controller('LandingPageController', [function() {

    }])

.controller('WaitlistController', ['$scope', '$firebase', 'FIREBASE_URL', function($scope, $firebase, FIREBASE_URL) {

    // Connect $scope.parties to live Firebase data.
    var partiesRef = new Firebase(FIREBASE_URL + 'parties');
    $scope.parties = $firebase(partiesRef);

    // Object to store data from the waitlist form.
    $scope.newParty = {
        name: '',
        phone: '',
        size: '',
        done: false,
        notified: 'No'
    };

    // Function to save a new party to the waitlist.
    $scope.saveParty = function() {
        $scope.parties.$add($scope.newParty);
        $scope.newParty = {
            name: '',
            phone: '',
            size: '',
            done: false,
            notified: 'No'
        };
    };

    // Function to sent a a text message
    $scope.sendTextMessage = function(party) {
        var textMessageRef = new Firebase(FIREBASE_URL + 'textMessages');
        var textMessages = $firebase(textMessageRef);
        var newTextMessage = {
            phoneNumber: party.phone,
            size: party.size,
            name: party.name
        };
        textMessages.$add(newTextMessage);
        party.notified = 'Yes';
        $scope.parties.$save(party.$id);
    };
}])

.controller('AuthController', ['$scope', 'authService', function($scope, authService) {
    $scope.user = { email: '', password: '' };
    $scope.register = function() {
        // auth.$createUser($scope.user.email, $scope.user.password)
        //     .then(function(data) {
        //         console.log(data);
        //         auth.$login('password', $scope.user);
        //         $scope.login();
        //     });
    };
    $scope.login = function() {
        authService.login($scope.user);
    };
    $scope.logout = function() {
        // auth.$logout();
        // $location.path('/');
    };
}]);<commit_msg>refactored controller to use auth service methods<commit_after>'use strict';

/* Controllers */

angular.module('myApp.controllers', [])
    .controller('LandingPageController', [function() {

    }])

.controller('WaitlistController', ['$scope', '$firebase', 'FIREBASE_URL', function($scope, $firebase, FIREBASE_URL) {

    // Connect $scope.parties to live Firebase data.
    var partiesRef = new Firebase(FIREBASE_URL + 'parties');
    $scope.parties = $firebase(partiesRef);

    // Object to store data from the waitlist form.
    $scope.newParty = {
        name: '',
        phone: '',
        size: '',
        done: false,
        notified: 'No'
    };

    // Function to save a new party to the waitlist.
    $scope.saveParty = function() {
        $scope.parties.$add($scope.newParty);
        $scope.newParty = {
            name: '',
            phone: '',
            size: '',
            done: false,
            notified: 'No'
        };
    };

    // Function to sent a a text message
    $scope.sendTextMessage = function(party) {
        var textMessageRef = new Firebase(FIREBASE_URL + 'textMessages');
        var textMessages = $firebase(textMessageRef);
        var newTextMessage = {
            phoneNumber: party.phone,
            size: party.size,
            name: party.name
        };
        textMessages.$add(newTextMessage);
        party.notified = 'Yes';
        $scope.parties.$save(party.$id);
    };
}])

.controller('AuthController', ['$scope', 'authService', function($scope, authService) {
    $scope.user = { email: '', password: '' };
    $scope.register = function() {
      authService.register($scope.user);
    };
    $scope.login = function() {
        authService.login($scope.user);
    };
    $scope.logout = function() {
        authService.login();
    };
}]);<|endoftext|>


<commit_before>'use strict';

/* Controllers */

var phonecatControllers = angular.module('phonecatControllers', []);

phonecatControllers.controller('PhoneListCtrl', ['$scope', 'Phone',
  function($scope, Phone) {
    $scope.phones = Phone.query();
    $scope.orderProp = 'age';
	$scope.left  = function() {
        if (!$scope.message || !$scope.message.length == 0)
            return;
        return $scope.message.length + " / " + 300;
    };
  }]);

phonecatControllers.controller('PhoneDetailCtrl', ['$scope', '$routeParams', 'Phone',
  function($scope, $routeParams, Phone) {
    $scope.phone = Phone.get({phoneId: $routeParams.phoneId}, function(phone) {
      $scope.mainImageUrl = phone.images[0];
    });

    $scope.setImage = function(imageUrl) {
      $scope.mainImageUrl = imageUrl;
    }
  }]);
<commit_msg>controller function 수정<commit_after>'use strict';

/* Controllers */

var phonecatControllers = angular.module('phonecatControllers', []);

phonecatControllers.controller('PhoneListCtrl', ['$scope', 'Phone',
  function($scope, Phone) {
    $scope.phones = Phone.query();
    $scope.orderProp = 'age';
  }]);

phonecatControllers.controller('PhoneDetailCtrl', ['$scope', '$routeParams', 'Phone',
  function($scope, $routeParams, Phone) {
    $scope.phone = Phone.get({phoneId: $routeParams.phoneId}, function(phone) {
      $scope.mainImageUrl = phone.images[0];
    });

    $scope.setImage = function(imageUrl) {
      $scope.mainImageUrl = imageUrl;
    }
  }]);
<|endoftext|>


<commit_before>'use strict';

var carApp = angular.module('carApp', ['ngRoute']);

carApp.config(['$routeProvider', function($routeProvider){
	$routeProvider
		.when('/buy',{
			templateUrl: 'template/buy.html',
			controller: 'BuyController'
		})
		.when('/',{
			templateUrl: 'template/home.html',
			controller: 'HomeController'
		})
		.when('/sell',{
			templateUrl: 'template/sell.html',
			controller: 'SellController'
		})
		.otherwise({
			redirectTo: '/'
		});
}]);

carApp.controller('carAppController', ['$scope', '$http', '$location', function($scope, $http, $location) {

}]);
carApp.controller('HomeController', ['$scope', '$http', '$location', function($scope, $http, $location) {

}]);

carApp.controller('BuyController', ['$scope', '$http', '$location', function($scope, $http, $location) {
		$http.get('cars/cars.json').success(function(data, status , headers, config) {
			$scope.cars = data;
		});
}]);
carApp.controller('SellController', ['$scope', '$http', '$location', function($scope, $http, $location) {

}]);
carApp.controller('SController', ['$scope', '$http', '$location', function($scope, $http, $location) {
	$scope.car = car;
}]);
carApp.controller('ShowAdController', ['$scope', '$http', '$location', function($scope, $http, $location) {
	$http.get('/car/car.json').success(function(data, status , headers, config) {
			$scope.cars = data;
		});
}]);
carApp.controller('Ctrl', ['$scope', '$http', '$location', function($scope, $http, $location) {
		$scope.list = {
        car: "",
        id: "",
        imageUrl: "",
        model: "",
        snippet: "",
        price: "",
        mileage: "",
        fuel: "",
        transmission: "",
        engine: "",
        phone: "",
        year:""
    };
	  $scope.submit = function() {
	    this.list.name = this.name;
	    this.list.car = this.car;
	    this.list.id = this.id;
	    this.list.imageUrl = this.imageUrl;
	    this.list.model = this.model;
	    this.list.snippet = this.snippet;
	    this.list.price = this.price;
	    this.list.mileage = this.mileage;
	    this.list.fuel = this.fuel;
	    this.list.transmission = this.transmission;
	    this.list.engine = this.engine;
	    this.list.phone = this.phone;
	    this.list.year = this.year;
	    $http.get('cars/cars.json').success(function(data, status , headers, config) {
				$scope.cars = data;
				$scope.cars.push($scope.list);
				console.log($scope.cars);
				$http.post('cars/cars.json').success(function(data, status , headers, config) {
					$scope.cars = data;
					console.log(1);
				});
			});
			$http.post('cars/cars.json').success(function(data, status , headers, config) {
					$scope.cars = data;
					console.log(1);
				});
		};
}]);
<commit_msg>Update controllers.js<commit_after>'use strict';

var carApp = angular.module('carApp', ['ngRoute']);

carApp.config(['$routeProvider', function($routeProvider){
	$routeProvider
		.when('/buy',{
			templateUrl: 'template/buy.html',
			controller: 'BuyController'
		})
		.when('/',{
			templateUrl: 'template/home.html',
			controller: 'HomeController'
		})
		.when('/sell',{
			templateUrl: 'template/sell.html',
			controller: 'SellController'
		})
		.otherwise({
			redirectTo: '/'
		});
}]);

carApp.controller('carAppController', ['$scope', '$http', '$location', function($scope, $http, $location) {

}]);
carApp.controller('HomeController', ['$scope', '$http', '$location', function($scope, $http, $location) {

}]);

carApp.controller('BuyController', ['$scope', '$http', '$location', function($scope, $http, $location) {
		$http.get('..//cars/cars.json').success(function(data, status , headers, config) {
			$scope.cars = data;
		});
}]);
carApp.controller('SellController', ['$scope', '$http', '$location', function($scope, $http, $location) {

}]);
carApp.controller('SController', ['$scope', '$http', '$location', function($scope, $http, $location) {
	$scope.car = car;
}]);
carApp.controller('ShowAdController', ['$scope', '$http', '$location', function($scope, $http, $location) {
	$http.get('/car/car.json').success(function(data, status , headers, config) {
			$scope.cars = data;
		});
}]);
carApp.controller('Ctrl', ['$scope', '$http', '$location', function($scope, $http, $location) {
		$scope.list = {
        car: "",
        id: "",
        imageUrl: "",
        model: "",
        snippet: "",
        price: "",
        mileage: "",
        fuel: "",
        transmission: "",
        engine: "",
        phone: "",
        year:""
    };
	  $scope.submit = function() {
	    this.list.name = this.name;
	    this.list.car = this.car;
	    this.list.id = this.id;
	    this.list.imageUrl = this.imageUrl;
	    this.list.model = this.model;
	    this.list.snippet = this.snippet;
	    this.list.price = this.price;
	    this.list.mileage = this.mileage;
	    this.list.fuel = this.fuel;
	    this.list.transmission = this.transmission;
	    this.list.engine = this.engine;
	    this.list.phone = this.phone;
	    this.list.year = this.year;
	    $http.get('cars/cars.json').success(function(data, status , headers, config) {
				$scope.cars = data;
				$scope.cars.push($scope.list);
				console.log($scope.cars);
				$http.post('cars/cars.json').success(function(data, status , headers, config) {
					$scope.cars = data;
					console.log(1);
				});
			});
			$http.post('cars/cars.json').success(function(data, status , headers, config) {
					$scope.cars = data;
					console.log(1);
				});
		};
}]);
<|endoftext|>


<commit_before>'use strict';

/* Controllers */

angular.module('myApp.controllers', []).
controller('MainCtrl', function($scope, $http) {
    $scope.parseOriginalUrlStatus = 'waiting';
    $scope.done_scraping_original_url = false;

    $scope.statusCodeResult = function(statusCode) {
    };

    $scope.startRunningTest = function() {
		$scope.done_scraping_original_url = false;
        $scope.linksInfo = [];
        $scope.parseOriginalUrlStatus = 'calling';
		if (!$scope.linkCheckForm.url_to_scrape.$error.pattern) {
			$http.get('/slurp', {
				params: {
					url_to_scrape: $scope.url_to_scrape
				}
			})
				.success(function(data) {
					console.log(data);
					if (!data.success) {
						console.log('no success');
						$scope.parseOriginalUrlStatus = 'invalid';
					} else {
						$scope.parseOriginalUrlStatus = 'waiting';
						$scope.done_scraping_original_url = true;
						$scope.externalWebSiteJSON = angular.toJson(data, true);
						if (data.success) {
							var links = data.links;
							if (links.length > 1) {
								$scope.retrieved_urls = links;
								$scope.$broadcast('checkLinks');
							} else {
								$scope.parseOriginalUrlStatus = 'invalid';
							}
						}
					}

				});
		} else {
			$scope.parseOriginalUrlStatus = 'invalid';
		}
    };
    $scope.checkUrl = function(url_to_check_index) {
        console.log("checking ", $scope.retrieved_urls[url_to_check_index].href);
        $http.get('/check', {
            params: {
                url_to_check: $scope.retrieved_urls[url_to_check_index].href
            }
        })
            .success(function(data) {
                $scope.retrieved_urls[url_to_check_index].checkResult = data;
            })
    }
});
<commit_msg>remove empty method<commit_after>'use strict';

/* Controllers */

angular.module('myApp.controllers', []).
controller('MainCtrl', function($scope, $http) {
    $scope.parseOriginalUrlStatus = 'waiting';
    $scope.done_scraping_original_url = false;

    $scope.startRunningTest = function() {
		$scope.done_scraping_original_url = false;
        $scope.linksInfo = [];
        $scope.parseOriginalUrlStatus = 'calling';
		if (!$scope.linkCheckForm.url_to_scrape.$error.pattern) {
			$http.get('/slurp', {
				params: {
					url_to_scrape: $scope.url_to_scrape
				}
			})
				.success(function(data) {
					console.log(data);
					if (!data.success) {
						console.log('no success');
						$scope.parseOriginalUrlStatus = 'invalid';
					} else {
						$scope.parseOriginalUrlStatus = 'waiting';
						$scope.done_scraping_original_url = true;
						$scope.externalWebSiteJSON = angular.toJson(data, true);
						if (data.success) {
							var links = data.links;
							if (links.length > 1) {
								$scope.retrieved_urls = links;
								$scope.$broadcast('checkLinks');
							} else {
								$scope.parseOriginalUrlStatus = 'invalid';
							}
						}
					}

				});
		} else {
			$scope.parseOriginalUrlStatus = 'invalid';
		}
    };
    $scope.checkUrl = function(url_to_check_index) {
        console.log("checking ", $scope.retrieved_urls[url_to_check_index].href);
        $http.get('/check', {
            params: {
                url_to_check: $scope.retrieved_urls[url_to_check_index].href
            }
        })
            .success(function(data) {
                $scope.retrieved_urls[url_to_check_index].checkResult = data;
            })
    }
});
<|endoftext|>


<commit_before>import { render, findDOMNode, createRenderer } from '../../../src/DOM/rendering';
import createStaticVElementClone from '../../../src/factories/createStaticVElementClone';
import { disableRecycling } from '../../../src/DOM/recycling';
import { initDevToolsHooks, exitDevToolsHooks }  from '../../../src/DOM/devtools';

if (typeof window !== 'undefined' && window.document) {
	initDevToolsHooks(window);
}

export default {
	render,
	findDOMNode,
	createRenderer,
	createStaticVElementClone,
	disableRecycling
};
<commit_msg>fixed a bad export on inferno-dom<commit_after>import { render, findDOMNode, createRenderer } from '../../../src/DOM/rendering';
import createStaticVElementClone from '../../../src/factories/createStaticVElementClone';
import { disableRecycling } from '../../../src/DOM/recycling';
import { initDevToolsHooks }  from '../../../src/DOM/devtools';

if (typeof window !== 'undefined' && window.document) {
	initDevToolsHooks(window);
}

export default {
	render,
	findDOMNode,
	createRenderer,
	createStaticVElementClone,
	disableRecycling
};
<|endoftext|>


<commit_before><commit_msg>Should be semicolon.<commit_after><|endoftext|>


<commit_before><commit_msg>Fix List / scalar mismatch<commit_after><|endoftext|>


<commit_before><commit_msg>Fix bug #454<commit_after><|endoftext|>


<commit_before><commit_msg>style: fix eslint errors<commit_after><|endoftext|>


<commit_before><commit_msg>Simplify the regex + document it<commit_after><|endoftext|>