<commit_before>import PropTypes from 'prop-types';
import React from 'react';
import { Grid } from 'react-flexbox-grid/lib';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import { sendPasswordReset } from '../../actions/userActions';
import ChangePasswordForm from './ChangePasswordForm';
import { addNotice } from '../../actions/appActions';
import { LEVEL_ERROR } from '../common/Notice';

const localMessages = {
  tite: { id: 'user.resetPassword.title', defaultMessage: 'Reset Your Password' },
  button: { id: 'user.resetPassword.button', defaultMessage: 'Reset Your Password' },
  failed: { id: 'user.resetPassword.failed', defaultMessage: 'Sorry, something went wrong.' },
  badToken: { id: 'user.resetPassword.badToken', defaultMessage: 'That is an invalid reset token. Check to see if you have a newer link from us in your email.' },
};

const ResetPasswordContainer = (props) => {
  const { handlePasswordReset } = props;
  return (
    <Grid>
      <ChangePasswordForm
        titleMsg={localMessages.tite}
        buttonMsg={localMessages.button}
        onSubmit={handlePasswordReset}
      />
    </Grid>
  );
};

ResetPasswordContainer.propTypes = {
  // form router
  location: PropTypes.object.isRequired,
  // from dispatch
  handlePasswordReset: PropTypes.func.isRequired,
};

const mapDispatchToProps = (dispatch, ownProps) => ({
  handlePasswordReset: (values) => {
    const email = ownProps.location.query.email;
    const passwordResetToken = ownProps.location.query.password_reset_token;
    dispatch(sendPasswordReset({ ...values, email, password_reset_token: passwordResetToken }))
    .then((response) => {
      if (response.success) {
        if (response.success === 1) {
          dispatch(push('/user/reset-password-success'));
        } else {
          dispatch(addNotice({ message: localMessages.failed, level: LEVEL_ERROR }));
        }
      } else if (response.message.includes('Password reset token is invalid')) {
        dispatch(addNotice({ message: localMessages.badToken, level: LEVEL_ERROR }));
      }
    });
  },
});

export default
  connect(null, mapDispatchToProps)(
    ResetPasswordContainer
  );
