<commit_before>const
  fs = require('fs'),
  path = require('path'),
  compileTemplate = require('lodash.template')

const
  log = require('./helpers/logger')('app:generator')
  appPaths = require('./app-paths'),
  quasarFolder = appPaths.resolve.app('.quasar')

class Generator {
  constructor (quasarConfig) {
    const { ctx, preFetch, ...cfg } = quasarConfig.getBuildConfig()

    this.alreadyGenerated = false
    this.quasarConfig = quasarConfig

    const paths = [
      'app.js',
      'client-entry.js',
      'import-quasar.js'
    ]

    this.files = []

    if (preFetch) {
      paths.push('client-prefetch.js')
    }
    if (ctx.mode.ssr) {
      paths.push('server-entry.js')
    }
    if (ctx.mode.tauri) {
      const { generate } = require(require.resolve('@quasar/tauri/mode/entry', {
        paths: [ appPaths.appDir ]
      }))
      generate(quasarFolder, cfg, ctx)
    }

    this.files = paths.map(file => {
      const
        content = fs.readFileSync(
          appPaths.resolve.cli(`templates/entry/${file}`),
          'utf-8'
        ),
        filename = path.basename(file)

      return {
        filename,
        dest: path.join(quasarFolder, filename),
        template: compileTemplate(content)
      }
    })
  }

  build () {
    log(`Generating Webpack entry point`)
    const data = this.quasarConfig.getBuildConfig()

    // ensure .quasar folder
    if (!fs.existsSync(quasarFolder)){
      fs.mkdirSync(quasarFolder)
    }

    this.files.forEach(file => {
      fs.writeFileSync(file.dest, file.template(data), 'utf-8')
    })

    if (!this.alreadyGenerated) {
      const then = Date.now() / 1000 - 120

      this.files.forEach(file => {
        fs.utimes(file.dest, then, then, function (err) { if (err) throw err })
      })

      this.alreadyGenerated = true
    }
  }
}

module.exports = Generator
<commit_msg>Update generator.js<commit_after>const
  fs = require('fs'),
  path = require('path'),
  compileTemplate = require('lodash.template')

const
  log = require('./helpers/logger')('app:generator')
  appPaths = require('./app-paths'),
  quasarFolder = appPaths.resolve.app('.quasar')

class Generator {
  constructor (quasarConfig) {
    const { ctx, preFetch, ...cfg } = quasarConfig.getBuildConfig()

    this.alreadyGenerated = false
    this.quasarConfig = quasarConfig

    const paths = [
      'app.js',
      'client-entry.js',
      'import-quasar.js'
    ]

    if (preFetch) {
      paths.push('client-prefetch.js')
    }
    if (ctx.mode.ssr) {
      paths.push('server-entry.js')
    }
    if (ctx.mode.tauri) {
      const { generate } = require(require.resolve('@quasar/tauri/mode/entry', {
        paths: [ appPaths.appDir ]
      }))
      generate(quasarFolder, cfg, ctx)
    }

    this.files = paths.map(file => {
      const
        content = fs.readFileSync(
          appPaths.resolve.cli(`templates/entry/${file}`),
          'utf-8'
        ),
        filename = path.basename(file)

      return {
        filename,
        dest: path.join(quasarFolder, filename),
        template: compileTemplate(content)
      }
    })
  }

  build () {
    log(`Generating Webpack entry point`)
    const data = this.quasarConfig.getBuildConfig()

    // ensure .quasar folder
    if (!fs.existsSync(quasarFolder)){
      fs.mkdirSync(quasarFolder)
    }

    this.files.forEach(file => {
      fs.writeFileSync(file.dest, file.template(data), 'utf-8')
    })

    if (!this.alreadyGenerated) {
      const then = Date.now() / 1000 - 120

      this.files.forEach(file => {
        fs.utimes(file.dest, then, then, function (err) { if (err) throw err })
      })

      this.alreadyGenerated = true
    }
  }
}

module.exports = Generator
<|endoftext|>


<commit_before>/**
 * ResizeHandle.js
 *
 * Copyright, Moxiecode Systems AB
 * Released under LGPL License.
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/**
 * Renders a resize handle that fires ResizeStart, Resize and ResizeEnd events.
 *
 * @-x-less ResizeHandle.less
 * @class tinymce.ui.ResizeHandle
 * @extends tinymce.ui.Widget
 */
define("tinymce/ui/ResizeHandle", [
	"tinymce/ui/Widget",
	"tinymce/ui/DragHelper"
], function(Widget, DragHelper) {
	"use strict";

	return Widget.extend({
		/**
		 * Renders the control as a HTML string.
		 *
		 * @method renderHtml
		 * @return {String} HTML representing the control.
		 */
		renderHtml: function() {
			var self = this, prefix = self.classPrefix;

			self.addClass('resizehandle');

			if (self.settings.direction == "both") {
				self.addClass('resizehandle-both');
			}

			self.canFocus = false;

			return (
				'
' +
					'' +
				'
'
			);
		},

		/**
		 * Called after the control has been rendered.
		 *
		 * @method postRender
		 */
		postRender: function() {
			var self = this;

			self._super();

			self.resizeDragHelper = new DragHelper(this._id, {
				start: function() {
					self.fire('ResizeStart');
				},

				drag: function(e) {
					if (self.settings.direction != "both") {
						e.deltaX = 0;
					}

					self.fire('Resize', e);
				},

				end: function() {
					self.fire('ResizeEnd');
				}
			});
		},

		remove: function() {
			if (this.resizeDragHelper) {
				this.resizeDragHelper.destroy();
			}

			return this._super();
		}
	});
});<commit_msg>Fixed so ResizeEnd event gets fired on the ResizeHandle control.<commit_after>/**
 * ResizeHandle.js
 *
 * Copyright, Moxiecode Systems AB
 * Released under LGPL License.
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/**
 * Renders a resize handle that fires ResizeStart, Resize and ResizeEnd events.
 *
 * @-x-less ResizeHandle.less
 * @class tinymce.ui.ResizeHandle
 * @extends tinymce.ui.Widget
 */
define("tinymce/ui/ResizeHandle", [
	"tinymce/ui/Widget",
	"tinymce/ui/DragHelper"
], function(Widget, DragHelper) {
	"use strict";

	return Widget.extend({
		/**
		 * Renders the control as a HTML string.
		 *
		 * @method renderHtml
		 * @return {String} HTML representing the control.
		 */
		renderHtml: function() {
			var self = this, prefix = self.classPrefix;

			self.addClass('resizehandle');

			if (self.settings.direction == "both") {
				self.addClass('resizehandle-both');
			}

			self.canFocus = false;

			return (
				'
' +
					'' +
				'
'
			);
		},

		/**
		 * Called after the control has been rendered.
		 *
		 * @method postRender
		 */
		postRender: function() {
			var self = this;

			self._super();

			self.resizeDragHelper = new DragHelper(this._id, {
				start: function() {
					self.fire('ResizeStart');
				},

				drag: function(e) {
					if (self.settings.direction != "both") {
						e.deltaX = 0;
					}

					self.fire('Resize', e);
				},

				stop: function() {
					self.fire('ResizeEnd');
				}
			});
		},

		remove: function() {
			if (this.resizeDragHelper) {
				this.resizeDragHelper.destroy();
			}

			return this._super();
		}
	});
});<|endoftext|>


<commit_before>const Command = require('../Command');

module.exports = Command.extend({
    commandName: 'ts',
    commandAliases: ['teamspeak', 'mumble'],
    processMessage: function (message, tokens) {
        return message.channel.send(this.i18n.__mf("You can connect to our TeamSpeak at `{url}` (but, by personal preference, Discord is better).", {url: 'ts.shotbow.net'}));
    }
});
<commit_msg>Removed !ts command, as we no longer have a TS server.<commit_after><|endoftext|>


<commit_before>/**
 * @param {string} S
 * @return {string}
 */
var toGoatLatin = function(S) {
    let isVowel = function (c) {
        return c === 'a' || c === 'e' || c === 'i' || c === 'o' || c === 'u' ||
               c === 'A' || c === 'E' || c === 'I' || c === 'O' || c === 'U';
    };
    let ans = "";
    let postfix = "a";
    let wordList = S.split(' ');
    for (let [i, word] of wordList.entries()) {
        if (word.length === 0) { continue; }
        let glword = "";
        if (isVowel(word[0])) {
            glword += word + "ma";
        } else {
            glword += word.substr(1) + word[0] + "ma";
        }
        glword += postfix;
        postfix += "a";
        ans += glword;
        ans += (i === wordList.length - 1) ? "":" ";
    }
    return ans;
};
// TEST
[
    "",
    "a",
    "I speak Goat Latin",
    "The quick brown fox jumped over the lazy dog",
].forEach(t => {
    console.log(t, "->", toGoatLatin(t));
});<commit_msg>August Leetcoding Challenge: Revisited p824e goat latin in JS<commit_after>/**
 * @param {string} S
 * @return {string}
 */
var toGoatLatin = function (S) {
  const vowels = new Set('aeiouAEIOU');
  const words = S.split(' ');
  for (let i = 0; i < words.length; ++i) {
    if (!vowels.has(words[i][0]))
      words[i] = words[i].substring(1) + words[i][0];
    words[i] += 'ma';
    for (let j = 0; j < i + 1; ++j) words[i] += 'a';
  }
  return words.join(' ');
};
// TEST
[
  ['a', 'amaa'],
  ['b', 'bmaa'],
  ['bc', 'cbmaa'],
  ['I speak Goat Latin', 'Imaa peaksmaaa oatGmaaaa atinLmaaaaa'],
  [
    'The quick brown fox jumped over the lazy dog',
    'heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa',
  ],
].forEach((t) => {
  const actual = toGoatLatin(t[0]);
  console.log('Goat Latin of', t[0], '->', actual);
  console.assert(actual === t[1]);
});
<|endoftext|>


<commit_before>/**
 * Created with IntelliJ IDEA.
 * User: kehoro
 * Date: 22/11/12
 * Time: 20:22
 * To change this template use File | Settings | File Templates.
 */

Ext.define('default.model.Offline', {
  extend: 'Ext.data.Model',
  config: {
    fields: [
      'name'
    ],
    identifier:'uuid', // needed to avoid console warnings!
    proxy: {
      type: 'localstorage',
      id  : 'news'
    }
  }
});<commit_msg>Fixing comments and highlighting UUID issue<commit_after>/**
 * User: Robert Kehoe
 * Date: 22/11/12
 * Time: 20:22
 * Use Sencha Touch inbuilt WebStorage API to persist data to the users browser
 */

Ext.define('default.model.Offline', {
  extend: 'Ext.data.Model',
  config: {
    fields: [
      'name'
    ],
    identifier:'uuid', // IMPORTANT, needed to avoid console warnings!
    proxy: {
      type: 'localstorage',
      id  : 'news'
    }
  }
});<|endoftext|>


