<commit_before>#!/usr/bin/env node
'use strict';

var _minimist = require('minimist');

var _minimist2 = _interopRequireDefault(_minimist);

var _util = require('util');

var _index = require('./index');

var _index2 = _interopRequireDefault(_index);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var args = (0, _minimist2.default)(process.argv.slice(2));

var defaultConfig = {
  provider: 'saucelabs',
  code: 'var x = 3; window.__results__.push(window.navigator.userAgent);',
  browsers: {
    'Google Chrome': {
      name: 'chrome',
      versions: {
        latest: '46'
      },
      os: 'Windows'
    },
    'Mozilla Firefox': {
      name: 'Firefox',
      versions: {
        latest: '42'
      },
      os: 'Windows'
    },
    'Microsoft Internet Explorer': {
      name: 'Internet Explorer',
      versions: {
        latest: '11',
        previous: '10',
        old: '9'
      },
      os: 'Windows'
    },
    'Apple Safari': {
      name: 'Safari',
      versions: {
        latest: '9',
        previous: '8',
        old: '7'
      },
      os: 'OS X'
    },
    'Microsoft Edge': {
      name: 'Microsoft Edge',
      versions: {
        latest: '20', // works in SL
        previous: '12' // works in BS
      },
      os: 'Windows'
    },
    'Safari Mobile': {
      name: 'Safari',
      versions: {
        latest: {
          osVersion: '8.3',
          devices: ['iPhone', 'iPad']
        },
        previous: {
          osVersion: '7.0',
          devices: ['iPhone', 'iPad']
        }
      },
      os: 'iOS'
    },
    'Android Browser': {
      name: 'Android Browser',
      versions: {
        'Lollipop': '5.0',
        'Jelly Bean': 'Jelly Bean'
      }
    }
  }
};

var config = {
  credentials: {
    userName: args.user || args.u,
    accessToken: args.token || args.t
  },
  browsers: args.code || args.b ? JSON.parse(args.code || args.b) : defaultConfig.browsers,
  code: args.code || args.c || defaultConfig.code,
  url: args.code || args.s || undefined,
  provider: args.provider || args.p || defaultConfig.provider,
  verbose: true,
  timeout: args.code || args.s ? 2000 : 1000
};

(0, _index2.default)(config).then(function (results) {
  return console.log((0, _util.inspect)(results, { depth: 10 })), process.exit(0);
}, function (err) {
  return console.error(err), process.exit(1);
});<commit_msg>Build dist/<commit_after>#!/usr/bin/env node
'use strict';

var _minimist = require('minimist');

var _minimist2 = _interopRequireDefault(_minimist);

var _util = require('util');

var _index = require('./index');

var _index2 = _interopRequireDefault(_index);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var args = (0, _minimist2.default)(process.argv.slice(2));

var defaultConfig = {
  provider: 'saucelabs',
  code: 'var x = 3; window.__results__.push(window.navigator.userAgent);',
  browsers: {
    'Google Chrome': {
      name: 'chrome',
      versions: {
        latest: '46'
      },
      os: 'Windows'
    },
    'Mozilla Firefox': {
      name: 'Firefox',
      versions: {
        latest: '42'
      },
      os: 'Windows'
    },
    'Microsoft Internet Explorer': {
      name: 'Internet Explorer',
      versions: {
        latest: '11',
        previous: '10',
        old: '9'
      },
      os: 'Windows'
    },
    'Apple Safari': {
      name: 'Safari',
      versions: {
        latest: '9',
        previous: '8',
        old: '7'
      },
      os: 'OS X'
    },
    'Microsoft Edge': {
      name: 'Microsoft Edge',
      versions: {
        latest: '20', // works in SL
        previous: '12' // works in BS
      },
      os: 'Windows'
    },
    'Safari Mobile': {
      name: 'Safari',
      versions: {
        latest: {
          osVersion: '8.3',
          devices: ['iPhone', 'iPad']
        },
        previous: {
          osVersion: '7.0',
          devices: ['iPhone', 'iPad']
        }
      },
      os: 'iOS'
    },
    'Android Browser': {
      name: 'Android Browser',
      versions: {
        'Lollipop': '5.0',
        'Jelly Bean': 'Jelly Bean'
      }
    }
  }
};

var config = {
  credentials: {
    userName: args.user || args.u,
    accessToken: args.token || args.t
  },
  browsers: args.code || args.b ? JSON.parse(args.code || args.b) : defaultConfig.browsers,
  code: args.code || args.c || defaultConfig.code,
  url: args.code || args.s || void 0,
  provider: args.provider || args.p || defaultConfig.provider,
  verbose: true,
  timeout: args.code || args.s ? 2000 : 1000
};

(0, _index2.default)(config).then(function (results) {
  return console.log((0, _util.inspect)(results, { depth: 10 })), process.exit(0);
}, function (err) {
  return console.error(err), process.exit(1);
});<|endoftext|>


<commit_before>//Angela Fan

var gene_name = "CKS1B";