<commit_msg>more work on password reset flow (#862)<commit_after>import PropTypes from 'prop-types';
import React from 'react';
import { Grid } from 'react-flexbox-grid/lib';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import { sendPasswordReset } from '../../actions/userActions';
import ChangePasswordForm from './ChangePasswordForm';
import { addNotice } from '../../actions/appActions';
import { LEVEL_ERROR } from '../common/Notice';

const localMessages = {
  tite: { id: 'user.resetPassword.title', defaultMessage: 'Reset Your Password' },
  button: { id: 'user.resetPassword.button', defaultMessage: 'Reset Your Password' },
  failed: { id: 'user.resetPassword.failed', defaultMessage: 'Sorry, something went wrong.' },
  badToken: { id: 'user.resetPassword.badToken', defaultMessage: 'That is an invalid reset token. Check to see if you have a newer link from us in your email.' },
};

const ResetPasswordContainer = (props) => {
  const { handlePasswordReset } = props;
  return (
    <Grid>
      <ChangePasswordForm
        titleMsg={localMessages.tite}
        buttonMsg={localMessages.button}
        onSubmit={handlePasswordReset}
      />
    </Grid>
  );
};

ResetPasswordContainer.propTypes = {
  // form router
  location: PropTypes.object.isRequired,
  // from dispatch
  handlePasswordReset: PropTypes.func.isRequired,
};

const mapDispatchToProps = (dispatch, ownProps) => ({
  handlePasswordReset: (values) => {
    // this link came from the email, so we need to grab the props to submit off of the url
    const email = ownProps.location.query.email;
    const passwordResetToken = ownProps.location.query.password_reset_token;
    // send the request to reset the password
    return dispatch(sendPasswordReset({ ...values, email, password_reset_token: passwordResetToken }))
      .then((response) => {
        if (response.success) { // the token was ok
          // and the pswd change worked
          if (response.success === 1) {
            return dispatch(push('/user/reset-password-success'));  // them them it worked
          }
          // or it failed
          return dispatch(addNotice({ message: localMessages.failed, level: LEVEL_ERROR }));
        } else if (response.message.includes('Password reset token is invalid')) {
          // the token was not valid
          return dispatch(addNotice({ message: localMessages.badToken, level: LEVEL_ERROR }));
        }
        // someone else bad happened
        return dispatch(addNotice({ message: localMessages.failed, level: LEVEL_ERROR }));
      });
  },
});

export default
  connect(null, mapDispatchToProps)(
    ResetPasswordContainer
  );
<|endoftext|>


<commit_before>'use strict';

/* global module, require */
module.exports = function(grunt) {

	var jsConnectorFiles = ['connectors/v2/*.js']; // intentionally does not contain all files yet
	var jsCoreFiles = ['Gruntfile.js', 'core/**/*.js', 'options/options.js', 'popups/*.js'];
	var jsTestFiles = ['tests/**/*.js'];
	var jsonFiles = ['*.json', '.jshintrc', '.csslintrc'];
	var htmlFiles = ['options/*.html', 'popups/*.html', 'dialogs/**/*.html'];
	var cssFiles = ['options/options.css', 'popups/base.css', 'dialogs/base.css'];

	grunt.initConfig({
		bump: {
			options: {
				files: ['manifest.json'],
				commit: true,
				commitFiles: ['manifest.json'],
				push: false
			}
		},
		jshint: {
			all: [jsCoreFiles, jsConnectorFiles],
			options: {
				jshintrc: true,
				reporter: require('jshint-stylish')
			}
		},
		compress: {
			main: {
				options: {
					archive: 'web-scrobbler.zip',
					pretty: true
				},
				expand: true,
				src: [
					'connectors/**', 'core/**', 'dialogs/**',
					'icons/**', 'options/**', 'popups/**', 'vendor/**',
					'manifest.json', 'README.md', 'LICENSE.txt', '*.png'
				]
			}
		},
		lintspaces: {
			all: {
				src: [
					jsCoreFiles, jsConnectorFiles, jsTestFiles, jsonFiles, cssFiles, htmlFiles
				],

				options: {
					editorconfig: '.editorconfig',
					ignores: [
						'js-comments'
					]
				}
			}
		},
		jsonlint: {
			sample: {
				src: [ jsonFiles ]
			}
		},
		csslint: {
			options: {
				csslintrc: '.csslintrc'
			},
			strict: {
				src: [cssFiles]
			}
		},
		exec: {
			publish: {
				cmd: 'node scripts/publish-chrome-extension web-scrobbler.zip'
			},
			run_tests: {
				command: 'node tests/runner.js'
			}
		}
	});

	grunt.loadNpmTasks('grunt-bump');
	grunt.loadNpmTasks('grunt-contrib-jshint');
	grunt.loadNpmTasks('grunt-contrib-compress');
	grunt.loadNpmTasks('grunt-lintspaces');
	grunt.loadNpmTasks('grunt-jsonlint');
	grunt.loadNpmTasks('grunt-contrib-csslint');
	grunt.loadNpmTasks('grunt-exec');

	grunt.registerTask('lint', ['jshint', 'csslint', 'jsonlint', 'lintspaces']);
	grunt.registerTask('publish', ['compress', 'exec:publish']);
	grunt.registerTask('release', (ver) => {
		grunt.task.run(`bump:${ver}`);
		grunt.task.run('publish');
	});
	grunt.registerTask('test', ['exec:run_tests']);
	grunt.registerTask('default', ['lint']);
};
<commit_msg>Lint test files<commit_after>'use strict';

/* global module, require */
module.exports = function(grunt) {

	var jsConnectorFiles = ['connectors/v2/*.js']; // intentionally does not contain all files yet
	var jsCoreFiles = ['Gruntfile.js', 'core/**/*.js', 'options/options.js', 'popups/*.js'];
	var jsTestFiles = ['tests/**/*.js'];
	var jsonFiles = ['*.json', '.jshintrc', '.csslintrc'];
	var htmlFiles = ['options/*.html', 'popups/*.html', 'dialogs/**/*.html'];
	var cssFiles = ['options/options.css', 'popups/base.css', 'dialogs/base.css'];

	grunt.initConfig({
		bump: {
			options: {
				files: ['manifest.json'],
				commit: true,
				commitFiles: ['manifest.json'],
				push: false
			}
		},
		jshint: {
			all: [jsCoreFiles, jsConnectorFiles, jsTestFiles],
			options: {
				jshintrc: true,
				reporter: require('jshint-stylish')
			}
		},
		compress: {
			main: {
				options: {
					archive: 'web-scrobbler.zip',
					pretty: true
				},
				expand: true,
				src: [
					'connectors/**', 'core/**', 'dialogs/**',
					'icons/**', 'options/**', 'popups/**', 'vendor/**',
					'manifest.json', 'README.md', 'LICENSE.txt', '*.png'
				]
			}
		},
		lintspaces: {
			all: {
				src: [
					jsCoreFiles, jsConnectorFiles, jsTestFiles, jsonFiles, cssFiles, htmlFiles
				],

				options: {
					editorconfig: '.editorconfig',
					ignores: [
						'js-comments'
					]
				}
			}
		},
		jsonlint: {
			sample: {
				src: [ jsonFiles ]
			}
		},
		csslint: {
			options: {
				csslintrc: '.csslintrc'
			},
			strict: {
				src: [cssFiles]
			}
		},
		exec: {
			publish: {
				cmd: 'node scripts/publish-chrome-extension web-scrobbler.zip'
			},
			run_tests: {
				command: 'node tests/runner.js'
			}
		}
	});

	grunt.loadNpmTasks('grunt-bump');
	grunt.loadNpmTasks('grunt-contrib-jshint');
	grunt.loadNpmTasks('grunt-contrib-compress');
	grunt.loadNpmTasks('grunt-lintspaces');
	grunt.loadNpmTasks('grunt-jsonlint');
	grunt.loadNpmTasks('grunt-contrib-csslint');
	grunt.loadNpmTasks('grunt-exec');

	grunt.registerTask('lint', ['jshint', 'csslint', 'jsonlint', 'lintspaces']);
	grunt.registerTask('publish', ['compress', 'exec:publish']);
	grunt.registerTask('release', (ver) => {
		grunt.task.run(`bump:${ver}`);
		grunt.task.run('publish');
	});
	grunt.registerTask('test', ['exec:run_tests']);
	grunt.registerTask('default', ['lint']);
};
<|endoftext|>


<commit_before>module.exports = function(grunt) {

	grunt.initConfig({
		'connect': {
			demo: {
				options: {
					open: true,
					keepalive: true
				}
			}
		},
		'gh-pages': {
			options: {
				clone: 'bower_components/input-password'
			},
			src: [
			'bower_components/**/*',
			'!bower_components/input-password/**/*',
			'demo/*', 'src/*', 'index.html', 'preview.png'
			]
		},
		'replace': {
			example: {
				src: ['src/*'],
				dest: 'dist/',
				replacements: [{
					from: 'bower_components',
					to: '..'
				}]
			}
		},
		'push': {
			options: {
				files: ['package.json', 'bower.json'],
				updateConfigs: [],
				push: {
					releaseBranch: ['develop', 'master']
				},
				add: true,
				addFiles: ['.'],
				commit: true,
				commitMessage: 'Release %VERSION%',
				commitFiles: ['-a'],
				createTag: true,
				tagName: '%VERSION%',
				tagMessage: 'Version %VERSION%',
				push: true,
				pushTo: 'origin',
				npm: true,
				npmTag: 'Release %VERSION%',
				gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d'
			}
		},
		'uglify': {
			dist: {
				files: {
					'dist/input-password.js': 'src/input-password.js'
				}
			}
		},
		'cssmin': {
			dist: {
				files: {
					'dist/input-password.css': 'src/input-password.css'
				}
			}
		},
		'htmlmin': {
			dist: {
				options: {
					removeComments: true,
					removeCommentsFromCDATA: true,
					removeCDATASectionsFromCDATA: true,
					collapseWhitespace: true,
					conservativeCollapse: true
				},
				files: {
					'dist/input-password.html': 'src/input-password.html'
				}
			}
		}
	});

grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-htmlmin');
grunt.loadNpmTasks('grunt-gh-pages');
grunt.loadNpmTasks('grunt-text-replace');
grunt.loadNpmTasks('grunt-push-release');

grunt.registerTask('build',  ['replace', 'uglify', 'cssmin', 'htmlmin']);
grunt.registerTask('deploy', ['gh-pages']);
grunt.registerTask('serve', ['connect']);

};
<commit_msg>include all demo and src files<commit_after>module.exports = function(grunt) {

	grunt.initConfig({
		'connect': {
			demo: {
				options: {
					open: true,
					keepalive: true
				}
			}
		},
		'gh-pages': {
			options: {
				clone: 'bower_components/input-password'
			},
			src: [
			'bower_components/**/*',
			'!bower_components/input-password/**/*',
			'demo/**/*', 'src/**/*', 'index.html', 'preview.png'
			]
		},
		'replace': {
			example: {
				src: ['src/*'],
				dest: 'dist/',
				replacements: [{
					from: 'bower_components',
					to: '..'
				}]
			}
		},
		'push': {
			options: {
				files: ['package.json', 'bower.json'],
				updateConfigs: [],
				push: {
					releaseBranch: ['develop', 'master']
				},
				add: true,
				addFiles: ['.'],
				commit: true,
				commitMessage: 'Release %VERSION%',
				commitFiles: ['-a'],
				createTag: true,
				tagName: '%VERSION%',
				tagMessage: 'Version %VERSION%',
				push: true,
				pushTo: 'origin',
				npm: true,
				npmTag: 'Release %VERSION%',
				gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d'
			}
		},
		'uglify': {
			dist: {
				files: {
					'dist/input-password.js': 'src/input-password.js'
				}
			}
		},
		'cssmin': {
			dist: {
				files: {
					'dist/input-password.css': 'src/input-password.css'
				}
			}
		},
		'htmlmin': {
			dist: {
				options: {
					removeComments: true,
					removeCommentsFromCDATA: true,
					removeCDATASectionsFromCDATA: true,
					collapseWhitespace: true,
					conservativeCollapse: true
				},
				files: {
					'dist/input-password.html': 'src/input-password.html'
				}
			}
		}
	});

grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-htmlmin');
grunt.loadNpmTasks('grunt-gh-pages');
grunt.loadNpmTasks('grunt-text-replace');
grunt.loadNpmTasks('grunt-push-release');

grunt.registerTask('build',  ['replace', 'uglify', 'cssmin', 'htmlmin']);
grunt.registerTask('deploy', ['gh-pages']);
grunt.registerTask('serve', ['connect']);

};
<|endoftext|>


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

    var geojsonFeature = [];
    var allowedPoints = d3.map([]);

    var geojsonMarkerGeoportalOptions = {
        radius: 5,
        fillColor: "#ff0000",
        color: "white",
        weight: 2,
        opacity: 1,
        fillOpacity: 0.6
    };

    var geojsonMarkerNaturaListaInvOptions = {
        radius: 5,
        fillColor: "#0b9c31",
        color: "white",
        weight: 2,
        opacity: 1,
        fillOpacity: 0.6
    };

    var geojsonMarkerNaturaListaCasualOptions = {
        radius: 5,
        fillColor: "#FFFF00",
        color: "white",
        weight: 2,
        opacity: 1,
        fillOpacity: 0.6
    };

    var customOptions ={
        'maxWidth': '500',
        'className' : 'custom'
    };

    /***************************************************************** Layer creation */

    var OSM_layer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png');

    // Google satellite map layer
    var GSM_layer = L.tileLayer('http://{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}&labels=true',{
        maxZoom: 20,
        subdomains:['mt0','mt1','mt2','mt3']
    });

    // Google terrain map layer
    var GTM_layer = L.tileLayer('http://{s}.google.com/vt/lyrs=p&x={x}&y={y}&z={z}',{
        maxZoom: 20,
        subdomains:['mt0','mt1','mt2','mt3']
    });
    // Google Hybrid
    var GHM_layer = L.tileLayer('http://{s}.google.com/vt/lyrs=y&x={x}&y={y}&z={z}',{
        maxZoom: 20,
        subdomains:['mt0','mt1','mt2','mt3']
    });
    var drawnItems = new L.FeatureGroup();

    var milliseconds = new Date().getTime();

    var species_layer;
    var markersLayer;

    /***************************************************************** map switcher */
    /* Quite var, para poder tener acceso a la variable fuera del scope*/
    map = L.map('map', {
        center: [23.79162789, -102.04376221],
        zoom: 5,
        //maxBounds: L.latLngBounds(L.latLng(14.3227,-86.4236),L.latLng(32.4306,-118.2727)),
        layers: [
            OSM_layer,
            GSM_layer,
            GTM_layer,
            GHM_layer
        ]
    });

    /***************************************************************** layer switcher */
    var baseMaps = {
        "Open Street Maps": OSM_layer,
        "Vista de Satélite": GSM_layer,
        "Vista de terreno": GTM_layer,
        "Vista Híbrida": GHM_layer
    };

    var overlayMaps = {
        //"Malla": grid_wms
    };

    var layer_control = L.control.layers(baseMaps).addTo(map);

    /***************************************************************** aditional controls */
    function addPointLayerGeoportal(){
        geojsonFeature =  { "type": "FeatureCollection",
            "features": allowedPoints.values()};

        markersLayer = L.markerClusterGroup({ maxClusterRadius: 30, chunkedLoading: true, which_layer: 'geoportal'});

        species_layer = L.geoJson(geojsonFeature, {
            pointToLayer: function (feature, latlng) {
                return L.circleMarker(latlng, geojsonMarkerGeoportalOptions);
            },
            onEachFeature: function (feature, layer) {
                coordinates = parseFloat(feature.geometry.coordinates[1]).toFixed(2) + ", " +  parseFloat(feature.geometry.coordinates[0]).toFixed(2);
                var p_contenido = content_geoportal(feature.properties.d);
                layer.bindPopup(p_contenido);
            }
        });

        markersLayer.addLayer(species_layer);
        map.addLayer(markersLayer);
        layer_control.addOverlay(markersLayer, "Registros de museos, colectas y proyectos de CONABIO (SNIB)");
    }

    function addPointLayerNaturaLista(){
        geojsonFeature =  { "type": "FeatureCollection",
            "features": allowedPoints.values()};

        markersLayer = L.markerClusterGroup({ maxClusterRadius: 30, chunkedLoading: true, which_layer: 'naturalista'});

        species_layer = L.geoJson(geojsonFeature, {
            pointToLayer: function (feature, latlng) {
                return L.circleMarker(latlng, geojsonMarkerNaturaListaInvOptions);
                //para cuando tenga tiempo, poner el ícono como DEBE de ser!!!
                //return L.marker(latlng, {icon: L.divIcon({className: "glyphicon glyphicon-map-marker"})});
            },
            onEachFeature: function (feature, layer) {
                coordinates = parseFloat(feature.geometry.coordinates[1]).toFixed(2) + ", " +  parseFloat(feature.geometry.coordinates[0]).toFixed(2);
                var p_contenido = content_naturalista(feature.properties.d);
                layer.bindPopup(p_contenido);
            }
        });

        markersLayer.addLayer(species_layer);
        map.addLayer(markersLayer);
        layer_control.addOverlay(markersLayer, "Observaciones de ");
    }

/*
    var kmlLayer = new L.KML("/assets/cnb-canlupusgw.kml", {async: true});
    map.addLayer(kmlLayer);

    layer_control.addOverlay(kmlLayer, "Distribución potencial (CONABIO)");
*/

    function content_geoportal(feature){
        var contenido = "";

        contenido += "
" + name() + "
";
        contenido += "
Localidad:

" + feature.localidad + "
";
        contenido += "
Municipio:

" + feature.municipiomapa + "
";
        contenido += "
Estado:

" + feature.estadomapa + "
";
        contenido += "
País:

" + feature.paismapa + "
";
        contenido += "
Fecha:

" + feature.fechacolecta + "
";
        contenido += "
Colector:

" + feature.colector + "
";
        contenido += "
Colección:

" + feature.coleccion + "
";
        contenido += "
Institución:

" + feature.institucion + "
";
        contenido += "
País de la colección:

" + feature.paiscoleccion + "
";

        if (feature.proyecto.length > 0 && feature.urlproyecto.length > 0)
            contenido += "
Proyecto:

" + feature.proyecto + "
";

        contenido += "
Más información:

consultar
";

        return "
" + contenido + "
";
    }

    function content_naturalista(feature){
        var contenido = "";

        contenido += "
" + name() + "
";

        if (feature.photos.length > 0)
        {
            contenido += "

"
            contenido += "
Atribución:

" + feature.photos[0].attribution + "
";
        }

        /*contenido += "
Ubicación:

" + feature.place_guess + "
";*/
        contenido += "
Fecha:

" + feature.observed_on + "
";
        contenido += "
¿silvestre / naturalizado?:

" + (feature.captive == true ? 'sí' : 'no') + "
";
        contenido += "
Grado de calidad:

" + I18n.t('quality_grade.' + feature.quality_grade) + "
";
        contenido += "
URL NaturaLista:

ver la observación
";

        return "
" + contenido + "
";
    }

    function name()
    {
        if (I18n.locale == 'es')
        {
            if (NOMBRE_COMUN_PRINCIPAL.length > 0)
                return NOMBRE_COMUN_PRINCIPAL + " (" + TAXON.nombre_cientifico + ")";
            else
                return "(" + TAXON.nombre_cientifico + ")";
        } else {
            return "(" + TAXON.nombre_cientifico + ")";
        }
    }

    var geojson_geoportal = function()
    {
        $.ajax({
            url: GEO.geoportal_url,
            //url: "http://colibri.conabio.gob.mx:9000/snib?qtype=getSpecies&rd=plantae&taxlevel=genero&taxvalue=zea",
            dataType : "json",
            success : function (d){
                allowedPoints = d3.map([]);

                for(i=0;i<d.length;i++)
                {
                    item_id = JSON.parse(d[i].json_geom).coordinates.toString();

                    // this map is fill with the records in the database from an specie, so it discards repetive elemnts.
                    allowedPoints.set(item_id, {
                        "type"      : "Feature",
                        "properties": {d: d[i]},
                        "geometry"  : JSON.parse(d[i].json_geom)
                    });
                }

                addPointLayerGeoportal();
            },
            error: function( jqXHR ,  textStatus,  errorThrown ){
                console.log("error: " + textStatus);
                console.log(errorThrown);
                console.log(jqXHR.responseText);
            }
        });  // termina ajax
    };

    var geojson_naturalista = function(){
        $.ajax({
            url: "/especies/" + TAXON.id + "/naturalista",
            dataType : "json",
            beforeSend: function(xhr){
                xhr.setRequestHeader('X-Test-Header', 'test-value');
                xhr.setRequestHeader("Accept","text/json");
            },
            success : function (d){
                allowedPoints = d3.map([]);

                for(i=0;i<d.length;i++){
                    //var item_id_json = JSON.parse(d[i]);
                    item_id = d[i].longitude + "," + d[i].latitude;

                    // this map is fill with the records in the database from an specie, so it discards repetive elemnts.
                    allowedPoints.set(item_id, {
                        "type"      : "Feature",
                        "properties": {d: d[i]},
                        "geometry"  : {coordinates: [parseFloat(d[i].longitude), parseFloat(d[i].latitude)], type: "Point"}
                    });
                }
                addPointLayerNaturaLista();
            },
            error: function( jqXHR ,  textStatus,  errorThrown ){
                console.log("error: " + textStatus);
                console.log(errorThrown);
                console.log(jqXHR.responseText);
            }
        });  // termina ajax
    };

    if (GEO.cuales.indexOf("naturalista") >= 0) geojson_naturalista();
    if (GEO.cuales.indexOf("geoportal") >= 0) geojson_geoportal();

});