<commit_before>/*
 *     Copyright (c) 2013 CoNWeT Lab., Universidad Politécnica de Madrid
 *
 *     This file is part of Wirecloud Platform.
 *
 *     Wirecloud Platform is free software: you can redistribute it and/or
 *     modify it under the terms of the GNU Affero General Public License as
 *     published by the Free Software Foundation, either version 3 of the
 *     License, or (at your option) any later version.
 *
 *     Wirecloud is distributed in the hope that it will be useful, but WITHOUT
 *     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 *     License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with Wirecloud Platform.  If not, see
 *     <http://www.gnu.org/licenses/>.
 *
 */

/*global Constants, gettext, LogManagerFactory, StyledElements, Wirecloud, LayoutManagerFactory*/

(function () {

    "use strict";

    var GenericInterfaceSettingsMenuItems, clickCallback;

    GenericInterfaceSettingsMenuItems = function GenericInterfaceSettingsMenuItems(geinterface) {
        this.geinterface = geinterface;
    };
    GenericInterfaceSettingsMenuItems.prototype = new StyledElements.DynamicMenuItems();

    GenericInterfaceSettingsMenuItems.prototype.build = function build(context) {
        var label;
        var item, items = [];

        item = new StyledElements.MenuItem(gettext('Reorder endpoints'), function () {
                this.wiringEditor.ChangeObjectEditing(this);
        }.bind(this.geinterface));
        item.setDisabled(this.geinterface.sourceAnchors.length <= 1 && this.geinterface.targetAnchors.length <= 1);
        items.push(item);

        item = new StyledElements.MenuItem(gettext('Settings'), function () {
            var window_menu;
            if (this.ioperator) {
                window_menu = new Wirecloud.ui.OperatorPreferencesWindowMenu();
                window_menu.show(this.ioperator);
            } else {
                window_menu = new Wirecloud.Widget.PreferencesWindowMenu();
                window_menu.show(this.iwidget);
            }
        }.bind(this.geinterface));
        if ('ioperator' in this.geinterface) {
            item.setDisabled(this.geinterface.ioperator.meta.preferenceList.length == 0);
        } else {
            item.setDisabled(this.geinterface.iwidget.widget.getTemplate().getUserPrefs().length == 0);
        }
        items.push(item);

        return items;
    };

    Wirecloud.ui.WiringEditor.GenericInterfaceSettingsMenuItems = GenericInterfaceSettingsMenuItems;
})();
<commit_msg>Add minimize option in operator settings menu<commit_after>/*
 *     Copyright (c) 2013 CoNWeT Lab., Universidad Politécnica de Madrid
 *
 *     This file is part of Wirecloud Platform.
 *
 *     Wirecloud Platform is free software: you can redistribute it and/or
 *     modify it under the terms of the GNU Affero General Public License as
 *     published by the Free Software Foundation, either version 3 of the
 *     License, or (at your option) any later version.
 *
 *     Wirecloud is distributed in the hope that it will be useful, but WITHOUT
 *     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 *     License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with Wirecloud Platform.  If not, see
 *     <http://www.gnu.org/licenses/>.
 *
 */

/*global Constants, gettext, LogManagerFactory, StyledElements, Wirecloud, LayoutManagerFactory*/

(function () {

    "use strict";

    var GenericInterfaceSettingsMenuItems, clickCallback;

    GenericInterfaceSettingsMenuItems = function GenericInterfaceSettingsMenuItems(geinterface) {
        this.geinterface = geinterface;
    };
    GenericInterfaceSettingsMenuItems.prototype = new StyledElements.DynamicMenuItems();

    GenericInterfaceSettingsMenuItems.prototype.build = function build(context) {
        var label;
        var item, items = [];

        item = new StyledElements.MenuItem(gettext('Reorder endpoints'), function () {
                this.wiringEditor.ChangeObjectEditing(this);
        }.bind(this.geinterface));
        item.setDisabled(this.geinterface.sourceAnchors.length <= 1 && this.geinterface.targetAnchors.length <= 1);
        items.push(item);

        item = new StyledElements.MenuItem(gettext('Settings'), function () {
            var window_menu;
            if (this.ioperator) {
                window_menu = new Wirecloud.ui.OperatorPreferencesWindowMenu();
                window_menu.show(this.ioperator);
            } else {
                window_menu = new Wirecloud.Widget.PreferencesWindowMenu();
                window_menu.show(this.iwidget);
            }
        }.bind(this.geinterface));
        if ('ioperator' in this.geinterface) {
            item.setDisabled(this.geinterface.ioperator.meta.preferenceList.length == 0);
        } else {
            item.setDisabled(this.geinterface.iwidget.widget.getTemplate().getUserPrefs().length == 0);
        }
        items.push(item);

        if (this.geinterface.ioperator) {
            if (this.geinterface.isMinimized) {
                label = 'Maximize';
            } else {
                label = 'Minimize';
            }
            items.push(new StyledElements.MenuItem(gettext(label), function () {
                var interval;

                if (this.isMinimized) {
                    this.restore();
                } else {
                    this.minimize();
                }
            }.bind(this.geinterface)));
        }
        if (this.geinterface.numberOfSources > 1 || this.geinterface.numberOfTargets > 1) {
            items.push(new StyledElements.MenuItem(gettext('Reorder endpoints'), function () {
                    this.wiringEditor.ChangeObjectEditing(this);
            }.bind(this.geinterface)));
        }
        return items;
    };

    Wirecloud.ui.WiringEditor.GenericInterfaceSettingsMenuItems = GenericInterfaceSettingsMenuItems;
})();
<|endoftext|>


<commit_before>//Save some useful key codes for later, so I don't  have to remember the random number
var KEYCODE_LEFT = 37;
var KEYCODE_UP = 38;
var KEYCODE_RIGHT = 39;
var KEYCODE_DOWN = 40;
//var KEYCODE_a = 65;
//var KEYCODE_s = 83;
var KEYCODE_ESC = 27;

var canWidth = 800;
var canHeight = 450;

var CyberCloud = {};
var player;

function init(){
	var stage = new PIXI.Stage(0x000);
	var renderer = PIXI.autoDetectRenderer(canWidth,canHeight);
	document.body.appendChild(renderer.view);

	var assetsToLoad = ["graphics/playerShipSS.json", "graphics/StarField.png", "graphics/starFieldCloseAlph.png","graphics/Planet.png", "graphics/rock.png"];
	var loader = new PIXI.AssetLoader(assetsToLoad);
	loader.onComplete = onAssetsLoaded;
	loader.load();

	function onAssetsLoaded(){
		var playerShipTextures = [];
		playerShipTextures.push(PIXI.Texture.fromFrame("PlayerShip.png"));
		playerShipTextures.push(PIXI.Texture.fromFrame("PlayerShipGo.png"));

		CyberCloud.background = new PIXI.TilingSprite(PIXI.Texture.fromImage('graphics/StarField.png'),800,500);
		CyberCloud.lessBackBackground = new PIXI.TilingSprite(PIXI.Texture.fromImage('graphics/starFieldCloseAlph.png'),800,500);

		var planet = new PIXI.Sprite(PIXI.Texture.fromImage('graphics/Planet.png'));
		planet.anchor.x = 0.5;
		planet.anchor.y = 0.5;
		planet.position.x = 1000;
		planet.position.y = 1000;

		var rock = new PIXI.Sprite(PIXI.Texture.fromImage('graphics/rock.png'));

		rock.anchor.x = 0.5;
		rock.anchor.y = 0.5;
		rock.position.x = canWidth/2;
		rock.position.y = -100;

		CyberCloud.spaceRock = new floatingSpaceObject(rock, 50);

		CyberCloud.gameLevel = new PIXI.DisplayObjectContainer();
		//CyberCloud.gameLevel.width = 10000;
		//CyberCloud.gameLevel.height = 10000;

		var ship = new PIXI.MovieClip(playerShipTextures);

		ship.anchor.x = 0.5;
		ship.anchor.y = 0.5;
		ship.position.x = canWidth/2;
		ship.position.y = canHeight/2;

		ship.gotoAndStop(0);
		CyberCloud.gameLevel.addChild(planet);
		CyberCloud.gameLevel.addChild(ship);
		CyberCloud.gameLevel.addChild(rock);

		stage.addChild(CyberCloud.background);
		stage.addChild(CyberCloud.lessBackBackground);
		stage.addChild(CyberCloud.gameLevel);

		player = new playerShip(ship);

		requestAnimationFrame(animate);
		window.addEventListener('keydown',function(e){
			handleKeyDown(e,player);
		});
		window.addEventListener('keyup', function(e){
			handleKeyUp(e,player);
		});
	}

	function animate(){
		requestAnimationFrame(animate);
		player.update();
		CyberCloud.spaceRock.update();
		if(didCollide(player.radius, player.sprite.position.x, player.sprite.position.y, CyberCloud.spaceRock.radius, CyberCloud.spaceRock.sprite.position.x, CyberCloud.spaceRock.sprite.position.y)) calculateCollision(player, CyberCloud.spaceRock);
		renderer.render(stage);
	}

}

function didCollide(radius1, x1, y1, radius2, x2, y2){
	var dist = Math.sqrt(Math.pow(x2-x1,2)+Math.pow(y2-y1,2));
	var radii = radius1 + radius2;
	//console.log(Math.pow(x2-x1,2)-Math.pow(y2-y1,2));
	if(dist <= radii) return true;
	else return false;
}
function calculateCollision(moving,still){
	if(moving.velocity_x === 0 && moving.velocity_y === 0) {
		var temp = still;
		still = moving;
		moving = temp;
	}
	var deltaX = moving.sprite.position.x - still.sprite.position.x;
	var deltaY = moving.sprite.position.y - still.sprite.position.y;

	var angleStillIsPushedOffIn = Math.atan2(deltaY,deltaX)-1.57079633;

	var angleMovingBouncesOffIn = angleStillIsPushedOffIn;//moving will be pushed off in a right angle to angleStillIsPushedOffIn
	var movingVelocity = Math.sqrt(Math.pow(moving.velocity_x,2)+Math.pow(moving.velocity_y,2));
	var v1 = ((moving.mass - still.mass)*movingVelocity)/(moving.mass+still.mass);//resulting velocity of moving
	var v2 = (2*moving.mass*movingVelocity)/(moving.mass+still.mass);//Resulting velocity of still
	console.log("Calculate Collision!");
	console.log("angle Ship: "+radiansToDegrees(angleMovingBouncesOffIn)+" Velocity ship is pushed off in: "+v1);
	console.log("angle rock: "+radiansToDegrees(angleStillIsPushedOffIn)+" Velocity rock is pushed off in: "+v2);
	moving.accelerate(angleMovingBouncesOffIn, v1);
	still.accelerate(angleStillIsPushedOffIn, v2);
}

