<commit_before>(function(){

	function Init(){
		this.args = (function(a){
			return [].slice.call(a[0]);
		}(arguments));
		this.count = 10;
	}
	Init.prototype.fire = function(){
		if (arguments.length){
			localargs = [].slice.call(arguments);
			(function(a,b,c){
				switch(!!a[0]){
					case a[0] === 'default' :
						for(i = 1; i <= c; i++){
							db[b]['insert'](
									{"address": {
											"building": Math.floor(Math.random()*10001),
											"coord": [-(Math.random()*100000001/1000000).toFixed(6), (Math.random()*100000001/1000000).toFixed(6)],
											"street": ['East','South','West','North'][Math.floor(Math.random()*4)]+' '+Math.floor(Math.random()*101)+' Street',
											"zipcode": Math.floor(Math.random()*10001)
										},
									 "borough": ["Manhattan","Brooklyn","Queens","Staten","Bronx"][Math.floor(Math.random()*5)],
									 "cuisine": ["Bakery","Hamburgers","Irish","American","Jewish","Delicatessen","Ice","Chinese","Chicken","Turkish","Caribbean","Donuts","Sandwiches"][Math.floor(Math.random()*13)],
									 "grades": [
								 			{
								 				"date": {
								 					"date": randomDate(new Date(2000, 0, 1), new Date()).getTime()
								 					},
											 	"grade": "ABCD"[Math.floor(Math.random()*4)], "score": Math.floor(Math.random()*11)
											},
											{
												"date": {
											 		"date": randomDate(new Date(2000, 0, 1), new Date()).getTime()
												},
											 "grade": "ABCD"[Math.floor(Math.random()*4)], "score": Math.floor(Math.random()*11)
											},
											 {
											 	"date": {
											 		"date": randomDate(new Date(2000, 0, 1), new Date()).getTime()
											 	},
											 	"grade": "ABCD"[Math.floor(Math.random()*4)], "score": Math.floor(Math.random()*11)
											 },
											 {
											 	"date": {
											 		"date": randomDate(new Date(2000, 0, 1), new Date()).getTime()
											 	},
											 	"grade": "ABCD"[Math.floor(Math.random()*4)], "score": Math.floor(Math.random()*11)
											 },
											 {
											 	"date": {
											 		"date": randomDate(new Date(2000, 0, 1), new Date()).getTime()
											 	},
											 	"grade": "ABCD"[Math.floor(Math.random()*4)], "score": Math.floor(Math.random()*11)
											 }
									 	],
									 "name": ["Morris","Wendy","Riviera","Tov","Brunos","Kosher","Wilken","Regina","Taste","Wild","Seuda","Carvel","Nordic","Glorious","The","Sal","Bully","Steve","Harriet","Angelika"][Math.floor(Math.random()*20)]+" Shop",
									 "restaurant_id": String(Math.floor(Math.random()*30000000))
									}
							);
							print("Generated")
						}
						break;
					case typeof a[0] === 'object' && !Array.isArray(a[0]) && !isEmpty(a[0]) :
						result = {};
						(function(obj,nest){
							arr = [];
							for(i in obj){
								arr.push(i);
							}
							for(j = 0 ; j < arr.length; j++ ){
								if(typeof obj[arr[j]] === 'string'){
									if(nest){
										result[nest][arr[j]] = randomString()
									}else{
									result[arr[j]] = randomString()};
								}
								else if(typeof obj[arr[j]] === 'object' && !Array.isArray(obj[arr[j]]) && !isEmpty(obj[arr[j]]) ){
									result[arr[j]] = {};
									arguments.callee(obj[arr[j]], [arr[j]]);
								}
								else if(typeof obj[arr[j]] === 'object' && Array.isArray(obj[arr[j]]) && obj[arr[j]].length){
									print('arr');
								}
								else{
									print('wrong input');
								}
							}
						})(a[0])
						db[b]['insert'](result);
						break;
					default :
						print('wrong input , plz check the documentation');
						break;
				}
				function randomDate(start, end) {
				    return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
				}
				function isEmpty(obj) {

				    // null and undefined are "empty"
				    if (obj == null) return true;

				    // Assume if it has a length property with a non-zero value
				    // that that property is correct.
				    if (obj.length > 0)    return false;
				    if (obj.length === 0)  return true;

				    // Otherwise, does it have any properties of its own?
				    // Note that this doesn't handle
				    // toString and valueOf enumeration bugs in IE < 9
				    for (var key in obj) {
				        if (Object.prototype.hasOwnProperty.call(obj, key)) return false;
				    }

				    return true;
				}
				function randomString()
				{
				    var text = "";
				    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

				    for( var i=0; i < 5; i++ )
				        text += possible.charAt(Math.floor(Math.random() * possible.length));

				    return text;
				}
			}(localargs, this.args, this.count))
		}else{
			print("You can define some options or use Init(...).gen('default')" );
		}
	};

	Init.prototype.total = function(n){
		this.count = n;
		return this;
	}

	this.Geninit = function(){
		return new Init(arguments);
	}

}.call(this))<commit_msg>More addons<commit_after>(function(){

	// Initialization
	function Init(){
		this.args = (function(a){
			return [].slice.call(a[0]);
		}(arguments));
		this.count = 10;
	}

	// Take input and generate data base on the input
	Init.prototype.fire = function(){
		if (arguments.length){
			localargs = [].slice.call(arguments);
			(function(a,b,c){
				switch(true){
					case (a[0] === 'default') :
						for(i = 1; i <= c; i++){
							db[b]['insert'](
									{"address": {
											"building": Math.floor(Math.random()*10001),
											"coord": [-(Math.random()*100000001/1000000).toFixed(6), (Math.random()*100000001/1000000).toFixed(6)],
											"street": ['East','South','West','North'][Math.floor(Math.random()*4)]+' '+Math.floor(Math.random()*101)+' Street',
											"zipcode": Math.floor(Math.random()*10001)
										},
									 "borough": ["Manhattan","Brooklyn","Queens","Staten","Bronx"][Math.floor(Math.random()*5)],
									 "cuisine": ["Bakery","Hamburgers","Irish","American","Jewish","Delicatessen","Ice","Chinese","Chicken","Turkish","Caribbean","Donuts","Sandwiches"][Math.floor(Math.random()*13)],
									 "grades": [
								 			{
								 				"date": {
								 					"date": randomDate(new Date(2000, 0, 1), new Date()).getTime()
								 					},
											 	"grade": "ABCD"[Math.floor(Math.random()*4)], "score": Math.floor(Math.random()*11)
											},
											{
												"date": {
											 		"date": randomDate(new Date(2000, 0, 1), new Date()).getTime()
												},
											 "grade": "ABCD"[Math.floor(Math.random()*4)], "score": Math.floor(Math.random()*11)
											},
											 {
											 	"date": {
											 		"date": randomDate(new Date(2000, 0, 1), new Date()).getTime()
											 	},
											 	"grade": "ABCD"[Math.floor(Math.random()*4)], "score": Math.floor(Math.random()*11)
											 },
											 {
											 	"date": {
											 		"date": randomDate(new Date(2000, 0, 1), new Date()).getTime()
											 	},
											 	"grade": "ABCD"[Math.floor(Math.random()*4)], "score": Math.floor(Math.random()*11)
											 },
											 {
											 	"date": {
											 		"date": randomDate(new Date(2000, 0, 1), new Date()).getTime()
											 	},
											 	"grade": "ABCD"[Math.floor(Math.random()*4)], "score": Math.floor(Math.random()*11)
											 }
									 	],
									 "name": ["Morris","Wendy","Riviera","Tov","Brunos","Kosher","Wilken","Regina","Taste","Wild","Seuda","Carvel","Nordic","Glorious","The","Sal","Bully","Steve","Harriet","Angelika"][Math.floor(Math.random()*20)]+" Shop",
									 "restaurant_id": String(Math.floor(Math.random()*30000000))
									}
							);
						}
						print("\nAwesome ~ Generated "+c+" default test data\nUse db[collection].find().pretty(); to view :)\n");
						break;
					case typeof a[0] === 'object' && !Array.isArray(a[0]) && !isEmpty(a[0]) :
						for(z = 1; z <= c; z++){
							// Create an outer empty obj to collect the output
							result = {};
							// Recursion for nesting obj or array
							(function(obj,nest){

								// Basic setting
								arr = [];
								for(i in obj){
									arr.push(i);
								}

								for(j = 0 ; j < arr.length; j++ ){
									if(//typeof obj[arr[j]] === 'string' ||
										obj[arr[j]] === 'str'){

										// Recursion exit
										if(nest){
											result[nest][arr[j]] = randomString()
										}else{
										result[arr[j]] = randomString()};

									}
									// Handle number
									else if(//typeof obj[arr[j]] === 'number' ||
										obj[arr[j]] === 'num'){
										if(nest){
											result[nest][arr[j]] = randomNumber()
										}else{
										result[arr[j]] = randomNumber()};
									}
									// Handle boolean
									else if(//typeof obj[arr[j]] === 'boolean' ||
										obj[arr[j]] === 'bool'){
										if(nest){
											result[nest][arr[j]] = randomBool()
										}else{
										result[arr[j]] = randomBool()};
									}
									// Check if the current input is an obj
									else if(typeof obj[arr[j]] === 'object' && !Array.isArray(obj[arr[j]]) && !isEmpty(obj[arr[j]]) ){

										result[arr[j]] = {};
										arguments.callee(obj[arr[j]], [arr[j]]);
									}
									// Check if the current input is an array
									else if(typeof obj[arr[j]] === 'object' && Array.isArray(obj[arr[j]]) && obj[arr[j]].length){

										result[arr[j]] = [];
										arguments.callee(obj[arr[j]], [arr[j]]);

									}
									else{
										print('\nOops, Wrong input, Plz check the documentation\nOr try gen_Init[collection].fire(\'default\'); to get the default testing data :)\n ');
									}
								}
							})(a[0])
							db[b]['insert'](result);
						}
						print("\nAwesome ~ Generated "+c+" default test data\nUse db[collection].find().pretty(); to view :)\n");
						break;
					default :
						print('\nOops, Wrong input, Plz check the documentation\nOr try gen_Init[collection].fire(\'default\'); to get the default testing data :)\n ');
						break;
				}
				// Hoisting functions
				function randomDate(start, end) {
				    return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
				}

				// Check if the obj is empty
				function isEmpty(obj) {
				    if (obj == null) return true;
				    if (obj.length > 0)    return false;
				    if (obj.length === 0)  return true;
				    for (var key in obj) {
				        if (Object.prototype.hasOwnProperty.call(obj, key)) return false;
				    }
				    return true;
				}

				// Handle random string
				function randomString(){
				    var text = "";
				    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

				    for( var i=0; i < 5; i++ )
				        text += possible.charAt(Math.floor(Math.random() * possible.length));

				    return text;
				}

				// Handle random number
				function randomNumber(){
					return Math.floor(Math.random()*100);//for test
				}

				// Handle random boolean
				function randomBool(){
					return [true,false][Math.floor(Math.random()*2)]
				}
			}(localargs, this.args, this.count))
		}else{
			print("You can define some options or use Init(...).gen('default')" );
		}
	};

	// Specify the amount of data to insert
	Init.prototype.total = function(n){
		this.count = n;
		return this;
	}

	// Output to the global
	this.gen_Init = function(){
		return new Init(arguments);
	}

}.call(this))<|endoftext|>


<commit_before>// Copyright 2017, University of Colorado Boulder