<commit_msg>las observaciones casuales de NaturaLista en amaraillo<commit_after>$(document).ready(function(){

    var geojsonFeature = [];
    var allowedPoints = d3.map([]);

    var geojsonMarkerGeoportalOptions = {
        radius: 5,
        fillColor: "#ff0000",
        color: "white",
        weight: 2,
        opacity: 1,
        fillOpacity: 0.6
    };

    var geojsonMarkerNaturaListaInvOptions = {
        radius: 5,
        fillColor: "#0b9c31",
        color: "white",
        weight: 2,
        opacity: 1,
        fillOpacity: 0.6
    };

    var geojsonMarkerNaturaListaCasualOptions = {
        radius: 5,
        fillColor: "#FFFF00",
        color: "white",
        weight: 2,
        opacity: 1,
        fillOpacity: 0.6
    };

    var customOptions ={
        'maxWidth': '500',
        'className' : 'custom'
    };

    /***************************************************************** Layer creation */
    var OSM_layer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png');

    // Google terrain map layer
    var GTM_layer = L.tileLayer('http://{s}.google.com/vt/lyrs=p&x={x}&y={y}&z={z}',{
        maxZoom: 20,
        subdomains:['mt0','mt1','mt2','mt3']
    });
    // Google Hybrid
    var GHM_layer = L.tileLayer('http://{s}.google.com/vt/lyrs=y&x={x}&y={y}&z={z}',{
        maxZoom: 20,
        subdomains:['mt0','mt1','mt2','mt3']
    });
    var drawnItems = new L.FeatureGroup();

    var milliseconds = new Date().getTime();

    var species_layer;
    var markersLayer;

    /***************************************************************** map switcher */
    /* Quite var, para poder tener acceso a la variable fuera del scope*/
    map = L.map('map', {
        center: [23.79162789, -102.04376221],
        zoom: 5,
        //maxBounds: L.latLngBounds(L.latLng(14.3227,-86.4236),L.latLng(32.4306,-118.2727)),
        layers: [
            OSM_layer,
            GTM_layer,
            GHM_layer
        ]
    });

    /***************************************************************** layer switcher */
    var baseMaps = {
        "Open Street Maps": OSM_layer,
        "Vista de terreno": GTM_layer,
        "Vista Híbrida": GHM_layer
    };

    var layer_control = L.control.layers(baseMaps).addTo(map);

    /***************************************************************** aditional controls */
    function addPointLayerGeoportal(){
        geojsonFeature =  { "type": "FeatureCollection",
            "features": allowedPoints.values()};

        markersLayer = L.markerClusterGroup({ maxClusterRadius: 30, chunkedLoading: true, which_layer: 'geoportal'});

        species_layer = L.geoJson(geojsonFeature, {
            pointToLayer: function (feature, latlng) {
                return L.circleMarker(latlng, geojsonMarkerGeoportalOptions);
            },
            onEachFeature: function (feature, layer) {
                coordinates = parseFloat(feature.geometry.coordinates[1]).toFixed(2) + ", " +  parseFloat(feature.geometry.coordinates[0]).toFixed(2);
                var p_contenido = content_geoportal(feature.properties.d);
                layer.bindPopup(p_contenido);
            }
        });

        markersLayer.addLayer(species_layer);
        map.addLayer(markersLayer);
        layer_control.addOverlay(markersLayer, "" + allowedPoints.size() + " registros del SNIB
 (museos, colectas y proyectos de CONABIO)");
    }

    function addPointLayerNaturaLista(){
        geojsonFeature =  { "type": "FeatureCollection",
            "features": allowedPoints.values()};

        markersLayer = L.markerClusterGroup({ maxClusterRadius: 30, chunkedLoading: true, which_layer: 'naturalista'});

        species_layer = L.geoJson(geojsonFeature, {
            pointToLayer: function (feature, latlng) {
                // Para cuando es una observacion casual o de investigacion
                if (feature.properties.d.quality_grade == 'research')
                    return L.circleMarker(latlng, geojsonMarkerNaturaListaInvOptions);
                else
                    return L.circleMarker(latlng, geojsonMarkerNaturaListaCasualOptions);
                //para cuando tenga tiempo, poner el ícono como DEBE de ser!!!
                //return L.marker(latlng, {icon: L.divIcon({className: "glyphicon glyphicon-map-marker"})});
            },
            onEachFeature: function (feature, layer) {
                coordinates = parseFloat(feature.geometry.coordinates[1]).toFixed(2) + ", " +  parseFloat(feature.geometry.coordinates[0]).toFixed(2);
                var p_contenido = content_naturalista(feature.properties.d);
                layer.bindPopup(p_contenido);
            }
        });

        markersLayer.addLayer(species_layer);
        map.addLayer(markersLayer);
        layer_control.addOverlay(markersLayer, "" + allowedPoints.size() + " observaciones de ");
    }

/*
    var kmlLayer = new L.KML("/assets/cnb-canlupusgw.kml", {async: true});
    map.addLayer(kmlLayer);

    layer_control.addOverlay(kmlLayer, "Distribución potencial (CONABIO)");
*/

    function content_geoportal(feature){
        var contenido = "";

        contenido += "
" + name() + "
";
        contenido += "
Localidad:

" + feature.localidad + "
";
        contenido += "
Municipio:

" + feature.municipiomapa + "
";
        contenido += "
Estado:

" + feature.estadomapa + "
";
        contenido += "
País:

" + feature.paismapa + "
";
        contenido += "
Fecha:

" + feature.fechacolecta + "
";
        contenido += "
Colector:

" + feature.colector + "
";
        contenido += "
Colección:

" + feature.coleccion + "
";
        contenido += "
Institución:

" + feature.institucion + "
";
        contenido += "
País de la colección:

" + feature.paiscoleccion + "
";

        if (feature.proyecto.length > 0 && feature.urlproyecto.length > 0)
            contenido += "
Proyecto:

" + feature.proyecto + "
";

        contenido += "
Más información:

consultar
";

        return "
" + contenido + "
";
    }

    function content_naturalista(feature){
        var contenido = "";

        contenido += "
" + name() + "
";

        if (feature.photos.length > 0)
        {
            contenido += "

"
            contenido += "
Atribución:

" + feature.photos[0].attribution + "
";
        }

        /*contenido += "
Ubicación:

" + feature.place_guess + "
";*/
        contenido += "
Fecha:

" + feature.observed_on + "
";
        contenido += "
¿silvestre / naturalizado?:

" + (feature.captive == true ? 'sí' : 'no') + "
";
        contenido += "
Grado de calidad:

" + I18n.t('quality_grade.' + feature.quality_grade) + "
";
        contenido += "
URL NaturaLista:

ver la observación
";

        return "
" + contenido + "
";
    }

    function name()
    {
        if (I18n.locale == 'es')
        {
            if (NOMBRE_COMUN_PRINCIPAL.length > 0)
                return NOMBRE_COMUN_PRINCIPAL + " (" + TAXON.nombre_cientifico + ")";
            else
                return "(" + TAXON.nombre_cientifico + ")";
        } else {
            return "(" + TAXON.nombre_cientifico + ")";
        }
    }

    var geojson_geoportal = function()
    {
        $.ajax({
            url: GEO.geoportal_url,
            //url: "http://colibri.conabio.gob.mx:9000/snib?qtype=getSpecies&rd=plantae&taxlevel=genero&taxvalue=zea",
            dataType : "json",
            success : function (d){
                allowedPoints = d3.map([]);

                for(i=0;i<d.length;i++)
                {
                    item_id = JSON.parse(d[i].json_geom).coordinates.toString();

                    // this map is fill with the records in the database from an specie, so it discards repetive elemnts.
                    allowedPoints.set(item_id, {
                        "type"      : "Feature",
                        "properties": {d: d[i]},
                        "geometry"  : JSON.parse(d[i].json_geom)
                    });
                }

                addPointLayerGeoportal();
            },
            error: function( jqXHR ,  textStatus,  errorThrown ){
                console.log("error: " + textStatus);
                console.log(errorThrown);
                console.log(jqXHR.responseText);
            }
        });  // termina ajax
    };

    var geojson_naturalista = function(){
        $.ajax({
            url: "/especies/" + TAXON.id + "/naturalista",
            dataType : "json",
            beforeSend: function(xhr){
                xhr.setRequestHeader('X-Test-Header', 'test-value');
                xhr.setRequestHeader("Accept","text/json");
            },
            success : function (d){
                allowedPoints = d3.map([]);

                for(i=0;i<d.length;i++){
                    //var item_id_json = JSON.parse(d[i]);
                    item_id = d[i].longitude + "," + d[i].latitude;

                    // this map is fill with the records in the database from an specie, so it discards repetive elemnts.
                    allowedPoints.set(item_id, {
                        "type"      : "Feature",
                        "properties": {d: d[i]},
                        "geometry"  : {coordinates: [parseFloat(d[i].longitude), parseFloat(d[i].latitude)], type: "Point"}
                    });
                }
                addPointLayerNaturaLista();
            },
            error: function( jqXHR ,  textStatus,  errorThrown ){
                console.log("error: " + textStatus);
                console.log(errorThrown);
                console.log(jqXHR.responseText);
            }
        });  // termina ajax
    };

    if (GEO.cuales.indexOf("naturalista") >= 0) geojson_naturalista();
    if (GEO.cuales.indexOf("geoportal") >= 0) geojson_geoportal();

});

<|endoftext|>


<commit_before>/*jshint -W098 */

module.exports = function (grunt) {
	'use strict';

	var path = require('path');
	var util = require('util');

	var isTravis = (process.env.TRAVIS === 'true');
	var isVagrant = (process.env.PWD === '/vagrant');
	if (isVagrant) {
		grunt.log.writeln('-> ' + 'vagrant detected'.cyan);
	}
	var cpuCores = require('os').cpus().length;
	//grunt.log.writeln(util.inspect(process.env));

	var gtx = require('gruntfile-gtx').wrap(grunt);
	gtx.loadAuto();
	gtx.loadNpm([
		'mocha-unfunk-reporter'
	]);

	//defaults and one-off tasks
	gtx.config({
		pkg: gtx.readJSON('package.json'),
		jshint: {
			options: gtx.readJSON('.jshintrc', {
				reporter: './node_modules/jshint-path-reporter'
			}),
			support: ['Gruntfile.js', 'test/*.js', 'lib/**/*.js'],
			fixtures: ['test/**/fixtures/**/*.js']
		},
		tslint: {
			options: {
				configuration: gtx.readJSON('tslint.json'),
				formatter: 'tslint-path-formatter'
			},
			source: ['src/**/*.ts', '!src/test', '!src/spec'],
			helper: ['test/*.ts'],
			testing: [
				'src/test/**/*.ts',
				'src/spec/**/*.ts'
			]
		},
		todos: {
			options: {
				reporter: 'path',
				verbose: false,
				priorities: {
					low: /(NOTE|TODO)/,
					med: /(FIXME)/,
					high: /(BROKEN)/
				}
			},
			all: {
				options: {},
				src: ['src/**/*.ts', 'test/**/src/**/*.ts']
			}
		},
		clean: {
			tmp: ['tmp/**/*', 'test/tmp/**/*'],
			dump: ['test/modules/**/dump'],
			test: ['test/*/spec/build/**/*'],
			build: ['build/**', 'build/**/*.js', 'build/**/*.d.ts', 'build/**/*.js.map'],
			cruft: ['tscommand-*.tmp.txt']
		},
		copy: {
			cli: {
				files: [
				// includes files within path
					{expand: true, cwd: 'src', src: ['cli.js', '.gitattributes'], dest: 'build', filter: 'isFile'}
				]
			}
		},
		'regex-replace': {
			cli: {
				src: ['build/cli.js'],
				actions: [
					{
						name: 'eol',
						search: '\\r\\n',
						replace: '\n',
						flags: 'g'
					}
				]
			}
		},
		tv4: {
			packjson: {
				options: {
					root: function() {
						return require('package.json-schema').get();
					}
				},
				src: ['package.json']
			},
			tsd: {
				options: {
					multi: true,
					root: 'schema/tsd-v4.json'
				},
				src: ['tsd.json']
			},
			schemas: {
				options: {
					multi: true,
					root: 'http://json-schema.org/draft-04/schema#'
				},
				src: ['schema/*.json']
			}
		},
		mochaTest: {
			options: {
				reporter: 'mocha-unfunk-reporter',
				timeout: 3000
			},
			integrity: ['test/integrity.js'],
			// some extra js tests
			spec: ['test/spec/*.js']
		},
		typson: {
			options: {

			},
			http: {
				src: [
					'./src/http/types.ts'
				]
			}
		},
		mocha_unfunk: {
			dev: {
				options: {
					reportPending: true,
					stackFilter: true
				}
			}
		},
		ts_clean: {
			build: {
				src: ['build/**/*'],
				dot: true
			}
		},
		ts: {
			options: {
				module: 'commonjs',
				fast: 'never',
				target: 'es5',
				declaration: true,
				sourcemap: true,
				removeComments: true,
				noImplicitAny: false
			},
			api: {
				src: ['src/**/*.ts', '!src/test/**/*.ts', '!src/spec/**/*.ts', '!src/**/_ref.d.ts'],
				outDir: 'build/'
			},
			test: {
				src: ['src/test.ts'],
				outDir: 'build/'
			},
			/*blobSha: {
				src: ['src/util/blobSha.ts'],
				out: 'util/blobSha.js'
			},*/
			/*capture_task: {
				src: ['tasks/capture_cli.ts'],
				out: 'tasks/capture_cli.js'
			},*/
			//use this non-checked-in file to test small snippets of dev code
			dev: {
				src: ['src/dev.ts'],
				out: 'tmp/dev.js'
			},
			scratch: {
				options: {
					baseDir: './src'
				},
				src: ['src/dt/dt.ts'],
				outDir: 'tmp/'
			}
		},
		shell: {
			options: {
				failOnError: true,
				stdout: true
			},
			demo_help: {
				command: [
					'node', './build/cli.js',
					'-h',
					'--capture',
					'--style', 'ansi'
				].join(' '),
				options: {
				}
			},
			demo_html: {
				command: [
					'node', './build/cli.js',
					'-h',
					'--style', 'html'
				].join(' '),
				options: {
				}
			},
			scratch: {
				command: [
					'node', './tmp/dt/dt',
					'--stack'
				].join(' '),
				options: {
				}
			}
		}
	});

	// module tester macro
	gtx.define('moduleTest', function (macro, id) {
		var srcPath = 'src/spec/' + id + '/';

		var basePath = 'test/spec/' + id + '/';
		var tmpPath = basePath + 'tmp/';
		var outPath = basePath + 'build/';

		macro.add('clean', [tmpPath, outPath]);
		macro.add('ts', {
			options: {
				module: 'commonjs',
				target: 'es5',
				declaration: false,
				sourcemap: true,
				noImplicitAny: false
			},
			src: [srcPath + '**/*.ts'],
			outDir: outPath
		});
		macro.add('tslint', {
			src: [srcPath + '** /*.ts']
		});
		if (macro.getParam('http', 0) > 0) {
			macro.add('connect', {
				options: {
					port: macro.getParam('http'),
					base: basePath + 'www/'
				}
			});
		}
		macro.run('mocha_unfunk:dev');
		macro.add('mochaTest', {
			options: {
				timeout: macro.getParam('timeout', 3000)
			},
			src: [outPath + 'spec/**/*.js']
		});
		macro.tag('module');

		//TODO implement new gruntfile-gtx once() feature (run-once dependencies, like tslint:source or tslint:helper)
	}, {
		concurrent: cpuCores
	});

	var longTimer = (isVagrant ? 250000 : 10000);

	// modules
	gtx.create('xm', 'moduleTest', null, 'lib');
	gtx.create('git', 'moduleTest', {timeout: longTimer}, 'lib');
	gtx.create('tsd', 'moduleTest', {timeout: longTimer}, 'lib,core');
	gtx.create('core,api,cli', 'moduleTest', {timeout: longTimer}, 'core');
	gtx.create('http', 'moduleTest', {
		timeout: longTimer,
		http: 9090
	}, 'lib');

	gtx.alias('pre_publish', [
		/*'tv4:schemas',*/
		'tv4:tsd',
		'tv4:packjson',
		'rebuild',
		'regex-replace:cli',
		'ts_clean:build',
		// 'gtx:api',
		'mochaTest:integrity',
		'demo:help'
	]);

	// assemble!
	gtx.alias('prep', [
		'clean:tmp',
		'clean:test',
		'jshint:support',
		'jshint:fixtures',
		'mocha_unfunk:dev',
		'clean:cruft'
	]);
	gtx.alias('rebuild', [
		'clean:build',
		'prep',
		'ts:api',
		'clean:cruft',
		'copy:cli',
		'regex-replace:cli',
		'tslint:source',
		// 'export_declaration:api'
	]);
	gtx.alias('build', [
		'rebuild'
	]);
	gtx.alias('test', [
		'build',
		'tslint:testing',
		'gtx-type:moduleTest',
		'mochaTest:spec',
		'clean:cruft'
	]);
	gtx.alias('default', [
		'test'
	]);
	gtx.alias('demo:help', [
		'shell:demo_help'
	]);

	gtx.alias('dev', [
		'clean:build',
		'prep',
		'typson:http',
		//'ts:scratch',
		//'shell:scratch'
	]);

	gtx.alias('specjs', ['mochaTest:spec']);
	gtx.alias('scratch', ['clean:tmp', 'ts:scratch']);

	gtx.alias('debugger', ['gtx:api']);

	// additional editor toolbar mappings
	gtx.alias('edit_01', 'gtx:tsd');
	gtx.alias('edit_02', 'gtx:api');
	gtx.alias('edit_03', 'build', 'gtx:cli');
	gtx.alias('edit_04', 'gtx:core');
	gtx.alias('edit_05', 'gtx:git');
	gtx.alias('edit_06', 'gtx:xm');
	gtx.alias('edit_07', 'gtx:http');
	gtx.alias('edit_08', 'scratch');

	// build and send to grunt.initConfig();
	gtx.finalise();
};
<commit_msg>dropped schema and meta-schema validation from Gruntfile<commit_after>/*jshint -W098 */

module.exports = function (grunt) {
	'use strict';

	var path = require('path');
	var util = require('util');

	var isTravis = (process.env.TRAVIS === 'true');
	var isVagrant = (process.env.PWD === '/vagrant');
	if (isVagrant) {
		grunt.log.writeln('-> ' + 'vagrant detected'.cyan);
	}
	var cpuCores = require('os').cpus().length;
	//grunt.log.writeln(util.inspect(process.env));

	var gtx = require('gruntfile-gtx').wrap(grunt);
	gtx.loadAuto();
	gtx.loadNpm([
		'mocha-unfunk-reporter'
	]);

	//defaults and one-off tasks
	gtx.config({
		pkg: gtx.readJSON('package.json'),
		jshint: {
			options: gtx.readJSON('.jshintrc', {
				reporter: './node_modules/jshint-path-reporter'
			}),
			support: ['Gruntfile.js', 'test/*.js', 'lib/**/*.js'],
			fixtures: ['test/**/fixtures/**/*.js']
		},
		tslint: {
			options: {
				configuration: gtx.readJSON('tslint.json'),
				formatter: 'tslint-path-formatter'
			},
			source: ['src/**/*.ts', '!src/test', '!src/spec'],
			helper: ['test/*.ts'],
			testing: [
				'src/test/**/*.ts',
				'src/spec/**/*.ts'
			]
		},
		todos: {
			options: {
				reporter: 'path',
				verbose: false,
				priorities: {
					low: /(NOTE|TODO)/,
					med: /(FIXME)/,
					high: /(BROKEN)/
				}
			},
			all: {
				options: {},
				src: ['src/**/*.ts', 'test/**/src/**/*.ts']
			}
		},
		clean: {
			tmp: ['tmp/**/*', 'test/tmp/**/*'],
			dump: ['test/modules/**/dump'],
			test: ['test/*/spec/build/**/*'],
			build: ['build/**', 'build/**/*.js', 'build/**/*.d.ts', 'build/**/*.js.map'],
			cruft: ['tscommand-*.tmp.txt']
		},
		copy: {
			cli: {
				files: [
				// includes files within path
					{expand: true, cwd: 'src', src: ['cli.js', '.gitattributes'], dest: 'build', filter: 'isFile'}
				]
			}
		},
		'regex-replace': {
			cli: {
				src: ['build/cli.js'],
				actions: [
					{
						name: 'eol',
						search: '\\r\\n',
						replace: '\n',
						flags: 'g'
					}
				]
			}
		},
		tv4: {
			packjson: {
				options: {
					root: function() {
						return require('package.json-schema').get();
					}
				},
				src: ['package.json']
			}
		},
		mochaTest: {
			options: {
				reporter: 'mocha-unfunk-reporter',
				timeout: 3000
			},
			integrity: ['test/integrity.js'],
			// some extra js tests
			spec: ['test/spec/*.js']
		},
		typson: {
			options: {

			},
			http: {
				src: [
					'./src/http/types.ts'
				]
			}
		},
		mocha_unfunk: {
			dev: {
				options: {
					reportPending: true,
					stackFilter: true
				}
			}
		},
		ts_clean: {
			build: {
				src: ['build/**/*'],
				dot: true
			}
		},
		ts: {
			options: {
				module: 'commonjs',
				fast: 'never',
				target: 'es5',
				declaration: true,
				sourcemap: true,
				removeComments: true,
				noImplicitAny: false
			},
			api: {
				src: ['src/**/*.ts', '!src/test/**/*.ts', '!src/spec/**/*.ts', '!src/**/_ref.d.ts'],
				outDir: 'build/'
			},
			test: {
				src: ['src/test.ts'],
				outDir: 'build/'
			},
			/*blobSha: {
				src: ['src/util/blobSha.ts'],
				out: 'util/blobSha.js'
			},*/
			/*capture_task: {
				src: ['tasks/capture_cli.ts'],
				out: 'tasks/capture_cli.js'
			},*/
			//use this non-checked-in file to test small snippets of dev code
			dev: {
				src: ['src/dev.ts'],
				out: 'tmp/dev.js'
			},
			scratch: {
				options: {
					baseDir: './src'
				},
				src: ['src/dt/dt.ts'],
				outDir: 'tmp/'
			}
		},
		shell: {
			options: {
				failOnError: true,
				stdout: true
			},
			demo_help: {
				command: [
					'node', './build/cli.js',
					'-h',
					'--capture',
					'--style', 'ansi'
				].join(' '),
				options: {
				}
			},
			demo_html: {
				command: [
					'node', './build/cli.js',
					'-h',
					'--style', 'html'
				].join(' '),
				options: {
				}
			},
			scratch: {
				command: [
					'node', './tmp/dt/dt',
					'--stack'
				].join(' '),
				options: {
				}
			}
		}
	});

	// module tester macro
	gtx.define('moduleTest', function (macro, id) {
		var srcPath = 'src/spec/' + id + '/';

		var basePath = 'test/spec/' + id + '/';
		var tmpPath = basePath + 'tmp/';
		var outPath = basePath + 'build/';

		macro.add('clean', [tmpPath, outPath]);
		macro.add('ts', {
			options: {
				module: 'commonjs',
				target: 'es5',
				declaration: false,
				sourcemap: true,
				noImplicitAny: false
			},
			src: [srcPath + '**/*.ts'],
			outDir: outPath
		});
		macro.add('tslint', {
			src: [srcPath + '** /*.ts']
		});
		if (macro.getParam('http', 0) > 0) {
			macro.add('connect', {
				options: {
					port: macro.getParam('http'),
					base: basePath + 'www/'
				}
			});
		}
		macro.run('mocha_unfunk:dev');
		macro.add('mochaTest', {
			options: {
				timeout: macro.getParam('timeout', 3000)
			},
			src: [outPath + 'spec/**/*.js']
		});
		macro.tag('module');

		//TODO implement new gruntfile-gtx once() feature (run-once dependencies, like tslint:source or tslint:helper)
	}, {
		concurrent: cpuCores
	});

	var longTimer = (isVagrant ? 250000 : 10000);

	// modules
	gtx.create('xm', 'moduleTest', null, 'lib');
	gtx.create('git', 'moduleTest', {timeout: longTimer}, 'lib');
	gtx.create('tsd', 'moduleTest', {timeout: longTimer}, 'lib,core');
	gtx.create('core,api,cli', 'moduleTest', {timeout: longTimer}, 'core');
	gtx.create('http', 'moduleTest', {
		timeout: longTimer,
		http: 9090
	}, 'lib');

	gtx.alias('pre_publish', [
		'tv4:packjson',
		'rebuild',
		'regex-replace:cli',
		'ts_clean:build',
		// 'gtx:api',
		'mochaTest:integrity',
		'demo:help'
	]);

	// assemble!
	gtx.alias('prep', [
		'clean:tmp',
		'clean:test',
		'jshint:support',
		'jshint:fixtures',
		'mocha_unfunk:dev',
		'clean:cruft'
	]);
	gtx.alias('rebuild', [
		'clean:build',
		'prep',
		'ts:api',
		'clean:cruft',
		'copy:cli',
		'regex-replace:cli',
		'tslint:source',
		// 'export_declaration:api'
	]);
	gtx.alias('build', [
		'rebuild'
	]);
	gtx.alias('test', [
		'build',
		'tslint:testing',
		'gtx-type:moduleTest',
		'mochaTest:spec',
		'clean:cruft'
	]);
	gtx.alias('default', [
		'test'
	]);
	gtx.alias('demo:help', [
		'shell:demo_help'
	]);

	gtx.alias('dev', [
		'clean:build',
		'prep',
		'typson:http',
		//'ts:scratch',
		//'shell:scratch'
	]);

	gtx.alias('specjs', ['mochaTest:spec']);
	gtx.alias('scratch', ['clean:tmp', 'ts:scratch']);

	gtx.alias('debugger', ['gtx:api']);

	// additional editor toolbar mappings
	gtx.alias('edit_01', 'gtx:tsd');
	gtx.alias('edit_02', 'gtx:api');
	gtx.alias('edit_03', 'build', 'gtx:cli');
	gtx.alias('edit_04', 'gtx:core');
	gtx.alias('edit_05', 'gtx:git');
	gtx.alias('edit_06', 'gtx:xm');
	gtx.alias('edit_07', 'gtx:http');
	gtx.alias('edit_08', 'scratch');

	// build and send to grunt.initConfig();
	gtx.finalise();
};
<|endoftext|>


<commit_before>/**
 * Created by novacrazy on 7/8/14.
 */

module.exports = function( grunt ) {

    grunt.loadNpmTasks( 'grunt-babel' );
    grunt.loadNpmTasks( 'grunt-contrib-clean' );
    grunt.loadNpmTasks( 'grunt-banner' );

    var LICENSE = '/****\n * ' + grunt.file.read( './LICENSE', {encoding: 'utf-8'} ).replace( /\n/ig, '\n * ' )
                  + '\n ****/';

    grunt.initConfig( {
        babel:     {
            options:      {
                loose:        "all",
                ast:          false,
                sourceMaps: false,
                nonStandard:  false,
                compact:      "false",
                modules:      "common",
                experimental: true
            },
            build_modern: {
                options: {
                    blacklist: [
                        'es3.memberExpressionLiterals',
                        'es3.propertyLiterals',
                        'regenerator', //es6.generators
                        'es6.properties.shorthand'
                    ],
                    optional:  [
                        'runtime',
                        'spec.undefinedToVoid',
                        'es7.functionBind',
                        'minification.constantFolding',
                        'minification.propertyLiterals',
                        'es7.exportExtensions',
                        'bluebirdCoroutines',
                        'es7.classProperties'
                    ]
                },
                files:   [{
                    expand: true,
                    cwd:    './src/',
                    src:    './**/*.js',
                    dest:   './build/modern/'
                }]
            },
            build_compat: {
                options: {
                    optional: [
                        'runtime',
                        'spec.undefinedToVoid',
                        'es7.functionBind',
                        'minification.constantFolding',
                        'minification.propertyLiterals',
                        'es7.exportExtensions',
                        'es7.asyncFunctions',
                        'regenerator',
                        'es7.classProperties'
                    ]
                },
                files:   [{
                    expand: true,
                    cwd:    './src/',
                    src:    './**/*.js',
                    dest:   './build/compat/'
                }]
            },
            build_binary: {
                options: {
                    optional: [
                        'runtime',
                        'spec.undefinedToVoid',
                        'minification.constantFolding',
                        'minification.propertyLiterals',
                        'es7.classProperties'
                    ]
                },
                files:   [{
                    expand: true,
                    cwd:    './bin/',
                    src:    './**/*.es6',
                    dest:   './bin/',
                    ext:    '.js'
                }]
            }
        },
        usebanner: {
            license: {
                options: {
                    position:  'top',
                    banner:    LICENSE,
                    linebreak: true
                },
                files:   {
                    src: ['./build/**/*.js']
                }
            }
        },
        clean:     {
            build: {
                src: ['./build', './bin/**/*.js', './bin/**/*.map']
            }
        }
    } );

    grunt.registerTask( 'build', ['clean:build', 'babel', 'usebanner:license'] );
    grunt.registerTask( 'default', ['build'] );
};
<commit_msg>Gruntfile: Add task for building tests<commit_after>/**
 * Created by novacrazy on 7/8/14.
 */

module.exports = function( grunt ) {

    grunt.loadNpmTasks( 'grunt-babel' );
    grunt.loadNpmTasks( 'grunt-contrib-clean' );
    grunt.loadNpmTasks( 'grunt-banner' );

    var LICENSE = '/****\n * ' + grunt.file.read( './LICENSE', {encoding: 'utf-8'} ).replace( /\n/ig, '\n * ' )
                  + '\n ****/';

    grunt.initConfig( {
        babel:     {
            options:      {
                loose:        "all",
                ast:          false,
                sourceMaps: false,
                nonStandard:  false,
                compact:      "false",
                modules:      "common",
                experimental: true
            },
            build_modern: {
                options: {
                    blacklist: [
                        'es3.memberExpressionLiterals',
                        'es3.propertyLiterals',
                        'regenerator', //es6.generators
                        'es6.properties.shorthand'
                    ],
                    optional:  [
                        'runtime',
                        'spec.undefinedToVoid',
                        'es7.functionBind',
                        'minification.constantFolding',
                        'minification.propertyLiterals',
                        'es7.exportExtensions',
                        'bluebirdCoroutines',
                        'es7.classProperties'
                    ]
                },
                files:   [{
                    expand: true,
                    cwd:    './src/',
                    src:    './**/*.js',
                    dest:   './build/modern/'
                }]
            },
            build_compat: {
                options: {
                    optional: [
                        'runtime',
                        'spec.undefinedToVoid',
                        'es7.functionBind',
                        'minification.constantFolding',
                        'minification.propertyLiterals',
                        'es7.exportExtensions',
                        'es7.asyncFunctions',
                        'regenerator',
                        'es7.classProperties'
                    ]
                },
                files:   [{
                    expand: true,
                    cwd:    './src/',
                    src:    './**/*.js',
                    dest:   './build/compat/'
                }]
            },
            build_binary: {
                options: {
                    optional: [
                        'runtime',
                        'spec.undefinedToVoid',
                        'minification.constantFolding',
                        'minification.propertyLiterals',
                        'es7.classProperties'
                    ]
                },
                files:   [{
                    expand: true,
                    cwd:    './bin/',
                    src:    './**/*.es6',
                    dest:   './bin/',
                    ext:    '.js'
                }]
            },
            build_tests:  {
                options: {
                    blacklist: [
                        'es3.memberExpressionLiterals',
                        'es3.propertyLiterals',
                        'regenerator', //es6.generators
                        'es6.properties.shorthand'
                    ],
                    optional:  [
                        'runtime',
                        'spec.undefinedToVoid',
                        'es7.functionBind',
                        'minification.constantFolding',
                        'minification.propertyLiterals'
                    ]
                },
                files:   [{
                    expand: true,
                    cwd:    './test/src/',
                    src:    './**/*.js',
                    dest:   './test/build/'
                }]
            }
        },
        usebanner: {
            license: {
                options: {
                    position:  'top',
                    banner:    LICENSE,
                    linebreak: true
                },
                files:   {
                    src: ['./build/**/*.js']
                }
            }
        },
        clean:     {
            build: {
                src: ['./build', './bin/**/*.js', './bin/**/*.map']
            },
            tests: {
                src: ['./test/build']
            }
        }
    } );

    grunt.registerTask( 'build', ['clean:build',
                                  'babel:build_modern',
                                  'babel:build_compat',
                                  'babel:build_binary',
                                  'usebanner:license'] );

    grunt.registerTask( 'build-tests', ['clean:tests', 'babel:build_tests'] );

    grunt.registerTask( 'default', ['build', 'build-tests'] );
};
<|endoftext|>


<commit_before>'use strict';

module.exports = function(grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        curl: {
            'extlib/qunit.js': 'http://code.jquery.com/qunit/qunit-1.14.0.js',
            'extlib/qunit.css': 'http://code.jquery.com/qunit/qunit-1.14.0.css'
        },
        markdown: {
            all: {
                files: [
                    {
                        expand: true,
                        src: 'README.md',
                        dest: '',
                        ext: '.html'
                    }
                ]
            }
        },
        jsdoc: {
            dist: {
                src: [
                    'lib/kclv.js'
                ],
                dest: 'doc',
                options: {
                    lenient: true
                }
            }
        },
        clean: {
            doc: [
                'README.html',
                'doc/*',
                '!doc/generator.bat'
            ],
            chart: [
                'chart/*',
                '!chart/.exists'
            ],
            dist: [
                '<%= concat.dist.dest %>',
                '*.zip'
            ]
        },
        concat: {
            options: {
                stripBanners: true,
                process: function(source, path) {
                    return source.replace(
                        // Remove script mode syntax and append origin.
                        /(^|\r?\n)\s*('use strict'|"use strict");?\s*/,
                        [
                            '// Source: ' + path,
                            '',
                            ''
                        ].join(grunt.util.linefeed)
                    );
                },
                banner: [
                    '/**',
                    ' * @fileOverview <%= pkg.description %>.',
                    ' *     This module added {@code <%= pkg.name %>} ' +
                        'symbol to the global namespace.',
                    ' * @version <%= pkg.version %> (Released at ' +
                        '<%= grunt.template.today("isoDateTime") %>' +
                        '<%= grunt.template.today("o") %>)',
                    ' * @author <%= pkg.author.email %> ' +
                        '(<%= pkg.author.name %>)',
                    ' * @license <%= pkg.licenses[0].type %> ' +
                        '(See LICENSE file)',
                    ' */',
                    '',
                    "'use strict'; // Script mode syntax (Whole-library)",
                    '',
                    ''
                ].join(grunt.util.linefeed)
            },
            dist: {
                src: [
                    // Note: Don't specify 'lib/*.js'! It is order-sensitive.
                    'lib/main.js', // It has script mode and global namespace.
                    'lib/inscription.js',
                    'lib/factory.js',
                    'lib/formatter.js',
                    'lib/exception.js',
                    'lib/array.js',
                    'lib/pseudo-interface.js',
                    'lib/configuration.js',
                    'lib/stream.js',
                    'lib/date.js',
                    'lib/game.js',
                    'lib/agent.js',
                    'lib/tokenizer.js',
                    'lib/selector.js',
                    'lib/projector.js',
                    'lib/relation.js',
                    'lib/table.js',
                    'lib/chart.js',
                    'lib/template.js',
                    'lib/visualizer.js'
                ],
                dest: 'lib/kclv.js',
                nonull: true
            }
        },
        compress: {
            dist: {
                options: {
                    archive: '<%= pkg.name %>-<%= pkg.version %>.zip'
                },
                files: [
                    {
                        src: [
                            'README.html',
                            'LICENSE',
                            'configuration.json',
                            'visualizer.wsf',
                            'chart/**',
                            '<%= concat.dist.dest %>',
                            'lib/polyfill.js',
                            'template/**'
                        ]
                    }
                ]
            }
        },
        jshint: {
            files: [
                'Gruntfile.js',
                // 'configuration.json',
                'lib/*.js',
                '!<%= concat.dist.dest %>',
                '!lib/polyfill.js',
                'test/*.js',
                'test/.jshintrc',
                'test/.csslintrc'
            ],
            options: {
                jshintrc: 'test/.jshintrc'
            }
        },
        csslint: {
            dist: {
                src: [
                    'template/chart.css'
                ],
                options: {
                    csslintrc: 'test/.csslintrc'
                }
            }
        },
        qunit: {
            files: [
                'test/harness.html'
            ]
        }
    });

    grunt.loadNpmTasks('grunt-curl');
    grunt.registerTask(
        'build',
        [
            'curl'
        ]
    );

    grunt.loadNpmTasks('grunt-markdown');
    grunt.loadNpmTasks('grunt-jsdoc');
    grunt.registerTask(
        'doc',
        [
            'markdown',
            'jsdoc'
        ]
    );

    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-compress');
    grunt.registerTask(
        'dist',
        [
            'clean',
            'markdown',
            'concat',
            'compress:dist'
        ]
    );

    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-csslint');
    grunt.loadNpmTasks('grunt-contrib-qunit');
    grunt.registerTask(
        'test',
        [
            'csslint',
            'jshint',
            'concat',
            'qunit'
        ]
    );
};
<commit_msg>Divide JSHint's targets to lint delicately<commit_after>'use strict';