//find the files the gene is in
d3.csv("/Documents/Bradner_work/hockey-sticks/lookup_table.csv", function(error, data){
	//MM1S_H3K27AC_DMSO_HOCKEY.csv
	var input = gene_name;

	var data_length = data.length;

	var file_name_array = [];

	for (var i = 0; i < data.length; i++) {
		//console.log("hello")
		if (data[i].gene == input) {
			if (data[i].file) {

				file_name_array.push(String(data[i].file).split(";"))

				//file_name_array.push(data[i].file);
				//console.log(data[i].file)
				break;
			}
		}
	}

	var ranking_array = [];

	for (var i = 0; i < file_name_array[0].length; i++) {

		var current_file = file_name_array[0][i];

		//console.log(current_file)

		d3.csv("/Documents/Bradner_work/hockey-sticks/" + current_file, function(error, current_data) {

			//console.log(current_data)

			current_data.forEach(function(d) {

				var genes = d.PROXIMAL_GENES.split(";");
				// if (i==1) {
				// 	console.log(genes)
				// }
				for (var j = 0; j < genes.length; j++) {
					if (i == 1) {
						//console.log(genes[j])
					}
					if (genes[j] == gene_name) {

						console.log("hello")

						ranking_array.push({"filename": current_file, "rank": +d.RANK, "prox_genes": d.PROXIMAL_GENES,
							"super": +d.IS_SUPER, "signal": +d.SIGNAL, "top_gene": d.TOP_GENE, "function": d.PROXIMAL_FUNCTION,
							"start": +d.START, "stop": +d.STOP, "chromosome": d.CHROM});

						//console.log(ranking_array)

						var current_file_name = current_file.split("_HOCKEY")[0];

						current_file_name = "/Documents/Bradner_work/hockey-sticks/" + current_file_name + "_plots/" + "SE_plots_" + current_file_name + "_" + d.REGION_ID + ".pdf";

						$("#pdf_window")
							.append('
 <object data=' + current_file_name +
							' type="application/pdf" width="840px" height="580"> alt : test.pdf </object>
' )

					}
				}

			});

			//console.log(ranking_array)

			tip = d3.tip().attr('class', 'd3-tip');

			var margin = {top: 50, right: 50, bottom: 50, left: 100},
			    width = 1200 - margin.left - margin.right,
			    height = 300 - margin.top - margin.bottom;

			var x = d3.scale.ordinal()
			    .rangeRoundBands([0, width], .1);

			var y = d3.scale.linear()
			    .range([height, 0]);

			var xAxis = d3.svg.axis()
			    .scale(x)
			    .orient("bottom")
			    .tickFormat("");

			var yAxis = d3.svg.axis()
			    .scale(y)
			    .orient("left")
			    .outerTickSize([0]);

			var svg = d3.select("body").append("svg")
			    .attr("width", width + margin.left + margin.right)
			    .attr("height", height + margin.top + margin.bottom)
			  .append("g")
			    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

			svg.call(tip)

			x.domain([0, ranking_array.length]);
			y.domain([0, d3.max(ranking_array, function(d) { return d.rank; })]);

			svg.append("g")
		      	.attr("class", "x axis")
		      	.attr("transform", "translate(0," + height + ")")
		      	.call(xAxis)
		      	.append("text")
		      	.attr("x", 1000)
		      	.attr("y", 15)
		      	.style("text-anchor", "middle")
		      	.text("Files");

			svg.append("g")
		      	.attr("class", "y axis")
		      	.call(yAxis)
		    	.append("text")
		      	.attr("transform", "rotate(-90)")
		      	.attr("dy", "-3.71em")
		      	.style("text-anchor", "end")
		      	.text("Super-enhancer rank");

			svg.selectAll(".bar")
			    .data(ranking_array)
			    .enter().append("rect")
			    .attr("class", "bar")
			    .attr("x", function(d, i) {
			    	return x(i)
			    })
			    .attr("width", x.rangeBand()-2)
			    .attr("y", function(d) { return y(d.rank); })
			    .attr("height", function(d) { return height - y(d.rank); })
			    .on("mouseover", function(d) {

			    	console.log(d)

			    	tip.html("File: " + d.filename + "
Rank: " + d.rank)

			    	return tip.show(d)

			    })
			    .on("mouseout", function(d) {
			    	return tip.hide(d)
			    });

			function type(d) {
			  d.frequency = +d.rank;
			  return d;
			}

			d3.select("input#by_rank").on("change", change_rank);

			function change_rank() {

				// Copy-on-write since tweens are evaluated after a delay.
				var x0 = x.domain(data.sort(this.checked
				    ? function(a, b) { return b.rank - a.rank; }
				    : function(a, b) { return d3.ascending(a.file, b.file); })
				    .map(function(d) { return d.file; }))
				    .copy();

				var transition = svg.transition().duration(750),
				    delay = function(d, i) { return i * 50; };

				transition.selectAll(".bar")
				    .delay(delay)
				    .attr("x", function(d) { return x0(d.file); });

				transition.select(".x.axis")
				    .call(xAxis)
				  .selectAll("g")
				    .delay(delay);

			}

			// d3.select("input#cost").on("change", change_cost);

			// 	function change_cost() {

			// 	    // Copy-on-write since tweens are evaluated after a delay.
			// 	    var x0 = item_percent_x.domain(items.sort(this.checked
			// 	        ? function(a, b) {
			// 	        	if (a.dname == "Aegis of the Immortal" || a.dname == "Cheese") {
			// 	        		a.cost = 100000;
			// 	        	}
			// 	        	if (b.dname == "Aegis of the Immortal" || b.dname == "Cheese") {
			// 	        		b.cost = 100000;
			// 	        	}
			// 	        	return d3.ascending(a.cost, b.cost);
			// 	        }
			// 	        : function(a, b) { return d3.ascending(a.name, b.name); })
			// 	        .map(function(d) { return d.name; }))
			// 	        .copy();

			// 	    var transition = svg_item_percent.transition().duration(750),
			// 	        delay = function(d, i) { return i * 10; };

			// 	    transition.selectAll(".bar")
			// 	        .delay(delay)
			// 	        .attr("x", function(d) { return x0(d.name); });

			// 	    transition.select(".x.axis")
			// 	        .call(item_percent_xAxis)
			// 	      .selectAll("g")
			// 	        .delay(delay);
			// 	  }

		})

	}

});

<commit_msg>fixed pdf files not appearing correctly<commit_after>//Angela Fan

var gene_name = "CKS1B";

//find the files the gene is in
d3.csv("/Documents/Bradner_work/hockey-sticks/lookup_table.csv", function(error, data){
	//MM1S_H3K27AC_DMSO_HOCKEY.csv
	var input = gene_name;

	var data_length = data.length;

	var file_name_array = [];

	for (var i = 0; i < data.length; i++) {
		//console.log("hello")
		if (data[i].gene == input) {
			if (data[i].file) {

				file_name_array.push(String(data[i].file).split(";"))

				//file_name_array.push(data[i].file);
				//console.log(data[i].file)
				break;
			}
		}
	}

	var ranking_array = [];

	for (var i = 0; i < file_name_array[0].length; i++) {

		var current_file = file_name_array[0][i];

		console.log(i)

		console.log(current_file)

		//console.log(current_file)

		plot(current_file)

		function plot(current_file) {
			d3.csv("/Documents/Bradner_work/hockey-sticks/" + current_file, function(error, current_data) {

				console.log(current_file)

				console.log(i)

				current_data.forEach(function(d) {

					var genes = d.PROXIMAL_GENES.split(";");
					// if (i==1) {
					// 	console.log(genes)
					// }
					for (var j = 0; j < genes.length; j++) {
						if (i == 1) {
							//console.log(genes[j])
						}
						if (genes[j] == gene_name) {

							console.log(current_file)

							ranking_array.push({"filename": current_file, "rank": +d.RANK, "prox_genes": d.PROXIMAL_GENES,
								"super": +d.IS_SUPER, "signal": +d.SIGNAL, "top_gene": d.TOP_GENE, "function": d.PROXIMAL_FUNCTION,
								"start": +d.START, "stop": +d.STOP, "chromosome": d.CHROM});

							//console.log(ranking_array)

							var current_file_name = current_file.split("_HOCKEY")[0];

							console.log(d)

							current_file_name = "/Documents/Bradner_work/hockey-sticks/" + current_file_name + "_plots/" + "SE_plots_" + current_file_name + "_" + d.REGION_ID + ".pdf";

							$("#pdf_window")
								.append('
 <object data=' + current_file_name +
								' type="application/pdf" width="840px" height="580"> alt : test.pdf </object>
' )

						}
					}

				});

				//console.log(ranking_array)

				tip = d3.tip().attr('class', 'd3-tip');

				var margin = {top: 50, right: 50, bottom: 50, left: 100},
				    width = 1200 - margin.left - margin.right,
				    height = 300 - margin.top - margin.bottom;

				var x = d3.scale.ordinal()
				    .rangeRoundBands([0, width], .1);

				var y = d3.scale.linear()
				    .range([height, 0]);

				var xAxis = d3.svg.axis()
				    .scale(x)
				    .orient("bottom")
				    .tickFormat("");

				var yAxis = d3.svg.axis()
				    .scale(y)
				    .orient("left")
				    .outerTickSize([0]);

				var svg = d3.select("body").append("svg")
				    .attr("width", width + margin.left + margin.right)
				    .attr("height", height + margin.top + margin.bottom)
				  .append("g")
				    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

				svg.call(tip)

				x.domain([0, ranking_array.length]);
				y.domain([0, d3.max(ranking_array, function(d) { return d.rank; })]);

				svg.append("g")
			      	.attr("class", "x axis")
			      	.attr("transform", "translate(0," + height + ")")
			      	.call(xAxis)
			      	.append("text")
			      	.attr("x", 1000)
			      	.attr("y", 15)
			      	.style("text-anchor", "middle")
			      	.text("Files");

				svg.append("g")
			      	.attr("class", "y axis")
			      	.call(yAxis)
			    	.append("text")
			      	.attr("transform", "rotate(-90)")
			      	.attr("dy", "-3.71em")
			      	.style("text-anchor", "end")
			      	.text("Super-enhancer rank");

				svg.selectAll(".bar")
				    .data(ranking_array)
				    .enter().append("rect")
				    .attr("class", "bar")
				    .attr("x", function(d, i) {
				    	return x(i)
				    })
				    .attr("width", x.rangeBand()-2)
				    .attr("y", function(d) { return y(d.rank); })
				    .attr("height", function(d) { return height - y(d.rank); })
				    .on("mouseover", function(d) {

				    	console.log(d)

				    	tip.html("File: " + d.filename + "
Rank: " + d.rank)

				    	return tip.show(d)

				    })
				    .on("mouseout", function(d) {
				    	return tip.hide(d)
				    });

				function type(d) {
				  d.frequency = +d.rank;
				  return d;
				}

				d3.select("input#by_rank").on("change", change_rank);

				function change_rank() {

					// Copy-on-write since tweens are evaluated after a delay.
					var x0 = x.domain(data.sort(this.checked
					    ? function(a, b) { return b.rank - a.rank; }
					    : function(a, b) { return d3.ascending(a.file, b.file); })
					    .map(function(d) { return d.file; }))
					    .copy();

					var transition = svg.transition().duration(750),
					    delay = function(d, i) { return i * 50; };

					transition.selectAll(".bar")
					    .delay(delay)
					    .attr("x", function(d) { return x0(d.file); });

					transition.select(".x.axis")
					    .call(xAxis)
					  .selectAll("g")
					    .delay(delay);

				}

			})
		}

	}

});

<|endoftext|>


<commit_before>// @flow
import React from 'react';
import classnames from 'classnames';

import Markdown from 'components/Markdown';
import {
  buildNavHref,
  getType,
  isImport,
  isImportOrInService,
  onClickHref,
  simplifyName,
} from 'utils';

import type { Service } from 'generated/version/ServiceType';

import styles from 'application/components/parameter-list.css';

const ParameterList = (
  {
    name,
    type,
    required,
    description,
    example,
    defaultValue,
    service,
    importedServices,
    parentModel,
  }: {
    name: string,
    type: string,
    required: boolean,
    description?: string,
    example?: string,
    defaultValue?: string,
    service: Service,
    importedServices: Service[],
    parentModel: string,
  } = {}
) => {
  const possibleImportType = `${parentModel.substring(0, parentModel.lastIndexOf('.'))}.${type}`;
  const modelType = isImport(possibleImportType, importedServices)
    ? possibleImportType
    : type;
  const typeClickFn = isImportOrInService(
    getType(modelType),
    service,
    importedServices
  )
    ? onClickHref(
        buildNavHref({
          organization: service.organization.key,
          application: service.application.key,
          model: getType(modelType),
        })
      )
    : null;

  return (

        <a name={`${getType(parentModel)}.${name}`} className={styles.name}>
          {name}

        {/*

          {simplifyName(modelType)}

 */}

          {simplifyName(modelType)}

        {required ?
required
 : null}

        {description
          ? <Markdown source={description} className={styles.description} />
          :
No description
}
        {example
          ?

              Example{example}

          : null}
        {defaultValue
          ?

              Default{defaultValue}

          : null}

  );
};

export default ParameterList;
<commit_msg>Display the min and max property of fields<commit_after>// @flow
import React from 'react';
import classnames from 'classnames';

import Markdown from 'components/Markdown';
import {
  buildNavHref,
  getType,
  isImport,
  isImportOrInService,
  onClickHref,
  simplifyName,
} from 'utils';

import type { Service } from 'generated/version/ServiceType';

import styles from 'application/components/parameter-list.css';

const ParameterList = (
  {
    name,
    type,
    required,
    description,
    minimum,
    maximum,
    example,
    defaultValue,
    service,
    importedServices,
    parentModel,
  }: {
      name: string,
      type: string,
      required: boolean,
      minimum?: number,
      maximum?: number,
      description?: string,
      example?: string,
      defaultValue?: string,
      service: Service,
      importedServices: Service[],
      parentModel: string,
    } = {}
) => {
  const possibleImportType = `${parentModel.substring(0, parentModel.lastIndexOf('.'))}.${type}`;
  const modelType = isImport(possibleImportType, importedServices)
    ? possibleImportType
    : type;
  const typeClickFn = isImportOrInService(
    getType(modelType),
    service,
    importedServices
  )
    ? onClickHref(
      buildNavHref({
        organization: service.organization.key,
        application: service.application.key,
        model: getType(modelType),
      })
    )
    : null;

  return (

        <a name={`${getType(parentModel)}.${name}`} className={styles.name}>
          {name}

        {/*

          {simplifyName(modelType)}

 */}

          {simplifyName(modelType)}

        {required ?
required
 : null}

        {description
          ? <Markdown source={description} className={styles.description} />
          :
No description
}
        {minimum
          ?

            Minimum{minimum}

          : null
        }
        {maximum
          ?

            Maximum{maximum}

          : null
        }
        {example
          ?

            Example{example}

          : null}
        {defaultValue
          ?

            Default{defaultValue}

          : null}

  );
};

export default ParameterList;
<|endoftext|>


<commit_before>var status = require('http-status-codes');

var Models = require('../../models');
var registrationInformation = require('../../models/queries/registrationInformation');

module.exports = {
  getAll: function (req, res) {
    Models.Scout.findAll({
      attributes: [['id', 'scout_id'], 'firstname', 'lastname', 'troop', 'notes',
        'emergency_name', 'emergency_relation', 'emergency_phone'],
      include: [{
        model: Models.Event,
        as: 'registrations',
        attributes: [['id', 'event_id'], 'year', 'semester'],
        through: {
          as: 'details'
        },
      }, {
        model: Models.User,
        as: 'user',
        attributes: [['id', 'user_id'], 'firstname', 'lastname', 'email']
      }]
    })
      .then(function (scouts) {
        res.status(status.OK).json(scouts);
      })
      .catch(function (err) {
        res.status(status.BAD_REQUEST).send(err);
      });
  },
  getScout: function (req, res) {
    Models.Scout.findById(req.params.scoutId, {
      attributes: [['id', 'scout_id'], 'firstname', 'lastname', 'troop', 'notes',
        'emergency_name', 'emergency_relation', 'emergency_phone',
        'birthday'],
      include: [{
        model: Models.Event,
        as: 'registrations',
        attributes: [['id', 'event_id'], 'year', 'semester'],
        through: {
          as: 'details'
        },
      }, {
        model: Models.User,
        as: 'user',
        attributes: [['id', 'user_id'], 'firstname', 'lastname', 'email']
      }]
    })
      .then(function (scouts) {
        res.status(status.OK).json(scouts);
      })
      .catch(function (err) {
        console.log(err);
        res.status(status.BAD_REQUEST).json(err);
      });
  },
  getRegistrations: function (req, res) {
    var query = registrationInformation;
    var scoutId = req.params.scoutId;

    query.where = {
      scout_id: scoutId
    };

    Models.Registration.findAll(query)
      .then(function (registrations) {
        res.status(status.OK).json(registrations);
      })
      .catch(function (err) {
        res.status(status.BAD_REQUEST).json({
          message: 'Could not get registration for scout ' + scoutId,
          error: err
        });
      });
  },
  getPreferences: function (req, res) {
    getRegistrationDetails(req, res, 'preferences');
  },
  getAssignments: function (req, res) {
    getRegistrationDetails(req, res, 'assignments');
  },
  getPurchases: function (req, res) {
    getRegistrationDetails(req, res, 'purchases');
  },
  getProjectedCost: function (req, res) {
    getCost(req, res, 'projectedCost');
  },
  getActualCost: function (req, res) {
    getCost(req, res, 'actualCost');
  }
};

function getRegistrationDetails(req, res, object) {
  var scoutId = req.params.scoutId;
  var registrationId = req.params.registrationId;

  var possibleQueries = {
    'preferences': {
      model: Models.Offering,
      modelAttributes: ['badge_id', ['id', 'offering_id']],
      joinAttributes: ['rank']
    },
    'assignments': {
      model: Models.Offering,
      modelAttributes: ['badge_id', ['id', 'offering_id']],
      joinAttributes: ['periods']
    },
    'purchases': {
      model: Models.Purchasable,
      joinAttributes: ['quantity', 'size']
    }
  };

  if (object in possibleQueries) {
    return Models.Registration.find({
      where: {
        id: registrationId,
        scout_id: scoutId
      },
      include: [{
        model: possibleQueries[object].model,
        as: object,
        attributes: possibleQueries[object].modelAttributes,
        through: {
          as: 'details',
          attributes: possibleQueries[object].joinAttributes
        }
      }]
    })
      .then(function (registration) {
        res.status(status.OK).json(registration[object]);
      })
      .catch(function () {
        res.status(status.BAD_REQUEST).end();
      });
  } else {
    return res.status(status.INTERNAL_SERVER_ERROR);
  }
}

function getCost(req, res, type) {
  var scoutId = req.params.scoutId;
  var registrationId = req.params.registrationId;

  return Models.Registration.find({
    where: {
      id: registrationId,
      scout_id: scoutId
    }
  })
    .then(function (registration) {
      return registration[type];
    })
    .then(function (cost) {
      res.status(status.OK).json({
        cost: String(cost.toFixed(2))
      });
    })
    .catch(function () {
      res.status(status.BAD_REQUEST).end();
    });
}
<commit_msg>Return details<commit_after>var status = require('http-status-codes');

var Models = require('../../models');
var registrationInformation = require('../../models/queries/registrationInformation');

module.exports = {
  getAll: function (req, res) {
    Models.Scout.findAll({
      attributes: [['id', 'scout_id'], 'firstname', 'lastname', 'troop', 'notes',
        'emergency_name', 'emergency_relation', 'emergency_phone'],
      include: [{
        model: Models.Event,
        as: 'registrations',
        attributes: [['id', 'event_id'], 'year', 'semester'],
        through: {
          as: 'details'
        },
      }, {
        model: Models.User,
        as: 'user',
        attributes: [['id', 'user_id'], 'firstname', 'lastname', 'email']
      }]
    })
      .then(function (scouts) {
        res.status(status.OK).json(scouts);
      })
      .catch(function (err) {
        res.status(status.BAD_REQUEST).send(err);
      });
  },
  getScout: function (req, res) {
    Models.Scout.findById(req.params.scoutId, {
      attributes: [['id', 'scout_id'], 'firstname', 'lastname', 'troop', 'notes',
        'emergency_name', 'emergency_relation', 'emergency_phone',
        'birthday'],
      include: [{
        model: Models.Event,
        as: 'registrations',
        attributes: [['id', 'event_id'], 'year', 'semester'],
        through: {
          as: 'details'
        },
      }, {
        model: Models.User,
        as: 'user',
        attributes: [['id', 'user_id'], 'firstname', 'lastname', 'email', 'details']
      }]
    })
      .then(function (scouts) {
        res.status(status.OK).json(scouts);
      })
      .catch(function (err) {
        console.log(err);
        res.status(status.BAD_REQUEST).json(err);
      });
  },
  getRegistrations: function (req, res) {
    var query = registrationInformation;
    var scoutId = req.params.scoutId;

    query.where = {
      scout_id: scoutId
    };

    Models.Registration.findAll(query)
      .then(function (registrations) {
        res.status(status.OK).json(registrations);
      })
      .catch(function (err) {
        res.status(status.BAD_REQUEST).json({
          message: 'Could not get registration for scout ' + scoutId,
          error: err
        });
      });
  },
  getPreferences: function (req, res) {
    getRegistrationDetails(req, res, 'preferences');
  },
  getAssignments: function (req, res) {
    getRegistrationDetails(req, res, 'assignments');
  },
  getPurchases: function (req, res) {
    getRegistrationDetails(req, res, 'purchases');
  },
  getProjectedCost: function (req, res) {
    getCost(req, res, 'projectedCost');
  },
  getActualCost: function (req, res) {
    getCost(req, res, 'actualCost');
  }
};

function getRegistrationDetails(req, res, object) {
  var scoutId = req.params.scoutId;
  var registrationId = req.params.registrationId;

  var possibleQueries = {
    'preferences': {
      model: Models.Offering,
      modelAttributes: ['badge_id', ['id', 'offering_id']],
      joinAttributes: ['rank']
    },
    'assignments': {
      model: Models.Offering,
      modelAttributes: ['badge_id', ['id', 'offering_id']],
      joinAttributes: ['periods']
    },
    'purchases': {
      model: Models.Purchasable,
      joinAttributes: ['quantity', 'size']
    }
  };

  if (object in possibleQueries) {
    return Models.Registration.find({
      where: {
        id: registrationId,
        scout_id: scoutId
      },
      include: [{
        model: possibleQueries[object].model,
        as: object,
        attributes: possibleQueries[object].modelAttributes,
        through: {
          as: 'details',
          attributes: possibleQueries[object].joinAttributes
        }
      }]
    })
      .then(function (registration) {
        res.status(status.OK).json(registration[object]);
      })
      .catch(function () {
        res.status(status.BAD_REQUEST).end();
      });
  } else {
    return res.status(status.INTERNAL_SERVER_ERROR);
  }
}

function getCost(req, res, type) {
  var scoutId = req.params.scoutId;
  var registrationId = req.params.registrationId;

  return Models.Registration.find({
    where: {
      id: registrationId,
      scout_id: scoutId
    }
  })
    .then(function (registration) {
      return registration[type];
    })
    .then(function (cost) {
      res.status(status.OK).json({
        cost: String(cost.toFixed(2))
      });
    })
    .catch(function () {
      res.status(status.BAD_REQUEST).end();
    });
}
<|endoftext|>


<commit_before>/**
 * The resizable unit main file
 *
 * Copyright (C) 2010-2011 Nikolay Nemshilov
 */
var Resizable = new Widget({
  extend: {
    version: '2.2.2',

    EVENTS: $w('resize start release'),

    Options: {
      direction:  null, // 'top', 'left', 'right', 'bottom', null for bidrectional

      minWidth:   null,
      maxWidth:   null,
      minHeight:  null,
      maxHeight:  null
    }
  },

  /**
   * Basic constructor
   *
   * @param Element reference
   * @param Object options
   * @return void
   */
  initialize: function(element, options) {
    this
      .$super('resizable', this.old_inst = $(element))
      .setOptions(options);

    if (this.options.direction) {
      this.addClass('rui-resizable-'+ this.options.direction);
    } else {
      this.addClass('rui-resizable');
    }

    // initializing the inner structure
    this.content = this.first('.rui-resizable-content') ||
      $E('div', {'class': 'rui-resizable-content'}).insert(this.children()).insertTo(this);
    this.handle  = this.first('.rui-resizable-handle')  ||
      $E('div', {'class': 'rui-resizable-handle'}).insertTo(this);

    // resizing the content block so it fully fit the resizable element
    this.content.setWidth(this.size().x -
      parseInt(this.getStyle('borderLeftWidth'), 10) -
      parseInt(this.getStyle('borderRightWidth'), 10)
    );
    if (this.options.direction !== 'left' && this.options.direction !== 'right') {
      this.content.setHeight(this.size().y -
        parseInt(this.getStyle('borderTopWidth'), 10) -
        parseInt(this.getStyle('borderBottomWidth'), 10)
      );
    }
  },

  /**
   * destructor
   *
   * @return Resizable this
   */
  destroy: function() {
    this
      .removeClass('rui-resizable')
      .removeClass('rui-resizable-top')
      .removeClass('rui-resizable-left')
      .removeClass('rui-resizable-right')
      .removeClass('rui-resizable-bottom')
      .insert(this.content._.childNodes);

    this.content.remove();
    this.handle.remove();

    // swapping the old element back
    if (this.old_inst) {
      Wrapper.Cache[$uid(this._)] = this.old_inst;
    }

    return this;
  },

  /**
   * Overriding the method to recognize the direction
   * option from the element class-name
   *
   * @param Object options
   * @return Resizable this
   */
  setOptions: function(options, context) {
    options = options || {};

    // trying to recognize the direction
    $w('top left right bottom').each(function(direction) {
      if (this.hasClass('rui-resizable-'+ direction)) {
        options.direction = direction;
      }
    }, this);

    return this.$super(options, context);
  },

  /**
   * Starts the resizing process
   *
   * @param Event mouse event
   */
  start: function(event) {
    this.prevSizes = this.size();
    this.prevEvPos = event.position();

    // used later during the resize process
    this.contXDiff = this.size().x - this.content.size().x;
    this.contYDiff = this.size().y - this.content.size().y;

    // trying to recognize the boundaries
    $w('minWidth maxWidth minHeight maxHeight').each(function(dimension) {
      this[dimension] = this.findDim(dimension);
    }, this);

    return this.fire('start', {original: event});
  },

  /**
   * Tracks the event during the resize process
   *
   * @param Event mouse event
   */
  track: function(event) {
    var event_pos = event.position(), prev_pos = this.prevEvPos,
        handle    = this.handle.dimensions(),
        prev_size = this.prevSizes, width = prev_size.x, height = prev_size.y,
        x_diff    = prev_pos.x - event_pos.x,
        y_diff    = prev_pos.y - event_pos.y,
        min_x     = this.minWidth,
        max_x     = this.maxWidth,
        min_y     = this.minHeight,
        max_y     = this.maxHeight,
        options   = this.options,
        direction = options.direction;

    // calculating the new size
    width  += (direction === 'left' ? 1 : -1) * x_diff;
    height += (direction === 'top'  ? 1 : -1) * y_diff;

    // applying the boundaries
    if (width  < min_x) { width  = min_x; }
    if (width  > max_x) { width  = max_x; }
    if (height < min_y) { height = min_y; }
    if (height > max_y) { height = max_y; }

    // applying the sizes
    if (prev_size.x !== width && direction !== 'top' && direction !== 'bottom') {
      this.setWidth(width);
    }
    if (prev_size.y !== height && direction !== 'left' && direction !== 'right') {
      this.setHeight(height);
    }

    // adjusting the previous cursor position so that it didn't had a shift
    if (width == min_x || width == max_x) {
      event_pos.x = handle.left + handle.width / 2;
    }
    if (height == min_y || height == max_y) {
      event_pos.y = handle.top + handle.height / 2;
    }

    this.prevEvPos = event_pos;
    this.prevSizes = this.size();

    this.fire('resize', {original: event});
  },

  /**
   * Sets the width of the widget
   *
   * @param Number width
   * @return Resizable this
   */
  setWidth: function(width) {
    this.content.setWidth(width - this.contXDiff);
    return this.$super(width);
  },

  /**
   * Sets the height of the widget
   *
   * @param Number height
   * @return Resizable this
   */
  setHeight: function(height) {
    this.content.setHeight(height - this.contYDiff);
    return this.$super(height);
  },

  /**
   * Marks it the end of the action
   *
   * @return Resizable this
   */
  release: function(event) {
    return this.fire('release', {original: event});
  },

// protected

  // finds dimensions of the element
  findDim: function(dimension) {
    var style = this.options[dimension] || this.getStyle(dimension);

    if (style && /\d+/.test(style) && parseFloat(style) > 0) {
      var what  = R(dimension).include('Width') ? 'width' : 'height',
          dummy = (this._dummy || (this._dummy = $E('div', {
            style: 'visibility:hidden;z-index:-1'
          })))
          .setStyle(what, style)
          .insertTo(this, 'before');

      var size = dummy._['offset' + R(what).capitalize()];
      dummy.remove();

      return size;
    }
  }
});
<commit_msg>Resizable bumping up the version number<commit_after>/**
 * The resizable unit main file
 *
 * Copyright (C) 2010-2011 Nikolay Nemshilov
 */
var Resizable = new Widget({
  extend: {
    version: '2.2.3',

    EVENTS: $w('resize start release'),

    Options: {
      direction:  null, // 'top', 'left', 'right', 'bottom', null for bidrectional

      minWidth:   null,
      maxWidth:   null,
      minHeight:  null,
      maxHeight:  null
    }
  },

  /**
   * Basic constructor
   *
   * @param Element reference
   * @param Object options
   * @return void
   */
  initialize: function(element, options) {
    this
      .$super('resizable', this.old_inst = $(element))
      .setOptions(options);

    if (this.options.direction) {
      this.addClass('rui-resizable-'+ this.options.direction);
    } else {
      this.addClass('rui-resizable');
    }

    // initializing the inner structure
    this.content = this.first('.rui-resizable-content') ||
      $E('div', {'class': 'rui-resizable-content'}).insert(this.children()).insertTo(this);
    this.handle  = this.first('.rui-resizable-handle')  ||
      $E('div', {'class': 'rui-resizable-handle'}).insertTo(this);

    // resizing the content block so it fully fit the resizable element
    this.content.setWidth(this.size().x -
      parseInt(this.getStyle('borderLeftWidth'), 10) -
      parseInt(this.getStyle('borderRightWidth'), 10)
    );
    if (this.options.direction !== 'left' && this.options.direction !== 'right') {
      this.content.setHeight(this.size().y -
        parseInt(this.getStyle('borderTopWidth'), 10) -
        parseInt(this.getStyle('borderBottomWidth'), 10)
      );
    }
  },

  /**
   * destructor
   *
   * @return Resizable this
   */
  destroy: function() {
    this
      .removeClass('rui-resizable')
      .removeClass('rui-resizable-top')
      .removeClass('rui-resizable-left')
      .removeClass('rui-resizable-right')
      .removeClass('rui-resizable-bottom')
      .insert(this.content._.childNodes);

    this.content.remove();
    this.handle.remove();

    // swapping the old element back
    if (this.old_inst) {
      Wrapper.Cache[$uid(this._)] = this.old_inst;
    }

    return this;
  },

  /**
   * Overriding the method to recognize the direction
   * option from the element class-name
   *
   * @param Object options
   * @return Resizable this
   */
  setOptions: function(options, context) {
    options = options || {};

    // trying to recognize the direction
    $w('top left right bottom').each(function(direction) {
      if (this.hasClass('rui-resizable-'+ direction)) {
        options.direction = direction;
      }
    }, this);

    return this.$super(options, context);
  },

  /**
   * Starts the resizing process
   *
   * @param Event mouse event
   */
  start: function(event) {
    this.prevSizes = this.size();
    this.prevEvPos = event.position();

    // used later during the resize process
    this.contXDiff = this.size().x - this.content.size().x;
    this.contYDiff = this.size().y - this.content.size().y;

    // trying to recognize the boundaries
    $w('minWidth maxWidth minHeight maxHeight').each(function(dimension) {
      this[dimension] = this.findDim(dimension);
    }, this);

    return this.fire('start', {original: event});
  },

  /**
   * Tracks the event during the resize process
   *
   * @param Event mouse event
   */
  track: function(event) {
    var event_pos = event.position(), prev_pos = this.prevEvPos,
        handle    = this.handle.dimensions(),
        prev_size = this.prevSizes, width = prev_size.x, height = prev_size.y,
        x_diff    = prev_pos.x - event_pos.x,
        y_diff    = prev_pos.y - event_pos.y,
        min_x     = this.minWidth,
        max_x     = this.maxWidth,
        min_y     = this.minHeight,
        max_y     = this.maxHeight,
        options   = this.options,
        direction = options.direction;

    // calculating the new size
    width  += (direction === 'left' ? 1 : -1) * x_diff;
    height += (direction === 'top'  ? 1 : -1) * y_diff;

    // applying the boundaries
    if (width  < min_x) { width  = min_x; }
    if (width  > max_x) { width  = max_x; }
    if (height < min_y) { height = min_y; }
    if (height > max_y) { height = max_y; }

    // applying the sizes
    if (prev_size.x !== width && direction !== 'top' && direction !== 'bottom') {
      this.setWidth(width);
    }
    if (prev_size.y !== height && direction !== 'left' && direction !== 'right') {
      this.setHeight(height);
    }

    // adjusting the previous cursor position so that it didn't had a shift
    if (width == min_x || width == max_x) {
      event_pos.x = handle.left + handle.width / 2;
    }
    if (height == min_y || height == max_y) {
      event_pos.y = handle.top + handle.height / 2;
    }

    this.prevEvPos = event_pos;
    this.prevSizes = this.size();

    this.fire('resize', {original: event});
  },

  /**
   * Sets the width of the widget
   *
   * @param Number width
   * @return Resizable this
   */
  setWidth: function(width) {
    this.content.setWidth(width - this.contXDiff);
    return this.$super(width);
  },

  /**
   * Sets the height of the widget
   *
   * @param Number height
   * @return Resizable this
   */
  setHeight: function(height) {
    this.content.setHeight(height - this.contYDiff);
    return this.$super(height);
  },

  /**
   * Marks it the end of the action
   *
   * @return Resizable this
   */
  release: function(event) {
    return this.fire('release', {original: event});
  },

// protected

  // finds dimensions of the element
  findDim: function(dimension) {
    var style = this.options[dimension] || this.getStyle(dimension);

    if (style && /\d+/.test(style) && parseFloat(style) > 0) {
      var what  = R(dimension).include('Width') ? 'width' : 'height',
          dummy = (this._dummy || (this._dummy = $E('div', {
            style: 'visibility:hidden;z-index:-1'
          })))
          .setStyle(what, style)
          .insertTo(this, 'before');

      var size = dummy._['offset' + R(what).capitalize()];
      dummy.remove();

      return size;
    }
  }
});
<|endoftext|>


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

/*jslint bitwise: true*/

"use strict";

var DOMProperty = require('DOMProperty');
var ExecutionEnvironment = require('ExecutionEnvironment');

var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE;
var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY;
var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE;
var HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS;
var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE;
var HAS_POSITIVE_NUMERIC_VALUE =
  DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE;
var HAS_OVERLOADED_BOOLEAN_VALUE =
  DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE;

var hasSVG;
if (ExecutionEnvironment.canUseDOM) {
  var implementation = document.implementation;
  hasSVG = (
    implementation &&
    implementation.hasFeature &&
    implementation.hasFeature(
      'http://www.w3.org/TR/SVG11/feature#BasicStructure',
      '1.1'
    )
  );
}

var HTMLDOMPropertyConfig = {
  isCustomAttribute: RegExp.prototype.test.bind(
    /^(data|aria)-[a-z_][a-z\d_.\-]*$/
  ),
  Properties: {
    /**
     * Standard Properties
     */
    accept: null,
    accessKey: null,
    action: null,
    allowFullScreen: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
    allowTransparency: MUST_USE_ATTRIBUTE,
    alt: null,
    async: HAS_BOOLEAN_VALUE,
    autoComplete: null,
    // autoFocus is polyfilled/normalized by AutoFocusMixin
    // autoFocus: HAS_BOOLEAN_VALUE,
    autoPlay: HAS_BOOLEAN_VALUE,
    cellPadding: null,
    cellSpacing: null,
    charSet: MUST_USE_ATTRIBUTE,
    checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    // To set className on SVG elements, it's necessary to use .setAttribute;
    // this works on HTML elements too in all browsers except IE8. Conveniently,
    // IE8 doesn't support SVG and so we can simply use the attribute in
    // browsers that support SVG and the property in browsers that don't,
    // regardless of whether the element is HTML or SVG.
    className: hasSVG ? MUST_USE_ATTRIBUTE : MUST_USE_PROPERTY,
    cols: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
    colSpan: null,
    content: null,
    contentEditable: null,
    contextMenu: MUST_USE_ATTRIBUTE,
    controls: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    coords: null,
    crossOrigin: null,
    data: null, // For `<object />` acts as `src`.
    dateTime: MUST_USE_ATTRIBUTE,
    defer: HAS_BOOLEAN_VALUE,
    dir: null,
    disabled: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
    download: HAS_OVERLOADED_BOOLEAN_VALUE,
    draggable: null,
    encType: null,
    form: MUST_USE_ATTRIBUTE,
    formNoValidate: HAS_BOOLEAN_VALUE,
    frameBorder: MUST_USE_ATTRIBUTE,
    height: MUST_USE_ATTRIBUTE,
    hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
    href: null,
    hrefLang: null,
    htmlFor: null,
    httpEquiv: null,
    icon: null,
    id: MUST_USE_PROPERTY,
    label: null,
    lang: null,
    list: null,
    loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    max: null,
    maxLength: MUST_USE_ATTRIBUTE,
    media: null,
    mediaGroup: null,
    method: null,
    min: null,
    multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    name: null,
    noValidate: HAS_BOOLEAN_VALUE,
    pattern: null,
    placeholder: null,
    poster: null,
    preload: null,
    radioGroup: null,
    readOnly: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    rel: null,
    required: HAS_BOOLEAN_VALUE,
    role: MUST_USE_ATTRIBUTE,
    rows: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
    rowSpan: null,
    sandbox: null,
    scope: null,
    scrollLeft: MUST_USE_PROPERTY,
    scrolling: null,
    scrollTop: MUST_USE_PROPERTY,
    seamless: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
    selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    shape: null,
    size: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
    sizes: null,
    span: HAS_POSITIVE_NUMERIC_VALUE,
    spellCheck: null,
    src: null,
    srcDoc: MUST_USE_PROPERTY,
    srcSet: null,
    start: HAS_NUMERIC_VALUE,
    step: null,
    style: null,
    tabIndex: null,
    target: null,
    title: null,
    type: null,
    useMap: null,
    value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS,
    width: MUST_USE_ATTRIBUTE,
    wmode: MUST_USE_ATTRIBUTE,

    /**
     * Non-standard Properties
     */
    autoCapitalize: null, // Supported in Mobile Safari for keyboard hints
    autoCorrect: null, // Supported in Mobile Safari for keyboard hints
    itemProp: MUST_USE_ATTRIBUTE, // Microdata: http://schema.org/docs/gs.html
    itemScope: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, // Microdata: http://schema.org/docs/gs.html
    itemType: MUST_USE_ATTRIBUTE, // Microdata: http://schema.org/docs/gs.html
    property: null // Supports OG in meta tags
  },
  DOMAttributeNames: {
    className: 'class',
    htmlFor: 'for',
    httpEquiv: 'http-equiv'
  },
  DOMPropertyNames: {
    autoCapitalize: 'autocapitalize',
    autoComplete: 'autocomplete',
    autoCorrect: 'autocorrect',
    autoFocus: 'autofocus',
    autoPlay: 'autoplay',
    encType: 'enctype',
    hrefLang: 'hreflang',
    radioGroup: 'radiogroup',
    spellCheck: 'spellcheck',
    srcDoc: 'srcdoc',
    srcSet: 'srcset'
  }
};

module.exports = HTMLDOMPropertyConfig;
<commit_msg>use attribute for media, srcSet and sizes<commit_after>/**
 * Copyright 2013-2014 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @providesModule HTMLDOMPropertyConfig
 */

/*jslint bitwise: true*/

"use strict";

var DOMProperty = require('DOMProperty');
var ExecutionEnvironment = require('ExecutionEnvironment');

var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE;
var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY;
var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE;
var HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS;
var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE;
var HAS_POSITIVE_NUMERIC_VALUE =
  DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE;
var HAS_OVERLOADED_BOOLEAN_VALUE =
  DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE;

var hasSVG;
if (ExecutionEnvironment.canUseDOM) {
  var implementation = document.implementation;
  hasSVG = (
    implementation &&
    implementation.hasFeature &&
    implementation.hasFeature(
      'http://www.w3.org/TR/SVG11/feature#BasicStructure',
      '1.1'
    )
  );
}

var HTMLDOMPropertyConfig = {
  isCustomAttribute: RegExp.prototype.test.bind(
    /^(data|aria)-[a-z_][a-z\d_.\-]*$/
  ),
  Properties: {
    /**
     * Standard Properties
     */
    accept: null,
    accessKey: null,
    action: null,
    allowFullScreen: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
    allowTransparency: MUST_USE_ATTRIBUTE,
    alt: null,
    async: HAS_BOOLEAN_VALUE,
    autoComplete: null,
    // autoFocus is polyfilled/normalized by AutoFocusMixin
    // autoFocus: HAS_BOOLEAN_VALUE,
    autoPlay: HAS_BOOLEAN_VALUE,
    cellPadding: null,
    cellSpacing: null,
    charSet: MUST_USE_ATTRIBUTE,
    checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    // To set className on SVG elements, it's necessary to use .setAttribute;
    // this works on HTML elements too in all browsers except IE8. Conveniently,
    // IE8 doesn't support SVG and so we can simply use the attribute in
    // browsers that support SVG and the property in browsers that don't,
    // regardless of whether the element is HTML or SVG.
    className: hasSVG ? MUST_USE_ATTRIBUTE : MUST_USE_PROPERTY,
    cols: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
    colSpan: null,
    content: null,
    contentEditable: null,
    contextMenu: MUST_USE_ATTRIBUTE,
    controls: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    coords: null,
    crossOrigin: null,
    data: null, // For `<object />` acts as `src`.
    dateTime: MUST_USE_ATTRIBUTE,
    defer: HAS_BOOLEAN_VALUE,
    dir: null,
    disabled: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
    download: HAS_OVERLOADED_BOOLEAN_VALUE,
    draggable: null,
    encType: null,
    form: MUST_USE_ATTRIBUTE,
    formNoValidate: HAS_BOOLEAN_VALUE,
    frameBorder: MUST_USE_ATTRIBUTE,
    height: MUST_USE_ATTRIBUTE,
    hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
    href: null,
    hrefLang: null,
    htmlFor: null,
    httpEquiv: null,
    icon: null,
    id: MUST_USE_PROPERTY,
    label: null,
    lang: null,
    list: null,
    loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    max: null,
    maxLength: MUST_USE_ATTRIBUTE,
    media: MUST_USE_ATTRIBUTE,
    mediaGroup: null,
    method: null,
    min: null,
    multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    name: null,
    noValidate: HAS_BOOLEAN_VALUE,
    pattern: null,
    placeholder: null,
    poster: null,
    preload: null,
    radioGroup: null,
    readOnly: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    rel: null,
    required: HAS_BOOLEAN_VALUE,
    role: MUST_USE_ATTRIBUTE,
    rows: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
    rowSpan: null,
    sandbox: null,
    scope: null,
    scrollLeft: MUST_USE_PROPERTY,
    scrolling: null,
    scrollTop: MUST_USE_PROPERTY,
    seamless: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
    selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    shape: null,
    size: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
    sizes: MUST_USE_ATTRIBUTE,
    span: HAS_POSITIVE_NUMERIC_VALUE,
    spellCheck: null,
    src: null,
    srcDoc: MUST_USE_PROPERTY,
    srcSet: MUST_USE_ATTRIBUTE,
    start: HAS_NUMERIC_VALUE,
    step: null,
    style: null,
    tabIndex: null,
    target: null,
    title: null,
    type: null,
    useMap: null,
    value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS,
    width: MUST_USE_ATTRIBUTE,
    wmode: MUST_USE_ATTRIBUTE,

    /**
     * Non-standard Properties
     */
    autoCapitalize: null, // Supported in Mobile Safari for keyboard hints
    autoCorrect: null, // Supported in Mobile Safari for keyboard hints
    itemProp: MUST_USE_ATTRIBUTE, // Microdata: http://schema.org/docs/gs.html
    itemScope: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, // Microdata: http://schema.org/docs/gs.html
    itemType: MUST_USE_ATTRIBUTE, // Microdata: http://schema.org/docs/gs.html
    property: null // Supports OG in meta tags
  },
  DOMAttributeNames: {
    className: 'class',
    htmlFor: 'for',
    httpEquiv: 'http-equiv'
  },
  DOMPropertyNames: {
    autoCapitalize: 'autocapitalize',
    autoComplete: 'autocomplete',
    autoCorrect: 'autocorrect',
    autoFocus: 'autofocus',
    autoPlay: 'autoplay',
    encType: 'enctype',
    hrefLang: 'hreflang',
    radioGroup: 'radiogroup',
    spellCheck: 'spellcheck',
    srcDoc: 'srcdoc',
    srcSet: 'srcset'
  }
};

module.exports = HTMLDOMPropertyConfig;
<|endoftext|>


<commit_before>/**
 * Pimcore
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.pimcore.org/license
 *
 * @copyright  Copyright (c) 2009-2014 pimcore GmbH (http://www.pimcore.org)
 * @license    http://www.pimcore.org/license     New BSD License
 */

pimcore.registerNS("pimcore.document.tags.table");
pimcore.document.tags.table = Class.create(pimcore.document.tag, {

    initialize: function(id, name, options, data, inherited) {

        this.id = id;
        this.name = name;
        this.setupWrapper();
        options = this.parseOptions(options);

        if (!data) {
            data = [
                [" "]
            ];
            if (options.defaults) {
                if (options.defaults.cols) {
                    for (var i = 0; i < (options.defaults.cols - 1); i++) {
                        data[0].push(" ");
                    }
                }
                if (options.defaults.rows) {
                    for (var i = 0; i < (options.defaults.rows - 1); i++) {
                        data.push(data[0]);
                    }
                }
                if (options.defaults.data) {
                    data = options.defaults.data;
                }
            }
        }

        options.value = data;
        options.name = id + "_editable";
        options.frame = true;
        options.layout = "fit";
        options.autoHeight = true;

        delete options["height"];

        this.options = options;

        if (!this.panel) {
            this.panel = new Ext.Panel(this.options);
        }

        this.panel.render(id);

        this.initStore(data);

        this.initGrid();
    },

    initGrid: function () {

        this.panel.removeAll();

        var data = this.store.queryBy(function(record, id) {
            return true;
        });
        var columns = [];

        var fields = this.store.getInitialConfig().fields;

        if (data.items[0]) {
            for (var i = 0; i < fields.length; i++) {
                columns.push({
                    dataIndex: fields[i].name,
                    editor: new Ext.form.TextField({
                        allowBlank: true
                    }),
                    sortable: false
                });
            }
        }

        this.cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
            clicksToEdit: 1
        });

        this.grid = Ext.create('Ext.grid.Panel', {
            store: this.store,
            width: 700,
            border: false,
            columns:columns,
            stripeRows: true,
            columnLines: true,
            selModel: Ext.create('Ext.selection.CellModel'),
            autoHeight: true,
            plugins: [
                this.cellEditing
            ],
            tbar: [
                {
                    iconCls: "pimcore_tag_table_addcol",
                    handler: this.addColumn.bind(this)
                },
                {
                    iconCls: "pimcore_tag_table_delcol",
                    handler: this.deleteColumn.bind(this)
                },
                {
                    iconCls: "pimcore_tag_table_addrow",
                    handler: this.addRow.bind(this)
                },
                {
                    iconCls: "pimcore_tag_table_delrow",
                    handler: this.deleteRow.bind(this)
                },
                {
                    iconCls: "pimcore_tag_table_empty",
                    handler: this.initStore.bind(this, [
                        [" "]
                    ])
                }
            ]
        });
        this.panel.add(this.grid);
        this.panel.doLayout();
    },

    initStore: function (data) {
        var storeFields = [];
        if (data[0]) {
            for (var i = 0; i < data[0].length; i++) {
                storeFields.push({
                    name: "col_" + i
                });
            }
        }

        this.store = new Ext.data.ArrayStore({
            fields: storeFields
        });

        this.store.loadData(data);
        this.initGrid();
    },

    addColumn : function  () {

        var currentData = this.getValue();

        for (var i = 0; i < currentData.length; i++) {
            currentData[i].push(" ");
        }

        this.initStore(currentData);
    },

    addRow: function  () {
        var initData = {};

        for (var o = 0; o < this.grid.getColumnModel().config.length; o++) {
            initData["col_" + o] = " ";
        }

        this.store.add(new this.store.recordType(initData, this.store.getCount() + 1));
    },

    deleteRow : function  () {
        var selected = this.grid.getSelectionModel();
        if (selected.selection) {
            this.store.remove(selected.selection.record);
        }
    },

    deleteColumn: function () {
        var selected = this.grid.getSelectionModel();

        if (selected.selection) {
            var column = selected.selection.colIdx;

            var currentData = this.getValue();

            for (var i = 0; i < currentData.length; i++) {
                currentData[i].splice(column, 1);
            }

            this.initStore(currentData);
        }
    },

    getValue: function () {
        var data = this.store.queryBy(function(record, id) {
            return true;
        });

        var fields = this.store.getInitialConfig().fields;

        var storedData = [];
        var tmData = [];
        for (var i = 0; i < data.items.length; i++) {
            tmData = [];

            for (var u = 0; u < fields.length; u++) {
                tmData.push(data.items[i].data[fields[u].name]);
            }
            storedData.push(tmData);
        }

        return storedData;
    },

    getType: function () {
        return "table";
    }
});<commit_msg>document  table tag: fixed "add row" action<commit_after>/**
 * Pimcore
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.pimcore.org/license
 *
 * @copyright  Copyright (c) 2009-2014 pimcore GmbH (http://www.pimcore.org)
 * @license    http://www.pimcore.org/license     New BSD License
 */

pimcore.registerNS("pimcore.document.tags.table");
pimcore.document.tags.table = Class.create(pimcore.document.tag, {

    initialize: function(id, name, options, data, inherited) {

        this.id = id;
        this.name = name;
        this.setupWrapper();
        options = this.parseOptions(options);

        if (!data) {
            data = [
                [" "]
            ];
            if (options.defaults) {
                if (options.defaults.cols) {
                    for (var i = 0; i < (options.defaults.cols - 1); i++) {
                        data[0].push(" ");
                    }
                }
                if (options.defaults.rows) {
                    for (var i = 0; i < (options.defaults.rows - 1); i++) {
                        data.push(data[0]);
                    }
                }
                if (options.defaults.data) {
                    data = options.defaults.data;
                }
            }
        }

        options.value = data;
        options.name = id + "_editable";
        options.frame = true;
        options.layout = "fit";
        options.autoHeight = true;

        delete options["height"];

        this.options = options;

        if (!this.panel) {
            this.panel = new Ext.Panel(this.options);
        }

        this.panel.render(id);

        this.initStore(data);

        this.initGrid();
    },

    initGrid: function () {

        this.panel.removeAll();

        var data = this.store.queryBy(function(record, id) {
            return true;
        });
        var columns = [];

        var fields = this.store.getInitialConfig().fields;

        if (data.items[0]) {
            for (var i = 0; i < fields.length; i++) {
                columns.push({
                    dataIndex: fields[i].name,
                    editor: new Ext.form.TextField({
                        allowBlank: true
                    }),
                    sortable: false
                });
            }
        }

        this.cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
            clicksToEdit: 1
        });

        this.grid = Ext.create('Ext.grid.Panel', {
            store: this.store,
            width: 700,
            border: false,
            columns:columns,
            stripeRows: true,
            columnLines: true,
            selModel: Ext.create('Ext.selection.CellModel'),
            autoHeight: true,
            plugins: [
                this.cellEditing
            ],
            tbar: [
                {
                    iconCls: "pimcore_tag_table_addcol",
                    handler: this.addColumn.bind(this)
                },
                {
                    iconCls: "pimcore_tag_table_delcol",
                    handler: this.deleteColumn.bind(this)
                },
                {
                    iconCls: "pimcore_tag_table_addrow",
                    handler: this.addRow.bind(this)
                },
                {
                    iconCls: "pimcore_tag_table_delrow",
                    handler: this.deleteRow.bind(this)
                },
                {
                    iconCls: "pimcore_tag_table_empty",
                    handler: this.initStore.bind(this, [
                        [" "]
                    ])
                }
            ]
        });
        this.panel.add(this.grid);
        this.panel.doLayout();
    },

    initStore: function (data) {
        var storeFields = [];
        if (data[0]) {
            for (var i = 0; i < data[0].length; i++) {
                storeFields.push({
                    name: "col_" + i
                });
            }
        }

        this.store = new Ext.data.ArrayStore({
            fields: storeFields
        });

        this.store.loadData(data);
        this.initGrid();
    },

    addColumn : function  () {

        var currentData = this.getValue();

        for (var i = 0; i < currentData.length; i++) {
            currentData[i].push(" ");
        }

        this.initStore(currentData);
    },

    addRow: function  () {
        var initData = {};

        var columnnManager = this.grid.getColumnManager();
        var columns = columnnManager.getColumns();

        for (var o = 0; o < columns.length; o++) {
            initData["col_" + o] = " ";
        }

        this.store.add(initData);
    },

    deleteRow : function  () {
        var selected = this.grid.getSelectionModel();
        if (selected.selection) {
            this.store.remove(selected.selection.record);
        }
    },

    deleteColumn: function () {
        var selected = this.grid.getSelectionModel();

        if (selected.selection) {
            var column = selected.selection.colIdx;

            var currentData = this.getValue();

            for (var i = 0; i < currentData.length; i++) {
                currentData[i].splice(column, 1);
            }

            this.initStore(currentData);
        }
    },

    getValue: function () {
        var data = this.store.queryBy(function(record, id) {
            return true;
        });

        var fields = this.store.getInitialConfig().fields;

        var storedData = [];
        var tmData = [];
        for (var i = 0; i < data.items.length; i++) {
            tmData = [];

            for (var u = 0; u < fields.length; u++) {
                tmData.push(data.items[i].data[fields[u].name]);
            }
            storedData.push(tmData);
        }

        return storedData;
    },

    getType: function () {
        return "table";
    }
});<|endoftext|>