function floatingSpaceObject(sprite, radius){
	this.velocity_x = 0;
	this.velocity_y = 0;
	this.radius = radius;
	this.sprite = sprite;
	this.mass = 50;

	this.updatePosition = function(){
		this.sprite.position.x += this.velocity_x;
		this.sprite.position.y += this.velocity_y;
	};
	this.deg_conv = function(angle){
		if (angle < 0){
			angle += 360;
		}
		else if (angle > 360){
			angle -= 360;
		}
		angle -= 90;
		return angle;
	};
	this.accelerate = function(directionInRadians, acceleration){
		var degree = radiansToDegrees(directionInRadians);
		degree = this.deg_conv(degree);

		var diffx = Math.cos(degree * (Math.PI / 180)) * acceleration;
		var diffy = Math.sin(degree * (Math.PI / 180)) * acceleration;
		this.velocity_x += diffx;
		this.velocity_y += diffy;

	};

	this.update = function(){
		this.updatePosition();
	};

}

function playerShip(sprite){

	this.sprite = sprite;

	this.acceleration_rate = 0.1;
	this.rotating_l = false;
	this.rotating_r = false;
	this.accelerating = false;
	this.breaking = false;
	this.radius = 22;
	this.mass = 10;

	this.update_position = function(){
		this.sprite.position.x += this.velocity_x;
		this.sprite.position.y += this.velocity_y;
		CyberCloud.background.tilePosition.x -= this.velocity_x/10;
		CyberCloud.background.tilePosition.y -= this.velocity_y/10;
		CyberCloud.lessBackBackground.tilePosition.x -= this.velocity_x/5;
		CyberCloud.lessBackBackground.tilePosition.y -= this.velocity_y/5;
		CyberCloud.gameLevel.position.x -= this.velocity_x;
		CyberCloud.gameLevel.position.y -= this.velocity_y;
	};
	/*
	this.screen_wrap = function(){
	if (this.sprite.position.x > canWidth+10) {
	this.sprite.position.x = 0;
}
else if (this.sprite.position.x < -10){
this.sprite.position.x = canWidth;
}
if (this.sprite.position.y > canHeight+10) {
this.sprite.position.y = 0;
}
else if (this.sprite.position.y < -10) {
this.sprite.position.y = canHeight;
}
};
*/
this.apply_breaks = function(){
	if (this.velocity_x > -1 && this.velocity_x < 1){
		this.velocity_x = 0;
	}
	if (this.velocity_y > -1 && this.velocity_y < 1){
		this.velocity_y = 0;
	}
	if ( 0 > this.velocity_x){
		this.velocity_x += this.acceleration_rate;
	}
	else if ( 0 < this.velocity_x){
		this.velocity_x -= this.acceleration_rate;
	}
	if ( 0 > this.velocity_y){
		this.velocity_y += this.acceleration_rate;
	}
	else if ( 0 < this.velocity_y){
		this.velocity_y -= this.acceleration_rate;
	}
};
this.spin_ship = function(){
	if (this.rotating_l){
		this.sprite.rotation -= 0.1;
	}
	if (this.rotating_r){
		this.sprite.rotation += 0.1;
	}

};
this.update = function(){

	if(this.rotating_l || this.rotating_r){
		this.spin_ship();
	}
	if(this.breaking){
		this.apply_breaks();
	}
	if(this.accelerating){
		this.accelerate(this.sprite.rotation, this.acceleration_rate);
		this.sprite.gotoAndStop(1);
	}
	else this.sprite.gotoAndStop(0);
	this.update_position();
	//this.screen_wrap();

};
}
playerShip.prototype = new floatingSpaceObject();
function radiansToDegrees(radians){
	return radians*(180/Math.PI);
}
function handleKeyDown(e,player) {
	switch (e.keyCode) {
		case KEYCODE_RIGHT:
			player.rotating_r = true;
		break;
		case KEYCODE_LEFT:
			player.rotating_l = true;
		break;
		case KEYCODE_UP:
			player.accelerating = true;
		break;
		case KEYCODE_DOWN:
			player.breaking = true;
		break;
		case KEYCODE_ESC:
			//pauseMenu();
		break;
	}
}
//Do different things when a button is released
function handleKeyUp(e,player) {
	switch (e.keyCode) {
		case KEYCODE_RIGHT:
			player.rotating_r = false;
		break;
		case KEYCODE_LEFT:
			player.rotating_l = false;
		break;
		case KEYCODE_UP:
			player.accelerating = false;
		break;
		case KEYCODE_DOWN:
			player.breaking = false;
		break;
	}
}
document.addEventListener('DOMContentLoaded', init );
<commit_msg>Added 'firewall'; refactored<commit_after>"use strict";
//Save some useful key codes for later, so I don't  have to remember the random number
var KEYCODE_LEFT = 37;
var KEYCODE_UP = 38;
var KEYCODE_RIGHT = 39;
var KEYCODE_DOWN = 40;
//var KEYCODE_a = 65;
//var KEYCODE_s = 83;
var KEYCODE_ESC = 27;

var canWidth = 800;
var canHeight = 450;
var levelWidth
var levelH

var CyberCloud = {};

function init(){
	var stage = new PIXI.Stage(0x000);
	var renderer = PIXI.autoDetectRenderer(canWidth,canHeight);
	document.body.appendChild(renderer.view);

	var assetsToLoad = ["graphics/playerShipSS.json", "graphics/StarField.png", "graphics/starFieldCloseAlph.png","graphics/Planet.png", "graphics/rock.png"];
	var loader = new PIXI.AssetLoader(assetsToLoad);
	loader.onComplete = onAssetsLoaded;
	loader.load();

	function onAssetsLoaded(){
		var playerShipTextures = [];
		playerShipTextures.push(PIXI.Texture.fromFrame("PlayerShip.png"));
		playerShipTextures.push(PIXI.Texture.fromFrame("PlayerShipGo.png"));

		CyberCloud.background = new PIXI.TilingSprite(PIXI.Texture.fromImage('graphics/StarField.png'),800,500);
		CyberCloud.lessBackBackground = new PIXI.TilingSprite(PIXI.Texture.fromImage('graphics/starFieldCloseAlph.png'),800,500);

		CyberCloud.gameLevel = new PIXI.DisplayObjectContainer();
		CyberCloud.gameLevel.levelWidth = 10000;
		CyberCloud.gameLevel.levelHeight = 10000;

		var planet = new PIXI.Sprite(PIXI.Texture.fromImage('graphics/Planet.png'));
		planet.anchor.x = 0.5;
		planet.anchor.y = 0.5;
		planet.position.x = 1000;
		planet.position.y = 1000;

		var rock = new PIXI.Sprite(PIXI.Texture.fromImage('graphics/rock.png'));

		rock.anchor.x = 0.5;
		rock.anchor.y = 0.5;
		rock.position.x = canWidth/2;
		rock.position.y = 100;

		CyberCloud.spaceRock = new floatingSpaceObject(rock, 50);

		var fireWall = new PIXI.Graphics();
		fireWall.lineStyle(30, 0xCC0000);
		fireWall.drawRect(0, 0, CyberCloud.gameLevel.levelWidth, CyberCloud.gameLevel.levelHeight);

		var ship = new PIXI.MovieClip(playerShipTextures);

		ship.anchor.x = 0.5;
		ship.anchor.y = 0.5;
		ship.position.x = canWidth/2;
		ship.position.y = canHeight/2;
		ship.gotoAndStop(0);

		CyberCloud.gameLevel.addChild(planet);
		CyberCloud.gameLevel.addChild(ship);
		CyberCloud.gameLevel.addChild(rock);
		CyberCloud.gameLevel.addChild(fireWall);

		stage.addChild(CyberCloud.background);
		stage.addChild(CyberCloud.lessBackBackground);
		stage.addChild(CyberCloud.gameLevel);

		CyberCloud.player = new playerShip(ship);

		requestAnimationFrame(animate);
		window.addEventListener('keydown',function(e){
			handleKeyDown(e);
		});
		window.addEventListener('keyup', function(e){
			handleKeyUp(e);
		});
	}

	function animate(){
		requestAnimationFrame(animate);
		CyberCloud.player.update();
		CyberCloud.spaceRock.update();
		if(didCollide(CyberCloud.player, CyberCloud.spaceRock))
			calculateCollision(CyberCloud.player, CyberCloud.spaceRock);
		didItHitAWall(CyberCloud.player);
		didItHitAWall(CyberCloud.spaceRock);
		renderer.render(stage);
	}

}

function didCollide(thing1, thing2){
	var xDiff = Math.pow(thing2.sprite.position.x-thing1.sprite.position.x,2);
	var yDiff = Math.pow(thing2.sprite.position.y-thing1.sprite.position.y,2);
	var dist = Math.sqrt(xDiff+yDiff);
	var radii = thing1.radius + thing2.radius;
	if(dist <= radii) return true;
		else return false;
}
function calculateCollision(moving,still){
	if(moving.velocity_x === 0 && moving.velocity_y === 0) {
		var temp = still;
		still = moving;
		moving = temp;
	}
	var deltaX = moving.sprite.position.x - still.sprite.position.x;
	var deltaY = moving.sprite.position.y - still.sprite.position.y;

	var angleStillIsPushedOffIn = Math.atan2(deltaY,deltaX)-1.57079633;

	var angleMovingBouncesOffIn = angleStillIsPushedOffIn;//moving will be pushed off in a right angle to angleStillIsPushedOffIn
	var movingVelocity = Math.sqrt(Math.pow(moving.velocity_x,2)+Math.pow(moving.velocity_y,2));
	var v1 = ((moving.mass - still.mass)*movingVelocity)/(moving.mass+still.mass);//resulting velocity of moving
	var v2 = (2*moving.mass*movingVelocity)/(moving.mass+still.mass);//Resulting velocity of still
	/*
	console.log("Calculate Collision!");
	console.log("angle Ship: "+radiansToDegrees(angleMovingBouncesOffIn)+" Velocity ship is pushed off in: "+v1);
	console.log("angle rock: "+radiansToDegrees(angleStillIsPushedOffIn)+" Velocity rock is pushed off in: "+v2);
	*/
	moving.accelerate(angleMovingBouncesOffIn, v1);
	still.accelerate(angleStillIsPushedOffIn, v2);
}
function didItHitAWall(it){
	var wall = {
		sprite:{
			position:{
				x:0,
				y:0
			}
		},
		mass : 1000000,
		accelerate: function(herp,derp){}
	};
	if(it.sprite.position.x < it.radius){
		//console.log('Wall Crash!');
		wall.sprite.position.x = it.sprite.position.x-it.radius;
		wall.sprite.position.y = it.sprite.position.y;
		calculateCollision(it,wall);
	}else if(it.sprite.position.x > CyberCloud.gameLevel.levelWidth - it.radius){
		wall.sprite.position.x = it.sprite.position.x+it.radius;
		wall.sprite.position.y = it.sprite.position.y;
		calculateCollision(it,wall);
	}
	if(it.sprite.position.y < it.radius){
		//console.log('Wall Crash!');
		wall.sprite.position.y = it.sprite.position.y-it.radius;
		wall.sprite.position.x = it.sprite.position.x;
		calculateCollision(it,wall);
	}else if(it.sprite.position.y > CyberCloud.gameLevel.levelHeight - it.radius){
		wall.sprite.position.y = it.sprite.position.y+it.radius;
		wall.sprite.position.x = it.sprite.position.x;
		calculateCollision(it,wall);
	}
}
function floatingSpaceObject(sprite, radius){
	this.velocity_x = 0;
	this.velocity_y = 0;
	this.radius = radius;
	this.sprite = sprite;
	this.mass = 100;

	this.updatePosition = function(){
		this.sprite.position.x += this.velocity_x;
		this.sprite.position.y += this.velocity_y;
	};
	this.deg_conv = function(angle){
		if (angle < 0){
			angle += 360;
		}
		else if (angle > 360){
			angle -= 360;
		}
		angle -= 90;
		return angle;
	};
	this.accelerate = function(directionInRadians, acceleration){
		var degree = radiansToDegrees(directionInRadians);
		degree = this.deg_conv(degree);

		var diffx = Math.cos(degree * (Math.PI / 180)) * acceleration;
		var diffy = Math.sin(degree * (Math.PI / 180)) * acceleration;
		this.velocity_x += diffx;
		this.velocity_y += diffy;

	};

	this.update = function(){
		this.updatePosition();
	};

}