module.exports = function(grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        curl: {
            'extlib/qunit.js': 'http://code.jquery.com/qunit/qunit-1.14.0.js',
            'extlib/qunit.css': 'http://code.jquery.com/qunit/qunit-1.14.0.css'
        },
        markdown: {
            all: {
                files: [
                    {
                        expand: true,
                        src: 'README.md',
                        dest: '',
                        ext: '.html'
                    }
                ]
            }
        },
        jsdoc: {
            dist: {
                src: [
                    'lib/kclv.js'
                ],
                dest: 'doc',
                options: {
                    lenient: true
                }
            }
        },
        clean: {
            doc: [
                'README.html',
                'doc/*',
                '!doc/generator.bat'
            ],
            chart: [
                'chart/*',
                '!chart/.exists'
            ],
            dist: [
                '<%= concat.dist.dest %>',
                '*.zip'
            ]
        },
        concat: {
            options: {
                stripBanners: true,
                process: function(source, path) {
                    return source.replace(
                        // Remove script mode syntax and append origin.
                        /(^|\r?\n)\s*('use strict'|"use strict");?\s*/,
                        [
                            '// Source: ' + path,
                            '',
                            ''
                        ].join(grunt.util.linefeed)
                    );
                },
                banner: [
                    '/**',
                    ' * @fileOverview <%= pkg.description %>.',
                    ' *     This module added {@code <%= pkg.name %>} ' +
                        'symbol to the global namespace.',
                    ' * @version <%= pkg.version %> (Released at ' +
                        '<%= grunt.template.today("isoDateTime") %>' +
                        '<%= grunt.template.today("o") %>)',
                    ' * @author <%= pkg.author.email %> ' +
                        '(<%= pkg.author.name %>)',
                    ' * @license <%= pkg.licenses[0].type %> ' +
                        '(See LICENSE file)',
                    ' */',
                    '',
                    "'use strict'; // Script mode syntax (Whole-library)",
                    '',
                    ''
                ].join(grunt.util.linefeed)
            },
            dist: {
                src: [
                    // Note: Don't specify 'lib/*.js'! It is order-sensitive.
                    'lib/main.js', // It has script mode and global namespace.
                    'lib/inscription.js',
                    'lib/factory.js',
                    'lib/formatter.js',
                    'lib/exception.js',
                    'lib/array.js',
                    'lib/pseudo-interface.js',
                    'lib/configuration.js',
                    'lib/stream.js',
                    'lib/date.js',
                    'lib/game.js',
                    'lib/agent.js',
                    'lib/tokenizer.js',
                    'lib/selector.js',
                    'lib/projector.js',
                    'lib/relation.js',
                    'lib/table.js',
                    'lib/chart.js',
                    'lib/template.js',
                    'lib/visualizer.js'
                ],
                dest: 'lib/kclv.js',
                nonull: true
            }
        },
        compress: {
            dist: {
                options: {
                    archive: '<%= pkg.name %>-<%= pkg.version %>.zip'
                },
                files: [
                    {
                        src: [
                            'README.html',
                            'LICENSE',
                            'configuration.json',
                            'visualizer.wsf',
                            'chart/**',
                            '<%= concat.dist.dest %>',
                            'lib/polyfill.js',
                            'template/**'
                        ]
                    }
                ]
            }
        },
        jshint: {
            self: [
                'Gruntfile.js',
            ],
            test: [
                'test/*.js',
                'test/.jshintrc',
                'test/.csshintrc'
            ],
            dist: [
                // 'configuration.json',
                'lib/*.js',
                '!<%= concat.dist.dest %>',
                '!lib/polyfill.js'
            ],
            options: {
                jshintrc: 'test/.jshintrc'
            }
        },
        csslint: {
            dist: {
                src: [
                    'template/chart.css'
                ],
                options: {
                    csslintrc: 'test/.csslintrc'
                }
            }
        },
        qunit: {
            files: [
                'test/harness.html'
            ]
        }
    });

    grunt.loadNpmTasks('grunt-curl');
    grunt.registerTask(
        'build',
        [
            'curl'
        ]
    );

    grunt.loadNpmTasks('grunt-markdown');
    grunt.loadNpmTasks('grunt-jsdoc');
    grunt.registerTask(
        'doc',
        [
            'markdown',
            'jsdoc'
        ]
    );

    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-compress');
    grunt.registerTask(
        'dist',
        [
            'clean',
            'markdown',
            'concat',
            'compress:dist'
        ]
    );

    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-csslint');
    grunt.loadNpmTasks('grunt-contrib-qunit');
    grunt.registerTask(
        'test',
        [
            'csslint',
            'jshint',
            'concat',
            'qunit'
        ]
    );
};
<|endoftext|>