/**
 * Manages a queue of Utterances that are read in order by a screen reader.  This queue typically reads
 * things in a first-in-first-out manner, but it is possible to send an alert directly to the front of
 * the queue.  Items in the queue are sent to the screen reader front to back with a certain delay interval.
 *
 * Screen readers are inconsistent in the way that they order alerts, some use last-in-first-out order,
 * others use first-in-first-out order, others just read the last alert that was provided. This queue
 * manages order and improves consistency.
 *
 * NOTE: utteranceQueue is a type but instantiated and returned as a singleton.  It is initialized by Sim.js and if
 * something adds an alert to the queue before Sim.js has initialized the queue, the result will be a silent no-op.
 *
 * @author Jesse Greenberg (PhET Interactive Simulations)
 * @author Michael Kauzmann (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var AriaHerald = require( 'SCENERY_PHET/accessibility/AriaHerald' );
  var inherit = require( 'PHET_CORE/inherit' );
  var PhetioObject = require( 'TANDEM/PhetioObject' );
  var sceneryPhet = require( 'SCENERY_PHET/sceneryPhet' );
  var Tandem = require( 'TANDEM/Tandem' );
  var Timer = require( 'PHET_CORE/Timer' );
  var Utterance = require( 'SCENERY_PHET/accessibility/Utterance' );
  var UtteranceQueueIO = require( 'SCENERY_PHET/accessibility/UtteranceQueueIO' );

  // {Utterance} - array of utterances, spoken in first to last order
  var queue = [];

  // the interval for sending alerts to the screen reader, in milliseconds
  var interval = 500;

  // whether or not Utterances moving through the queue are read by a screen reader
  var muted = false;

  // whether the UtterancesQueue is alerting, and if you can add/remove utterances
  var enabled = true;

  // initialization is like utteranceQueue's constructor. No-ops all around if not initialized (cheers).
  var initialized = false;

  function utteranceQueue() {

    PhetioObject.call( this ); // options will be provided in initialize (if it is ever called)
  }

  inherit( PhetioObject, utteranceQueue, {

    /**
     * Add an utterance ot the end of the queue.  If the utterance has a type of alert which
     * is already in the queue, the older alert will be immediately removed.
     *
     * @public
     * @param {Utterance|string} utterance
     */
    addToBack: function( utterance ) {
      assert && assert( utterance instanceof Utterance || typeof utterance === 'string',
        'utterance queue only supports string or type Utterance.' );

      // No-op function if the utteranceQueue is disabled
      if ( !enabled || !initialized ) {
        return;
      }

      if ( typeof utterance === 'string' ) {
        utterance = new Utterance( utterance );
      }

      // if there are any other items in the queue of the same type, remove them immediately
      // because the new utterance is meant to replace them
      if ( utterance.typeId ) {
        for ( var i = queue.length - 1; i >= 0; i-- ) {
          var otherUtterance = queue[ i ];
          if ( otherUtterance.typeId === utterance.typeId ) {
            queue.splice( i, 1 );
          }
        }
      }

      queue.push( utterance );
    },

    /**
     * Add an utterance to the front of the queue to be read immediately.
     * @param {Utterance|string} utterance
     */
    addToFront: function( utterance ) {
      assert && assert( utterance instanceof Utterance || typeof utterance === 'string',
        'utterance queue only supports string or type Utterance.' );

      // No-op function if the utteranceQueue is disabled
      if ( !enabled || !initialized ) {
        return;
      }

      if ( typeof utterance === 'string' ) {
        utterance = new Utterance( utterance );
      }
      queue.unshift( utterance );
    },

    /**
     * Move to the next item in the queue. Checks the Utterance predicate first, if predicate
     * returns false, no alert will be read. Called privately by Timer.setInterval
     *
     * @private
     */
    next: function() {

      // get and remove the next item from the queue
      var nextUtterance = queue.shift();

      // only speak the utterance if the Utterance predicate returns true
      if ( nextUtterance && !muted && nextUtterance.predicate() ) {

        // phet-io event to the data stream
        this.startEvent( 'model', 'announced', { utterance: nextUtterance.text } );

        // Pass the utterance text on to be set in the PDOM.
        AriaHerald.announcePolite( nextUtterance.text );

        this.endEvent();
      }
    },

    /**
     * Clear the utteranceQueue of all Utterances, any Utterances remaining in the queue will
     * not be announced by the screen reader.
     *
     * @public
     */
    clear: function() {
      queue = [];
    },

    /**
     * Set whether or not the utterance queue is muted.  When muted, Utterances will still
     * move through the queue, but nothing will be sent to assistive technology.
     *
     * @param {boolean} isMuted
     */
    setMuted: function( isMuted ) {
      muted = isMuted;
    },
    set muted( isMuted ) { this.setMuted( isMuted ); },

    /**
     * Get whether or not the utteranceQueue is muted.  When muted, Utterances will still
     * move through the queue, but nothing will be read by asistive technology.
     * @public
     */
    getMuted: function() {
      return muted;
    },
    get muted() { return this.getMuted(); },

    /**
     * Set whether or not the utterance queue is enabled.  When enabled, Utterances cannot be added to
     * the queue, and the Queue cannot be cleared. Also nothing will be sent to assistive technology.
     *
     * @param {boolean} isEnabled
     */
    setEnabled: function( isEnabled ) {
      enabled = isEnabled;
    },
    set enabled( isEnabled ) { this.setEnabled( isEnabled ); },

    /**
     * Get whether or not the utterance queue is enabled.  When enabled, Utterances cannot be added to
     * the queue, and the Queue cannot be cleared. Also nothing will be sent to assistive technology.
     * @public
     */
    getEnabled: function() {
      return enabled;
    },
    get enabled() { return this.getEnabled(); },

    /**
     * Get the interval that alerts are sent to the screen reader.
     *
     * @public
     * @return {number}
     */
    getInterval: function() {
      return interval;
    },
    get interval() { return this.getInterval(); },

    /**
     * Set the alert interval in milliseconds
     * @public
     * @param {number} alertInterval
     */
    setInterval: function( alertInterval ) {
      interval = alertInterval;
    },
    set interval( alertInterval ) { this.setInterval( alertInterval ); },

    /**
     * Basically a constructor for the queue. Setup necessary processes for running the queue and register
     * the phet-io tandem. If utteranceQueue is not initialized (say, when accessibility is not enabled), all functions
     * will be no-ops. See type documentation above for NOTE.
     * @public
     */
    initialize: function() {
      initialized = true;

      var self = this;

      // step the alert queue
      Timer.setInterval( function() {

        // No-op function if the utteranceQueue is disabled
          if ( !enabled ) {
            return;
          }

          self.next();
        }, this.interval
      );

      // TODO: can this be moved to the constructor?
      this.initializePhetioObject( {}, {
        tandem: Tandem.rootTandem.createTandem( 'utteranceQueue' ),
        phetioType: UtteranceQueueIO,
        phetioState: false
      } );
    }
  } );

  var instance = new utteranceQueue();

  sceneryPhet.register( 'utteranceQueue', instance );

  return instance;
} );<commit_msg>formatting<commit_after>// Copyright 2017, University of Colorado Boulder

/**
 * Manages a queue of Utterances that are read in order by a screen reader.  This queue typically reads
 * things in a first-in-first-out manner, but it is possible to send an alert directly to the front of
 * the queue.  Items in the queue are sent to the screen reader front to back with a certain delay interval.
 *
 * Screen readers are inconsistent in the way that they order alerts, some use last-in-first-out order,
 * others use first-in-first-out order, others just read the last alert that was provided. This queue
 * manages order and improves consistency.
 *
 * NOTE: utteranceQueue is a type but instantiated and returned as a singleton.  It is initialized by Sim.js and if
 * something adds an alert to the queue before Sim.js has initialized the queue, the result will be a silent no-op.
 *
 * @author Jesse Greenberg (PhET Interactive Simulations)
 * @author Michael Kauzmann (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var AriaHerald = require( 'SCENERY_PHET/accessibility/AriaHerald' );
  var inherit = require( 'PHET_CORE/inherit' );
  var PhetioObject = require( 'TANDEM/PhetioObject' );
  var sceneryPhet = require( 'SCENERY_PHET/sceneryPhet' );
  var Tandem = require( 'TANDEM/Tandem' );
  var Timer = require( 'PHET_CORE/Timer' );
  var Utterance = require( 'SCENERY_PHET/accessibility/Utterance' );
  var UtteranceQueueIO = require( 'SCENERY_PHET/accessibility/UtteranceQueueIO' );

  // {Utterance} - array of utterances, spoken in first to last order
  var queue = [];

  // the interval for sending alerts to the screen reader, in milliseconds
  var interval = 500;

  // whether or not Utterances moving through the queue are read by a screen reader
  var muted = false;

  // whether the UtterancesQueue is alerting, and if you can add/remove utterances
  var enabled = true;

  // initialization is like utteranceQueue's constructor. No-ops all around if not initialized (cheers).
  var initialized = false;

  function utteranceQueue() {

    PhetioObject.call( this ); // options will be provided in initialize (if it is ever called)
  }

  inherit( PhetioObject, utteranceQueue, {

    /**
     * Add an utterance ot the end of the queue.  If the utterance has a type of alert which
     * is already in the queue, the older alert will be immediately removed.
     *
     * @public
     * @param {Utterance|string} utterance
     */
    addToBack: function( utterance ) {
      assert && assert( utterance instanceof Utterance || typeof utterance === 'string',
        'utterance queue only supports string or type Utterance.' );

      // No-op function if the utteranceQueue is disabled
      if ( !enabled || !initialized ) {
        return;
      }

      if ( typeof utterance === 'string' ) {
        utterance = new Utterance( utterance );
      }

      // if there are any other items in the queue of the same type, remove them immediately
      // because the new utterance is meant to replace them
      if ( utterance.typeId ) {
        for ( var i = queue.length - 1; i >= 0; i-- ) {
          var otherUtterance = queue[ i ];
          if ( otherUtterance.typeId === utterance.typeId ) {
            queue.splice( i, 1 );
          }
        }
      }

      queue.push( utterance );
    },

    /**
     * Add an utterance to the front of the queue to be read immediately.
     * @param {Utterance|string} utterance
     */
    addToFront: function( utterance ) {
      assert && assert( utterance instanceof Utterance || typeof utterance === 'string',
        'utterance queue only supports string or type Utterance.' );

      // No-op function if the utteranceQueue is disabled
      if ( !enabled || !initialized ) {
        return;
      }

      if ( typeof utterance === 'string' ) {
        utterance = new Utterance( utterance );
      }
      queue.unshift( utterance );
    },

    /**
     * Move to the next item in the queue. Checks the Utterance predicate first, if predicate
     * returns false, no alert will be read. Called privately by Timer.setInterval
     *
     * @private
     */
    next: function() {

      // get and remove the next item from the queue
      var nextUtterance = queue.shift();

      // only speak the utterance if the Utterance predicate returns true
      if ( nextUtterance && !muted && nextUtterance.predicate() ) {

        // phet-io event to the data stream
        this.startEvent( 'model', 'announced', { utterance: nextUtterance.text } );

        // Pass the utterance text on to be set in the PDOM.
        AriaHerald.announcePolite( nextUtterance.text );

        this.endEvent();
      }
    },

    /**
     * Clear the utteranceQueue of all Utterances, any Utterances remaining in the queue will
     * not be announced by the screen reader.
     *
     * @public
     */
    clear: function() {
      queue = [];
    },

    /**
     * Set whether or not the utterance queue is muted.  When muted, Utterances will still
     * move through the queue, but nothing will be sent to assistive technology.
     *
     * @param {boolean} isMuted
     */
    setMuted: function( isMuted ) {
      muted = isMuted;
    },
    set muted( isMuted ) { this.setMuted( isMuted ); },

    /**
     * Get whether or not the utteranceQueue is muted.  When muted, Utterances will still
     * move through the queue, but nothing will be read by asistive technology.
     * @public
     */
    getMuted: function() {
      return muted;
    },
    get muted() { return this.getMuted(); },

    /**
     * Set whether or not the utterance queue is enabled.  When enabled, Utterances cannot be added to
     * the queue, and the Queue cannot be cleared. Also nothing will be sent to assistive technology.
     *
     * @param {boolean} isEnabled
     */
    setEnabled: function( isEnabled ) {
      enabled = isEnabled;
    },
    set enabled( isEnabled ) { this.setEnabled( isEnabled ); },

    /**
     * Get whether or not the utterance queue is enabled.  When enabled, Utterances cannot be added to
     * the queue, and the Queue cannot be cleared. Also nothing will be sent to assistive technology.
     * @public
     */
    getEnabled: function() {
      return enabled;
    },
    get enabled() { return this.getEnabled(); },

    /**
     * Get the interval that alerts are sent to the screen reader.
     *
     * @public
     * @return {number}
     */
    getInterval: function() {
      return interval;
    },
    get interval() { return this.getInterval(); },

    /**
     * Set the alert interval in milliseconds
     * @public
     * @param {number} alertInterval
     */
    setInterval: function( alertInterval ) {
      interval = alertInterval;
    },
    set interval( alertInterval ) { this.setInterval( alertInterval ); },

    /**
     * Basically a constructor for the queue. Setup necessary processes for running the queue and register
     * the phet-io tandem. If utteranceQueue is not initialized (say, when accessibility is not enabled), all functions
     * will be no-ops. See type documentation above for NOTE.
     * @public
     */
    initialize: function() {
      initialized = true;

      var self = this;

      // step the alert queue
      Timer.setInterval( function() {

        // No-op function if the utteranceQueue is disabled
        if ( !enabled ) {
          return;
        }

        self.next();
      }, this.interval );

      // TODO: can this be moved to the constructor?
      this.initializePhetioObject( {}, {
        tandem: Tandem.rootTandem.createTandem( 'utteranceQueue' ),
        phetioType: UtteranceQueueIO,
        phetioState: false
      } );
    }
  } );

  var instance = new utteranceQueue();

  sceneryPhet.register( 'utteranceQueue', instance );

  return instance;
} );<|endoftext|>