function playerShip(sprite){

	this.sprite = sprite;

	this.acceleration_rate = 0.1;
	this.rotating_l = false;
	this.rotating_r = false;
	this.accelerating = false;
	this.breaking = false;
	this.radius = 22;
	this.mass = 10;

	this.update_position = function(){
		this.sprite.position.x += this.velocity_x;
		this.sprite.position.y += this.velocity_y;
		CyberCloud.background.tilePosition.x -= this.velocity_x/10;
		CyberCloud.background.tilePosition.y -= this.velocity_y/10;
		CyberCloud.lessBackBackground.tilePosition.x -= this.velocity_x/5;
		CyberCloud.lessBackBackground.tilePosition.y -= this.velocity_y/5;
		CyberCloud.gameLevel.position.x -= this.velocity_x;
		CyberCloud.gameLevel.position.y -= this.velocity_y;
	};
this.apply_breaks = function(){
	if (this.velocity_x > -1 && this.velocity_x < 1){
		this.velocity_x = 0;
	}
	if (this.velocity_y > -1 && this.velocity_y < 1){
		this.velocity_y = 0;
	}
	if ( 0 > this.velocity_x){
		this.velocity_x += this.acceleration_rate;
	}
	else if ( 0 < this.velocity_x){
		this.velocity_x -= this.acceleration_rate;
	}
	if ( 0 > this.velocity_y){
		this.velocity_y += this.acceleration_rate;
	}
	else if ( 0 < this.velocity_y){
		this.velocity_y -= this.acceleration_rate;
	}
};
this.spin_ship = function(){
	if (this.rotating_l){
		this.sprite.rotation -= 0.1;
	}
	if (this.rotating_r){
		this.sprite.rotation += 0.1;
	}

};
this.update = function(){

	if(this.rotating_l || this.rotating_r){
		this.spin_ship();
	}
	if(this.breaking){
		this.apply_breaks();
	}
	if(this.accelerating){
		this.accelerate(this.sprite.rotation, this.acceleration_rate);
		this.sprite.gotoAndStop(1);
	}
	else this.sprite.gotoAndStop(0);
	this.update_position();
	//this.screen_wrap();

};
}
playerShip.prototype = new floatingSpaceObject();
function radiansToDegrees(radians){
	return radians*(180/Math.PI);
}
function handleKeyDown(e) {
	switch (e.keyCode) {
		case KEYCODE_RIGHT:
			CyberCloud.player.rotating_r = true;
		break;
		case KEYCODE_LEFT:
			CyberCloud.player.rotating_l = true;
		break;
		case KEYCODE_UP:
			CyberCloud.player.accelerating = true;
		break;
		case KEYCODE_DOWN:
			CyberCloud.player.breaking = true;
		break;
		case KEYCODE_ESC:
			//pauseMenu();
		break;
	}
}
//Do different things when a button is released
function handleKeyUp(e) {
	switch (e.keyCode) {
		case KEYCODE_RIGHT:
			CyberCloud.player.rotating_r = false;
		break;
		case KEYCODE_LEFT:
			CyberCloud.player.rotating_l = false;
		break;
		case KEYCODE_UP:
			CyberCloud.player.accelerating = false;
		break;
		case KEYCODE_DOWN:
			CyberCloud.player.breaking = false;
		break;
	}
}
document.addEventListener('DOMContentLoaded', init );
<|endoftext|>


<commit_before>
function DOMElement (node, tagName) {
    this._node = node;

    this._requestingUpdate = false;

    this._changeQueue = [];

    this._classes = ['fa-surface'];
    this._requestingEventListeners = [];
    this._styles = {
        display: 'none'
    };
    this._attributes = {};
    this._content = null;

    this._tagName = tagName ? tagName : 'div';
    this._id = node.addComponent(this);
}

DOMElement.prototype.getValue = function getValue () {
    return {
        classes: this._classes,
        styles: this._styles,
        attributes: this._attributes,
        content: this._content
    };
};

DOMElement.prototype.onUpdate = function onUpdate () {
    var node = this._node;
    var queue = this._changeQueue;
    var len = queue.length;

    if (len && node) {
        node.sendDrawCommand('WITH');
        node.sendDrawCommand(node.getLocation());
        node.sendDrawCommand('DOM');

        while (len--) node.sendDrawCommand(queue.shift());
    }

    this._requestingUpdate = false;
};

DOMElement.prototype.onMount = function onMount (node, id) {
    this._node = node;
    this._id = id;
    this.draw();
    this.setAttribute('data-fa-path', node.getLocation());
};

DOMElement.prototype.onDismount = function onDismount () {
    this.setProperty('display', 'none');
    this.setAttribute('data-fa-path', '');
    this._changeQueue.push('RECALL');
};

DOMElement.prototype.onShow = function onShow () {
    this.setProperty('display', 'block');
};

DOMElement.prototype.onHide = function onHide () {
    this.setProperty('display', 'none');
    this._changeQueue.push('RECALL');
};

DOMElement.prototype.onTransformChange = function onTransformChange (transform) {
    this._changeQueue.push('CHANGE_TRANSFORM');
    for (var i = 0, len = transform.length ; i < len ; i++)
        this._changeQueue.push(transform[i]);

    if (!this._requestingUpdate) this._requestUpdate();
};

DOMElement.prototype.onSizeChange = function onSizeChange (size) {
    var sizeMode = this._node.getSizeMode();
    var sizedX = sizeMode[0] !== Node.RENDER_SIZE;
    var sizedY = sizeMode[1] !== Node.RENDER_SIZE;
    this._changeQueue.push('CHANGE_SIZE',
            sizedX ? size[0] : sizedX,
            sizedY ? size[1] : sizedY);

    if (!this._requestingUpdate) this._requestUpdate();
    return this;
};

DOMElement.prototype.onAddUIEvent = function onAddUIEvent (UIEvent, methods, properties) {
    this._changeQueue.push('ADD_EVENT_LISTERNER', UIEvent);
    if (methods != null) this._changeQueue.push(methods);
    if (properties != null) this._changeQueue.push(properties);
    if (!this._requestingUpdate) this._requestUpdate();
    this._changeQueue.push('EVENT_END');
};

DOMElement.prototype.onSizeModeChange = function onSizeModeChange (sizeMode) {
    var size = this._node.getSize();
    var sizedX = sizeMode[0] !== Node.RENDER_SIZE;
    var sizedY = sizeMode[1] !== Node.RENDER_SIZE;
    if (sizedX) this.setProperty('width', size[0] + 'px');
    if (sizedY) this.setProperty('height', size[1] + 'px');
};

DOMElement.prototype._requestUpdate = function _requestUpdate () {
    if (!this._requestingUpdate) {
        this._node.requestUpdate(this._id);
        this._requestingUpdate = true;
    }
};

DOMElement.prototype.init = function init () {
    this._changeQueue.push('INIT_DOM', this._tagName);
    this.onTransformChange(this._node.getTransform());
    this.onSizeChange(this._node.getSize());
    if (!this._requestingUpdate) this._requestUpdate();
};

DOMElement.prototype.setID = function setID (id) {
    this.setAttribute('ID', id);
    return this;
};

DOMElement.prototype.addClass = function addClass (value) {
    if (this._classes.indexOf(value) < 0) {
        this._changeQueue.push('ADD_CLASS', value);
        this._classes.push(value);
        if (!this._requestingUpdate) this._requestUpdate();
        return this;
    }

    if (this._inDraw) {
        this._changeQueue.push('ADD_CLASS', value);
        if (!this._requestingUpdate) this._requestUpdate();
    }
    return this;
};

DOMElement.prototype.removeClass = function removeClass (value) {
    var index = this._classes.indexOf(value);

    if (index < 0) return this;

    this._changeQueue.push('REMOVE_CLASS', value);

    this._classes.splice(index, 1);

    if (!this._requestingUpdate) this._requestUpdate();
    return this;
};

DOMElement.prototype.setAttribute = function setAttribute (name, value) {
    if (this._attributes[name] !== value || this._inDraw) {
        this._attributes[name] = value;
        this._changeQueue.push('CHANGE_ATTRIBUTE', name, value);
        if (!this._requestUpdate) this._requestUpdate();
    }
    return this;
};

DOMElement.prototype.setProperty = function setProperty (name, value) {
    if (this._styles[name] !== value || this._inDraw) {
        this._styles[name] = value;
        this._changeQueue.push('CHANGE_PROPERTY', name, value);
        if (!this._requestingUpdate) this._requestUpdate();
    }
    return this;
};

DOMElement.prototype.setContent = function setContent (content) {
    if (this._content !== content || this._inDraw) {
        this._content = content;
        this._changeQueue.push('CHANGE_CONTENT', content);
        this._requestUpdate();
    }
    return this;
};

DOMElement.prototype.draw = function draw () {
    var key;
    var i;
    var len;

    this._inDraw = true;

    this.init();

    for (i = 0, len = this._classes.length ; i < len ; i++)
        this.addClass(this._classes[i]);

    for (key in this._styles)
        if (this._styles[key])
            this.setProperty(key, this._styles[key]);

    for (key in this._attributes)
        if (this._attributes[key])
            this.setAttribute(key, this._attributes[key]);

    this._inDraw = false;
};

module.exports = DOMElement;

<commit_msg>fix: Always send INIT_DOM first<commit_after>
function DOMElement (node, tagName) {
    this._node = node;

    this._requestingUpdate = false;

    this._changeQueue = [];

    this._classes = ['fa-surface'];
    this._requestingEventListeners = [];
    this._styles = {
        display: 'none'
    };
    this._attributes = {};
    this._content = null;

    this._tagName = tagName ? tagName : 'div';
    this._id = node.addComponent(this);
}

DOMElement.prototype.getValue = function getValue () {
    return {
        classes: this._classes,
        styles: this._styles,
        attributes: this._attributes,
        content: this._content
    };
};