<commit_before>"use strict";
var APP_ID = undefined;  // TODO replace with your app ID (OPTIONAL).

var GAME_LENGTH = 5;  // The number of questions per trivia game.
var GAME_STATES = {
    TRIVIA: "_TRIVIAMODE", // Asking trivia questions.
    START: "_STARTMODE", // Entry point, start the game.
    HELP: "_HELPMODE" // The user is asking for help.
};
var questions = require("./questions");

/**
 * When editing your questions pay attention to your punctuation. Make sure you use question marks or periods.
 * Make sure the first answer is the correct one. Set at least ANSWER_COUNT answers, any extras will be shuffled in.
 */
var languageString = {
    "en-US": {
        "translation": {
            "QUESTIONS" : questions,
            "GAME_NAME" : "Capital quiz by Elroy and Rocco", // Be sure to change this for your skill.
            "HELP_MESSAGE": "I will ask you %s questions. Respond with the correct answer.",
            "REPEAT_QUESTION_MESSAGE": "To repeat the last question, say, repeat. ",
            "ASK_MESSAGE_START": "Would you like to start playing? ",
            "HELP_REPROMPT": "To give an answer to a question, respond with the city name of your choice.",
            "STOP_MESSAGE": "Would you like to keep playing?",
            "CANCEL_MESSAGE": "Ok, let\'s play again soon.",
            "NO_MESSAGE": "Ok, we\'ll play another time. Goodbye!",
            "TRIVIA_UNHANDLED": "Try saying a number between 1 and %s",
            "HELP_UNHANDLED": "Say yes to continue, or no to end the game.",
            "START_UNHANDLED": "Say start to start a new game.",
            "NEW_GAME_MESSAGE": "Welcome to %s. ",
            "WELCOME_MESSAGE": "I will ask you %s questions, try to get as many right as you can. " +
            "You can run but you can't hide. Bitch! ",
            "ANSWER_CORRECT_MESSAGE": "correct. ",
            "ANSWER_WRONG_MESSAGE": "wrong. ",
            "CORRECT_ANSWER_MESSAGE": "The correct answer is %s: %s. ",
            "ANSWER_IS_MESSAGE": "That answer is ",
            "TELL_QUESTION_MESSAGE": "Question %s. %s ",
            "GAME_OVER_MESSAGE": "You got %s out of %s questions correct. Thank you for playing!",
            "SCORE_IS_MESSAGE": "Your score is %s.",
            "CAPITAL_QUESTION": "What is the capital of %s? ",
            "CAPITAL_ANSWER": "The capital of %s is %s. "
        }
    }
};