<commit_before>/*jslint indent: 2, maxlen: 120, vars: true, white: true, plusplus: true, nonpropdel: true, nomen: true, sloppy: true */
/*global require, fail, assertTrue, assertEqual */

////////////////////////////////////////////////////////////////////////////////
/// @brief test the endpoints
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

(function () {

var jsunity = require("jsunity");
var arangodb = require("org/arangodb");
var arango = arangodb.arango;
var db = arangodb.db;
var ERRORS = arangodb.errors;
var originalEndpoint = arango.getEndpoint().replace(/localhost/, '127.0.0.1');

// -----------------------------------------------------------------------------
// --SECTION--                                                   endpoints tests
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief test suite
////////////////////////////////////////////////////////////////////////////////

function EndpointsSuite () {

  var cleanupEndpoints = function () {
    db._useDatabase("_system");

    db._listEndpoints().forEach(function (e) {
      if (e.endpoint.replace(/localhost/, '127.0.0.1') !== originalEndpoint) {
        db._removeEndpoint(e.endpoint);
      }
    });
  };

  var filterDefault = function (endpoints) {
    var result = [ ];

    endpoints.forEach(function (e) {
      if (e.endpoint.replace(/localhost/, '127.0.0.1') !== originalEndpoint) {
        result.push(e);
      }
    });

    return result;
  };

  return {

////////////////////////////////////////////////////////////////////////////////
/// @brief set up
////////////////////////////////////////////////////////////////////////////////

    setUp : function () {
      cleanupEndpoints();
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief tear down
////////////////////////////////////////////////////////////////////////////////

    tearDown : function () {
      cleanupEndpoints();

      var i;
      for (i = 0; i < 3; ++i) {
        try {
          db._dropDatabase("UnitTestsDatabase" + i);
        }
        catch (err) {
        }
      }

      arango.reconnect(originalEndpoint, "", "root", "");
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief add a few endpoints and check the list result
////////////////////////////////////////////////////////////////////////////////

    testListEndpoints : function () {
      assertEqual("_system", db._name());

      var i;
      var base = 30000 + parseInt(Math.random() * 10000, 10);

      // open a few endpoints
      var dbNames = [ ];
      for (i = 0; i < 3; ++i) {
        db._configureEndpoint("tcp://127.0.0.1:" + (base + i), dbNames);
        dbNames.push("db" + i);
      }

      var expected = [
        { endpoint: "tcp://127.0.0.1:" + base, databases: [ ] },
        { endpoint: "tcp://127.0.0.1:" + (base + 1), databases: [ "db0" ] },
        { endpoint: "tcp://127.0.0.1:" + (base + 2), databases: [ "db0", "db1" ] }
      ];

      var actual = filterDefault(db._listEndpoints());
      assertEqual(expected, actual);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test configure
////////////////////////////////////////////////////////////////////////////////

    testConfigureEndpoints : function () {
      assertEqual("_system", db._name());

      var i;
      var base = 30000 + parseInt(Math.random() * 10000, 10);

      // open a few endpoints
      var dbNames = [ ];
      for (i = 0; i < 3; ++i) {
        db._configureEndpoint("tcp://127.0.0.1:" + (base + i), dbNames);
        dbNames.push("db" + i);
      }

      db._configureEndpoint("tcp://127.0.0.1:" + (base + 2), [ ]);
      db._configureEndpoint("tcp://127.0.0.1:" + (base + 1), [ "abc", "def" ]);
      db._configureEndpoint("tcp://127.0.0.1:" + (base ), [ "_system" ]);

      var expected = [
        { endpoint: "tcp://127.0.0.1:" + base, databases: [ "_system" ] },
        { endpoint: "tcp://127.0.0.1:" + (base + 1), databases: [ "abc", "def" ] },
        { endpoint: "tcp://127.0.0.1:" + (base + 2), databases: [ ] }
      ];

      var actual = filterDefault(db._listEndpoints());
      assertEqual(expected, actual);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test configure
////////////////////////////////////////////////////////////////////////////////

    testConfigureInvalidEndpoints : function () {
      assertEqual("_system", db._name());

      var base = 30000 + parseInt(Math.random() * 10000, 10);

      try {
        // invalid type for 2nd argument
        db._configureEndpoint("tcp://127.0.0.1:" + base, { });
        fail();
      }
      catch (err1) {
        assertEqual(ERRORS.ERROR_BAD_PARAMETER.code, err1.errorNum);
      }

      try {
        // invalid type for 2nd argument
        db._configureEndpoint("tcp://127.0.0.1:" + base, "_system");
        fail();
      }
      catch (err2) {
        assertEqual(ERRORS.ERROR_BAD_PARAMETER.code, err2.errorNum);
      }

      try {
        // invalid type for 1st argument
        db._configureEndpoint("foo", "_system");
        fail();
      }
      catch (err3) {
        assertEqual(ERRORS.ERROR_BAD_PARAMETER.code, err3.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test remove
////////////////////////////////////////////////////////////////////////////////

    testRemoveEndpoints : function () {
      assertEqual("_system", db._name());

      var i;
      var base = 30000 + parseInt(Math.random() * 10000, 10);

      // open a few endpoints
      var dbNames = [ ];
      for (i = 0; i < 3; ++i) {
        db._configureEndpoint("tcp://127.0.0.1:" + (base + i), dbNames);
        dbNames.push("db" + i);
      }

      // remove one
      assertTrue(db._removeEndpoint("tcp://127.0.0.1:" + base));

      var expected = [
        { endpoint: "tcp://127.0.0.1:" + (base + 1), databases: [ "db0" ] },
        { endpoint: "tcp://127.0.0.1:" + (base + 2), databases: [ "db0", "db1" ] }
      ];

      var actual = filterDefault(db._listEndpoints());
      assertEqual(expected, actual);

      // remove next
      assertTrue(db._removeEndpoint("tcp://127.0.0.1:" + (base + 2)));

      expected = [
        { endpoint: "tcp://127.0.0.1:" + (base + 1), databases: [ "db0" ] }
      ];

      actual = filterDefault(db._listEndpoints());
      assertEqual(expected, actual);

      // remove last
      assertTrue(db._removeEndpoint("tcp://127.0.0.1:" + (base + 1)));

      expected = [
      ];

      actual = filterDefault(db._listEndpoints());
      assertEqual(expected, actual);

      try {
        // remove non-existing
        db._removeEndpoint("tcp://127.0.0.1:" + base);
        fail();
      }
      catch (err) {
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test database access
////////////////////////////////////////////////////////////////////////////////

    testDatabaseAccess : function () {
      // create some databases
      db._createDatabase("UnitTestsDatabase0");
      db._createDatabase("UnitTestsDatabase1");
      db._createDatabase("UnitTestsDatabase2");

      var base = 30000 + parseInt(Math.random() * 10000, 10);

      // create a few endpoints
      db._configureEndpoint("tcp://127.0.0.1:" + (base), [ ]);
      db._configureEndpoint("tcp://127.0.0.1:" + (base + 1), [ "UnitTestsDatabase0" ]);
      db._configureEndpoint("tcp://127.0.0.1:" + (base + 2), [ "UnitTestsDatabase1" ]);
      db._configureEndpoint("tcp://127.0.0.1:" + (base + 3), [ "UnitTestsDatabase0", "UnitTestsDatabase1" ]);
      db._configureEndpoint("tcp://127.0.0.1:" + (base + 4), [ "UnitTestsDatabase1", "_system" ]);

      // and now connect to the endpoints
      var test = function (endpoint, endpoints) {
        endpoints.forEach(function (e) {
          if (e[1] === null) {
            try {
              arango.reconnect(endpoint, e[0], "root", "");
              fail();
            }
            catch (err) {
            }
          }
          else {
            arango.reconnect(endpoint, e[0], "root", "");
            assertEqual(e[1], db._name());
          }
        });
      };

      var endpoints;

      endpoints = [
        [ "", "_system" ],
        [ "_system", "_system" ],
        [ "UnitTestsDatabase0", "UnitTestsDatabase0" ],
        [ "UnitTestsDatabase1", "UnitTestsDatabase1" ]
      ];

      test("tcp://127.0.0.1:" + (base), endpoints);

      endpoints = [
        [ "", "UnitTestsDatabase0" ],
        [ "_system", null ],
        [ "UnitTestsDatabase0", "UnitTestsDatabase0" ],
        [ "UnitTestsDatabase1", null ]
      ];

      test("tcp://127.0.0.1:" + (base + 1), endpoints);

      endpoints = [
        [ "", "UnitTestsDatabase1" ],
        [ "_system", null ],
        [ "UnitTestsDatabase0", null ],
        [ "UnitTestsDatabase1", "UnitTestsDatabase1" ]
      ];

      test("tcp://127.0.0.1:" + (base + 2), endpoints);

      endpoints = [
        [ "", "UnitTestsDatabase0" ],
        [ "_system", null ],
        [ "UnitTestsDatabase0", "UnitTestsDatabase0" ],
        [ "UnitTestsDatabase1", "UnitTestsDatabase1" ]
      ];

      test("tcp://127.0.0.1:" + (base + 3), endpoints);

      endpoints = [
        [ "", "UnitTestsDatabase1" ],
        [ "_system", "_system" ],
        [ "UnitTestsDatabase0", null ],
        [ "UnitTestsDatabase1", "UnitTestsDatabase1" ]
      ];

      test("tcp://127.0.0.1:" + (base + 4), endpoints);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test non-system
////////////////////////////////////////////////////////////////////////////////

    testEndpointsNonSystem : function () {
      assertEqual("_system", db._name());

      try {
        db._dropDatabase("UnitTestsDatabase0");
      }
      catch (err1) {
      }

      db._createDatabase("UnitTestsDatabase0");
      db._useDatabase("UnitTestsDatabase0");

      // _listEndpoints is forbidden
      try {
        db._listEndpoints();
        fail();
      }
      catch (err2) {
        assertEqual(ERRORS.ERROR_ARANGO_USE_SYSTEM_DATABASE.code, err2.errorNum);
      }

      // _configureEndpoint is forbidden
      try {
        var base = 30000 + parseInt(Math.random() * 10000, 10);
        db._configureEndpoint("tcp://127.0.0.1:" + base, [ ]);
        fail();
      }
      catch (err3) {
        assertEqual(ERRORS.ERROR_ARANGO_USE_SYSTEM_DATABASE.code, err3.errorNum);
      }
    }

  };
}

// -----------------------------------------------------------------------------
// --SECTION--                                                              main
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suite
////////////////////////////////////////////////////////////////////////////////

jsunity.run(EndpointsSuite);

return jsunity.done();
}());

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\)"
// End:

<commit_msg>fix invalid database name<commit_after>/*jslint indent: 2, maxlen: 120, vars: true, white: true, plusplus: true, nonpropdel: true, nomen: true, sloppy: true */
/*global require, fail, assertTrue, assertEqual */

////////////////////////////////////////////////////////////////////////////////
/// @brief test the endpoints
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

(function () {

var jsunity = require("jsunity");
var arangodb = require("org/arangodb");
var arango = arangodb.arango;
var db = arangodb.db;
var ERRORS = arangodb.errors;
var originalEndpoint = arango.getEndpoint().replace(/localhost/, '127.0.0.1');

// -----------------------------------------------------------------------------
// --SECTION--                                                   endpoints tests
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief test suite
////////////////////////////////////////////////////////////////////////////////

function EndpointsSuite () {

  var cleanupEndpoints = function () {
    db._useDatabase("_system");

    db._listEndpoints().forEach(function (e) {
      if (e.endpoint.replace(/localhost/, '127.0.0.1') !== originalEndpoint) {
        db._removeEndpoint(e.endpoint);
      }
    });
  };

  var filterDefault = function (endpoints) {
    var result = [ ];

    endpoints.forEach(function (e) {
      if (e.endpoint.replace(/localhost/, '127.0.0.1') !== originalEndpoint) {
        result.push(e);
      }
    });

    return result;
  };

  return {

////////////////////////////////////////////////////////////////////////////////
/// @brief set up
////////////////////////////////////////////////////////////////////////////////

    setUp : function () {
      cleanupEndpoints();
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief tear down
////////////////////////////////////////////////////////////////////////////////

    tearDown : function () {
      cleanupEndpoints();

      var i;
      for (i = 0; i < 3; ++i) {
        try {
          db._dropDatabase("UnitTestsDatabase" + i);
        }
        catch (err) {
        }
      }

      arango.reconnect(originalEndpoint, "_system", "root", "");
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief add a few endpoints and check the list result
////////////////////////////////////////////////////////////////////////////////

    testListEndpoints : function () {
      assertEqual("_system", db._name());

      var i;
      var base = 30000 + parseInt(Math.random() * 10000, 10);

      // open a few endpoints
      var dbNames = [ ];
      for (i = 0; i < 3; ++i) {
        db._configureEndpoint("tcp://127.0.0.1:" + (base + i), dbNames);
        dbNames.push("db" + i);
      }

      var expected = [
        { endpoint: "tcp://127.0.0.1:" + base, databases: [ ] },
        { endpoint: "tcp://127.0.0.1:" + (base + 1), databases: [ "db0" ] },
        { endpoint: "tcp://127.0.0.1:" + (base + 2), databases: [ "db0", "db1" ] }
      ];

      var actual = filterDefault(db._listEndpoints());
      assertEqual(expected, actual);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test configure
////////////////////////////////////////////////////////////////////////////////

    testConfigureEndpoints : function () {
      assertEqual("_system", db._name());

      var i;
      var base = 30000 + parseInt(Math.random() * 10000, 10);

      // open a few endpoints
      var dbNames = [ ];
      for (i = 0; i < 3; ++i) {
        db._configureEndpoint("tcp://127.0.0.1:" + (base + i), dbNames);
        dbNames.push("db" + i);
      }

      db._configureEndpoint("tcp://127.0.0.1:" + (base + 2), [ ]);
      db._configureEndpoint("tcp://127.0.0.1:" + (base + 1), [ "abc", "def" ]);
      db._configureEndpoint("tcp://127.0.0.1:" + (base ), [ "_system" ]);

      var expected = [
        { endpoint: "tcp://127.0.0.1:" + base, databases: [ "_system" ] },
        { endpoint: "tcp://127.0.0.1:" + (base + 1), databases: [ "abc", "def" ] },
        { endpoint: "tcp://127.0.0.1:" + (base + 2), databases: [ ] }
      ];

      var actual = filterDefault(db._listEndpoints());
      assertEqual(expected, actual);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test configure
////////////////////////////////////////////////////////////////////////////////

    testConfigureInvalidEndpoints : function () {
      assertEqual("_system", db._name());

      var base = 30000 + parseInt(Math.random() * 10000, 10);

      try {
        // invalid type for 2nd argument
        db._configureEndpoint("tcp://127.0.0.1:" + base, { });
        fail();
      }
      catch (err1) {
        assertEqual(ERRORS.ERROR_BAD_PARAMETER.code, err1.errorNum);
      }

      try {
        // invalid type for 2nd argument
        db._configureEndpoint("tcp://127.0.0.1:" + base, "_system");
        fail();
      }
      catch (err2) {
        assertEqual(ERRORS.ERROR_BAD_PARAMETER.code, err2.errorNum);
      }

      try {
        // invalid type for 1st argument
        db._configureEndpoint("foo", "_system");
        fail();
      }
      catch (err3) {
        assertEqual(ERRORS.ERROR_BAD_PARAMETER.code, err3.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test remove
////////////////////////////////////////////////////////////////////////////////

    testRemoveEndpoints : function () {
      assertEqual("_system", db._name());

      var i;
      var base = 30000 + parseInt(Math.random() * 10000, 10);

      // open a few endpoints
      var dbNames = [ ];
      for (i = 0; i < 3; ++i) {
        db._configureEndpoint("tcp://127.0.0.1:" + (base + i), dbNames);
        dbNames.push("db" + i);
      }

      // remove one
      assertTrue(db._removeEndpoint("tcp://127.0.0.1:" + base));

      var expected = [
        { endpoint: "tcp://127.0.0.1:" + (base + 1), databases: [ "db0" ] },
        { endpoint: "tcp://127.0.0.1:" + (base + 2), databases: [ "db0", "db1" ] }
      ];

      var actual = filterDefault(db._listEndpoints());
      assertEqual(expected, actual);

      // remove next
      assertTrue(db._removeEndpoint("tcp://127.0.0.1:" + (base + 2)));

      expected = [
        { endpoint: "tcp://127.0.0.1:" + (base + 1), databases: [ "db0" ] }
      ];

      actual = filterDefault(db._listEndpoints());
      assertEqual(expected, actual);

      // remove last
      assertTrue(db._removeEndpoint("tcp://127.0.0.1:" + (base + 1)));

      expected = [
      ];

      actual = filterDefault(db._listEndpoints());
      assertEqual(expected, actual);

      try {
        // remove non-existing
        db._removeEndpoint("tcp://127.0.0.1:" + base);
        fail();
      }
      catch (err) {
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test database access
////////////////////////////////////////////////////////////////////////////////

    testDatabaseAccess : function () {
      // create some databases
      db._createDatabase("UnitTestsDatabase0");
      db._createDatabase("UnitTestsDatabase1");
      db._createDatabase("UnitTestsDatabase2");

      var base = 30000 + parseInt(Math.random() * 10000, 10);

      // create a few endpoints
      db._configureEndpoint("tcp://127.0.0.1:" + (base), [ ]);
      db._configureEndpoint("tcp://127.0.0.1:" + (base + 1), [ "UnitTestsDatabase0" ]);
      db._configureEndpoint("tcp://127.0.0.1:" + (base + 2), [ "UnitTestsDatabase1" ]);
      db._configureEndpoint("tcp://127.0.0.1:" + (base + 3), [ "UnitTestsDatabase0", "UnitTestsDatabase1" ]);
      db._configureEndpoint("tcp://127.0.0.1:" + (base + 4), [ "UnitTestsDatabase1", "_system" ]);

      // and now connect to the endpoints
      var test = function (endpoint, endpoints) {
        endpoints.forEach(function (e) {
          if (e[1] === null) {
            try {
              arango.reconnect(endpoint, e[0], "root", "");
              fail();
            }
            catch (err) {
            }
          }
          else {
            arango.reconnect(endpoint, e[0], "root", "");
            assertEqual(e[1], db._name());
          }
        });
      };

      var endpoints;

      endpoints = [
        [ "", "_system" ],
        [ "_system", "_system" ],
        [ "UnitTestsDatabase0", "UnitTestsDatabase0" ],
        [ "UnitTestsDatabase1", "UnitTestsDatabase1" ]
      ];

      test("tcp://127.0.0.1:" + (base), endpoints);

      endpoints = [
        [ "", "UnitTestsDatabase0" ],
        [ "_system", null ],
        [ "UnitTestsDatabase0", "UnitTestsDatabase0" ],
        [ "UnitTestsDatabase1", null ]
      ];

      test("tcp://127.0.0.1:" + (base + 1), endpoints);

      endpoints = [
        [ "", "UnitTestsDatabase1" ],
        [ "_system", null ],
        [ "UnitTestsDatabase0", null ],
        [ "UnitTestsDatabase1", "UnitTestsDatabase1" ]
      ];

      test("tcp://127.0.0.1:" + (base + 2), endpoints);

      endpoints = [
        [ "", "UnitTestsDatabase0" ],
        [ "_system", null ],
        [ "UnitTestsDatabase0", "UnitTestsDatabase0" ],
        [ "UnitTestsDatabase1", "UnitTestsDatabase1" ]
      ];

      test("tcp://127.0.0.1:" + (base + 3), endpoints);

      endpoints = [
        [ "", "UnitTestsDatabase1" ],
        [ "_system", "_system" ],
        [ "UnitTestsDatabase0", null ],
        [ "UnitTestsDatabase1", "UnitTestsDatabase1" ]
      ];

      test("tcp://127.0.0.1:" + (base + 4), endpoints);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test non-system
////////////////////////////////////////////////////////////////////////////////

    testEndpointsNonSystem : function () {
      assertEqual("_system", db._name());

      try {
        db._dropDatabase("UnitTestsDatabase0");
      }
      catch (err1) {
      }

      db._createDatabase("UnitTestsDatabase0");
      db._useDatabase("UnitTestsDatabase0");

      // _listEndpoints is forbidden
      try {
        db._listEndpoints();
        fail();
      }
      catch (err2) {
        assertEqual(ERRORS.ERROR_ARANGO_USE_SYSTEM_DATABASE.code, err2.errorNum);
      }

      // _configureEndpoint is forbidden
      try {
        var base = 30000 + parseInt(Math.random() * 10000, 10);
        db._configureEndpoint("tcp://127.0.0.1:" + base, [ ]);
        fail();
      }
      catch (err3) {
        assertEqual(ERRORS.ERROR_ARANGO_USE_SYSTEM_DATABASE.code, err3.errorNum);
      }
    }

  };
}

// -----------------------------------------------------------------------------
// --SECTION--                                                              main
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suite
////////////////////////////////////////////////////////////////////////////////

jsunity.run(EndpointsSuite);

return jsunity.done();
}());

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\)"
// End:

<|endoftext|>


<commit_before>// Copyright 2018, University of Colorado Boulder

/**
 * Control panel for interactive-equation. Copied from graphing-lines.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 * @author Andrea Lin
 */
define( function( require ) {
  'use strict';

  // modules
  var BooleanProperty = require( 'AXON/BooleanProperty' );
  var Checkbox = require( 'SUN/Checkbox' );
  var EraserButton = require( 'SCENERY_PHET/buttons/EraserButton' );
  var FontAwesomeNode = require( 'SUN/FontAwesomeNode' );
  var GQColors = require( 'GRAPHING_QUADRATICS/common/GQColors' );
  var graphingQuadratics = require( 'GRAPHING_QUADRATICS/graphingQuadratics' );
  var HBox = require( 'SCENERY/nodes/HBox' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Panel = require( 'SUN/Panel' );
  var PhetColorScheme = require( 'SCENERY_PHET/PhetColorScheme' );
  var RectangularPushButton = require( 'SUN/buttons/RectangularPushButton' );

  /**
   * @constructor
   */
  function EquationControls( options ) {

    options = _.extend( {
      fill: GQColors.CONTROL_PANEL_BACKGROUND,
      xMargin: 10,
      yMargin: 10
    }, options );

    // Save Line button
    var saveLineIcon = new FontAwesomeNode( 'camera' );
    var saveLineButton = new RectangularPushButton( {
      content: saveLineIcon,
      baseColor: PhetColorScheme.BUTTON_YELLOW
    } );

    // Erase Lines button
    var eraseLinesButton = new EraserButton();

    // Hide Lines checkbox
    var hideLinesIcon = new FontAwesomeNode( 'eye_close' );
    var hideLinesCheckbox = new Checkbox( hideLinesIcon, new BooleanProperty( true ) );

    // horizontal layout of buttons
    var buttons = new HBox( {
      children: [ saveLineButton, eraseLinesButton, hideLinesCheckbox ],
      spacing: 20
    } );

    Panel.call( this, buttons, options );
  }

  graphingQuadratics.register( 'EquationControls', EquationControls );

  return inherit( Panel, EquationControls );
} );<commit_msg>hideLinesCheckbox default unchecked<commit_after>// Copyright 2018, University of Colorado Boulder

/**
 * Control panel for interactive-equation. Copied from graphing-lines.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 * @author Andrea Lin
 */
define( function( require ) {
  'use strict';

  // modules
  var BooleanProperty = require( 'AXON/BooleanProperty' );
  var Checkbox = require( 'SUN/Checkbox' );
  var EraserButton = require( 'SCENERY_PHET/buttons/EraserButton' );
  var FontAwesomeNode = require( 'SUN/FontAwesomeNode' );
  var GQColors = require( 'GRAPHING_QUADRATICS/common/GQColors' );
  var graphingQuadratics = require( 'GRAPHING_QUADRATICS/graphingQuadratics' );
  var HBox = require( 'SCENERY/nodes/HBox' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Panel = require( 'SUN/Panel' );
  var PhetColorScheme = require( 'SCENERY_PHET/PhetColorScheme' );
  var RectangularPushButton = require( 'SUN/buttons/RectangularPushButton' );

  /**
   * @constructor
   */
  function EquationControls( options ) {

    options = _.extend( {
      fill: GQColors.CONTROL_PANEL_BACKGROUND,
      xMargin: 10,
      yMargin: 10
    }, options );

    // Save Line button
    var saveLineIcon = new FontAwesomeNode( 'camera' );
    var saveLineButton = new RectangularPushButton( {
      content: saveLineIcon,
      baseColor: PhetColorScheme.BUTTON_YELLOW
    } );

    // Erase Lines button
    var eraseLinesButton = new EraserButton();

    // Hide Lines checkbox
    var hideLinesIcon = new FontAwesomeNode( 'eye_close' );
    var hideLinesCheckbox = new Checkbox( hideLinesIcon, new BooleanProperty( false ) );

    // horizontal layout of buttons
    var buttons = new HBox( {
      children: [ saveLineButton, eraseLinesButton, hideLinesCheckbox ],
      spacing: 20
    } );

    Panel.call( this, buttons, options );
  }

  graphingQuadratics.register( 'EquationControls', EquationControls );

  return inherit( Panel, EquationControls );
} );<|endoftext|>


<commit_before>app.directive('componentSettings', function() {
  return {
    restrict: 'E',
    scope: {
      settings: '='
    },
    templateUrl: 'js/directives/componentSettings.html'
  };
});<commit_msg>componentSettings inherits root $scope<commit_after>app.directive('componentSettings', function() {
  return {
    restrict: 'E',
    scope: false,
    templateUrl: 'js/directives/componentSettings.html'
  };
});<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * 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.
 */

var CellParser = {
  __proto__: grammar,

  START: alt(sym('number'), sym('formula'), sym('string')),

  formula: seq1(1, '=', sym('expr')),

  expr: alt(
    sym('number'),
    sym('cell'),
    sym('add'),
    sym('sub'),
    sym('mul'),
    sym('div'),
    sym('mod'),
    sym('sum'),
    sym('prod')
  ),

  add:  seq(literal_ic('add('),  sym('expr'), ',', sym('expr'), ')'),
  sub:  seq(literal_ic('sub('),  sym('expr'), ',', sym('expr'), ')'),
  mul:  seq(literal_ic('mul('),  sym('expr'), ',', sym('expr'), ')'),
  div:  seq(literal_ic('div('),  sym('expr'), ',', sym('expr'), ')'),
  mod:  seq(literal_ic('mod('),  sym('expr'), ',', sym('expr'), ')'),
  sum:  seq(literal_ic('sum('),  sym('vargs'), ')'),
  prod: seq(literal_ic('prod('), sym('vargs'), ')'),

  vargs: repeat(alt(sym('range'), sym('expr')), ','),

  range: seq(sym('col'), sym('row'), ':', sym('col'), sym('row')),

  number: str(seq(
    optional('-'),
    str(alt(
      seq(str(repeat(sym('digit'))), '.', str(plus(sym('digit')))),
      plus(sym('digit')))))),

  cell: seq(sym('col'), sym('row')),

  col: alt(sym('az'), sym('AZ')),

  digit: range('0', '9'),

  az: range('a', 'z'),

  AZ: range('A', 'Z'),

  row: str(repeat(sym('digit'), null, 1, 2)),

  string: str(repeat(anyChar))
}.addActions({
  add: function(a) { return function(cs) { return a[1](cs) + a[3](cs); }; },
  sub: function(a) { return function(cs) { return a[1](cs) - a[3](cs); }; },
  mul: function(a) { return function(cs) { return a[1](cs) * a[3](cs); }; },
  div: function(a) { return function(cs) { return a[1](cs) / a[3](cs); }; },
  mod: function(a) { return function(cs) { return a[1](cs) % a[3](cs); }; },
  sum: function(a) { return function(cs) {
    var arr = a[1](cs), sum = 0;
    for ( var i = 0 ; i < arr.length ; i++ ) sum += arr[i];
    return sum;
  }; },
  prod: function(a) { return function(cs) {
    var arr = a[1](cs), prod = 1;
    for ( var i = 0 ; i < arr.length ; i++ ) prod *= arr[i];
    return prod;
  }; },
  az:  function(c) { return c.toUpperCase(); },
  //AZ:  function(c) { return c.charCodeAt(0) - 'A'.charCodeAt(0); },
  row: function(c) { return parseInt(c); },
  number: function(s) { var f = parseFloat(s); return function() { return f; }; },
  cell: function(a) { return function(cs) { return cs.cell(a[0] + a[1]).numValue; }; },
  vargs: function(a) {
    return function(cs) {
      var ret = [];
      for ( var i = 0 ; i < a.length ; i++ ) {
        var r = a[i](cs);
        if ( Array.isArray(r) )
          ret.pushAll(r);
        else
          ret.push(r);
      }
      return ret;
    }
  },
  range: function(a) {
    var c1 = a[0], r1 = a[1], c2 = a[3], r2 = a[4];
    return function(cs) {
      var ret = [];
      for ( var c = c1 ; c <= c2; c++ )
        for ( var r = r1 ; r <= r2 ; r++ )
          ret.push(cs.cell(c + r).numValue);
      return ret;
    }
  },
  string: function(s) { return function() { return s; }; }
});

// https://www.artima.com/pins1ed/the-scells-spreadsheet.html
MODEL({
  package: 'foam.demos.sevenguis',
  name: 'CellsU2',
  extends: 'foam.u2.Element',
  imports:  [ 'dynamicFn' ],
  exports:  [ 'as cells' ],

  models: [
    {
      name: 'Cell',
      extends: 'foam.ui.View',
      requires: [ 'foam.ui.TextFieldView' ],
      imports: [ 'cells' ],
      documentation: function() {/*
        Doesn't build inner views until value is set or user clicks on view.
        This complicates the design but saves memory and startup time.
      */},
      properties: [
        {
          name: 'formula',
          displayWidth: 10
        },
        {
          name: 'value',
          adapt: function(_, v) {
            var ret = parseFloat(v);
            return ret && ! Number.isInteger(ret) ? ret.toFixed(2) : v;
          },
          displayWidth: 12
        },
        {
          name: 'numValue',
          getter: function() { return parseFloat(this.value); }
        }
      ],
      methods: [
        function initHTML() {
          this.SUPER();

          if ( this.hasOwnProperty('value') ) {
            this.initValueHTML();
          } else {
            this.value$.addListener(this.initValueHTML.bind(this));
            this.$.addEventListener('click', this.onClickWhenEmpty);
          }
        },
        function initValueHTML() {
          this.$.removeEventListener('click', this.onClickWhenEmpty);
          this.$.innerHTML = this.toValueHTML();

          this.valueView.initHTML();
          this.formulaView.initHTML();

          this.valueView.$.addEventListener('click',  this.onClick);
          this.formulaView.$.addEventListener('blur', this.onBlur);
          this.formula$.addListener(this.onBlur);
        }
      ],
      listeners: [
        {
          name: 'onClickWhenEmpty',
          code: function() {
            this.initValueHTML();
            this.onClick();
          }
        },
        {
          name: 'onClick',
          code: function() {
            DOM.setClass(this.$, 'formula', true);
            this.formulaView.$.focus();
          }
        },
        {
          name: 'onBlur',
          code: function() { DOM.setClass(this.$, 'formula', false); }
        }
      ],
      templates: [
        function CSS() {/*
          .cellView > span {
            display: block;
            height: 15px;
            padding: 2px;
            width: 100%;
          }
          .cellView > input {
            border:  none;
            display: none;
            margin-left: 2px;
            outline: none;
          }
          .cellView                 { outline: 1px solid white; }
          .cellView.formula         { outline: 1px solid blue; }
          .cellView.formula > input { display: inherit; }
          .cellView.formula > span  { display: none; }
        */},
        function toHTML() {/*

        */},
        function toValueHTML() {/*
          $$formula $$value{mode: 'read-only', escapeHTML: false}
        */}
      ]
    }
  ],
  properties: [
    [ 'rows',    99 ],
    [ 'columns', 26 ],
    {
      name: 'cells',
      factory: function() { return {}; }
    },
    {
      name: 'parser',
      factory: function() { return CellParser; }
    }
  ],
  methods: [
    function init() {
      this.SUPER();

      // Two sample spreadsheets
      // Spreadsheet taken from Visicalc
this.load({"A0":"Item","B0":"No.","C0":"Unit","D0":"Cost","A1":"Muck Rake","B1":"43","C1":"12.95","D1":"=mul(B1,C1)","A2":"Buzz Cut","B2":"15","C2":"6.76","D2":"=mul(B2,C2)","A3":"Toe Toner","B3":"250","C3":"49.95","D3":"=mul(B3,C3)","A4":"Eye Snuff","B4":"2","C4":"4.95","D4":"=mul(B4,C4)","C5":"Subtotal","D5":"=sum(D1:D4)","B6":"9.75","C6":"Tax","D6":"=div(mul(B6,D5),100)","C7":"Total","D7":"=add(D5,D6)"});

      // Spreadsheet to test all functions
//      this.load({"A0":"Formulas","B0":"Values","A1":" 1","B1":"1","A2":" 10","B2":"10","A3":" 10.12","B3":"10.12","A4":" -10.1","B4":"-10.1","A5":" foobar","B5":"foobar","A6":" =add(1,2)","B6":"=add(1,2)","A7":" =sub(2,1)","B7":"=sub(2,1)","A8":" =mul(2,3)","B8":"=mul(2,3)","A9":" =div(9,3)","B9":"=div(9,3)","A10":" =mod(8,3)","B10":"=mod(8,3)","A11":" =add(mul(2,3),div(3,2))","B11":"=add(mul(2,3),div(3,2))","A12":" =A1","B12":"=A1","A13":" =add(A1,B1)","B13":"=add(A1,B1)","A14":" =sum(1,2,3,4,5)","B14":"=sum(1,2,3,4,5)","A15":" =sum(B6:B10)","B15":"=sum(B6:B10)","A16":" =prod(B6:B10)","B16":"=prod(B6:B10)"});
    },
    function load(map) {
      for ( var key in map ) this.cell(key).formula = String(map[key]);
    },
    function save() {
      var map = {};
      for ( var key in this.cells ) {
        var cell = this.cells[key];
        if ( cell.formula !== '' ) map[key] = cell.formula;
      }
      return map;
    },
    function cellName(c, r) {
      return String.fromCharCode(65 + c) + r;
    },
    function cell(name) {
      var self = this;
      var cell = this.cells[name];
      var cancel = null;
      if ( ! cell ) {
        cell = this.cells[name] = this.Cell.create();
        cell.formula$.addListener(function(_, __, ___, formula) {
          var f = self.parser.parseString(formula);
          cancel && cancel.destroy();
          cancel = self.dynamicFn(f.bind(null, self), function(v) {
            cell.value = v;
          });
        });
      }
      return cell;
    },
    function cellE(j, i) {
      var c = this.E('td');

      c.add(this.E('input'));

      return c;
    }
  ],
  templates: [
    function CSS() {/*
      .cells tr, .cells td, .cells th, .cells input {
        color: #333;
        font: 13px roboto, arial, sans-serif;
      }
      .cells tr { height: 26px; }
      .cells { overflow: auto; }
      .cell { min-width: 102px; }
      table.cells, .cells th, .cells td { border: 1px solid #ccc; }
      .cells td { height: 100%; }
      .cells th, .cells td {
        border-right: none;
        border-bottom: none;
      }
      table.cells {
        border-left: none;
        border-top: none;
      }
      .cells th {
        background: #eee;
        color: #333;
        padding: 2px 18px;
      }
    */},
    function toE() {/*

          {{String.fromCharCode(65 + j)}}

          {{i}}
          {{this.cellE(j, i)}}

    */}
  ]
});
<commit_msg>CellsU2 work.<commit_after>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * 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.
 */

var CellParser = {
  __proto__: grammar,

  START: alt(sym('number'), sym('formula'), sym('string')),

  formula: seq1(1, '=', sym('expr')),

  expr: alt(
    sym('number'),
    sym('cell'),
    sym('add'),
    sym('sub'),
    sym('mul'),
    sym('div'),
    sym('mod'),
    sym('sum'),
    sym('prod')
  ),

  add:  seq(literal_ic('add('),  sym('expr'), ',', sym('expr'), ')'),
  sub:  seq(literal_ic('sub('),  sym('expr'), ',', sym('expr'), ')'),
  mul:  seq(literal_ic('mul('),  sym('expr'), ',', sym('expr'), ')'),
  div:  seq(literal_ic('div('),  sym('expr'), ',', sym('expr'), ')'),
  mod:  seq(literal_ic('mod('),  sym('expr'), ',', sym('expr'), ')'),
  sum:  seq(literal_ic('sum('),  sym('vargs'), ')'),
  prod: seq(literal_ic('prod('), sym('vargs'), ')'),

  vargs: repeat(alt(sym('range'), sym('expr')), ','),

  range: seq(sym('col'), sym('row'), ':', sym('col'), sym('row')),

  number: str(seq(
    optional('-'),
    str(alt(
      seq(str(repeat(sym('digit'))), '.', str(plus(sym('digit')))),
      plus(sym('digit')))))),

  cell: seq(sym('col'), sym('row')),

  col: alt(sym('az'), sym('AZ')),

  digit: range('0', '9'),

  az: range('a', 'z'),

  AZ: range('A', 'Z'),

  row: str(repeat(sym('digit'), null, 1, 2)),

  string: str(repeat(anyChar))
}.addActions({
  add: function(a) { return function(cs) { return a[1](cs) + a[3](cs); }; },
  sub: function(a) { return function(cs) { return a[1](cs) - a[3](cs); }; },
  mul: function(a) { return function(cs) { return a[1](cs) * a[3](cs); }; },
  div: function(a) { return function(cs) { return a[1](cs) / a[3](cs); }; },
  mod: function(a) { return function(cs) { return a[1](cs) % a[3](cs); }; },
  sum: function(a) { return function(cs) {
    var arr = a[1](cs), sum = 0;
    for ( var i = 0 ; i < arr.length ; i++ ) sum += arr[i];
    return sum;
  }; },
  prod: function(a) { return function(cs) {
    var arr = a[1](cs), prod = 1;
    for ( var i = 0 ; i < arr.length ; i++ ) prod *= arr[i];
    return prod;
  }; },
  az:  function(c) { return c.toUpperCase(); },
  //AZ:  function(c) { return c.charCodeAt(0) - 'A'.charCodeAt(0); },
  row: function(c) { return parseInt(c); },
  number: function(s) { var f = parseFloat(s); return function() { return f; }; },
  cell: function(a) { return function(cs) { return cs.cell(a[0] + a[1]).numValue; }; },
  vargs: function(a) {
    return function(cs) {
      var ret = [];
      for ( var i = 0 ; i < a.length ; i++ ) {
        var r = a[i](cs);
        if ( Array.isArray(r) )
          ret.pushAll(r);
        else
          ret.push(r);
      }
      return ret;
    }
  },
  range: function(a) {
    var c1 = a[0], r1 = a[1], c2 = a[3], r2 = a[4];
    return function(cs) {
      var ret = [];
      for ( var c = c1 ; c <= c2; c++ )
        for ( var r = r1 ; r <= r2 ; r++ )
          ret.push(cs.cell(c + r).numValue);
      return ret;
    }
  },
  string: function(s) { return function() { return s; }; }
});

// https://www.artima.com/pins1ed/the-scells-spreadsheet.html
MODEL({
  package: 'foam.demos.sevenguis',
  name: 'CellsU2',
  extends: 'foam.u2.Element',

  requires: [ 'foam.u2.Input', 'foam.u2.ElementParser' ],
  imports:  [ 'dynamicFn' ],
  exports:  [ 'as cells' ],

  models: [
    {
      name: 'Cell',
      extends: 'foam.ui.View',
      requires: [ 'foam.ui.TextFieldView' ],
      imports: [ 'cells' ],
      documentation: function() {/*
        Doesn't build inner views until value is set or user clicks on view.
        This complicates the design but saves memory and startup time.
      */},
      properties: [
        {
          name: 'formula',
          displayWidth: 10
        },
        {
          name: 'value',
          adapt: function(_, v) {
            var ret = parseFloat(v);
            return ret && ! Number.isInteger(ret) ? ret.toFixed(2) : v;
          },
          displayWidth: 12
        },
        {
          name: 'numValue',
          getter: function() { return parseFloat(this.value); }
        }
      ],
      methods: [
        function initHTML() {
          this.SUPER();

          if ( this.hasOwnProperty('value') ) {
            this.initValueHTML();
          } else {
            this.value$.addListener(this.initValueHTML.bind(this));
            this.$.addEventListener('click', this.onClickWhenEmpty);
          }
        },
        function initValueHTML() {
          this.$.removeEventListener('click', this.onClickWhenEmpty);
          this.$.innerHTML = this.toValueHTML();

          this.valueView.initHTML();
          this.formulaView.initHTML();

          this.valueView.$.addEventListener('click',  this.onClick);
          this.formulaView.$.addEventListener('blur', this.onBlur);
          this.formula$.addListener(this.onBlur);
        }
      ],
      listeners: [
        {
          name: 'onClickWhenEmpty',
          code: function() {
            this.initValueHTML();
            this.onClick();
          }
        },
        {
          name: 'onClick',
          code: function() {
            DOM.setClass(this.$, 'formula', true);
            this.formulaView.$.focus();
          }
        },
        {
          name: 'onBlur',
          code: function() { DOM.setClass(this.$, 'formula', false); }
        }
      ],
      templates: [
        function CSS() {/*
          .cellView > span {
            display: block;
            height: 15px;
            padding: 2px;
            width: 100%;
          }
          .cellView > input {
            border:  none;
            display: none;
            margin-left: 2px;
            outline: none;
          }
          .cellView                 { outline: 1px solid white; }
          .cellView.formula         { outline: 1px solid blue; }
          .cellView.formula > input { display: inherit; }
          .cellView.formula > span  { display: none; }
        */},
        function toHTML() {/*

        */},
        function toValueHTML() {/*
          $$formula $$value{mode: 'read-only', escapeHTML: false}
        */}
      ]
    }
  ],
  properties: [
//    [ 'rows',    99 ],
//    [ 'columns', 26 ],
    [ 'rows',    5 ],
    [ 'columns', 5 ],
    {
      name: 'cells',
      factory: function() { return {}; }
    },
    {
      name: 'parser',
      factory: function() { return CellParser; }
    }
  ],
  methods: [
    function init() {
      this.SUPER();

      this.ElementParser.getPrototype();

      // Two sample spreadsheets
      // Spreadsheet taken from Visicalc
this.load({"A0":"Item","B0":"No.","C0":"Unit","D0":"Cost","A1":"Muck Rake","B1":"43","C1":"12.95","D1":"=mul(B1,C1)","A2":"Buzz Cut","B2":"15","C2":"6.76","D2":"=mul(B2,C2)","A3":"Toe Toner","B3":"250","C3":"49.95","D3":"=mul(B3,C3)","A4":"Eye Snuff","B4":"2","C4":"4.95","D4":"=mul(B4,C4)","C5":"Subtotal","D5":"=sum(D1:D4)","B6":"9.75","C6":"Tax","D6":"=div(mul(B6,D5),100)","C7":"Total","D7":"=add(D5,D6)"});

      // Spreadsheet to test all functions
//      this.load({"A0":"Formulas","B0":"Values","A1":" 1","B1":"1","A2":" 10","B2":"10","A3":" 10.12","B3":"10.12","A4":" -10.1","B4":"-10.1","A5":" foobar","B5":"foobar","A6":" =add(1,2)","B6":"=add(1,2)","A7":" =sub(2,1)","B7":"=sub(2,1)","A8":" =mul(2,3)","B8":"=mul(2,3)","A9":" =div(9,3)","B9":"=div(9,3)","A10":" =mod(8,3)","B10":"=mod(8,3)","A11":" =add(mul(2,3),div(3,2))","B11":"=add(mul(2,3),div(3,2))","A12":" =A1","B12":"=A1","A13":" =add(A1,B1)","B13":"=add(A1,B1)","A14":" =sum(1,2,3,4,5)","B14":"=sum(1,2,3,4,5)","A15":" =sum(B6:B10)","B15":"=sum(B6:B10)","A16":" =prod(B6:B10)","B16":"=prod(B6:B10)"});
    },
    function load(map) {
      for ( var key in map ) this.cell(key).formula = String(map[key]);
    },
    function save() {
      var map = {};
      for ( var key in this.cells ) {
        var cell = this.cells[key];
        if ( cell.formula !== '' ) map[key] = cell.formula;
      }
      return map;
    },
    function cellName(c, r) {
      return String.fromCharCode(65 + c) + r;
    },
    function cell(name) {
      var self = this;
      var cell = this.cells[name];
      var cancel = null;
      if ( ! cell ) {
        cell = this.cells[name] = this.Cell.create();
        cell.formula$.addListener(function(_, __, ___, formula) {
          var f = self.parser.parseString(formula);
          cancel && cancel.destroy();
          cancel = self.dynamicFn(f.bind(null, self), function(v) {
            cell.value = v;
          });
        });
      }
      return cell;
    },
    function cellE(j, i) {
      var c = this.E('td');
      c.add(this.E('input'));
      return c;
    }
  ],
  templates: [
    function CSS() {/*
      $ tr, $ td, $ th, $ input {
        color: #333;
        font: 13px roboto, arial, sans-serif;
      }
      $ tr { height: 26px; }
      $ { overflow: auto; }
      $-cell { min-width: 102px; }
      table.$, $ th, $ td { border: 1px solid #ccc; }
      $ td { height: 100%; }
      $ th, .cells td {
        border-right: none;
        border-bottom: none;
      }
      table.$ {
        border-left: none;
        border-top: none;
      }
      $ th {
        background: #eee;
        color: #333;
        padding: 2px 18px;
      }
    */},
    function initE() {/*#U2

          {{String.fromCharCode(65 + j)}}

          {{i}}
          {{this.cellE(j, i)}}

    */}
  ]
});
<|endoftext|>


<commit_before>'use strict';
if (typeof Levels === 'undefined') var Levels = {};

Levels.VehicleSteeringSimple = function()
{
	this.name = "VehicleSteeringSimple";
	this.title = "Vehicle Steering";

	this.sampleSolution = "function controlFunction(vehicle){\n	return 0.1*(vehicle.lidarPoints[0].distance - vehicle.lidarPoints[4].distance);\n};";
	this.boilerPlateCode = "function controlFunction(vehicle){\n	return -0.03;\n};";
	this.description = "TODO";
	ImageDataCache.load('track.png');
	this.model = new Models.Vehicle({trackImgURL: 'track.png'});
}

Levels.VehicleSteeringSimple.prototype.levelComplete = function()
{
	return Math.abs(this.model.x - 82) < 4
		&& Math.abs(this.model.y - 46) < 4;
}

Levels.VehicleSteeringSimple.prototype.levelFailed = function()
{
	return this.model.detectCollision();
}

Levels.VehicleSteeringSimple.prototype.simulate = function (dt, controlFunc)
{
	this.model = this.model.simulate (dt, controlFunc);
}

Levels.VehicleSteeringSimple.prototype.getSimulationTime = function() {return this.model.T;}
<commit_msg>lvl description<commit_after>'use strict';
if (typeof Levels === 'undefined') var Levels = {};

Levels.VehicleSteeringSimple = function()
{
	this.name = "VehicleSteeringSimple";
	this.title = "Vehicle Steering";

	this.sampleSolution = "function controlFunction(vehicle){\n	return 0.1*(vehicle.lidarPoints[0].distance - vehicle.lidarPoints[4].distance);\n};";
	this.boilerPlateCode = "function controlFunction(vehicle){\n	return -0.03;\n};";
	this.description = "Steer the vehicle along the track by calculating the necessary steering angle in radians. The vehicle speed is constant. The vehicle has sensors that tell the distance to the track's edge in different directions relative to the vehicle.";
	ImageDataCache.load('track.png');
	this.model = new Models.Vehicle({trackImgURL: 'track.png'});
}

Levels.VehicleSteeringSimple.prototype.levelComplete = function()
{
	return Math.abs(this.model.x - 82) < 4
		&& Math.abs(this.model.y - 46) < 4;
}

Levels.VehicleSteeringSimple.prototype.levelFailed = function()
{
	return this.model.detectCollision();
}

Levels.VehicleSteeringSimple.prototype.simulate = function (dt, controlFunc)
{
	this.model = this.model.simulate (dt, controlFunc);
}

Levels.VehicleSteeringSimple.prototype.getSimulationTime = function() {return this.model.T;}
<|endoftext|>


<commit_before>/** -*- compile-command: "jslint-cli FirstPersonManipulator.js" -*-
 * Authors:
 *  Matt Fontaine <tehqin@gmail.com>
 *  Cedric Pinson <cedric.pinson@plopbyte.com>
 */

/**
 *  FirstPersonManipulator
 *  @class
 */
osgGA.FirstPersonManipulator = function () {
    osgGA.Manipulator.call(this);
    this.init();
};

/** @lends osgGA.FirstPersonManipulator.prototype */
osgGA.FirstPersonManipulator.prototype = osg.objectInehrit(osgGA.Manipulator.prototype, {
    setNode: function(node) {
        this._node = node;
        this.computeHomePosition();
    },
    computeHomePosition: function() {
        if (this._node !== undefined) {
            var bs = this._node.getBound();
            this._radius = bs.radius();
            this._eye = [ 0, -bs.radius()*1.5, 0 ];

            this._angleVertical = 0.0;
            this._angleHorizontal = 0.0;
        }
    },
    init: function()
    {
        this._direction = [0.0, 1.0, 0.0];
        this._angleVertical = 0.0;
        this._angleHorizontal = 0.0;
        this._eye = [0, 25.0, 10.0];
        this._up = [0, 0, 1];
        this._buttonup = true;
        this._radius = 1;
        this._forward = new osgGA.OrbitManipulator.Interpolator(1);
        this._side = new osgGA.OrbitManipulator.Interpolator(1);
        this._lookPosition = new osgGA.OrbitManipulator.Interpolator(2);
        this._stepFactor = 1.0; // meaning radius*stepFactor to move
        this._target = new Array(3); osg.Vec3.init(this._target);
    },
    reset: function()
    {
        this.init();
    },

    getEyePosition: function(eye) {
        eye[0] = this._eye[0];
        eye[1] = this._eye[1];
        eye[2] = this._eye[2];
        return eye;
    },

    setEyePosition: function(eye) {
        this._eye[0] = eye[0];
        this._eye[1] = eye[1];
        this._eye[2] = eye[2];
    },

    getTarget: function(pos, distance) {
        if (distance === undefined) {
            distance = 25;
        }
        var dir = osg.Vec3.mult(this._direction, distance, new Array(3));
        osg.Vec3.add(this._eye, dir, pos);
    },

    setTarget: function(pos) {
        this._target[0] = pos[0];
        this._target[1] = pos[1];
        this._target[2] = pos[2];
        var dir = new Array(3);
        osg.Vec3.sub(pos, this._eye, dir);
        dir[2] = 0;
        osg.Vec3.normalize(dir, dir);
        this._angleHorizontal = Math.acos(dir[1]);
        if (dir[0] < 0) {
            this._angleHorizontal = -this._angleHorizontal;
        }
        osg.Vec3.sub(pos, this._eye, dir);
        osg.Vec3.normalize(dir, dir);

        this._angleVertical = -Math.asin(dir[2]);
        osg.Vec3.copy(dir, this._direction);
    },

    mousedown: function(ev)
    {
        var pos = this.getPositionRelativeToCanvas(ev);
        this._lookPosition.set(pos[0], pos[1]);
        this._buttonup = false;
    },
    mouseup: function(ev) {
        this._buttonup = true;
    },
    mousemove: function(ev)
    {
        if (this._buttonup === true) { return; }

        var curX;
        var curY;
        var deltaX;
        var deltaY;
        var pos = this.getPositionRelativeToCanvas(ev);

        this._lookPosition.setTarget(pos[0], pos[1]);
    },

    computeRotation: function(dx, dy)
    {
        this._angleVertical += dy*0.01;
        this._angleHorizontal -= dx*0.01;

        var first = [];
        var second = [];
        var rotMat = [];
        osg.Matrix.makeRotate(this._angleVertical, 1, 0, 0, first);
        osg.Matrix.makeRotate(this._angleHorizontal, 0, 0, 1, second);
        osg.Matrix.mult(second, first, rotMat);
        //rotMat = second;

        this._direction = osg.Matrix.transformVec3(rotMat, [0, 1, 0], []);
        osg.Vec3.normalize(this._direction, this._direction);

        this._up = osg.Matrix.transformVec3(rotMat, [0, 0, 1], [] );
    },

    update: function(nv) {
        var t = nv.getFrameStamp().getSimulationTime();
        if (this._lastUpdate === undefined) {
            this._lastUpdate = t;
        }
        var dt = t - this._lastUpdate;
        this._lastUpdate = t;

        this._forward.update();
        this._side.update();
        var delta = this._lookPosition.update();

        this.computeRotation(-delta[0]*0.5, -delta[1]*0.5);

        var vec = new Array(2);
        vec[0] = this._forward.getCurrent()[0];
        vec[1] = this._side.getCurrent()[0];
        if (osg.Vec2.length(vec) > 1.0) {
            osg.Vec2.normalize(vec, vec);
        }
        var factor = this._radius;
        if (this._radius < 1e-3) {
            factor = 1.0;
        }
        this.moveForward(vec[0] * factor*this._stepFactor*dt);
        this.strafe(vec[1] * factor*this._stepFactor*dt);

        var target = osg.Vec3.add(this._eye, this._direction, []);
        this._target = target;

        osg.Matrix.makeLookAt(this._eye, target, this._up, this._inverseMatrix);
    },

    getInverseMatrix: function()
    {
        return this._inverseMatrix;
    },

    moveForward: function(distance)
    {
        var d = osg.Vec3.mult(osg.Vec3.normalize(this._direction, []), distance, []);
        this._eye = osg.Vec3.add(this._eye, d, []);
    },

    strafe: function(distance)
    {
        var cx = osg.Vec3.cross(this._direction, this._up, []);
        var d = osg.Vec3.mult(osg.Vec3.normalize(cx,cx), distance, []);
        this._eye = osg.Vec3.add(this._eye, d, []);
    },

    keydown: function(event) {
        if (event.keyCode === 32) {
            this.computeHomePosition();
        } else if (event.keyCode === 87 || event.keyCode === 90 ){ // w/z
            this._forward.setTarget(1);
            return false;
        }
        else if (event.keyCode === 83){ // S
            this._forward.setTarget(-1);
            return false;
        }
        else if (event.keyCode === 68){ // D
            this._side.setTarget(1);
            return false;
        }
        else if (event.keyCode === 65 || event.keyCode === 81){ // a/q
            this._side.setTarget(-1);
            return false;
        }
    },

    keyup: function(event) {
        if (event.keyCode === 87 || event.keyCode === 90) { // w/z
            this._forward.setTarget(0);
            return false;
        }
        else if (event.keyCode == 83){ // S
            this._forward.setTarget(0);
            return false;
        }
        else if (event.keyCode == 68){ // D
            this._side.setTarget(0);
            return false;
        }
        else if (event.keyCode === 65 || event.keyCode === 81){ // a/q
            this._side.setTarget(0);
            return false;
        }
    }

});
<commit_msg>set mousewheel to change the stepFactor in maniupalor<commit_after>/** -*- compile-command: "jslint-cli FirstPersonManipulator.js" -*-
 * Authors:
 *  Matt Fontaine <tehqin@gmail.com>
 *  Cedric Pinson <cedric.pinson@plopbyte.com>
 */

/**
 *  FirstPersonManipulator
 *  @class
 */
osgGA.FirstPersonManipulator = function () {
    osgGA.Manipulator.call(this);
    this.init();
};

/** @lends osgGA.FirstPersonManipulator.prototype */
osgGA.FirstPersonManipulator.prototype = osg.objectInehrit(osgGA.Manipulator.prototype, {
    setNode: function(node) {
        this._node = node;
        this.computeHomePosition();
    },
    computeHomePosition: function() {
        if (this._node !== undefined) {
            var bs = this._node.getBound();
            this._radius = bs.radius();
            this._eye = [ 0, -bs.radius()*1.5, 0 ];

            this._angleVertical = 0.0;
            this._angleHorizontal = 0.0;
        }
    },
    init: function()
    {
        this._direction = [0.0, 1.0, 0.0];
        this._angleVertical = 0.0;
        this._angleHorizontal = 0.0;
        this._eye = [0, 25.0, 10.0];
        this._up = [0, 0, 1];
        this._buttonup = true;
        this._radius = 1;
        this._forward = new osgGA.OrbitManipulator.Interpolator(1);
        this._side = new osgGA.OrbitManipulator.Interpolator(1);
        this._lookPosition = new osgGA.OrbitManipulator.Interpolator(2);
        this._stepFactor = 1.0; // meaning radius*stepFactor to move
        this._target = new Array(3); osg.Vec3.init(this._target);
    },
    reset: function()
    {
        this.init();
    },

    getEyePosition: function(eye) {
        eye[0] = this._eye[0];
        eye[1] = this._eye[1];
        eye[2] = this._eye[2];
        return eye;
    },

    setEyePosition: function(eye) {
        this._eye[0] = eye[0];
        this._eye[1] = eye[1];
        this._eye[2] = eye[2];
    },

    getTarget: function(pos, distance) {
        if (distance === undefined) {
            distance = 25;
        }
        var dir = osg.Vec3.mult(this._direction, distance, new Array(3));
        osg.Vec3.add(this._eye, dir, pos);
    },

    setTarget: function(pos) {
        this._target[0] = pos[0];
        this._target[1] = pos[1];
        this._target[2] = pos[2];
        var dir = new Array(3);
        osg.Vec3.sub(pos, this._eye, dir);
        dir[2] = 0;
        osg.Vec3.normalize(dir, dir);
        this._angleHorizontal = Math.acos(dir[1]);
        if (dir[0] < 0) {
            this._angleHorizontal = -this._angleHorizontal;
        }
        osg.Vec3.sub(pos, this._eye, dir);
        osg.Vec3.normalize(dir, dir);

        this._angleVertical = -Math.asin(dir[2]);
        osg.Vec3.copy(dir, this._direction);
    },

    mousedown: function(ev)
    {
        var pos = this.getPositionRelativeToCanvas(ev);
        this._lookPosition.set(pos[0], pos[1]);
        this._buttonup = false;
    },
    mouseup: function(ev) {
        this._buttonup = true;
    },
    mousemove: function(ev)
    {
        if (this._buttonup === true) { return; }

        var curX;
        var curY;
        var deltaX;
        var deltaY;
        var pos = this.getPositionRelativeToCanvas(ev);

        this._lookPosition.setTarget(pos[0], pos[1]);
    },

    computeRotation: function(dx, dy)
    {
        this._angleVertical += dy*0.01;
        this._angleHorizontal -= dx*0.01;

        var first = [];
        var second = [];
        var rotMat = [];
        osg.Matrix.makeRotate(this._angleVertical, 1, 0, 0, first);
        osg.Matrix.makeRotate(this._angleHorizontal, 0, 0, 1, second);
        osg.Matrix.mult(second, first, rotMat);
        //rotMat = second;

        this._direction = osg.Matrix.transformVec3(rotMat, [0, 1, 0], []);
        osg.Vec3.normalize(this._direction, this._direction);

        this._up = osg.Matrix.transformVec3(rotMat, [0, 0, 1], [] );
    },

    mousewheel: function(ev, intDelta, deltaX, deltaY) {
        ev.preventDefault();
        this._stepFactor = Math.min(Math.max(0.001,this._stepFactor+intDelta*0.01), 4.0);
    },

    update: function(nv) {
        var t = nv.getFrameStamp().getSimulationTime();
        if (this._lastUpdate === undefined) {
            this._lastUpdate = t;
        }
        var dt = t - this._lastUpdate;
        this._lastUpdate = t;

        this._forward.update();
        this._side.update();
        var delta = this._lookPosition.update();

        this.computeRotation(-delta[0]*0.5, -delta[1]*0.5);

        var vec = new Array(2);
        vec[0] = this._forward.getCurrent()[0];
        vec[1] = this._side.getCurrent()[0];
        if (osg.Vec2.length(vec) > 1.0) {
            osg.Vec2.normalize(vec, vec);
        }
        var factor = this._radius;
        if (this._radius < 1e-3) {
            factor = 1.0;
        }
        this.moveForward(vec[0] * factor*this._stepFactor*dt);
        this.strafe(vec[1] * factor*this._stepFactor*dt);

        var target = osg.Vec3.add(this._eye, this._direction, []);
        this._target = target;

        osg.Matrix.makeLookAt(this._eye, target, this._up, this._inverseMatrix);
    },

    getInverseMatrix: function()
    {
        return this._inverseMatrix;
    },

    moveForward: function(distance)
    {
        var d = osg.Vec3.mult(osg.Vec3.normalize(this._direction, []), distance, []);
        this._eye = osg.Vec3.add(this._eye, d, []);
    },

    strafe: function(distance)
    {
        var cx = osg.Vec3.cross(this._direction, this._up, []);
        var d = osg.Vec3.mult(osg.Vec3.normalize(cx,cx), distance, []);
        this._eye = osg.Vec3.add(this._eye, d, []);
    },

    keydown: function(event) {
        if (event.keyCode === 32) {
            this.computeHomePosition();
        } else if (event.keyCode === 87 || event.keyCode === 90 ){ // w/z
            this._forward.setTarget(1);
            return false;
        }
        else if (event.keyCode === 83){ // S
            this._forward.setTarget(-1);
            return false;
        }
        else if (event.keyCode === 68){ // D
            this._side.setTarget(1);
            return false;
        }
        else if (event.keyCode === 65 || event.keyCode === 81){ // a/q
            this._side.setTarget(-1);
            return false;
        }
    },

    keyup: function(event) {
        if (event.keyCode === 87 || event.keyCode === 90) { // w/z
            this._forward.setTarget(0);
            return false;
        }
        else if (event.keyCode == 83){ // S
            this._forward.setTarget(0);
            return false;
        }
        else if (event.keyCode == 68){ // D
            this._side.setTarget(0);
            return false;
        }
        else if (event.keyCode === 65 || event.keyCode === 81){ // a/q
            this._side.setTarget(0);
            return false;
        }
    }

});
<|endoftext|>


<commit_before>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');
    gvm.lastId = -1;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.projectCompletenessTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectCompletenessTitle");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.documents = ko.observableArray([]);

    gvm.addDocument = function(id, description, amount_required, weight) {
        var document = {id: id, description: description, amount_required: amount_required, weight: weight};
        gvm.documents.push(document);

        $('#removebtn-' + id).bind('click', function(event, data) {
            gvm.removeDocument(id, document);
            event.stopPropagation();
        })
    }

    gvm.addDocumentToSubmit = function() {
        ++gvm.lastId;
        gvm.addDocument(gvm.lastId, "", "", "");
    };

    gvm.getDocumentsToSubmit = function() {
        $.getJSON('/api/project/'+ gvm.projectId + '/documents', function(data) {
            $.each(data, function(i, item) {
                gvm.addDocument(item.id, item.description, item.amount_required, item.weight);
                gvm.lastId = item.id;
            });
        });
    };

    gvm.removeDocument = function(id, document) {
        if(id != -1) {
            $.ajax({
                url: "/api/delete/document/" + id,
                type: "DELETE",
                success: function() {
                    gvm.documents.remove(document);
                }
            })
        } else {
            gvm.documents.remove(document);
        }
    };

    gvm.saveDocumentsToSubmit = function() {
        console.log("big booty bitches");
        $.ajax({
            url: "/api/project/" + gvm.projectId + "/documents/" + gvm.lastId,
            type: "PUT",
            data: gvm.documents,
            success: function(data) {
                console.log("success");
            },
            error: function(data) {
                console.log("error");
            }
        });
    };
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getDocumentsToSubmit();
}<commit_msg>completeness page<commit_after>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');
    gvm.lastId = -1;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.projectCompletenessTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectCompletenessTitle");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.documents = ko.observableArray([]);

    gvm.addDocument = function(id, description, amount_required, weight) {
        var document = {id: id, description: description, amount_required: amount_required, weight: weight};
        gvm.documents.push(document);

        $('#removebtn-' + id).bind('click', function(event, data) {
            gvm.removeDocument(id, document);
            event.stopPropagation();
        })
    }

    gvm.addDocumentToSubmit = function() {
        ++gvm.lastId;
        gvm.addDocument(gvm.lastId, "", "", "");
    };

    gvm.getDocumentsToSubmit = function() {
        $.getJSON('/api/project/'+ gvm.projectId + '/documents', function(data) {
            $.each(data, function(i, item) {
                gvm.addDocument(item.id, item.description, item.amount_required, item.weight);
                gvm.lastId = item.id;
            });
        });
    };

    gvm.removeDocument = function(id, document) {
        if(id < gvm.lastId) {
            $.ajax({
                url: "/api/delete/document/" + id,
                type: "DELETE",
                success: function() {
                    gvm.documents.remove(document);
                }
            })
        } else {
            gvm.documents.remove(document);
        }
    };

    gvm.saveDocumentsToSubmit = function() {
        console.log("big booty bitches");
        $.ajax({
            url: "/api/project/" + gvm.projectId + "/documents/" + gvm.lastId,
            type: "PUT",
            data: gvm.documents,
            success: function(data) {
                console.log("success");
            },
            error: function(data) {
                console.log("error");
            }
        });
    };
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getDocumentsToSubmit();
}<|endoftext|>