DOMElement.prototype.onUpdate = function onUpdate () {
    var node = this._node;
    var queue = this._changeQueue;
    var len = queue.length;

    if (len && node) {
        node.sendDrawCommand('WITH');
        node.sendDrawCommand(node.getLocation());
        node.sendDrawCommand('DOM');

        while (len--) node.sendDrawCommand(queue.shift());
    }

    this._requestingUpdate = false;
};

DOMElement.prototype.onMount = function onMount (node, id) {
    this._node = node;
    this._id = id;
    this.draw();
    this.setAttribute('data-fa-path', node.getLocation());
};

DOMElement.prototype.onDismount = function onDismount () {
    this.setProperty('display', 'none');
    this.setAttribute('data-fa-path', '');
    this._changeQueue.push('RECALL');
    this._initialized = false;
};

DOMElement.prototype.onShow = function onShow () {
    this.setProperty('display', 'block');
};

DOMElement.prototype.onHide = function onHide () {
    this.setProperty('display', 'none');
    this._changeQueue.push('RECALL');
};

DOMElement.prototype.onTransformChange = function onTransformChange (transform) {
    this._changeQueue.push('CHANGE_TRANSFORM');
    for (var i = 0, len = transform.length ; i < len ; i++)
        this._changeQueue.push(transform[i]);

    if (!this._requestingUpdate) this._requestUpdate();
};

DOMElement.prototype.onSizeChange = function onSizeChange (size) {
    var sizeMode = this._node.getSizeMode();
    var sizedX = sizeMode[0] !== Node.RENDER_SIZE;
    var sizedY = sizeMode[1] !== Node.RENDER_SIZE;
    this._changeQueue.push('CHANGE_SIZE',
            sizedX ? size[0] : sizedX,
            sizedY ? size[1] : sizedY);

    if (!this._requestingUpdate) this._requestUpdate();
    return this;
};

DOMElement.prototype.onAddUIEvent = function onAddUIEvent (UIEvent, methods, properties) {
    this._changeQueue.push('ADD_EVENT_LISTERNER', UIEvent);
    if (methods != null) this._changeQueue.push(methods);
    if (properties != null) this._changeQueue.push(properties);
    if (!this._requestingUpdate) this._requestUpdate();
    this._changeQueue.push('EVENT_END');
};

DOMElement.prototype.onSizeModeChange = function onSizeModeChange (sizeMode) {
    var size = this._node.getSize();
    var sizedX = sizeMode[0] !== Node.RENDER_SIZE;
    var sizedY = sizeMode[1] !== Node.RENDER_SIZE;
    if (sizedX) this.setProperty('width', size[0] + 'px');
    if (sizedY) this.setProperty('height', size[1] + 'px');
};

DOMElement.prototype._requestUpdate = function _requestUpdate () {
    if (!this._requestingUpdate) {
        this._node.requestUpdate(this._id);
        this._requestingUpdate = true;
    }
};

DOMElement.prototype.init = function init () {
    this._changeQueue.push('INIT_DOM', this._tagName);
    this._initialized = true;
    this.onTransformChange(this._node.getTransform());
    this.onSizeChange(this._node.getSize());
    if (!this._requestingUpdate) this._requestUpdate();
};

DOMElement.prototype.setID = function setID (id) {
    this.setAttribute('id', id);
    return this;
};

DOMElement.prototype.addClass = function addClass (value) {
    if (this._classes.indexOf(value) < 0) {
        if (this._initialized) this._changeQueue.push('ADD_CLASS', value);
        this._classes.push(value);
        if (!this._requestingUpdate) this._requestUpdate();
        return this;
    }

    if (this._inDraw) {
        if (this._initialized) this._changeQueue.push('ADD_CLASS', value);
        if (!this._requestingUpdate) this._requestUpdate();
    }
    return this;
};

DOMElement.prototype.removeClass = function removeClass (value) {
    var index = this._classes.indexOf(value);

    if (index < 0) return this;

    this._changeQueue.push('REMOVE_CLASS', value);

    this._classes.splice(index, 1);

    if (!this._requestingUpdate) this._requestUpdate();
    return this;
};

DOMElement.prototype.setAttribute = function setAttribute (name, value) {
    if (this._attributes[name] !== value || this._inDraw) {
        this._attributes[name] = value;
        if (this._initialized) this._changeQueue.push('CHANGE_ATTRIBUTE', name, value);
        if (!this._requestUpdate) this._requestUpdate();
    }
    return this;
};

DOMElement.prototype.setProperty = function setProperty (name, value) {
    if (this._styles[name] !== value || this._inDraw) {
        this._styles[name] = value;
        if (this._initialized) this._changeQueue.push('CHANGE_PROPERTY', name, value);
        if (!this._requestingUpdate) this._requestUpdate();
    }
    return this;
};

DOMElement.prototype.setContent = function setContent (content) {
    if (this._content !== content || this._inDraw) {
        this._content = content;
        if (this._initialized) this._changeQueue.push('CHANGE_CONTENT', content);
        if (!this._requestingUpdate) this._requestUpdate();
    }
    return this;
};

DOMElement.prototype.draw = function draw () {
    var key;
    var i;
    var len;

    this._inDraw = true;

    this.init();

    for (i = 0, len = this._classes.length ; i < len ; i++)
        this.addClass(this._classes[i]);

    this.setContent(this._content);

    for (key in this._styles)
        if (this._styles[key])
            this.setProperty(key, this._styles[key]);

    for (key in this._attributes)
        if (this._attributes[key])
            this.setAttribute(key, this._attributes[key]);

    this._inDraw = false;
};

module.exports = DOMElement;

<|endoftext|>