var Alexa = require("alexa-sdk");
var APP_ID = undefined;  // TODO replace with your app ID (OPTIONAL).

exports.handler = function(event, context, callback) {
    var alexa = Alexa.handler(event, context);
    alexa.appId = APP_ID;
    // To enable string internationalization (i18n) features, set a resources object.
    alexa.resources = languageString;
    alexa.registerHandlers(newSessionHandlers, startStateHandlers, triviaStateHandlers, helpStateHandlers);
    alexa.execute();
};

var newSessionHandlers = {
    "LaunchRequest": function () {
        this.handler.state = GAME_STATES.START;
        this.emitWithState("StartGame", true);
    }
    ,
    "AMAZON.StartOverIntent": function() {
        this.handler.state = GAME_STATES.START;
        this.emitWithState("StartGame", true);
    },
    "AMAZON.HelpIntent": function() {
        this.handler.state = GAME_STATES.HELP;
        this.emitWithState("helpTheUser", true);
    },
    "Unhandled": function () {
        var speechOutput = this.t("START_UNHANDLED");
        this.emit(":ask", speechOutput, speechOutput);
    }
};

var startStateHandlers = Alexa.CreateStateHandler(GAME_STATES.START, {
    "StartGame": function (newGame) {
        var speechOutput = newGame ? this.t("NEW_GAME_MESSAGE", this.t("GAME_NAME")) + this.t("WELCOME_MESSAGE", GAME_LENGTH.toString()) : "";
        // Select GAME_LENGTH questions for the game
        var translatedQuestions = this.t("QUESTIONS");
        var gameQuestions = populateGameQuestions(translatedQuestions);

        var currentQuestionIndex = 0;
        var country = translatedQuestions[gameQuestions[currentQuestionIndex]].country;
        var spokenQuestion = this.t("CAPITAL_QUESTION", country);
        var repromptText = this.t("TELL_QUESTION_MESSAGE", "1", spokenQuestion);

        speechOutput += repromptText;

        var answer = translatedQuestions[gameQuestions[currentQuestionIndex]].capital;
        var answerText = this.t("CAPITAL_ANSWER", country, answer);

        Object.assign(this.attributes, {
            "speechOutput": repromptText,
            "repromptText": repromptText,
            "currentQuestionIndex": currentQuestionIndex,
            "questions": gameQuestions,
            "score": 0,
            "correctAnswer": answer,
            "correctAnswerText": answerText
        });

        // Set the current state to trivia mode. The skill will now use handlers defined in triviaStateHandlers
        this.handler.state = GAME_STATES.TRIVIA;
        this.emit(":askWithCard", speechOutput, repromptText, this.t("GAME_NAME"), repromptText);
    }
});

var triviaStateHandlers = Alexa.CreateStateHandler(GAME_STATES.TRIVIA, {
    "AnswerIntent": function () {
        handleUserGuess.call(this, false);
    },
    "DontKnowIntent": function () {
        handleUserGuess.call(this, true);
    },
    "AMAZON.StartOverIntent": function () {
        this.handler.state = GAME_STATES.START;
        this.emitWithState("StartGame", false);
    },
    "AMAZON.RepeatIntent": function () {
        this.emit(":ask", this.attributes["speechOutput"], this.attributes["repromptText"]);
    },
    "AMAZON.HelpIntent": function () {
        this.handler.state = GAME_STATES.HELP;
        this.emitWithState("helpTheUser", false);
    },
    "AMAZON.StopIntent": function () {
        this.handler.state = GAME_STATES.HELP;
        var speechOutput = this.t("STOP_MESSAGE");
        this.emit(":ask", speechOutput, speechOutput);
    },
    "AMAZON.CancelIntent": function () {
        this.emit(":tell", this.t("CANCEL_MESSAGE"));
    },
    "Unhandled": function () {
        var speechOutput = this.t("TRIVIA_UNHANDLED", ANSWER_COUNT.toString());
        this.emit(":ask", speechOutput, speechOutput);
    },
    "SessionEndedRequest": function () {
        console.log("Session ended in trivia state: " + this.event.request.reason);
    }
});