<commit_before>(function() {
    'use strict';

    angular
        .module('blocks.auth')
        .provider('auth', authProvider);

    authProvider.$inject = [];
    function authProvider() {
        /* jshint validthis:true */
        var config = {
            stateToRedirect: '',
            stateAuth: '',
            warningMsg: '',
            warningTitle: '',
            urlAuth: 'api/auth',
            errorAuthMsg: ''
        };

        this.configure = function(cfg) {
            angular.extend(config, cfg);
        };

        this.$get = Auth;

        Auth.$inject = ['$http', 'store', '$rootScope', '$state', 'logger'];
        /**
         * @param  {ng.IHttpService} $http
         * @param  {any} store
         * @param  {ng.IRootScopeService} $rootScope
         * @param  {ng.ui.IStateService} $state
         * @param  {any} logger
         */
        function Auth($http, store, $rootScope, $state, logger) {

            var service = {
                auth: auth,
                logout: logout,
                setAuth: setAuth,
                getAuth: getAuth,
                isAuthForRoute: isAuthForRoute
            };

            init();

            return service;

            ////////////////

            /**
             * auth
             *
             * Trata de obtener un token de
             * acceso por medio de la auth
             * de username y pass.
             *
             * @param {Object} data
             */
            function auth(data) {
                return $http({
                    method: 'POST',
                    url: config.urlAuth,
                    skipAuthorization: true,
                    data: data//{username: user, pass: pass}
                })
                .then(successAuth)
                .catch(failAuth);

                function successAuth(result) {
                    setAuth(result.data.jwt);
                    return $state.go(config.stateAuth);
                }

                function failAuth(result) {
                    return logger.error(config.errorAuthMsg, result.data, 'Auth Error');
                }
            }

            /**
             * logout
             *
             * Borra el token de acceso.
             */
            function logout() {
                return store.remove('token');
            }

            /**
             * setAuth
             *
             * Almacena el token de acceso.
             *
             * @param {string} token
             */
            function setAuth(token) {
                store.set('token', token);
            }

            /**
             * getAuth
             *
             * Retorna el token de acceso.
             *
             * @returns {*}
             */
            function getAuth() {
                return store.get('token');
            }

            function init() {
                isAuthForRoute();
            }

            function isAuthForRoute() {
                $rootScope.$on('$stateChangeStart',
                    function(event, toState, toParams, fromState, fromParams) {
                        if (toState.access && toState.access.requiredLogin && !getAuth()) {
                            event.preventDefault();
                            logger.warning(config.warningMsg, config.warningTitle);
                            $state.go(config.stateToRedirect);
                        }
                    }
                );
            }
        }
    }
})();
<commit_msg>Agregada en el block auth la funcionalidad para verificar si el token expiro.<commit_after>(function() {
    'use strict';

    angular
        .module('blocks.auth')
        .provider('auth', authProvider);

    authProvider.$inject = [];
    function authProvider() {
        /* jshint validthis:true */
        var config = {
            stateToRedirect: '',
            stateAuth: '',
            warningMsg: '',
            warningTitle: '',
            expiredMsg: '',
            expiredTitle: '',
            urlAuth: 'api/auth',
            errorAuthMsg: ''
        };

        this.configure = function(cfg) {
            angular.extend(config, cfg);
        };

        this.$get = Auth;

        Auth.$inject = ['$http', 'store', '$rootScope', '$state', 'logger', 'jwtHelper'];
        /**
         * @param  {ng.IHttpService} $http
         * @param  {any} store
         * @param  {ng.IRootScopeService} $rootScope
         * @param  {ng.ui.IStateService} $state
         * @param  {any} logger
         */
        function Auth($http, store, $rootScope, $state, logger, jwtHelper) {

            var service = {
                auth: auth,
                logout: logout,
                setAuth: setAuth,
                getAuth: getAuth,
                isAuthForRoute: isAuthForRoute
            };

            init();

            return service;

            ////////////////

            /**
             * auth
             *
             * Trata de obtener un token de
             * acceso por medio de la auth
             * de username y pass.
             *
             * @param {Object} data
             */
            function auth(data) {
                return $http({
                    method: 'POST',
                    url: config.urlAuth,
                    skipAuthorization: true,
                    data: data//{username: user, pass: pass}
                })
                .then(successAuth)
                .catch(failAuth);

                function successAuth(result) {
                    setAuth(result.data.jwt);
                    return $state.go(config.stateAuth);
                }

                function failAuth(result) {
                    return logger.error(config.errorAuthMsg, result.data, 'Auth Error');
                }
            }

            /**
             * logout
             *
             * Borra el token de acceso.
             */
            function logout() {
                return store.remove('token');
            }

            /**
             * setAuth
             *
             * Almacena el token de acceso.
             *
             * @param {string} token
             */
            function setAuth(token) {
                store.set('token', token);
            }

            /**
             * getAuth
             *
             * Retorna el token de acceso.
             *
             * @returns {*}
             */
            function getAuth() {
                return store.get('token');
            }

            function init() {
                isAuthForRoute();
                isTokenExpired();
            }

            function isAuthForRoute() {
                $rootScope.$on('$stateChangeStart',
                    function(event, toState, toParams, fromState, fromParams) {
                        if (toState.access && toState.access.requiredLogin && !getAuth()) {
                            event.preventDefault();
                            logger.warning(config.warningMsg, null, config.warningTitle);
                            $state.go(config.stateToRedirect);
                        }
                    }
                );
            }

            function isTokenExpired() {
                $rootScope.$on('$stateChangeSuccess',
                    function (event, toState, toParams, fromState, fromParams) {
                        var token = getAuth();
                        if (token) {
                            if (jwtHelper.isTokenExpired(token)) {
                                event.preventDefault();
                                logger.error(config.expiredMsg, null,
                                config.expiredTitle);
                                $state.go(config.stateToRedirect);
                            }
                        }
                    }
                );
            }
        }
    }
})();
<|endoftext|>