<commit_before>(function() {

    var directive = function() {
        return {
            restrict: "EA",
            bindToController: {
                stepIndex: '@'
            },
            require: ['thinkbigVisualQueryTransform', '^thinkbigStepper'],
            scope: {},
            controllerAs: 'vm',
            templateUrl: 'js/visual-query/visual-query-transform.html',
            controller: "VisualQueryTransformController",
            link: function($scope, element, attrs, controllers) {
                var thisController = controllers[0];
                var stepperController = controllers[1];
                //store a reference to the stepper if needed
                thisController.stepperController = stepperController;
            }

        };
    };

    var controller = function($scope, $log, $http, $mdToast, RestUrlService, VisualQueryService, HiveService, TableDataFunctions,
                              SideNavService, SparkShellService, VisualQueryColumnDelegate, uiGridConstants) {
        var self = this;
        //The model passed in from the previous step
        this.model = VisualQueryService.model;
        //Flag to determine if we can move on to the next step
        this.isValid = true;
        //The SQL String from the previous step
        this.sql = this.model.visualQuerySql;
        //The sql model passed over from the previous step
        this.sqlModel = this.model.visualQueryModel;
        //The array of columns with their respective Table, schema and alias passed over from the previous step
        //{column:'name', alias:'alias',tableName:'table name',tableColumn:'alias_name',dataType:'dataType'}
        this.selectedColumnsAndTables = this.model.selectedColumnsAndTables;
        //The query result transformed to the ag-grid model  (@see HiveService.transformToAgGrid
        this.tableData = {columns: [], rows: []};
        //Function History
        this.functionHistory = [];

        //The current formula string
        this.currentFormula = '';

        //flag to indicate if the Hive data is available
        this.hiveDataLoaded = false;
        //flag to indicate codemirror is ready
        this.codemirroLoaded = false;
        //the codemirror editor
        this.codemirrorEditor = null;
        //the tern server reference
        this.ternServer = null;

        //Function Command Holder
        //@see TableDataFunctions.js
        this.functionCommandHolder = null;

        //Flag to show/hide function history panel
        this.isShowFunctionHistory = false;

        // Flag to show/hide sample menu
        this.isShowSampleMenu = false;

        //Setup initial grid options
        this.gridOptions = {
            columnDefs: [],
            data: null,
            enableColumnResizing: true,
            enableFiltering: true,
            flatEntityAccess: true,
            onRegisterApi: function(grid) {
                self.gridApi = grid;
            }
        };

        // Translates expressions into Spark code
        this.sparkShellService = new SparkShellService(this.sql);

        //Code Mirror options.  Tern Server requires it be in javascript mode
        this.codemirrorOptions = {
            lineWrapping: false,
            indentWithTabs: false,
            smartIndent: false,
            lineNumbers: false,
            matchBrackets: false,
            autofocus: true,
            mode: 'javascript',
            scrollbarStyle: null
        };

        /**
         * Show and hide the Funciton History
         */
        this.toggleFunctionHistory = function() {
            self.isShowFunctionHistory = !self.isShowFunctionHistory;
        };

        /**
         * Toggle the visibility of the sample menu.
         */
        this.toggleSampleMenu = function() {
            self.isShowSampleMenu = !self.isShowSampleMenu;
        };

        //Callback when Codemirror has been loaded (reference is in the html page at:
        // ui-codemirror="{ onLoad : vm.codemirrorLoaded }"
        this.codemirrorLoaded = function(_editor) {
            //assign the editor to a variable on this object for future reference
            self.codemirrorEditor = _editor;
            //Set the width,height of the editor. Code mirror needs an explicit width/height
            _editor.setSize(700, 25);

            //disable users ability to add new lines.  The Formula bar is only 1 line
            _editor.on("beforeChange", function(instance, change) {
                var newtext = change.text.join("").replace(/\n/g, ""); // remove ALL \n !
                change.update(change.from, change.to, [newtext]);
                return true;
            });

            //hide the scrollbar
            _editor.on("change", function(instance, change) {
                //$(".CodeMirror-hscrollbar").css('display', 'none');
            });
            //set the flag to be loaded and then call out to update Autocomplete options
            self.codemirroLoaded = true;
            self.updateCodeMirrorAutoComplete();
        };

        /**
         * Creates a Tern server.
         */
        function createTernServer() {
            $http.get('js/vendor/tern/defs/tableFunctions.json').success(function(code) {
                self.sparkShellService.setFunctionDefs(code);

                self.ternServer = new CodeMirror.TernServer({defs: [code]});
                self.ternServer.server.addDefs(self.sparkShellService.getColumnDefs());

                var _editor = self.codemirrorEditor;
                _editor.setOption("extraKeys", {
                    "Ctrl-Space": function(cm) {
                        self.ternServer.complete(cm);
                    },
                    "Ctrl-I": function(cm) {
                        self.ternServer.showType(cm);
                    },
                    "Ctrl-O": function(cm) {
                        self.ternServer.showDocs(cm);
                    },
                    "Alt-.": function(cm) {
                        self.ternServer.jumpToDef(cm);
                    },
                    "Alt-,": function(cm) {
                        self.ternServer.jumpBack(cm);
                    },
                    "Ctrl-Q": function(cm) {
                        self.ternServer.rename(cm);
                    },
                    "Ctrl-.": function(cm) {
                        self.ternServer.selectName(cm);
                    }
                });
                _editor.on("blur", function() {
                    self.ternServer.hideDoc();
                });
                _editor.on("cursorActivity", self.showHint);
                _editor.on("focus", self.showHint);
            });
        }

        /**
         * Setup the CodeMirror and Tern Server autocomplete. This will only execute when both Hive and Code Mirror are fully
         * initialized.
         */
        this.updateCodeMirrorAutoComplete = function() {
            if (self.codemirroLoaded && self.hiveDataLoaded) {
                if (self.ternServer === null) {
                    createTernServer();
                } else {
                    var defs = self.sparkShellService.getColumnDefs();
                    self.ternServer.server.deleteDefs(defs["!name"]);
                    self.ternServer.server.addDefs(defs);
                }
            }
        };

        /**
         * Makes an asynchronous request to get the list of completions available at the cursor.
         *
         * @param {CodeMirror|CodeMirror.Doc} cm the code mirror instance
         * @param {Function} callback the callback function
         */
        this.getHint = function(cm, callback) {
            self.ternServer.getHint(cm, function(data) {
                // Complete function calls so arg hints can be displayed
                CodeMirror.on(data, "pick", function(completion) {
                    if (completion.data.type.substr(0, 3) === "fn(") {
                        var cursor = cm.getCursor();
                        cm.replaceRange("(", cursor, cursor, "complete");
                    }
                });

                // Display hints
                callback(data);
            });
        };
        this.getHint.async = true;

        /**
         * Shows either argument hints or identifier hints depending on the context.
         *
         * @param {CodeMirror|CodeMirror.Doc} cm the code mirror instance
         */
        this.showHint = function(cm) {
            // Show args if in a function
            var cursor = cm.getCursor();
            var token = cm.getTokenAt(cursor);
            var lexer = token.state.lexical;

            if (lexer.info === "call" && token.type !== "variable") {
                self.ternServer.updateArgHints(cm);
            } else {
                self.ternServer.hideDoc();
            }

            // Show completions if available
            if (cursor.ch === 0 || token.type === "variable" || (token.string === "." && lexer.type === "stat")) {
                cm.showHint({
                    completeSingle: false,
                    hint: self.getHint
                });
            }
        };

        /**
         * Query Hive using the query from the previous step. Set the Grids rows and columns
         */
        this.query = function() {
            //flag to indicate query is running
            this.executingQuery = true;

            return self.sparkShellService.transform().then(function(response) {
                //mark the query as finished
                self.executingQuery = false;

                // Clear previous filters
                if (typeof(self.gridApi) !== "undefined") {
                    self.gridApi.core.clearAllFilters();
                }

                //transform the result to the agGrid model
                var result = HiveService.transformQueryResultsToUiGridModel({data: response.data.results});

                angular.forEach(result.columns, function(column) {
                    column.headerCellTemplate = "visual-query/grid-header-cell";
                    column.delegate = new VisualQueryColumnDelegate(self);
                    column.filters = column.delegate.filters;
                });

                //store the result for use in the commands
                self.tableData = result;
                //update the ag-grid
                self.gridOptions.columnDefs = result.columns;
                self.gridOptions.data = result.rows;
                //mark the flag to indicate Hive is loaded
                self.hiveDataLoaded = true;
                self.updateCodeMirrorAutoComplete();

                //Initialize the Command function holder
                self.functionCommandHolder = TableDataFunctions.newCommandHolder({rows: result.rows, columns: result.columns});
            });
        };

        function updateGrid(tableData) {
            self.gridOptions.columnDefs = tableData.columns;
            self.gridOptions.data = tableData.rows;
        }

        /**
         * Adds formulas for column filters.
         */
        this.addFilters = function() {
            angular.forEach(self.gridApi.grid.columns, function(column) {
                angular.forEach(column.filters, function(filter) {
                    if (filter.term) {
                        if (filter.condition == uiGridConstants.filter.LESS_THAN) {
                            self.pushFormula("filter(lessThan(" + column.field + ", " + StringUtils.quote(filter.term) + "))");
                        } else if (filter.condition == uiGridConstants.filter.GREATER_THAN) {
                            self.pushFormula("filter(greaterThan(" + column.field + ", " + StringUtils.quote(filter.term) + "))");
                        } else if (filter.condition == uiGridConstants.filter.EXACT) {
                            self.pushFormula("filter(equal(" + column.field + ", " + StringUtils.quote(filter.term) + "))");
                        }
                    }
                });
            });
        };

        /**
         * Adds the specified formula to the current script and refreshes the table data.
         *
         * @param {string} formula the formula
         */
        this.addFunction = function(formula) {
            var tableData = self.functionCommandHolder.executeStr(formula);
            if (tableData != null && tableData != undefined) {
                updateGrid(tableData);

                self.addFilters();
                self.pushFormula(formula);
                self.query();
            }
        };

        /**
         * Appends the specified formula to the current script.
         *
         * @param {string} formula the formula
         */
        this.pushFormula = function(formula) {
            self.functionHistory.push(formula);

            self.ternServer.server.addFile("[doc]", formula);
            var file = self.ternServer.server.findFile("[doc]");
            self.sparkShellService.push(file.ast);
        };

        /**
         * Called when the user clicks Add on the function bar
         */
        this.onAddFunction = function() {
            self.addFunction(self.currentFormula);
        };

        //reference to the last command that was undone
        var lastUndo = '';

        this.onUndo = function() {
            var tableData = self.functionCommandHolder.undo();
            updateGrid(tableData);
            lastUndo = self.functionHistory.pop();
        };
        this.onRedo = function() {
            var tableData = self.functionCommandHolder.redo();
            updateGrid(tableData);
            self.functionHistory.push(lastUndo);
        };

        this.canUndo = function() {
            if (self.functionCommandHolder) {
                return self.functionCommandHolder.canUndo();
            } else {
                return false;
            }
        };
        this.canRedo = function() {
            if (self.functionCommandHolder) {
                return self.functionCommandHolder.canRedo();
            } else {
                return false;
            }
        };

        //Hide the left side nav bar
        SideNavService.hideSideNav();

        this.query();

        $scope.$on('$destroy', function() {
            //clean up code here
        });
    };

    angular.module(MODULE_FEED_MGR).controller('VisualQueryTransformController', controller);
    angular.module(MODULE_FEED_MGR)
            .directive('thinkbigVisualQueryTransform', directive);
})();
<commit_msg>Display an error dialog if the formula is invalid.<commit_after>(function() {

    var directive = function() {
        return {
            restrict: "EA",
            bindToController: {
                stepIndex: '@'
            },
            require: ['thinkbigVisualQueryTransform', '^thinkbigStepper'],
            scope: {},
            controllerAs: 'vm',
            templateUrl: 'js/visual-query/visual-query-transform.html',
            controller: "VisualQueryTransformController",
            link: function($scope, element, attrs, controllers) {
                var thisController = controllers[0];
                var stepperController = controllers[1];
                //store a reference to the stepper if needed
                thisController.stepperController = stepperController;
            }

        };
    };

    var controller = function($scope, $log, $http, $mdDialog, $mdToast, RestUrlService, VisualQueryService, HiveService,
                              TableDataFunctions, SideNavService, SparkShellService, VisualQueryColumnDelegate, uiGridConstants) {
        var self = this;
        //The model passed in from the previous step
        this.model = VisualQueryService.model;
        //Flag to determine if we can move on to the next step
        this.isValid = true;
        //The SQL String from the previous step
        this.sql = this.model.visualQuerySql;
        //The sql model passed over from the previous step
        this.sqlModel = this.model.visualQueryModel;
        //The array of columns with their respective Table, schema and alias passed over from the previous step
        //{column:'name', alias:'alias',tableName:'table name',tableColumn:'alias_name',dataType:'dataType'}
        this.selectedColumnsAndTables = this.model.selectedColumnsAndTables;
        //The query result transformed to the ag-grid model  (@see HiveService.transformToAgGrid
        this.tableData = {columns: [], rows: []};
        //Function History
        this.functionHistory = [];

        //The current formula string
        this.currentFormula = '';

        //flag to indicate if the Hive data is available
        this.hiveDataLoaded = false;
        //flag to indicate codemirror is ready
        this.codemirroLoaded = false;
        //the codemirror editor
        this.codemirrorEditor = null;
        //the tern server reference
        this.ternServer = null;

        //Function Command Holder
        //@see TableDataFunctions.js
        this.functionCommandHolder = null;

        //Flag to show/hide function history panel
        this.isShowFunctionHistory = false;

        // Flag to show/hide sample menu
        this.isShowSampleMenu = false;

        //Setup initial grid options
        this.gridOptions = {
            columnDefs: [],
            data: null,
            enableColumnResizing: true,
            enableFiltering: true,
            flatEntityAccess: true,
            onRegisterApi: function(grid) {
                self.gridApi = grid;
            }
        };

        // Translates expressions into Spark code
        this.sparkShellService = new SparkShellService(this.sql);

        //Code Mirror options.  Tern Server requires it be in javascript mode
        this.codemirrorOptions = {
            lineWrapping: false,
            indentWithTabs: false,
            smartIndent: false,
            lineNumbers: false,
            matchBrackets: false,
            autofocus: true,
            mode: 'javascript',
            scrollbarStyle: null
        };

        /**
         * Show and hide the Funciton History
         */
        this.toggleFunctionHistory = function() {
            self.isShowFunctionHistory = !self.isShowFunctionHistory;
        };

        /**
         * Toggle the visibility of the sample menu.
         */
        this.toggleSampleMenu = function() {
            self.isShowSampleMenu = !self.isShowSampleMenu;
        };

        //Callback when Codemirror has been loaded (reference is in the html page at:
        // ui-codemirror="{ onLoad : vm.codemirrorLoaded }"
        this.codemirrorLoaded = function(_editor) {
            //assign the editor to a variable on this object for future reference
            self.codemirrorEditor = _editor;
            //Set the width,height of the editor. Code mirror needs an explicit width/height
            _editor.setSize(700, 25);

            //disable users ability to add new lines.  The Formula bar is only 1 line
            _editor.on("beforeChange", function(instance, change) {
                var newtext = change.text.join("").replace(/\n/g, ""); // remove ALL \n !
                change.update(change.from, change.to, [newtext]);
                return true;
            });

            //hide the scrollbar
            _editor.on("change", function(instance, change) {
                //$(".CodeMirror-hscrollbar").css('display', 'none');
            });
            //set the flag to be loaded and then call out to update Autocomplete options
            self.codemirroLoaded = true;
            self.updateCodeMirrorAutoComplete();
        };

        /**
         * Creates a Tern server.
         */
        function createTernServer() {
            $http.get('js/vendor/tern/defs/tableFunctions.json').success(function(code) {
                self.sparkShellService.setFunctionDefs(code);

                self.ternServer = new CodeMirror.TernServer({defs: [code]});
                self.ternServer.server.addDefs(self.sparkShellService.getColumnDefs());

                var _editor = self.codemirrorEditor;
                _editor.setOption("extraKeys", {
                    "Ctrl-Space": function(cm) {
                        self.ternServer.complete(cm);
                    },
                    "Ctrl-I": function(cm) {
                        self.ternServer.showType(cm);
                    },
                    "Ctrl-O": function(cm) {
                        self.ternServer.showDocs(cm);
                    },
                    "Alt-.": function(cm) {
                        self.ternServer.jumpToDef(cm);
                    },
                    "Alt-,": function(cm) {
                        self.ternServer.jumpBack(cm);
                    },
                    "Ctrl-Q": function(cm) {
                        self.ternServer.rename(cm);
                    },
                    "Ctrl-.": function(cm) {
                        self.ternServer.selectName(cm);
                    }
                });
                _editor.on("blur", function() {
                    self.ternServer.hideDoc();
                });
                _editor.on("cursorActivity", self.showHint);
                _editor.on("focus", self.showHint);
            });
        }

        /**
         * Setup the CodeMirror and Tern Server autocomplete. This will only execute when both Hive and Code Mirror are fully
         * initialized.
         */
        this.updateCodeMirrorAutoComplete = function() {
            if (self.codemirroLoaded && self.hiveDataLoaded) {
                if (self.ternServer === null) {
                    createTernServer();
                } else {
                    var defs = self.sparkShellService.getColumnDefs();
                    self.ternServer.server.deleteDefs(defs["!name"]);
                    self.ternServer.server.addDefs(defs);
                }
            }
        };

        /**
         * Makes an asynchronous request to get the list of completions available at the cursor.
         *
         * @param {CodeMirror|CodeMirror.Doc} cm the code mirror instance
         * @param {Function} callback the callback function
         */
        this.getHint = function(cm, callback) {
            self.ternServer.getHint(cm, function(data) {
                // Complete function calls so arg hints can be displayed
                CodeMirror.on(data, "pick", function(completion) {
                    if (completion.data.type.substr(0, 3) === "fn(") {
                        var cursor = cm.getCursor();
                        cm.replaceRange("(", cursor, cursor, "complete");
                    }
                });

                // Display hints
                callback(data);
            });
        };
        this.getHint.async = true;

        /**
         * Shows either argument hints or identifier hints depending on the context.
         *
         * @param {CodeMirror|CodeMirror.Doc} cm the code mirror instance
         */
        this.showHint = function(cm) {
            // Show args if in a function
            var cursor = cm.getCursor();
            var token = cm.getTokenAt(cursor);
            var lexer = token.state.lexical;

            if (lexer.info === "call" && token.type !== "variable") {
                self.ternServer.updateArgHints(cm);
            } else {
                self.ternServer.hideDoc();
            }

            // Show completions if available
            if (cursor.ch === 0 || token.type === "variable" || (token.string === "." && lexer.type === "stat")) {
                cm.showHint({
                    completeSingle: false,
                    hint: self.getHint
                });
            }
        };

        /**
         * Query Hive using the query from the previous step. Set the Grids rows and columns
         */
        this.query = function() {
            //flag to indicate query is running
            this.executingQuery = true;

            return self.sparkShellService.transform().then(function(response) {
                //mark the query as finished
                self.executingQuery = false;

                // Clear previous filters
                if (typeof(self.gridApi) !== "undefined") {
                    self.gridApi.core.clearAllFilters();
                }

                //transform the result to the agGrid model
                var result = HiveService.transformQueryResultsToUiGridModel({data: response.data.results});

                angular.forEach(result.columns, function(column) {
                    column.headerCellTemplate = "visual-query/grid-header-cell";
                    column.delegate = new VisualQueryColumnDelegate(self);
                    column.filters = column.delegate.filters;
                });

                //store the result for use in the commands
                self.tableData = result;
                //update the ag-grid
                self.gridOptions.columnDefs = result.columns;
                self.gridOptions.data = result.rows;
                //mark the flag to indicate Hive is loaded
                self.hiveDataLoaded = true;
                self.updateCodeMirrorAutoComplete();

                //Initialize the Command function holder
                self.functionCommandHolder = TableDataFunctions.newCommandHolder({rows: result.rows, columns: result.columns});
            });
        };

        function updateGrid(tableData) {
            self.gridOptions.columnDefs = tableData.columns;
            self.gridOptions.data = tableData.rows;
        }

        /**
         * Adds formulas for column filters.
         */
        this.addFilters = function() {
            angular.forEach(self.gridApi.grid.columns, function(column) {
                angular.forEach(column.filters, function(filter) {
                    if (filter.term) {
                        if (filter.condition == uiGridConstants.filter.LESS_THAN) {
                            self.pushFormula("filter(lessThan(" + column.field + ", " + StringUtils.quote(filter.term) + "))");
                        } else if (filter.condition == uiGridConstants.filter.GREATER_THAN) {
                            self.pushFormula("filter(greaterThan(" + column.field + ", " + StringUtils.quote(filter.term) + "))");
                        } else if (filter.condition == uiGridConstants.filter.EXACT) {
                            self.pushFormula("filter(equal(" + column.field + ", " + StringUtils.quote(filter.term) + "))");
                        }
                    }
                });
            });
        };

        /**
         * Adds the specified formula to the current script and refreshes the table data.
         *
         * @param {string} formula the formula
         */
        this.addFunction = function(formula) {
            var tableData = self.functionCommandHolder.executeStr(formula);
            if (tableData != null && tableData != undefined) {
                updateGrid(tableData);

                self.addFilters();
                self.pushFormula(formula);
                self.query();
            }
        };

        /**
         * Appends the specified formula to the current script.
         *
         * @param {string} formula the formula
         */
        this.pushFormula = function(formula) {
            // Covert to a syntax tree
            self.ternServer.server.addFile("[doc]", formula);
            var file = self.ternServer.server.findFile("[doc]");

            // Add to the Spark script
            try {
                self.sparkShellService.push(file.ast);
            } catch (e) {
                var alert = $mdDialog.alert()
                        .parent($('body'))
                        .clickOutsideToClose(true)
                        .title("Error executing the query")
                        .textContent(e.message)
                        .ariaLabel("error executing the query")
                        .ok("Got it!");
                $mdDialog.show(alert);
                return;
            }

            // Add to function history
            self.functionHistory.push(formula);
        };

        /**
         * Called when the user clicks Add on the function bar
         */
        this.onAddFunction = function() {
            self.addFunction(self.currentFormula);
        };

        //reference to the last command that was undone
        var lastUndo = '';

        this.onUndo = function() {
            var tableData = self.functionCommandHolder.undo();
            updateGrid(tableData);
            lastUndo = self.functionHistory.pop();
        };
        this.onRedo = function() {
            var tableData = self.functionCommandHolder.redo();
            updateGrid(tableData);
            self.functionHistory.push(lastUndo);
        };

        this.canUndo = function() {
            if (self.functionCommandHolder) {
                return self.functionCommandHolder.canUndo();
            } else {
                return false;
            }
        };
        this.canRedo = function() {
            if (self.functionCommandHolder) {
                return self.functionCommandHolder.canRedo();
            } else {
                return false;
            }
        };

        //Hide the left side nav bar
        SideNavService.hideSideNav();

        this.query();

        $scope.$on('$destroy', function() {
            //clean up code here
        });
    };

    angular.module(MODULE_FEED_MGR).controller('VisualQueryTransformController', controller);
    angular.module(MODULE_FEED_MGR)
            .directive('thinkbigVisualQueryTransform', directive);
})();
<|endoftext|>