var helpStateHandlers = Alexa.CreateStateHandler(GAME_STATES.HELP, {
    "helpTheUser": function (newGame) {
        var askMessage = newGame ? this.t("ASK_MESSAGE_START") : this.t("REPEAT_QUESTION_MESSAGE") + this.t("STOP_MESSAGE");
        var speechOutput = this.t("HELP_MESSAGE", GAME_LENGTH) + askMessage;
        var repromptText = this.t("HELP_REPROMPT") + askMessage;
        this.emit(":ask", speechOutput, repromptText);
    },
    "AMAZON.StartOverIntent": function () {
        this.handler.state = GAME_STATES.START;
        this.emitWithState("StartGame", false);
    },
    "AMAZON.RepeatIntent": function () {
        var newGame = (this.attributes["speechOutput"] && this.attributes["repromptText"]) ? false : true;
        this.emitWithState("helpTheUser", newGame);
    },
    "AMAZON.HelpIntent": function() {
        var newGame = (this.attributes["speechOutput"] && this.attributes["repromptText"]) ? false : true;
        this.emitWithState("helpTheUser", newGame);
    },
    "AMAZON.YesIntent": function() {
        if (this.attributes["speechOutput"] && this.attributes["repromptText"]) {
            this.handler.state = GAME_STATES.TRIVIA;
            this.emitWithState("AMAZON.RepeatIntent");
        } else {
            this.handler.state = GAME_STATES.START;
            this.emitWithState("StartGame", false);
        }
    },
    "AMAZON.NoIntent": function() {
        var speechOutput = this.t("NO_MESSAGE");
        this.emit(":tell", speechOutput);
    },
    "AMAZON.StopIntent": function () {
        var speechOutput = this.t("STOP_MESSAGE");
        this.emit(":ask", speechOutput, speechOutput);
    },
    "AMAZON.CancelIntent": function () {
        this.emit(":tell", this.t("CANCEL_MESSAGE"));
    },
    "Unhandled": function () {
        var speechOutput = this.t("HELP_UNHANDLED");
        this.emit(":ask", speechOutput, speechOutput);
    },
    "SessionEndedRequest": function () {
        console.log("Session ended in help state: " + this.event.request.reason);
    }
});

function handleUserGuess(userGaveUp) {
    var answerSlotValid = isAnswerSlotValid(this.event.request.intent);
    var speechOutput = "";
    var speechOutputAnalysis = "";
    var gameQuestions = this.attributes.questions;
    var currentScore = parseInt(this.attributes.score);
    var currentQuestionIndex = parseInt(this.attributes.currentQuestionIndex);
    var correctAnswerText = this.attributes.correctAnswerText;
    var translatedQuestions = this.t("QUESTIONS");

    if (answerSlotValid && this.event.request.intent.slots.Answer.value == this.attributes.correctAnswer) {
        currentScore++;
        speechOutputAnalysis = this.t("ANSWER_CORRECT_MESSAGE");
    } else {
        if (!userGaveUp) {
            speechOutputAnalysis = this.t("ANSWER_WRONG_MESSAGE");
        }

        speechOutputAnalysis += correctAnswerText;
    }

    // Check if we can exit the game session after GAME_LENGTH questions (zero-indexed)
    if (currentQuestionIndex == GAME_LENGTH - 1) {
        speechOutput = userGaveUp ? "" : this.t("ANSWER_IS_MESSAGE");
        speechOutput += speechOutputAnalysis + this.t("GAME_OVER_MESSAGE", currentScore.toString(), GAME_LENGTH.toString());

        this.emit(":tell", speechOutput)
    } else {
        currentQuestionIndex += 1;
        var country = translatedQuestions[gameQuestions[currentQuestionIndex]].country;
        var spokenQuestion = this.t("CAPITAL_QUESTION", country);
        var questionIndexForSpeech = currentQuestionIndex + 1;
        var repromptText = this.t("TELL_QUESTION_MESSAGE", questionIndexForSpeech, spokenQuestion);

        speechOutput += userGaveUp ? "" : this.t("ANSWER_IS_MESSAGE");
        speechOutput += speechOutputAnalysis + this.t("SCORE_IS_MESSAGE", currentScore.toString()) + repromptText;

        var answer = translatedQuestions[gameQuestions[currentQuestionIndex]].capital;
        var answerText = this.t("CAPITAL_ANSWER", country, answer);
        Object.assign(this.attributes, {
            "speechOutput": repromptText,
            "repromptText": repromptText,
            "currentQuestionIndex": currentQuestionIndex,
            "questions": gameQuestions,
            "score": currentScore,
            "correctAnswer": answer,
            "correctAnswerText": answerText
        });

        this.emit(":askWithCard", speechOutput, repromptText, this.t("GAME_NAME"), repromptText);
    }
}

function populateGameQuestions(translatedQuestions) {
    var gameQuestions = [];
    var indexList = [];
    var index = translatedQuestions.length;

    if (GAME_LENGTH > index){
        throw new Error("Invalid Game Length.");
    }

    for (var i = 0; i < translatedQuestions.length; i++){
        indexList.push(i);
    }

    // Pick GAME_LENGTH random questions from the list to ask the user, make sure there are no repeats.
    for (var j = 0; j < GAME_LENGTH; j++){
        var rand = Math.floor(Math.random() * index);
        index -= 1;

        var temp = indexList[index];
        indexList[index] = indexList[rand];
        indexList[rand] = temp;
        gameQuestions.push(indexList[index]);
    }

    return gameQuestions;
}

function isAnswerSlotValid(intent) {
    return intent && intent.slots && intent.slots.Answer && intent.slots.Answer.value;
}<commit_msg>Translation changes<commit_after>"use strict";
var APP_ID = undefined;  // TODO replace with your app ID (OPTIONAL).

var GAME_LENGTH = 5;  // The number of questions per trivia game.
var GAME_STATES = {
    TRIVIA: "_TRIVIAMODE", // Asking trivia questions.
    START: "_STARTMODE", // Entry point, start the game.
    HELP: "_HELPMODE" // The user is asking for help.
};
var questions = require("./questions");

/**
 * When editing your questions pay attention to your punctuation. Make sure you use question marks or periods.
 * Make sure the first answer is the correct one. Set at least ANSWER_COUNT answers, any extras will be shuffled in.
 */
var languageString = {
    "en-US": {
        "translation": {
            "QUESTIONS" : questions,
            "GAME_NAME" : "Capital quiz by Elroy and Rocco", // Be sure to change this for your skill.
            "HELP_MESSAGE": "I will ask you %s questions. Respond with the correct answer. ",
            "REPEAT_QUESTION_MESSAGE": "To repeat the last question, say, repeat. ",
            "ASK_MESSAGE_START": "Would you like to start playing? ",
            "HELP_REPROMPT": "To give an answer to a question, respond with the city name of your choice. ",
            "STOP_MESSAGE": "Would you like to keep playing? ",
            "CANCEL_MESSAGE": "Ok, let\'s play again soon. ",
            "NO_MESSAGE": "Ok, we\'ll play another time. Goodbye! ",
            "TRIVIA_UNHANDLED": "Try saying a number between 1 and %s. ",
            "HELP_UNHANDLED": "Say yes to continue, or no to end the game. ",
            "START_UNHANDLED": "Say start to start a new game. ",
            "NEW_GAME_MESSAGE": "Welcome to %s. ",
            "WELCOME_MESSAGE": "I will ask you %s questions, try to get as many right as you can. " +
            "Let the games begin! ",
            "ANSWER_CORRECT_MESSAGE": "correct. ",
            "ANSWER_WRONG_MESSAGE": "wrong. ",
            "CORRECT_ANSWER_MESSAGE": "The correct answer is %s: %s. ",
            "ANSWER_IS_MESSAGE": "That answer is ",
            "TELL_QUESTION_MESSAGE": "Question %s. %s ",
            "GAME_OVER_MESSAGE": "You got %s out of %s questions correct. Thank you for playing! " +
            "Have a nice evening Olaf, Elroy and Rocco. ",
            "SCORE_IS_MESSAGE": "Your score is %s. ",
            "CAPITAL_QUESTION": "What is the capital of %s? ",
            "CAPITAL_ANSWER": "The capital of %s is %s. "
        }
    }
};

var Alexa = require("alexa-sdk");
var APP_ID = undefined;  // TODO replace with your app ID (OPTIONAL).

exports.handler = function(event, context, callback) {
    var alexa = Alexa.handler(event, context);
    alexa.appId = APP_ID;
    // To enable string internationalization (i18n) features, set a resources object.
    alexa.resources = languageString;
    alexa.registerHandlers(newSessionHandlers, startStateHandlers, triviaStateHandlers, helpStateHandlers);
    alexa.execute();
};

var newSessionHandlers = {
    "LaunchRequest": function () {
        this.handler.state = GAME_STATES.START;
        this.emitWithState("StartGame", true);
    }
    ,
    "AMAZON.StartOverIntent": function() {
        this.handler.state = GAME_STATES.START;
        this.emitWithState("StartGame", true);
    },
    "AMAZON.HelpIntent": function() {
        this.handler.state = GAME_STATES.HELP;
        this.emitWithState("helpTheUser", true);
    },
    "Unhandled": function () {
        var speechOutput = this.t("START_UNHANDLED");
        this.emit(":ask", speechOutput, speechOutput);
    }
};

var startStateHandlers = Alexa.CreateStateHandler(GAME_STATES.START, {
    "StartGame": function (newGame) {
        var speechOutput = newGame ? this.t("NEW_GAME_MESSAGE", this.t("GAME_NAME")) + this.t("WELCOME_MESSAGE", GAME_LENGTH.toString()) : "";
        // Select GAME_LENGTH questions for the game
        var translatedQuestions = this.t("QUESTIONS");
        var gameQuestions = populateGameQuestions(translatedQuestions);

        var currentQuestionIndex = 0;
        var country = translatedQuestions[gameQuestions[currentQuestionIndex]].country;
        var spokenQuestion = this.t("CAPITAL_QUESTION", country);
        var repromptText = this.t("TELL_QUESTION_MESSAGE", "1", spokenQuestion);

        speechOutput += repromptText;

        var answer = translatedQuestions[gameQuestions[currentQuestionIndex]].capital;
        var answerText = this.t("CAPITAL_ANSWER", country, answer);

        Object.assign(this.attributes, {
            "speechOutput": repromptText,
            "repromptText": repromptText,
            "currentQuestionIndex": currentQuestionIndex,
            "questions": gameQuestions,
            "score": 0,
            "correctAnswer": answer,
            "correctAnswerText": answerText
        });

        // Set the current state to trivia mode. The skill will now use handlers defined in triviaStateHandlers
        this.handler.state = GAME_STATES.TRIVIA;
        this.emit(":askWithCard", speechOutput, repromptText, this.t("GAME_NAME"), repromptText);
    }
});

var triviaStateHandlers = Alexa.CreateStateHandler(GAME_STATES.TRIVIA, {
    "AnswerIntent": function () {
        handleUserGuess.call(this, false);
    },
    "DontKnowIntent": function () {
        handleUserGuess.call(this, true);
    },
    "AMAZON.StartOverIntent": function () {
        this.handler.state = GAME_STATES.START;
        this.emitWithState("StartGame", false);
    },
    "AMAZON.RepeatIntent": function () {
        this.emit(":ask", this.attributes["speechOutput"], this.attributes["repromptText"]);
    },
    "AMAZON.HelpIntent": function () {
        this.handler.state = GAME_STATES.HELP;
        this.emitWithState("helpTheUser", false);
    },
    "AMAZON.StopIntent": function () {
        this.handler.state = GAME_STATES.HELP;
        var speechOutput = this.t("STOP_MESSAGE");
        this.emit(":ask", speechOutput, speechOutput);
    },
    "AMAZON.CancelIntent": function () {
        this.emit(":tell", this.t("CANCEL_MESSAGE"));
    },
    "Unhandled": function () {
        var speechOutput = this.t("TRIVIA_UNHANDLED", ANSWER_COUNT.toString());
        this.emit(":ask", speechOutput, speechOutput);
    },
    "SessionEndedRequest": function () {
        console.log("Session ended in trivia state: " + this.event.request.reason);
    }
});