<commit_before>$(function () {
    localStorage.clear();
    window.location = '/login.html';
});
<commit_msg>Remove jQuery / Zepto references from logout.<commit_after>localStorage.clear();
window.location = '/login.html';
<|endoftext|>


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

/**
 * @fileoverview An interface definition of a speech rule.
 *
 * A speech rule is a data structure along with supporting methods that
 * stipulates how to transform a tree structure such as XML, a browser DOM, or
 * HTML into a format (usually strings) suitable for rendering by a
 * text-to-speech engine.
 *
 * Speech rules consists of a variable number of speech rule components. Each
 * component describes how to construct a single utterance. Text-to-speech
 * renders the components in order.
 * @author dtseng@google.com (David Tseng)
 */

goog.provide('sre.SpeechRule');
goog.provide('sre.SpeechRule.Action');
goog.provide('sre.SpeechRule.Component');
goog.provide('sre.SpeechRule.DynamicCstr');
goog.provide('sre.SpeechRule.Precondition');
goog.provide('sre.SpeechRule.Type');

/**
 * Creates a speech rule with precondition, actions and admin information.
 * @constructor
 * @param {string} name The name of the rule.
 * @param {sre.SpeechRule.DynamicCstr} dynamic Dynamic constraint annotations
 *     of the rule.
 * @param {sre.SpeechRule.Precondition} prec Precondition of the rule.
 * @param {sre.SpeechRule.Action} action Action of the speech rule.
 */