<commit_before>YUI.add("juju-models", function(Y) {

var models = Y.namespace("juju.models");

var Charm = Y.Base.create('charm', Y.Model, [], {
    idAttribute: 'charm_id',
    ATTRS: {
	charm_id: {},
	name: {},
	url: {},
	description: {},
	config: {},
	metadata: {},
	sha256: {}
    }
});

models.Charm = Charm;

var CharmList = Y.Base.create('charmList', Y.ModelList, [], {
    model: Charm,
    ATTRS: {
    }
});
models.CharmList = CharmList;

Service = Y.Base.create('service', Y.Model, [], {
    idAttribute: 'name',
    ATTRS: {
	name: {},
	charm: {},
	config: {},
	constraints: {},
	exposed: {},
	relations: {}
    }
});
models.Service = Service;

ServiceList = Y.Base.create('serviceList', Y.ModelList, [], {
    model: Service,
    ATTRS: {
    }
});
models.ServiceList = ServiceList;

ServiceUnit = Y.Base.create('serviceUnit', Y.Model, [], {
    idAttribute: 'name',
    ATTRS: {
	name: {},
	service: {},
	machine: {},
	agent_state: {},
	// relations to unit relation state.
	relations: {},
	is_subordinate: {
            value: false // default
        },
	open_ports: {},
	public_address: {},
	private_address: {}
    }
});
models.ServiceUnit = ServiceUnit;

ServiceUnitList = Y.Base.create('serviceUnitList', Y.ModelList, [], {
    model: ServiceUnit,
    get_units_for_service: function(service, asList) {
        var options = {};
        if (asList != undefined) {
            options.asList = true;
        }
        var units = this.filter(options, function(m) {
            return m.get("service").get("id") === service.get("id");
        });
        return units;
    },
    ATTRS: {
    }
});
models.ServiceUnitList = ServiceUnitList;

Machine = Y.Base.create('machine', Y.Model, [], {
    idAttribute: 'machine_id',
    ATTRS: {
	machine_id: {},
	public_address: {},
	private_address: {}
    }
});
models.Machine = Machine;

MachineList = Y.Base.create('machineList', Y.ModelList, [], {
    model: Machine,
    ATTRS: {
    }
});

models.MachineList = MachineList;

Relation = Y.Base.create('relation', Y.Model, [], {
    idAttribute: 'relation_id',
    ATTRS: {
	relation_id: {},
	type: {},
	endpoints: {}
    }
});
models.Relation = Relation;

RelationList = Y.Base.create('relationList', Y.ModelList, [], {
    ATTRS: {
    }
});
models.RelationList = RelationList;

}, "0.1.0", {
    requires: [
        "model",
        "model-list"
    ]
});<commit_msg>stub for info state on unit lists<commit_after>YUI.add("juju-models", function(Y) {

var models = Y.namespace("juju.models");

var Charm = Y.Base.create('charm', Y.Model, [], {
    idAttribute: 'charm_id',
    ATTRS: {
	charm_id: {},
	name: {},
	url: {},
	description: {},
	config: {},
	metadata: {},
	sha256: {}
    }
});

models.Charm = Charm;

var CharmList = Y.Base.create('charmList', Y.ModelList, [], {
    model: Charm,
    ATTRS: {
    }
});
models.CharmList = CharmList;

Service = Y.Base.create('service', Y.Model, [], {
    idAttribute: 'name',
    ATTRS: {
	name: {},
	charm: {},
	config: {},
	constraints: {},
	exposed: {},
	relations: {}
    }
});
models.Service = Service;

ServiceList = Y.Base.create('serviceList', Y.ModelList, [], {
    model: Service,
    ATTRS: {
    }
});
models.ServiceList = ServiceList;

ServiceUnit = Y.Base.create('serviceUnit', Y.Model, [], {
    idAttribute: 'name',
    ATTRS: {
	name: {},
	service: {},
	machine: {},
	agent_state: {},
	// relations to unit relation state.
	relations: {},
	is_subordinate: {
            value: false // default
        },
	open_ports: {},
	public_address: {},
	private_address: {}
    }
});
models.ServiceUnit = ServiceUnit;

ServiceUnitList = Y.Base.create('serviceUnitList', Y.ModelList, [], {
    model: ServiceUnit,
    get_units_for_service: function(service, asList) {
        var options = {};
        if (asList != undefined) {
            options.asList = true;
        }
        var units = this.filter(options, function(m) {
            return m.get("service").get("id") === service.get("id");
        });
        return units;
    },
    /*
     *  Return information about the state of all units focused on the
     * 'worst' status information available. In this way if any unit is in
     *  an error state we can report that for the whole list.
     */
    get_informative_state: function() {

    }
    ATTRS: {
    }
});
models.ServiceUnitList = ServiceUnitList;

Machine = Y.Base.create('machine', Y.Model, [], {
    idAttribute: 'machine_id',
    ATTRS: {
	machine_id: {},
	public_address: {},
	private_address: {}
    }
});
models.Machine = Machine;

MachineList = Y.Base.create('machineList', Y.ModelList, [], {
    model: Machine,
    ATTRS: {
    }
});

models.MachineList = MachineList;

Relation = Y.Base.create('relation', Y.Model, [], {
    idAttribute: 'relation_id',
    ATTRS: {
	relation_id: {},
	type: {},
	endpoints: {}
    }
});
models.Relation = Relation;

RelationList = Y.Base.create('relationList', Y.ModelList, [], {
    ATTRS: {
    }
});
models.RelationList = RelationList;

}, "0.1.0", {
    requires: [
        "model",
        "model-list"
    ]
});<|endoftext|>


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

    angular.module('brewApp.services')
        .factory('Recipe', ['$q', 'User', 'Store', recipe]);

    function recipe($q, User, Store) {
        var _recipes;

        function save(recipe) {
            recipe.userId = recipe.UserId || User.id;

            return Store.store(recipe).then(function(id) {
                getRecipes(true);

                return id;
            });
        }

        function getRecipes(reload) {
            var deferred = $q.defer();

            if (User.context.recipes && reload === false) {
                _recipes = User.context.recipes;

                deferred.resolve(User.context.recipes);
            }
            else
                User.context.getRecipes().then(function(recipes) {
                    _recipes = recipes;

                    deferred.resolve(recipes);
                });

            return deferred.promise;
        }

        return {
            recipes: _recipes,
            save: save,
            getRecipes: getRecipes
        };
    };
})();
<commit_msg>Fixed bugs in recipe service.<commit_after>(function() {
    'use strict';

    angular.module('brewApp.services')
        .factory('Recipe', ['$q', 'User', 'Store', recipe]);

    function recipe($q, User, Store) {
        var _recipes = null;

        function save(recipe) {
            recipe.userId = recipe.userId || User.id;

            return Store.store(recipe).then(function(id) {
                getRecipes(true);

                return id;
            });
        }

        function getRecipes(reload) {
            var deferred = $q.defer();

            if (User.context.recipes && reload === false) {
                _recipes = User.context.recipes;

                deferred.resolve(User.context.recipes);
            }
            else
                User.context.getRecipes().then(function(recipes) {
                    _recipes = recipes;

                    deferred.resolve(recipes);
                });

            return deferred.promise;
        }

        return {
            recipes: _recipes,
            save: save,
            getRecipes: getRecipes
        };
    }
})();
<|endoftext|>