var helpStateHandlers = Alexa.CreateStateHandler(GAME_STATES.HELP, {
    "helpTheUser": function (newGame) {
        var askMessage = newGame ? this.t("ASK_MESSAGE_START") : this.t("REPEAT_QUESTION_MESSAGE") + this.t("STOP_MESSAGE");
        var speechOutput = this.t("HELP_MESSAGE", GAME_LENGTH) + askMessage;
        var repromptText = this.t("HELP_REPROMPT") + askMessage;
        this.emit(":ask", speechOutput, repromptText);
    },
    "AMAZON.StartOverIntent": function () {
        this.handler.state = GAME_STATES.START;
        this.emitWithState("StartGame", false);
    },
    "AMAZON.RepeatIntent": function () {
        var newGame = (this.attributes["speechOutput"] && this.attributes["repromptText"]) ? false : true;
        this.emitWithState("helpTheUser", newGame);
    },
    "AMAZON.HelpIntent": function() {
        var newGame = (this.attributes["speechOutput"] && this.attributes["repromptText"]) ? false : true;
        this.emitWithState("helpTheUser", newGame);
    },
    "AMAZON.YesIntent": function() {
        if (this.attributes["speechOutput"] && this.attributes["repromptText"]) {
            this.handler.state = GAME_STATES.TRIVIA;
            this.emitWithState("AMAZON.RepeatIntent");
        } else {
            this.handler.state = GAME_STATES.START;
            this.emitWithState("StartGame", false);
        }
    },
    "AMAZON.NoIntent": function() {
        var speechOutput = this.t("NO_MESSAGE");
        this.emit(":tell", speechOutput);
    },
    "AMAZON.StopIntent": function () {
        var speechOutput = this.t("STOP_MESSAGE");
        this.emit(":ask", speechOutput, speechOutput);
    },
    "AMAZON.CancelIntent": function () {
        this.emit(":tell", this.t("CANCEL_MESSAGE"));
    },
    "Unhandled": function () {
        var speechOutput = this.t("HELP_UNHANDLED");
        this.emit(":ask", speechOutput, speechOutput);
    },
    "SessionEndedRequest": function () {
        console.log("Session ended in help state: " + this.event.request.reason);
    }
});

function handleUserGuess(userGaveUp) {
    var answerSlotValid = isAnswerSlotValid(this.event.request.intent);
    var speechOutput = "";
    var speechOutputAnalysis = "";
    var gameQuestions = this.attributes.questions;
    var currentScore = parseInt(this.attributes.score);
    var currentQuestionIndex = parseInt(this.attributes.currentQuestionIndex);
    var correctAnswerText = this.attributes.correctAnswerText;
    var translatedQuestions = this.t("QUESTIONS");

    if (answerSlotValid && this.event.request.intent.slots.Answer.value == this.attributes.correctAnswer) {
        currentScore++;
        speechOutputAnalysis = this.t("ANSWER_CORRECT_MESSAGE");
    } else {
        if (!userGaveUp) {
            speechOutputAnalysis = this.t("ANSWER_WRONG_MESSAGE");
        }

        speechOutputAnalysis += correctAnswerText;
    }

    // Check if we can exit the game session after GAME_LENGTH questions (zero-indexed)
    if (currentQuestionIndex == GAME_LENGTH - 1) {
        speechOutput = userGaveUp ? "" : this.t("ANSWER_IS_MESSAGE");
        speechOutput += speechOutputAnalysis + this.t("GAME_OVER_MESSAGE", currentScore.toString(), GAME_LENGTH.toString());

        this.emit(":tell", speechOutput)
    } else {
        currentQuestionIndex += 1;
        var country = translatedQuestions[gameQuestions[currentQuestionIndex]].country;
        var spokenQuestion = this.t("CAPITAL_QUESTION", country);
        var questionIndexForSpeech = currentQuestionIndex + 1;
        var repromptText = this.t("TELL_QUESTION_MESSAGE", questionIndexForSpeech, spokenQuestion);

        speechOutput += userGaveUp ? "" : this.t("ANSWER_IS_MESSAGE");
        speechOutput += speechOutputAnalysis + this.t("SCORE_IS_MESSAGE", currentScore.toString()) + repromptText;

        var answer = translatedQuestions[gameQuestions[currentQuestionIndex]].capital;
        var answerText = this.t("CAPITAL_ANSWER", country, answer);
        Object.assign(this.attributes, {
            "speechOutput": repromptText,
            "repromptText": repromptText,
            "currentQuestionIndex": currentQuestionIndex,
            "questions": gameQuestions,
            "score": currentScore,
            "correctAnswer": answer,
            "correctAnswerText": answerText
        });

        this.emit(":askWithCard", speechOutput, repromptText, this.t("GAME_NAME"), repromptText);
    }
}

function populateGameQuestions(translatedQuestions) {
    var gameQuestions = [];
    var indexList = [];
    var index = translatedQuestions.length;

    if (GAME_LENGTH > index){
        throw new Error("Invalid Game Length.");
    }

    for (var i = 0; i < translatedQuestions.length; i++){
        indexList.push(i);
    }

    // Pick GAME_LENGTH random questions from the list to ask the user, make sure there are no repeats.
    for (var j = 0; j < GAME_LENGTH; j++){
        var rand = Math.floor(Math.random() * index);
        index -= 1;

        var temp = indexList[index];
        indexList[index] = indexList[rand];
        indexList[rand] = temp;
        gameQuestions.push(indexList[index]);
    }

    return gameQuestions;
}

function isAnswerSlotValid(intent) {
    return intent && intent.slots && intent.slots.Answer && intent.slots.Answer.value;
}<|endoftext|>


<commit_before>module.exports = function (grunt) {
    grunt.initConfig({
        "pkg": grunt.file.readJSON("package.json"),
        "meta": {
            "paths": {
                "source": "Source",
                "dist": "Distribution"
            }
        },
        "tslint": {
            "options": {
                "configuration": grunt.file.readJSON("tslint.json")
            },
            "files": {
                "src": ["<%= meta.paths.source %>/<%= pkg.name %>.ts"]
            }
        },
        "typescript": {
            "base": {
                "src": "<%= meta.paths.source %>/<%= pkg.name %>.ts",
                "dest": "<%= meta.paths.source %>/<%= pkg.name %>.js"
            }
        },
        "clean": ["<%= meta.paths.dist %>"],
        "copy": {
            "default": {
                "files": [{
                    "src": "<%= meta.paths.source %>/<%= pkg.name %>.ts",
                    "dest": "<%= meta.paths.dist %>/<%= pkg.name %>-<%= pkg.version %>.ts"
                }, {
                    "src": "<%= meta.paths.source %>/References/*.ts",
                    "dest": "<%= meta.paths.dist %>/",
                    "expand": true,
                    "flatten": true
                }, {
                    "src": "README.md",
                    "dest": "<%= meta.paths.dist %>/"
                }, {
                    "src": "README.md",
                    "dest": "<%= meta.paths.source %>/"
                }, {
                    "src": "LICENSE.txt",
                    "dest": "<%= meta.paths.dist %>/"
                }, {
                    "src": "LICENSE.txt",
                    "dest": "<%= meta.paths.source %>/"
                }]
            }
        },
        "uglify": {
            "options": {
                "compress": true
            },
            "dist": {
                "files": {
                    "<%= meta.paths.dist %>/<%= pkg.name %>-<%= pkg.version %>.min.js": ["<%= meta.paths.source %>/<%= pkg.name %>.js"],
                }
            }
        },
        "preprocess": {
            "dist": {
                "src": "<%= meta.paths.dist %>/<%= pkg.name %>-<%= pkg.version %>.ts",
                "dest": "<%= meta.paths.dist %>/<%= pkg.name %>-<%= pkg.version %>.ts"
            }
        },
        "mocha_phantomjs": {
            "all": ["Tests/*.html"]
        }
    });

    grunt.loadNpmTasks("grunt-contrib-clean");
    grunt.loadNpmTasks("grunt-contrib-copy");
    grunt.loadNpmTasks("grunt-contrib-uglify");
    grunt.loadNpmTasks("grunt-mocha-phantomjs");
    grunt.loadNpmTasks("grunt-preprocess");
    grunt.loadNpmTasks("grunt-tslint");
    grunt.loadNpmTasks("grunt-typescript");
    grunt.registerTask("default", [
        "tslint", "typescript", "clean", "copy", "uglify", "preprocess", "mocha_phantomjs"
    ]);
};<commit_msg>Added JS maps to grunt build<commit_after>module.exports = function (grunt) {
    grunt.initConfig({
        "pkg": grunt.file.readJSON("package.json"),
        "meta": {
            "paths": {
                "source": "Source",
                "dist": "Distribution"
            }
        },
        "tslint": {
            "options": {
                "configuration": grunt.file.readJSON("tslint.json")
            },
            "files": {
                "src": ["<%= meta.paths.source %>/<%= pkg.name %>.ts"]
            }
        },
        "typescript": {
            "base": {
                "src": "<%= meta.paths.source %>/<%= pkg.name %>.ts",
                "dest": "<%= meta.paths.source %>/<%= pkg.name %>.js"
            }
        },
        "clean": ["<%= meta.paths.dist %>"],
        "copy": {
            "default": {
                "files": [{
                    "src": "<%= meta.paths.source %>/<%= pkg.name %>.js",
                    "dest": "<%= meta.paths.dist %>/<%= pkg.name %>-<%= pkg.version %>.js"
                }, {
                    "src": "<%= meta.paths.source %>/<%= pkg.name %>.ts",
                    "dest": "<%= meta.paths.dist %>/<%= pkg.name %>-<%= pkg.version %>.ts"
                }, {
                    "src": "<%= meta.paths.source %>/References/*.ts",
                    "dest": "<%= meta.paths.dist %>/",
                    "expand": true,
                    "flatten": true
                }, {
                    "src": "README.md",
                    "dest": "<%= meta.paths.dist %>/"
                }, {
                    "src": "README.md",
                    "dest": "<%= meta.paths.source %>/"
                }, {
                    "src": "LICENSE.txt",
                    "dest": "<%= meta.paths.dist %>/"
                }, {
                    "src": "LICENSE.txt",
                    "dest": "<%= meta.paths.source %>/"
                }]
            }
        },
        "uglify": {
            "options": {
                "compress": true,
                "screwIE8": true,
                "sourceMap": true
            },
            "dist": {
                "files": {
                    "<%= meta.paths.dist %>/<%= pkg.name %>-<%= pkg.version %>.min.js": ["<%= meta.paths.source %>/<%= pkg.name %>.js"],
                }
            }
        },
        "preprocess": {
            "dist": {
                "src": "<%= meta.paths.dist %>/<%= pkg.name %>-<%= pkg.version %>.ts",
                "dest": "<%= meta.paths.dist %>/<%= pkg.name %>-<%= pkg.version %>.ts"
            }
        },
        "mocha_phantomjs": {
            "all": ["Tests/*.html"]
        }
    });

    grunt.loadNpmTasks("grunt-contrib-clean");
    grunt.loadNpmTasks("grunt-contrib-copy");
    grunt.loadNpmTasks("grunt-contrib-uglify");
    grunt.loadNpmTasks("grunt-mocha-phantomjs");
    grunt.loadNpmTasks("grunt-preprocess");
    grunt.loadNpmTasks("grunt-tslint");
    grunt.loadNpmTasks("grunt-typescript");
    grunt.registerTask("default", [
        "tslint", "typescript", "clean", "copy", "uglify", "preprocess", "mocha_phantomjs"
    ]);
};<|endoftext|>