sre.SpeechRule = function(name, dynamic, prec, action) {
  /** @type {string} */
  this.name = name;
  /** @type {sre.SpeechRule.DynamicCstr} */
  this.dynamicCstr = dynamic;
  /** @type {sre.SpeechRule.Precondition} */
  this.precondition = prec;
  /** @type {sre.SpeechRule.Action} */
  this.action = action;
};

/**
 *
 * @override
 */
sre.SpeechRule.prototype.toString = function() {
  return this.name + ' | ' +
      sre.SpeechRule.stringifyCstr(this.dynamicCstr) + ' | ' +
      this.precondition.toString() + ' ==> ' +
      this.action.toString();
};

/**
 * Mapping for types of speech rule components.
 * @enum {string}
 */
sre.SpeechRule.Type = {
  NODE: 'NODE',
  MULTI: 'MULTI',
  TEXT: 'TEXT',
  PERSONALITY: 'PERSONALITY'
};

/**
 * Maps a string to a valid speech rule type.
 * @param {string} str Input string.
 * @return {sre.SpeechRule.Type}
 */
sre.SpeechRule.Type.fromString = function(str) {
  switch (str) {
    case '[n]': return sre.SpeechRule.Type.NODE;
    case '[m]': return sre.SpeechRule.Type.MULTI;
    case '[t]': return sre.SpeechRule.Type.TEXT;
    case '[p]': return sre.SpeechRule.Type.PERSONALITY;
    default: throw 'Parse error: ' + str;
  }
};