<commit_before>/**
 * Functions to create and operate on CPUs.
 *
 * @module Engine/CPU
 */

/**
 * A CPU in a virgin state.
 *
 * @typedef  {Object}  CPU
 * @property {String}  phase
 * @property {String}  next
 * @property {Boolean} rst
 * @property {Boolean} read
 * @property {Boolean} write
 * @property {Number}  a
 * @property {Number}  dr
 * @property {Number}  ir
 * @property {Number}  ar
 * @property {Number}  pc
 */

/**
 * Create a CPU in a virgin state.
 *
 * @method create
 * @returns {CPU}
 */
export function create() {
	return {
		phase: 'reset',
		next: 'fetch1',
		rst: false,
		read: false,
		write: false,
		a: 0,
		dr: 0,
		ir: 0,
		ar: 0,
		pc: 0,
	};
}

/**
 * Executes one CPU cycle, returning the new state.
 *
 * @param   {CPU} state
 * @returns {CPU}
 */
export function cycle(state) {
	var receiver;
	const phase = state.next;
	switch (true) {
		case state.rst:       receiver = create; break;
		case phase in phases: receiver = phases[phase]; break;
		default:              return { ...state };
	}
	return { ...state, phase, ...receiver(state) };
}

/**
 * Handlers for every phase the CPU can transition to.
 *
 * @type {Object}
 */
export const phases = {
	fetch1,
	fetch2,
};

/**
 * First step of the instruction fetch phase. Asks for a memory read
 * at the program counter address on the address register, and
 * transitions to next fetch step.
 *
 * @method  fetch1
 * @param   {CPU} state
 * @returns {CPU}
 */
export function fetch1(state) {
	return {
		ar: state.pc,
		read: true,
		next: 'fetch2',
	};
}

/**
 * Second step of the instruction fetch phase. Reads the data from
 * memory into the instruction and address registers, then
 * increments the program counter.
 *
 * @param   {CPU} state
 * @returns {CPU}
 */
export function fetch2(state) {
	const ir = (state.dr & 0b11100000) >> 5;
	const ar = (state.dr & 0b00011111) >> 0;
	return {
		ir, ar,
		read: false,
		next: 'fetch1',
		pc: state.pc + 1,
	};
}

/**
 * Returns an overview of the state of a CPU as text.
 *
 * @param   {CPU} state
 * @returns {String}
 */
export function toString(state) {
	const rst = state.rst? 'yes' : 'no';
	const read = state.read? 'yes' : 'no';
	const write = state.write? 'yes' : 'no';
	const {phase, next, a, dr, ir, ar, pc} = state;
	return `CPU ${phase}->${next} RST:${rst} READ:${read} WRITE:${write} `
	     + `A:${a} AR:${ar} DR:${dr} IR:${ir} PC:${pc}`;
}
<commit_msg>Implemented a very simple ISA for testing.<commit_after>/**
 * Functions to create and operate on CPUs.
 *
 * @module Engine/CPU
 */

/**
 * A CPU in a virgin state.
 *
 * @typedef  {Object}  CPU
 * @property {String}  phase
 * @property {String}  next
 * @property {Boolean} rst
 * @property {Boolean} read
 * @property {Boolean} write
 * @property {Number}  a
 * @property {Number}  dr
 * @property {Number}  ir
 * @property {Number}  ar
 * @property {Number}  pc
 */

/**
 * Create a CPU in a virgin state.
 *
 * @method create
 * @returns {CPU}
 */
export function create() {
	return {
		phase: 'reset',
		next: 'fetch1',
		rst: false,
		read: false,
		write: false,
		a: 0,
		dr: 0,
		ir: 0,
		ar: 0,
		pc: 0,
	};
}

/**
 * Executes one CPU cycle, returning the new state.
 *
 * @param   {CPU} state
 * @returns {CPU}
 */
export function cycle(state) {
	var receiver;
	const phase = state.next;
	switch (true) {
		case state.rst:       receiver = create; break;
		case phase in phases: receiver = phases[phase]; break;
		default:              return { ...state };
	}
	return { ...state, phase, ...receiver(state) };
}

/**
 * Handlers for every phase the CPU can transition to.
 *
 * @type {Object}
 */
export const phases = {
	fetch1,
	fetch2,
	add1,
	add2,
	and1,
	and2,
	jmp1,
	inc1,
};

/**
 * A map between the opcodes supported by this CPU and the phase
 * transition that handles their execution.
 *
 * @type {Object}
 */
export const opcodes = {
	0b000: 'add1', /* ADD X - Adds X to A       */
	0b001: 'and1', /* AND X - ANDs X and A      */
	0b010: 'jmp1', /* JMP X - Jumps to X        */
	0b011: 'inc1', /* INC   - Increments A by 1 */
};

/**
 * First step of the instruction fetch phase. Asks for a memory read
 * at the program counter address on the address register.
 *
 * @method  fetch1
 * @param   {CPU} state
 * @returns {CPU}
 */
export function fetch1(state) {
	return {
		ar: state.pc,
		read: true,
		next: 'fetch2',
	};
}

/**
 * Second step of the instruction fetch phase. Reads the data from
 * memory into the instruction and address registers, then increments
 * the program counter. Will transition to the opcode handler, or
 * restart the fetch cycle if the opcode is invalid.
 *
 * @param   {CPU} state
 * @returns {CPU}
 */
export function fetch2(state) {
	const ir = (state.dr & 0b11100000) >> 5;
	const ar = (state.dr & 0b00011111) >> 0;
	const next = opcodes[ir] || 'fetch1';
	return {
		next, ir, ar,
		read: false,
		pc: state.pc + 1,
	};
}

/**
 * First step of the addition operation. Asks for a memory read at the
 * address register, and transitions to next add step.
 *
 * @param   {CPU} state
 * @returns {CPU}
 */
function add1(state) {
	return {
		ar: state.ar,
		read: true,
		next: 'add2',
	};
}

/**
 * Second step of the addition operation. Reads the data from memory
 * and adds it to the accumulator.
 *
 * @param   {CPU} state
 * @returns {CPU}
 */
function add2(state) {
	return {
		a: (state.a + state.dr) % 255,
		read: false,
		next: 'fetch1',
	};
}

/**
 * First step of the bitwise AND operation. Asks for a memory read at the
 * address register.
 *
 * @param   {CPU} state
 * @returns {CPU}
 */
function and1(state) {
	return {
		read: true,
		next: 'and2',
	};
}

/**
 * Second step of the bitwise AND operation. Reads the data from memory
 * and bitwise ANDs it to the accumulator.
 *
 * @param   {CPU} state
 * @returns {CPU}
 */
function and2(state) {
	return {
		a: (state.a & state.dr) % 255,
		read: false,
		next: 'fetch1',
	};
}

/**
 * Points the program counter to the address in the address register.
 *
 * @param   {CPU} state
 * @returns {CPU}
 */
function jmp1(state) {
	return {
		pc: state.dr & 0b00011111,
		next: 'fetch1',
	};
}

/**
 * Increments the accumulator by 1.
 *
 * @param   {CPU} state
 * @returns {CPU}
 */
function inc1(state) {
	return {
		a: state.a + 1,
		next: 'fetch1',
	};
}

/**
 * Returns an overview of the state of a CPU as text.
 *
 * @param   {CPU} state
 * @returns {String}
 */
export function toString(state) {
	const rst = state.rst? 'yes' : 'no';
	const read = state.read? 'yes' : 'no';
	const write = state.write? 'yes' : 'no';
	const {phase, next, a, dr, ir, ar, pc} = state;
	return `CPU ${phase}->${next} RST:${rst} READ:${read} WRITE:${write} `
	     + `A:${a} AR:${ar} DR:${dr} IR:${ir} PC:${pc}`;
}
<|endoftext|>