/**
 * Maps a speech rule type to a human-readable string.
 * @param {sre.SpeechRule.Type} speechType
 * @return {string} Output string.
 */
sre.SpeechRule.Type.toString = function(speechType) {
  switch (speechType) {
    case sre.SpeechRule.Type.NODE: return '[n]';
    case sre.SpeechRule.Type.MULTI: return '[m]';
    case sre.SpeechRule.Type.TEXT: return '[t]';
    case sre.SpeechRule.Type.PERSONALITY: return '[p]';
    default: throw 'Unknown type error: ' + speechType;
  }
};

/**
 * Defines a component within a speech rule.
 * @param {{type: sre.SpeechRule.Type, content: string}} kwargs The input
 * component in JSON format.
 * @constructor
 */
sre.SpeechRule.Component = function(kwargs) {
  /** @type {sre.SpeechRule.Type} */
  this.type = kwargs.type;

  /** @type {string} */
  this.content = kwargs.content;
};

/**
 * Parses a valid string representation of a speech component into a Component
 * object.
 * @param {string} input The input string.
 * @return {sre.SpeechRule.Component} The resulting component.
 */
sre.SpeechRule.Component.fromString = function(input) {
  // The output JSON.
  var output = {};

  // Parse the type.
  output.type = sre.SpeechRule.Type.fromString(input.substring(0, 3));

  // Prep the rest of the parsing.
  var rest = input.slice(3).trimLeft();
  if (!rest) {
    throw new sre.SpeechRule.OutputError('Missing content.');
  }

  switch (output.type) {
    case sre.SpeechRule.Type.TEXT:
      if (rest[0] == '"') {
        var quotedString = sre.SpeechRule.splitString_(rest, '\\(')[0].trim();
        if (quotedString.slice(-1) != '"') {
          throw new sre.SpeechRule.OutputError('Invalid string syntax.');
        }
        output.content = quotedString;
        rest = rest.slice(quotedString.length).trim();
        if (rest.indexOf('(') == -1) {
          rest = '';
        }
        // This break is conditional. If the content is not an explicit string,
        // it can be treated like node and multi type.
        break;
      }
    case sre.SpeechRule.Type.NODE:
    case sre.SpeechRule.Type.MULTI:
      var bracket = rest.indexOf(' (');
      if (bracket == -1) {
        output.content = rest.trim();
        rest = '';
        break;
      }
      output.content = rest.substring(0, bracket).trim();
      rest = rest.slice(bracket).trimLeft();
      break;
  }
  output = new sre.SpeechRule.Component(output);
  if (rest) {
    output.addAttributes(rest);
  }
  return output;
};

/**
 * @override
 */
sre.SpeechRule.Component.prototype.toString = function() {
  var strs = '';
  strs += sre.SpeechRule.Type.toString(this.type);
  strs += this.content ? ' ' + this.content : '';
  var attribs = this.getAttributes();
  if (attribs.length > 0) {
    strs += ' (' + attribs.join(', ') + ')';
  }
  return strs;
};

/**
 * Adds a single attribute to the component.
 * @param {string} attr String representation of an attribute.
 */
sre.SpeechRule.Component.prototype.addAttribute = function(attr) {
  var colon = attr.indexOf(':');
  if (colon == -1) {
    this[attr.trim()] = 'true';
  } else {
    this[attr.substring(0, colon).trim()] = attr.slice(colon + 1).trim();
  }
};

/**
 * Adds a list of attributes to the component.
 * @param {string} attrs String representation of attribute list.
 */
sre.SpeechRule.Component.prototype.addAttributes = function(attrs) {
  if (attrs[0] != '(' || attrs.slice(-1) != ')') {
    throw new sre.SpeechRule.OutputError(
        'Invalid attribute expression: ' + attrs);
  }
  var attribs = sre.SpeechRule.splitString_(attrs.slice(1, -1), ',');
  for (var i = 0; i < attribs.length; i++) {
    this.addAttribute(attribs[i]);
  }
};

/**
 * Transforms the attributes of an object into a list of strings.
 * @return {Array.<string>} List of translated attribute:value strings.
 */
sre.SpeechRule.Component.prototype.getAttributes = function() {
  var attribs = [];
  for (var key in this) {
    if (key != 'content' && key != 'type' && typeof(this[key]) != 'function') {
      attribs.push(key + ':' + this[key]);
    }
  }
  return attribs;
};

/**
 * A speech rule is a collection of speech components.
 * @param {Array.<sre.SpeechRule.Component>} components The input rule.
 * @constructor
 */
sre.SpeechRule.Action = function(components) {
  /** @type {Array.<sre.SpeechRule.Component>} */
  this.components = components;
};

/**
 * Parses an input string into a speech rule class object.
 * @param {string} input The input string.
 * @return {sre.SpeechRule.Action} The resulting object.
 */
sre.SpeechRule.Action.fromString = function(input) {
  var comps = sre.SpeechRule.splitString_(input, ';')
      .filter(function(x) {return x.match(/\S/);})
      .map(function(x) {return x.trim();});
  var newComps = [];
  for (var i = 0; i < comps.length; i++) {
    var comp = sre.SpeechRule.Component.fromString(comps[i]);
    if (comp) {
      newComps.push(comp);
    }
  }
  return new sre.SpeechRule.Action(newComps);
};

/**
 * @override
 */
sre.SpeechRule.Action.prototype.toString = function() {
  var comps = this.components.map(function(c) { return c.toString(); });
  return comps.join('; ');
};

// TODO (sorge) Separatation of xpath expressions and custom functions.
// Also test validity of xpath expressions.
/**
 * Constructs a valid precondition for a speech rule.
 * @param {string} query A node selector function or xpath expression.
 * @param {Array.<string>=} opt_constraints A list of constraint functions.
 * @constructor
 */
sre.SpeechRule.Precondition = function(query, opt_constraints) {
  /** @type {string} */
  this.query = query;

  /** @type {!Array.<string>} */
  this.constraints = opt_constraints || [];
};

/**
 * @override
 */
sre.SpeechRule.Precondition.prototype.toString = function() {
  var constrs = this.constraints.join(', ');
  return this.query + ', ' + constrs;
};

/**
 * Split a string wrt. a given separator symbol while not splitting inside of a
 * double quoted string. For example, splitting
 * '[t] "matrix; 3 by 3"; [n] ./*[1]' with separators ';' would yield
 * ['[t] "matrix; 3 by 3"', ' [n] ./*[1]'].
 * @param {string} str String to be split.
 * @param {string} sep Separator symbol.
 * @return {Array.<string>} A list of single component strings.
 * @private
 */
sre.SpeechRule.splitString_ = function(str, sep) {
  var strList = [];
  var prefix = '';

  while (str != '') {
    var sepPos = str.search(sep);
    if (sepPos == -1) {
      if ((str.match(/"/g) || []).length % 2 != 0) {
        throw new sre.SpeechRule.OutputError(
            'Invalid string in expression: ' + str);
      }
      strList.push(prefix + str);
      prefix = '';
      str = '';
    } else if (
        (str.substring(0, sepPos).match(/"/g) || []).length % 2 == 0) {
      strList.push(prefix + str.substring(0, sepPos));
      prefix = '';
      str = str.substring(sepPos + 1);
    } else {
      var nextQuot = str.substring(sepPos).search('"');
      if (nextQuot == -1) {
        throw new sre.SpeechRule.OutputError(
            'Invalid string in expression: ' + str);
      } else {
        prefix = prefix + str.substring(0, sepPos + nextQuot + 1);
        str = str.substring(sepPos + nextQuot + 1);
      }
    }
  }
  if (prefix) {
    strList.push(prefix);
  }
  return strList;
};

/**
 * Attributes for dynamic constraints.
 * We define one default attribute as style. Speech rule stores can add other
 * attributes later.
 * @enum {string}
 */
sre.SpeechRule.DynamicCstrAttrib =
    {
      STYLE: 'style'
    };

/**
 * Dynamic constraints are a means to specialize rules that can be changed
 * dynamically by the user, for example by choosing different styles, etc.
 * @typedef {!Object.<sre.SpeechRule.DynamicCstrAttrib, string>}
 */
sre.SpeechRule.DynamicCstr;

/**
 * Stringifies a dynamic constraint.
 * @param {sre.SpeechRule.DynamicCstr} cstr The constraint.
 * @return {string} The string version.
 */
sre.SpeechRule.stringifyCstr = function(cstr) {
  var cstrStrings = [];
  for (var key in cstr) {
    cstrStrings.push(cstr[key]);
  }
  return cstrStrings.join('.');
};

/**
 * Error object for signaling parsing errors.
 * @param {string} msg The error message.
 * @constructor
 * @extends {Error}
 */
sre.SpeechRule.OutputError = function(msg) {
  this.name = 'RuleError';
  this.message = msg || '';
};
goog.inherits(sre.SpeechRule.OutputError, Error);
<commit_msg>Proper inheritance of speech rule error.<commit_after>// Copyright 2013 Google Inc.
// Copyright 2014 Volker Sorge
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview An interface definition of a speech rule.
 *
 * A speech rule is a data structure along with supporting methods that
 * stipulates how to transform a tree structure such as XML, a browser DOM, or
 * HTML into a format (usually strings) suitable for rendering by a
 * text-to-speech engine.
 *
 * Speech rules consists of a variable number of speech rule components. Each
 * component describes how to construct a single utterance. Text-to-speech
 * renders the components in order.
 * @author dtseng@google.com (David Tseng)
 */

goog.provide('sre.SpeechRule');
goog.provide('sre.SpeechRule.Action');
goog.provide('sre.SpeechRule.Component');
goog.provide('sre.SpeechRule.DynamicCstr');
goog.provide('sre.SpeechRule.Precondition');
goog.provide('sre.SpeechRule.Type');

/**
 * Creates a speech rule with precondition, actions and admin information.
 * @constructor
 * @param {string} name The name of the rule.
 * @param {sre.SpeechRule.DynamicCstr} dynamic Dynamic constraint annotations
 *     of the rule.
 * @param {sre.SpeechRule.Precondition} prec Precondition of the rule.
 * @param {sre.SpeechRule.Action} action Action of the speech rule.
 */
sre.SpeechRule = function(name, dynamic, prec, action) {
  /** @type {string} */
  this.name = name;
  /** @type {sre.SpeechRule.DynamicCstr} */
  this.dynamicCstr = dynamic;
  /** @type {sre.SpeechRule.Precondition} */
  this.precondition = prec;
  /** @type {sre.SpeechRule.Action} */
  this.action = action;
};

/**
 *
 * @override
 */
sre.SpeechRule.prototype.toString = function() {
  return this.name + ' | ' +
      sre.SpeechRule.stringifyCstr(this.dynamicCstr) + ' | ' +
      this.precondition.toString() + ' ==> ' +
      this.action.toString();
};

/**
 * Mapping for types of speech rule components.
 * @enum {string}
 */
sre.SpeechRule.Type = {
  NODE: 'NODE',
  MULTI: 'MULTI',
  TEXT: 'TEXT',
  PERSONALITY: 'PERSONALITY'
};

/**
 * Maps a string to a valid speech rule type.
 * @param {string} str Input string.
 * @return {sre.SpeechRule.Type}
 */
sre.SpeechRule.Type.fromString = function(str) {
  switch (str) {
    case '[n]': return sre.SpeechRule.Type.NODE;
    case '[m]': return sre.SpeechRule.Type.MULTI;
    case '[t]': return sre.SpeechRule.Type.TEXT;
    case '[p]': return sre.SpeechRule.Type.PERSONALITY;
    default: throw 'Parse error: ' + str;
  }
};

/**
 * Maps a speech rule type to a human-readable string.
 * @param {sre.SpeechRule.Type} speechType
 * @return {string} Output string.
 */
sre.SpeechRule.Type.toString = function(speechType) {
  switch (speechType) {
    case sre.SpeechRule.Type.NODE: return '[n]';
    case sre.SpeechRule.Type.MULTI: return '[m]';
    case sre.SpeechRule.Type.TEXT: return '[t]';
    case sre.SpeechRule.Type.PERSONALITY: return '[p]';
    default: throw 'Unknown type error: ' + speechType;
  }
};

/**
 * Defines a component within a speech rule.
 * @param {{type: sre.SpeechRule.Type, content: string}} kwargs The input
 * component in JSON format.
 * @constructor
 */
sre.SpeechRule.Component = function(kwargs) {
  /** @type {sre.SpeechRule.Type} */
  this.type = kwargs.type;

  /** @type {string} */
  this.content = kwargs.content;
};

/**
 * Parses a valid string representation of a speech component into a Component
 * object.
 * @param {string} input The input string.
 * @return {sre.SpeechRule.Component} The resulting component.
 */
sre.SpeechRule.Component.fromString = function(input) {
  // The output JSON.
  var output = {};

  // Parse the type.
  output.type = sre.SpeechRule.Type.fromString(input.substring(0, 3));

  // Prep the rest of the parsing.
  var rest = input.slice(3).trimLeft();
  if (!rest) {
    throw new sre.SpeechRule.OutputError('Missing content.');
  }

  switch (output.type) {
    case sre.SpeechRule.Type.TEXT:
      if (rest[0] == '"') {
        var quotedString = sre.SpeechRule.splitString_(rest, '\\(')[0].trim();
        if (quotedString.slice(-1) != '"') {
          throw new sre.SpeechRule.OutputError('Invalid string syntax.');
        }
        output.content = quotedString;
        rest = rest.slice(quotedString.length).trim();
        if (rest.indexOf('(') == -1) {
          rest = '';
        }
        // This break is conditional. If the content is not an explicit string,
        // it can be treated like node and multi type.
        break;
      }
    case sre.SpeechRule.Type.NODE:
    case sre.SpeechRule.Type.MULTI:
      var bracket = rest.indexOf(' (');
      if (bracket == -1) {
        output.content = rest.trim();
        rest = '';
        break;
      }
      output.content = rest.substring(0, bracket).trim();
      rest = rest.slice(bracket).trimLeft();
      break;
  }
  output = new sre.SpeechRule.Component(output);
  if (rest) {
    output.addAttributes(rest);
  }
  return output;
};

/**
 * @override
 */
sre.SpeechRule.Component.prototype.toString = function() {
  var strs = '';
  strs += sre.SpeechRule.Type.toString(this.type);
  strs += this.content ? ' ' + this.content : '';
  var attribs = this.getAttributes();
  if (attribs.length > 0) {
    strs += ' (' + attribs.join(', ') + ')';
  }
  return strs;
};

/**
 * Adds a single attribute to the component.
 * @param {string} attr String representation of an attribute.
 */
sre.SpeechRule.Component.prototype.addAttribute = function(attr) {
  var colon = attr.indexOf(':');
  if (colon == -1) {
    this[attr.trim()] = 'true';
  } else {
    this[attr.substring(0, colon).trim()] = attr.slice(colon + 1).trim();
  }
};

/**
 * Adds a list of attributes to the component.
 * @param {string} attrs String representation of attribute list.
 */
sre.SpeechRule.Component.prototype.addAttributes = function(attrs) {
  if (attrs[0] != '(' || attrs.slice(-1) != ')') {
    throw new sre.SpeechRule.OutputError(
        'Invalid attribute expression: ' + attrs);
  }
  var attribs = sre.SpeechRule.splitString_(attrs.slice(1, -1), ',');
  for (var i = 0; i < attribs.length; i++) {
    this.addAttribute(attribs[i]);
  }
};

/**
 * Transforms the attributes of an object into a list of strings.
 * @return {Array.<string>} List of translated attribute:value strings.
 */
sre.SpeechRule.Component.prototype.getAttributes = function() {
  var attribs = [];
  for (var key in this) {
    if (key != 'content' && key != 'type' && typeof(this[key]) != 'function') {
      attribs.push(key + ':' + this[key]);
    }
  }
  return attribs;
};

/**
 * A speech rule is a collection of speech components.
 * @param {Array.<sre.SpeechRule.Component>} components The input rule.
 * @constructor
 */
sre.SpeechRule.Action = function(components) {
  /** @type {Array.<sre.SpeechRule.Component>} */
  this.components = components;
};

/**
 * Parses an input string into a speech rule class object.
 * @param {string} input The input string.
 * @return {sre.SpeechRule.Action} The resulting object.
 */
sre.SpeechRule.Action.fromString = function(input) {
  var comps = sre.SpeechRule.splitString_(input, ';')
      .filter(function(x) {return x.match(/\S/);})
      .map(function(x) {return x.trim();});
  var newComps = [];
  for (var i = 0; i < comps.length; i++) {
    var comp = sre.SpeechRule.Component.fromString(comps[i]);
    if (comp) {
      newComps.push(comp);
    }
  }
  return new sre.SpeechRule.Action(newComps);
};

/**
 * @override
 */
sre.SpeechRule.Action.prototype.toString = function() {
  var comps = this.components.map(function(c) { return c.toString(); });
  return comps.join('; ');
};

// TODO (sorge) Separatation of xpath expressions and custom functions.
// Also test validity of xpath expressions.
/**
 * Constructs a valid precondition for a speech rule.
 * @param {string} query A node selector function or xpath expression.
 * @param {Array.<string>=} opt_constraints A list of constraint functions.
 * @constructor
 */
sre.SpeechRule.Precondition = function(query, opt_constraints) {
  /** @type {string} */
  this.query = query;

  /** @type {!Array.<string>} */
  this.constraints = opt_constraints || [];
};

/**
 * @override
 */
sre.SpeechRule.Precondition.prototype.toString = function() {
  var constrs = this.constraints.join(', ');
  return this.query + ', ' + constrs;
};

/**
 * Split a string wrt. a given separator symbol while not splitting inside of a
 * double quoted string. For example, splitting
 * '[t] "matrix; 3 by 3"; [n] ./*[1]' with separators ';' would yield
 * ['[t] "matrix; 3 by 3"', ' [n] ./*[1]'].
 * @param {string} str String to be split.
 * @param {string} sep Separator symbol.
 * @return {Array.<string>} A list of single component strings.
 * @private
 */
sre.SpeechRule.splitString_ = function(str, sep) {
  var strList = [];
  var prefix = '';

  while (str != '') {
    var sepPos = str.search(sep);
    if (sepPos == -1) {
      if ((str.match(/"/g) || []).length % 2 != 0) {
        throw new sre.SpeechRule.OutputError(
            'Invalid string in expression: ' + str);
      }
      strList.push(prefix + str);
      prefix = '';
      str = '';
    } else if (
        (str.substring(0, sepPos).match(/"/g) || []).length % 2 == 0) {
      strList.push(prefix + str.substring(0, sepPos));
      prefix = '';
      str = str.substring(sepPos + 1);
    } else {
      var nextQuot = str.substring(sepPos).search('"');
      if (nextQuot == -1) {
        throw new sre.SpeechRule.OutputError(
            'Invalid string in expression: ' + str);
      } else {
        prefix = prefix + str.substring(0, sepPos + nextQuot + 1);
        str = str.substring(sepPos + nextQuot + 1);
      }
    }
  }
  if (prefix) {
    strList.push(prefix);
  }
  return strList;
};

/**
 * Attributes for dynamic constraints.
 * We define one default attribute as style. Speech rule stores can add other
 * attributes later.
 * @enum {string}
 */
sre.SpeechRule.DynamicCstrAttrib =
    {
      STYLE: 'style'
    };

/**
 * Dynamic constraints are a means to specialize rules that can be changed
 * dynamically by the user, for example by choosing different styles, etc.
 * @typedef {!Object.<sre.SpeechRule.DynamicCstrAttrib, string>}
 */
sre.SpeechRule.DynamicCstr;

/**
 * Stringifies a dynamic constraint.
 * @param {sre.SpeechRule.DynamicCstr} cstr The constraint.
 * @return {string} The string version.
 */
sre.SpeechRule.stringifyCstr = function(cstr) {
  var cstrStrings = [];
  for (var key in cstr) {
    cstrStrings.push(cstr[key]);
  }
  return cstrStrings.join('.');
};

/**
 * Error object for signaling parsing errors.
 * @param {string} msg The error message.
 * @constructor
 * @extends {Error}
 */
sre.SpeechRule.OutputError = function(msg) {
  goog.base(this, msg || '');
  this.name = 'RuleError';
};
goog.inherits(sre.SpeechRule.OutputError, Error);
<|endoftext|>