<commit_before>angular.module('electionsApp')
    .controller('formController', function ($rootScope, $state, dataFactory, $scope, $modal, localStorageService) {
        var vm = $scope;

        // To store formData
        vm.formData = {
            'batch': '',
            'senatorFirst': '',
            'senatorSecond': '',
            'senatorThird': ''
        };

        // For the breadcrumb navigation
        vm.totalStates = 7;
        vm.range = function(n) {
            return new Array(n);
        };

        // Obtain the list of batches from the dataFactory
        vm.batches = dataFactory.batches;

        // Make sure the correct stateName and stateCode are displayed everytime
        vm.stateName = $state.current.stateName;
        vm.stateCode = $state.current.stateCode;
        $rootScope.$on('$stateChangeSuccess', function(events, toState) {
            vm.stateName = toState.stateName;
            vm.stateCode = toState.stateCode;
        });

        // For the cancelVote Modal
        vm.open = function () {
            var modalInstance = $modal.open({
                templateUrl: 'partials/closeModal.html',
                controller: 'closeModalController'
            });

            modalInstance.result.then(function (status) {
                if (status === true) {
                    // Clean Up state before loggin out
                    localStorageService.clearAll();
                    $state.go('login');
                }
            });
        };
    });

angular.module('electionsApp')
    .controller('closeModalController', function ($scope, $modalInstance, dataFactory) {
        var vm = $scope;

        // To store the contents
        vm.selected = {};

        vm.ok = function () {
            if (vm.selected.cancelPassword === dataFactory.settings.cancelPassword) {
                $modalInstance.close(true);
            } else {
                $modalInstance.close(false);
            }
        };

        vm.cancel = function () {
            $modalInstance.dismiss('cancel');
        };
    });
<commit_msg>formData variables<commit_after>angular.module('electionsApp')
    .controller('formController', function ($rootScope, $state, dataFactory, $scope, $modal, localStorageService) {
        var vm = $scope;

        // To store formData
        vm.formData = {
            'batch': '',
            'senatorFirst': '',
            'senatorSecond': '',
            'senatorThird': '',
            'presidentFirst': '',
            'presidentSecond': '',
            'presidentThird': '',
            'presidentNoPreference': false,
            'culturalFirst': '',
            'culturalSecond': '',
            'culturalThird': '',
            'cultNoPreference': false,
            'sportsFirst': '',
            'sportsSecond': '',
            'sportsThird': '',
            'sportsNoPreference': false,
            'gamesFirst': '',
            'gamesSecond': '',
            'gamesThird': '',
            'gamesNoPreference': false,
            'scienceFirst': '',
            'scienceSecond': '',
            'scienceThird': '',
            'scienceNoPreference': false,
            'filmsFirst': '',
            'filmsSecond': '',
            'filmsThird': '',
            'filmsNoPreference':false
        };

        // For the breadcrumb navigation
        vm.totalStates = 7;
        vm.range = function(n) {
            return new Array(n);
        };

        // Obtain the list of batches from the dataFactory
        vm.batches = dataFactory.batches;

        // Make sure the correct stateName and stateCode are displayed everytime
        vm.stateName = $state.current.stateName;
        vm.stateCode = $state.current.stateCode;
        $rootScope.$on('$stateChangeSuccess', function(events, toState) {
            vm.stateName = toState.stateName;
            vm.stateCode = toState.stateCode;
        });

        // For the cancelVote Modal
        vm.open = function () {
            var modalInstance = $modal.open({
                templateUrl: 'partials/closeModal.html',
                controller: 'closeModalController'
            });

            modalInstance.result.then(function (status) {
                if (status === true) {
                    // Clean Up state before loggin out
                    localStorageService.clearAll();
                    $state.go('login');
                }
            });
        };
    });

angular.module('electionsApp')
    .controller('closeModalController', function ($scope, $modalInstance, dataFactory) {
        var vm = $scope;

        // To store the contents
        vm.selected = {};

        vm.ok = function () {
            if (vm.selected.cancelPassword === dataFactory.settings.cancelPassword) {
                $modalInstance.close(true);
            } else {
                $modalInstance.close(false);
            }
        };

        vm.cancel = function () {
            $modalInstance.dismiss('cancel');
        };
    });
<|endoftext|>


<commit_before>var gameModal = gameModal || {};

gameModal = function (game) {

    var _this = this;

    game.modals = {};

    /**
     * [hideModal description]
     * @param  {[type]} type [description]
     * @return {[type]}      [description]
     */
    this.hideModal = function (type) {
        window.console.log(type);
        game.modals[type].visible = false;
    };

    return {

        createModal: function (options) {

            var type = options.type || ''; // must be unique
            var includeBackground = options.includeBackground; // maybe not optional
            var backgroundColor = options.backgroundColor || "0x000000";
            var backgroundOpacity = options.backgroundOpacity === undefined ? 0.7 : options.backgroundOpacity;
            var modalCloseOnInput = options.modalCloseOnInput || false;
            var modalBackgroundCallback = options.modalBackgroundCallback || false;
            var vCenter = options.vCenter || true;
            var hCenter = options.hCenter || true;
            var itemsArr = options.itemsArr || [];
            var fixedToCamera = options.fixedToCamera || false;

            var modal;
            var modalGroup = game.add.group();
            if (fixedToCamera === true) {
                modalGroup.fixedToCamera = true;
                modalGroup.cameraOffset.x = 0;
                modalGroup.cameraOffset.y = 0;
            }

            if (includeBackground === true) {
                modal = game.add.graphics(game.width, game.height);
                modal.beginFill(backgroundColor, backgroundOpacity);
                modal.x = 0;
                modal.y = 0;

                modal.drawRect(0, 0, game.width, game.height);

                if (modalCloseOnInput === true) {

                    var innerModal = game.add.sprite(0, 0);
                    innerModal.inputEnabled = true;
                    innerModal.width = game.width;
                    innerModal.height = game.height;
                    innerModal.type = type;
                    innerModal.input.priorityID = 0;
                    innerModal.events.onInputDown.add(function (e, pointer) {
                        this.hideModal(e.type);
                    }, _this, 2);

                    modalGroup.add(innerModal);
                } else {

                    modalBackgroundCallback = true;
                }
            }

            if (modalBackgroundCallback) {
                var innerModal = game.add.sprite(0, 0);
                innerModal.inputEnabled = true;
                innerModal.width = game.width;
                innerModal.height = game.height;
                innerModal.type = type;
                innerModal.input.priorityID = 0;

                modalGroup.add(innerModal);
            }

            if (includeBackground) {
                modalGroup.add(modal);
            }

            var modalLabel;
            for (var i = 0; i < itemsArr.length; i += 1) {
                var item = itemsArr[i];
                var itemType = item.type || 'text';
                var itemColor = item.color || 0x000000;
                var itemFontfamily = item.fontFamily || 'Arial';
                var itemFontSize = item.fontSize || 32;
                var itemStroke = item.stroke || '0x000000';
                var itemStrokeThickness = item.strokeThickness || 0;
                var itemAlign = item.align || 'center';
                var offsetX = item.offsetX || 0;
                var offsetY = item.offsetY || 0;
                var contentScale = item.contentScale || 1;
                var content = item.content || "";
                var centerX = game.width / 2;
                var centerY = game.height / 2;
                var callback = item.callback || false;
                var textAlign = item.textAlign || "left";
                var atlasParent = item.atlasParent || "";
                var buttonHover = item.buttonHover || content;
                var buttonActive = item.buttonActive || content;
                var graphicColor = item.graphicColor || 0xffffff;
                var graphicOpacity = item.graphicOpacity || 1;
                var graphicW = item.graphicWidth || 200;
                var graphicH = item.graphicHeight || 200;
                var graphicRadius = item.graphicRadius || 0;
                var lockPosition = item.lockPosition || false;

                modalLabel = null;

                if (itemType === "text" || itemType === "bitmapText") {

                    if (itemType === "text") {
                        modalLabel = game.add.text(0, 0, content, {
                            font: itemFontSize + 'px ' + itemFontfamily,
                            fill: "#" + String(itemColor).replace("0x", ""),
                            stroke: "#" + String(itemStroke).replace("0x", ""),
                            strokeThickness: itemStrokeThickness,
                            align: itemAlign
                        });
                        modalLabel.contentType = 'text';
                        modalLabel.update();
                        modalLabel.x = ((game.width / 2) - (modalLabel.width / 2)) + offsetX;
                        modalLabel.y = ((game.height / 2) - (modalLabel.height / 2)) + offsetY;
                    } else {
                        modalLabel = game.add.bitmapText(0, 0, itemFontfamily, String(content), itemFontSize);
                        modalLabel.contentType = 'bitmapText';
                        modalLabel.align = textAlign;
                        modalLabel.updateText();
                        modalLabel.x = (centerX - (modalLabel.width / 2)) + offsetX;
                        modalLabel.y = (centerY - (modalLabel.height / 2)) + offsetY;
                    }

                } else if (itemType === "image") {
                    modalLabel = game.add.image(0, 0, content);
                    modalLabel.scale.setTo(contentScale, contentScale);
                    modalLabel.contentType = 'image';
                    modalLabel.x = (centerX - ((modalLabel.width) / 2)) + offsetX;
                    modalLabel.y = (centerY - ((modalLabel.height) / 2)) + offsetY;

                } else if (itemType === "sprite") {
                    modalLabel = game.add.sprite(0, 0, atlasParent, content);
                    modalLabel.scale.setTo(contentScale, contentScale);
                    modalLabel.contentType = 'sprite';
                    modalLabel.x = (centerX - ((modalLabel.width) / 2)) + offsetX;
                    modalLabel.y = (centerY - ((modalLabel.height) / 2)) + offsetY;

                } else if (itemType === "button") {
                    modalLabel = game.add.button(0, 0, atlasParent, callback, this, buttonHover, content, buttonActive, content);
                    modalLabel.scale.setTo(contentScale, contentScale);
                    modalLabel.contentType = 'button';
                    modalLabel.x = (centerX - ((modalLabel.width) / 2)) + offsetX;
                    modalLabel.y = (centerY - ((modalLabel.height) / 2)) + offsetY;

                } else if (itemType === "graphics") {
                    modalLabel = game.add.graphics(graphicW, graphicH);
                    modalLabel.beginFill(graphicColor, graphicOpacity);
                    if (graphicRadius <= 0) {
                        modalLabel.drawRect(0, 0, graphicW, graphicH);
                    } else {
                        modalLabel.drawRoundedRect(0, 0, graphicW, graphicH, graphicRadius);
                    }
                    modalLabel.endFill();
                    modalLabel.x = (centerX - ((modalLabel.width) / 2)) + offsetX;
                    modalLabel.y = (centerY - ((modalLabel.height) / 2)) + offsetY;
                }

                modalLabel["_offsetX"] = 0;
                modalLabel["_offsetY"] = 0;
                modalLabel["lockPosition"] = lockPosition;
                modalLabel._offsetX = offsetX;
                modalLabel._offsetY = offsetY;

                if (callback !== false && itemType !== "button") {
                    modalLabel.inputEnabled = true;
                    modalLabel.pixelPerfectClick = true;
                    modalLabel.priorityID = 10;
                    modalLabel.events.onInputDown.add(callback, modalLabel);
                }

                if (itemType !== "bitmapText" && itemType !== "graphics") {
                    modalLabel.bringToTop();
                    modalGroup.add(modalLabel);
                    modalLabel.bringToTop();
                    modalGroup.bringToTop(modalLabel);
                } else {
                    modalGroup.add(modalLabel);
                    modalGroup.bringToTop(modalLabel);
                }
            }

            modalGroup.visible = false;
            game.modals[type] = modalGroup;

        },
        updateModalValue: function (value, type, index, id) {
            var item;
            if (index !== undefined && index !== null) {
                item = game.modals[type].getChildAt(index);
            } else if (id !== undefined && id !== null) {

            }

            if (item.contentType === "text") {
                item.text = value;
                item.update();
                if (item.lockPosition === true) {

                } else {
                    item.x = ((game.width / 2) - (item.width / 2)) + item._offsetX;
                    item.y = ((game.height / 2) - (item.height / 2)) + item._offsetY;
                }
            } else if (item.contentType === "bitmapText") {
                item.text = value;
                item.updateText();
                if (item.lockPosition === true) {

                } else {
                    item.x = ((game.width / 2) - (item.width / 2)) + item._offsetX;
                    item.y = ((game.height / 2) - (item.height / 2)) + item._offsetY;
                }
            } else if (item.contentType === "image") {
                item.loadTexture(value);
            }

        },
        getModalItem: function (type, index) {
            return game.modals[type].getChildAt(index);
        },
        showModal: function (type) {
            game.world.bringToTop(game.modals[type]);
            game.modals[type].visible = true;
            // you can add animation here
        },
        hideModal: function (type) {
            game.modals[type].visible = false;
            // you can add animation here
        },
        destroyModal: function (type) {
            game.modals[type].destroy();
            delete game.modals[type];
        }
    };
};<commit_msg>Support tileSprite<commit_after>var gameModal = gameModal || {};

gameModal = function (game) {

    var _this = this;

    game.modals = {};

    /**
     * [hideModal description]
     * @param  {[type]} type [description]
     * @return {[type]}      [description]
     */
    this.hideModal = function (type) {
        window.console.log(type);
        game.modals[type].visible = false;
    };

    return {

        createModal: function (options) {

            var type = options.type || ''; // must be unique
            var includeBackground = options.includeBackground; // maybe not optional
            var backgroundColor = options.backgroundColor || "0x000000";
            var backgroundOpacity = options.backgroundOpacity === undefined ? 0.7 : options.backgroundOpacity;
            var modalCloseOnInput = options.modalCloseOnInput || false;
            var modalBackgroundCallback = options.modalBackgroundCallback || false;
            var vCenter = options.vCenter || true;
            var hCenter = options.hCenter || true;
            var itemsArr = options.itemsArr || [];
            var fixedToCamera = options.fixedToCamera || false;

            var modal;
            var modalGroup = game.add.group();
            if (fixedToCamera === true) {
                modalGroup.fixedToCamera = true;
                modalGroup.cameraOffset.x = 0;
                modalGroup.cameraOffset.y = 0;
            }

            if (includeBackground === true) {
                modal = game.add.graphics(game.width, game.height);
                modal.beginFill(backgroundColor, backgroundOpacity);
                modal.x = 0;
                modal.y = 0;

                modal.drawRect(0, 0, game.width, game.height);

                if (modalCloseOnInput === true) {

                    var innerModal = game.add.sprite(0, 0);
                    innerModal.inputEnabled = true;
                    innerModal.width = game.width;
                    innerModal.height = game.height;
                    innerModal.type = type;
                    innerModal.input.priorityID = 0;
                    innerModal.events.onInputDown.add(function (e, pointer) {
                        this.hideModal(e.type);
                    }, _this, 2);

                    modalGroup.add(innerModal);
                } else {

                    modalBackgroundCallback = true;
                }
            }

            if (modalBackgroundCallback) {
                var innerModal = game.add.sprite(0, 0);
                innerModal.inputEnabled = true;
                innerModal.width = game.width;
                innerModal.height = game.height;
                innerModal.type = type;
                innerModal.input.priorityID = 0;

                modalGroup.add(innerModal);
            }

            if (includeBackground) {
                modalGroup.add(modal);
            }

            var modalLabel;
            for (var i = 0; i < itemsArr.length; i += 1) {
                var item = itemsArr[i];
                var itemType = item.type || 'text';
                var itemColor = item.color || 0x000000;
                var itemFontfamily = item.fontFamily || 'Arial';
                var itemFontSize = item.fontSize || 32;
                var itemStroke = item.stroke || '0x000000';
                var itemStrokeThickness = item.strokeThickness || 0;
                var itemAlign = item.align || 'center';
                var offsetX = item.offsetX || 0;
                var offsetY = item.offsetY || 0;
                var contentScale = item.contentScale || 1;
                var content = item.content || "";
                var centerX = game.width / 2;
                var centerY = game.height / 2;
                var callback = item.callback || false;
                var textAlign = item.textAlign || "left";
                var atlasParent = item.atlasParent || "";
                var buttonHover = item.buttonHover || content;
                var buttonActive = item.buttonActive || content;
                var graphicColor = item.graphicColor || 0xffffff;
                var graphicOpacity = item.graphicOpacity || 1;
                var graphicW = item.graphicWidth || 200;
                var graphicH = item.graphicHeight || 200;
                var graphicRadius = item.graphicRadius || 0;
                var lockPosition = item.lockPosition || false;

                var itemAnchor = item.anchor || {x:0,y:0};
                var itemAngle = item.angle || 0;
                var itemX = item.x || 0;
        				var itemY = item.y || 0;
                var imageFrame = item.frame || false;
        				var tileSpriteWidth = item.tileSpriteWidth || game.width;
        				var tileSpriteHeight = item.tileSpriteHeight || game.height;

                modalLabel = null;

                if (itemType === "text" || itemType === "bitmapText") {

                    if (itemType === "text") {
                        modalLabel = game.add.text(0, 0, content, {
                            font: itemFontSize + 'px ' + itemFontfamily,
                            fill: "#" + String(itemColor).replace("0x", ""),
                            stroke: "#" + String(itemStroke).replace("0x", ""),
                            strokeThickness: itemStrokeThickness,
                            align: itemAlign
                        });
                        modalLabel.contentType = 'text';
                        modalLabel.update();
                        modalLabel.x = ((game.width / 2) - (modalLabel.width / 2)) + offsetX;
                        modalLabel.y = ((game.height / 2) - (modalLabel.height / 2)) + offsetY;
                    } else {
                        modalLabel = game.add.bitmapText(0, 0, itemFontfamily, String(content), itemFontSize);
                        modalLabel.contentType = 'bitmapText';
                        modalLabel.align = textAlign;
                        modalLabel.updateText();
                        modalLabel.x = (centerX - (modalLabel.width / 2)) + offsetX;
                        modalLabel.y = (centerY - (modalLabel.height / 2)) + offsetY;
                    }

                } else if (itemType === "image") {
                    modalLabel = game.add.image(0, 0, content);
                    modalLabel.scale.setTo(contentScale, contentScale);
                    modalLabel.contentType = 'image';
                    modalLabel.x = (centerX - ((modalLabel.width) / 2)) + offsetX;
                    modalLabel.y = (centerY - ((modalLabel.height) / 2)) + offsetY;
        				} else if (itemType === "tileSprite") {
          					modalLabel = game.add.tileSprite(itemX, itemY, tileSpriteWidth, tileSpriteHeight, content, imageFrame);
          					modalLabel.scale.setTo(contentScale, contentScale);
                    modalLabel.anchor.setTo(itemAnchor.x, itemAnchor.y);
                    modalLabel.angle = itemAngle;
          					modalLabel.contentType = 'tileSprite';
                } else if (itemType === "sprite") {
                    modalLabel = game.add.sprite(0, 0, atlasParent, content);
                    modalLabel.scale.setTo(contentScale, contentScale);
                    modalLabel.contentType = 'sprite';
                    modalLabel.x = (centerX - ((modalLabel.width) / 2)) + offsetX;
                    modalLabel.y = (centerY - ((modalLabel.height) / 2)) + offsetY;
                } else if (itemType === "button") {
                    modalLabel = game.add.button(0, 0, atlasParent, callback, this, buttonHover, content, buttonActive, content);
                    modalLabel.scale.setTo(contentScale, contentScale);
                    modalLabel.contentType = 'button';
                    modalLabel.x = (centerX - ((modalLabel.width) / 2)) + offsetX;
                    modalLabel.y = (centerY - ((modalLabel.height) / 2)) + offsetY;

                } else if (itemType === "graphics") {
                    modalLabel = game.add.graphics(graphicW, graphicH);
                    modalLabel.beginFill(graphicColor, graphicOpacity);
                    if (graphicRadius <= 0) {
                        modalLabel.drawRect(0, 0, graphicW, graphicH);
                    } else {
                        modalLabel.drawRoundedRect(0, 0, graphicW, graphicH, graphicRadius);
                    }
                    modalLabel.endFill();
                    modalLabel.x = (centerX - ((modalLabel.width) / 2)) + offsetX;
                    modalLabel.y = (centerY - ((modalLabel.height) / 2)) + offsetY;
                }

                modalLabel["_offsetX"] = 0;
                modalLabel["_offsetY"] = 0;
                modalLabel["lockPosition"] = lockPosition;
                modalLabel._offsetX = offsetX;
                modalLabel._offsetY = offsetY;

                if (callback !== false && itemType !== "button") {
                    modalLabel.inputEnabled = true;
                    modalLabel.pixelPerfectClick = true;
                    modalLabel.priorityID = 10;
                    modalLabel.events.onInputDown.add(callback, modalLabel);
                }

                if (itemType !== "bitmapText" && itemType !== "graphics") {
                    modalLabel.bringToTop();
                    modalGroup.add(modalLabel);
                    modalLabel.bringToTop();
                    modalGroup.bringToTop(modalLabel);
                } else {
                    modalGroup.add(modalLabel);
                    modalGroup.bringToTop(modalLabel);
                }
            }

            modalGroup.visible = false;
            game.modals[type] = modalGroup;

        },
        updateModalValue: function (value, type, index, id) {
            var item;
            if (index !== undefined && index !== null) {
                item = game.modals[type].getChildAt(index);
            } else if (id !== undefined && id !== null) {

            }

            if (item.contentType === "text") {
                item.text = value;
                item.update();
                if (item.lockPosition === true) {

                } else {
                    item.x = ((game.width / 2) - (item.width / 2)) + item._offsetX;
                    item.y = ((game.height / 2) - (item.height / 2)) + item._offsetY;
                }
            } else if (item.contentType === "bitmapText") {
                item.text = value;
                item.updateText();
                if (item.lockPosition === true) {

                } else {
                    item.x = ((game.width / 2) - (item.width / 2)) + item._offsetX;
                    item.y = ((game.height / 2) - (item.height / 2)) + item._offsetY;
                }
            } else if (item.contentType === "image") {
                item.loadTexture(value);
            }

        },
        getModalItem: function (type, index) {
            return game.modals[type].getChildAt(index);
        },
        showModal: function (type) {
            game.world.bringToTop(game.modals[type]);
            game.modals[type].visible = true;
            // you can add animation here
        },
        hideModal: function (type) {
            game.modals[type].visible = false;
            // you can add animation here
        },
        destroyModal: function (type) {
            game.modals[type].destroy();
            delete game.modals[type];
        }
    };
};
<|endoftext|>


<commit_before>import EventEmitter from 'wolfy87-eventemitter';
import cloneDeep from 'lodash.clonedeep';
import uuidV4 from 'uuid/v4';

/**
 * Model
 */
export default class Model extends EventEmitter {
  /**
   * Model.constructor
   * @param {Object} data JSON serializable object.
   * @param {...} args Arguments passed to _getDefaults().
   */
  constructor(data = {}, ...args) {
    super();
    // Set from parsed default data
    this._data = this._withDefaultData(this._parseData(data), ...args);
    // Store previous
    this._previousData = {};
  }
  /**
   * Get uuid.
   * @return {String}
   */
  get uuid() {
    return this.get('uuid');
  }
  /**
   * Underlying data object for model.
   * @return {String} Model polymorphic identity.
   */
  getModelIdentity() {
    return this.get('identity');
  }
  /**
   * Cloned underlying data object for model.
   * @return {Object} JSON serializable object.
   */
  getModelData() {
    return cloneDeep(this._data);
  }
  /**
   * Underlying data object reference.
   * @return {Object} JSON serializable object.
   */
  getRawModelData() {
    return this._data;
  }
  /**
   * Get value of data.property.
   * @param {String} property Name of property.
   * @param {*} defaultValue Default value to return if property is undefined.
   * @return {*}
   */
  get(property, defaultValue) {
    return this.has(property) ? this._data[property] : defaultValue;
  }
  /**
   * Return previous value of property.
   * @param {String} property Name of property.
   * @return {*}
   */
  getPrevious(property) {
    return this._previousData[property];
  }
  /**
   * Check if property is set in data.
   * @param {String} property Name of property.
   * @return {boolean} True if set.
   */
  has(property) {
    return this._data.hasOwnProperty(property);
  }
  /**
   * Check if previous value of property is same
   * as current.
   * @param {list of strings} properties Names of properties.
   * @return {boolean} True if any of them has changed.
   */
  hasChanged(...properties) {
    return properties.some(prop => this._previousData[prop] !== this._data[prop]);
  }
  /**
   * Set value of data.property.
   * @param {String} property Name of property.
   * @param {*} value Anything JSON serializable.
   * @param {Object} flags.
   * @return {Model} The Model object.
   */
  set(property, value, {setSilent, unsetIfFalsy} = {}) {
    // Previous value
    this._previousData[property] = this._data[property];
    // Unset if falsy
    if (unsetIfFalsy && !value) {
      value = undefined;
    }
    // If value different
    if (value !== this._data[property]) {
      // If value undefined, delete
      if (typeof value === 'undefined') {
        delete this._data[property];
      // Set new value
      } else {
        this._data[property] = value;
      }
      // Dispatch change event, if not silent
      if (!setSilent) {
        this.dispatchChange(property, value, this._previousData[property]);
      }
    }
    // Return
    return this;
  }
  /**
   * Toggle boolean property.
   * @param {String} property Name of property.
   * @param {Object} flags.
   * @return {Model} The Model object.
   */
  toggle(property, flags = {}) {
    const current = this.get(property, false); // False if not set
    return this.set(property, !current, flags); // Set to !current
  }
  /**
   * Unset value of data.property.
   * @param {String} property Name of property.
   * @param {Object} flags.
   * @return {Model} The Model object.
   */
  unset(property, flags = {}) {
    return this.set(property, undefined, flags);
  }
  /**
   * Reset underlying data object for model.
   * @param {Object} defaultData JSON serializable object.
   * @param {Object} flags.
   * @return {Model} The Model object.
   */
  resetData(defaultData, flags = {}) {
    let data = {};
    // Keep uuid and identity
    const {uuid, identity} = this._data;
    Object.assign(data, {uuid, identity});
    // Update data with defaults
    data = Object.assign(this._withDefaultData(data), defaultData);
    // Clear _data
    Object.keys(this._data).forEach(property => {
      delete this._data[property];
    });
    // Assign new data and return this
    return this.assignData(data, flags);
  }
  /**
   * Assign new data to underlying _data object.
   * @param {Object} newData JSON serializable object.
   * @param {Object} flags.
   * @return {Model} The Model object.
   */
  assignData(newData, {setSilent} = {}) {
    // Assign new data
    Object.assign(this._data, newData);
    // Notify if not silent. Dispatch for each property?
    if (!setSilent) {
      this.dispatchChange();
    }
    // Return
    return this;
  }
  /**
   * Return a copy of this model, with new uuids.
   * FIX: Better way to do this?
   * @return {Model} New instance of Model (or Model subclass).
   */
  copy() {
    // stringify data dict
    const jsonStr = JSON.stringify(this._data);
    // replace all uuids with new one's.
    const uuidRegexp = /"uuid":"........-....-....-....-............"/g;
    const newJsonStr = jsonStr.replace(uuidRegexp, () => {
      return '"uuid":"' + uuidV4() + '"';
    });
    // return instance of this
    const Constructor = this.constructor;
    return new Constructor(JSON.parse(newJsonStr));
  }
  /**
   * Interface for dispatching events.
   * Currently alias for EventEmitter.emit. May change.
   * @param {String} eventType Event type key.
   * @param {...} args Arguments passed to listeners.
   * @return {Model} The Model object.
   */
  dispatchEvent(eventType, ...args) {
    this.emit(eventType, ...[eventType, this].concat(args));
    // Return
    return this;
  }
  /**
   * Dispatch change events.
   * @param {String} property Name of property.
   * @param {*} newValue Anything JSON serializable.
   * @param {*} oldValue Anything JSON serializable.
   * @return {Model} The Model object.
   */
  dispatchChange(property, newValue, oldValue) {
    if (property) {
      this.dispatchEvent('change ' + property, newValue, oldValue);
    }
    return this.dispatchEvent('change');
  }
  /**
   * Alias for EventEmitter.addListener
   */
  addEventListener(event, listener) {
    this.addListener(event, listener);
    // Return
    return this;
  }
  /**
   * Alias for EventEmitter.removeListener
   */
  removeEventListener(event, listener) {
    this.removeListener(event, listener);
    // Return
    return this;
  }
  /**
   * Dispose model and sub models recursively.
   * Remove event listeners and delete references.
   * @return {Model} The Model object.
   */
  dispose() {
    // Remove event listeners
    this.removeAllListeners();
    // delete refs
    this._deleteReferences();
    // Return
    return this;
  }
  /**
   * Parse data object for model.
   * @param {...} data object for model.
   * @return {Object} Default data (JSON serializable object) for Model.
   */
  _parseData(data) {
    return data;
  }
  /**
   * Return default data object for new instance.
   * @param {...} constructorArgs List of arguments passed in constructor.
   * @return {Object} Default data (JSON serializable object) for Model.
   */
  _getDefaults(...constructorArgs) {
    return {
      // Model polymorphic identity
      identity: Model.identity,
      // model uuid
      uuid: uuidV4()
    };
  }
  /**
   * Assign defaults to data argument.
   * @param {Object} defaultData JSON serializable object.
   * @param {...} constructorArgs List of arguments passed in constructor.
   * @return {Object} Default data (JSON serializable object) for Model.
   */
  _withDefaultData(data, ...constructorArgs) {
    // Get defaults
    const defaults = Object.entries(this._getDefaults(...constructorArgs))
      .filter(entry => this._shouldSetDefaultValue(entry[0], data[entry[0]]))
      .reduce((d, entry) => { d[entry[0]] = entry[1]; return d; }, {});
    // Assign to data
    Object.keys(defaults).forEach(key => {
      data[key] = defaults[key];
    });
    // Return
    return data;
  }
  /**
   * Return true if _withDefaultData should set the default
   * value for this property.
   * @param {String} property Name of property.
   * @param {*} value Anything JSON serializable.
   * @return {Boolean}
   */
  _shouldSetDefaultValue(property, value) {
    return typeof value === 'undefined';
  }
  /**
   * Delete references set on model.
   */
  _deleteReferences() {
    delete this._data;
    delete this._previousData;
  }

}
// Polymorphic identity
Model.identity = 'mozy.Model';

/**
 * Model identities
 */
export const identities = new Map();

// Register Model
identities.set(Model.identity, Model);
<commit_msg>Model.resetData, _parseData before assign<commit_after>import EventEmitter from 'wolfy87-eventemitter';
import cloneDeep from 'lodash.clonedeep';
import uuidV4 from 'uuid/v4';

/**
 * Model
 */
export default class Model extends EventEmitter {
  /**
   * Model.constructor
   * @param {Object} data JSON serializable object.
   * @param {...} args Arguments passed to _getDefaults().
   */
  constructor(data = {}, ...args) {
    super();
    // Set from parsed default data
    this._data = this._withDefaultData(this._parseData(data), ...args);
    // Store previous
    this._previousData = {};
  }
  /**
   * Get uuid.
   * @return {String}
   */
  get uuid() {
    return this.get('uuid');
  }
  /**
   * Underlying data object for model.
   * @return {String} Model polymorphic identity.
   */
  getModelIdentity() {
    return this.get('identity');
  }
  /**
   * Cloned underlying data object for model.
   * @return {Object} JSON serializable object.
   */
  getModelData() {
    return cloneDeep(this._data);
  }
  /**
   * Underlying data object reference.
   * @return {Object} JSON serializable object.
   */
  getRawModelData() {
    return this._data;
  }
  /**
   * Get value of data.property.
   * @param {String} property Name of property.
   * @param {*} defaultValue Default value to return if property is undefined.
   * @return {*}
   */
  get(property, defaultValue) {
    return this.has(property) ? this._data[property] : defaultValue;
  }
  /**
   * Return previous value of property.
   * @param {String} property Name of property.
   * @return {*}
   */
  getPrevious(property) {
    return this._previousData[property];
  }
  /**
   * Check if property is set in data.
   * @param {String} property Name of property.
   * @return {boolean} True if set.
   */
  has(property) {
    return this._data.hasOwnProperty(property);
  }
  /**
   * Check if previous value of property is same
   * as current.
   * @param {list of strings} properties Names of properties.
   * @return {boolean} True if any of them has changed.
   */
  hasChanged(...properties) {
    return properties.some(prop => this._previousData[prop] !== this._data[prop]);
  }
  /**
   * Set value of data.property.
   * @param {String} property Name of property.
   * @param {*} value Anything JSON serializable.
   * @param {Object} flags.
   * @return {Model} The Model object.
   */
  set(property, value, {setSilent, unsetIfFalsy} = {}) {
    // Previous value
    this._previousData[property] = this._data[property];
    // Unset if falsy
    if (unsetIfFalsy && !value) {
      value = undefined;
    }
    // If value different
    if (value !== this._data[property]) {
      // If value undefined, delete
      if (typeof value === 'undefined') {
        delete this._data[property];
      // Set new value
      } else {
        this._data[property] = value;
      }
      // Dispatch change event, if not silent
      if (!setSilent) {
        this.dispatchChange(property, value, this._previousData[property]);
      }
    }
    // Return
    return this;
  }
  /**
   * Toggle boolean property.
   * @param {String} property Name of property.
   * @param {Object} flags.
   * @return {Model} The Model object.
   */
  toggle(property, flags = {}) {
    const current = this.get(property, false); // False if not set
    return this.set(property, !current, flags); // Set to !current
  }
  /**
   * Unset value of data.property.
   * @param {String} property Name of property.
   * @param {Object} flags.
   * @return {Model} The Model object.
   */
  unset(property, flags = {}) {
    return this.set(property, undefined, flags);
  }
  /**
   * Reset underlying data object for model.
   * @param {Object} defaultData JSON serializable object.
   * @param {Object} flags.
   * @return {Model} The Model object.
   */
  resetData(defaultData, flags = {}) {
    let data = {};
    // Keep uuid and identity
    const {uuid, identity} = this._data;
    Object.assign(data, {uuid, identity});
    // Update data with defaults
    data = Object.assign(this._withDefaultData(data), this._parseData(defaultData));
    // Clear _data
    Object.keys(this._data).forEach(property => {
      delete this._data[property];
    });
    // Assign new data and return this
    return this.assignData(data, flags);
  }
  /**
   * Assign new data to underlying _data object.
   * @param {Object} newData JSON serializable object.
   * @param {Object} flags.
   * @return {Model} The Model object.
   */
  assignData(newData, {setSilent} = {}) {
    // Assign new data
    Object.assign(this._data, newData);
    // Notify if not silent. Dispatch for each property?
    if (!setSilent) {
      this.dispatchChange();
    }
    // Return
    return this;
  }
  /**
   * Return a copy of this model, with new uuids.
   * FIX: Better way to do this?
   * @return {Model} New instance of Model (or Model subclass).
   */
  copy() {
    // stringify data dict
    const jsonStr = JSON.stringify(this._data);
    // replace all uuids with new one's.
    const uuidRegexp = /"uuid":"........-....-....-....-............"/g;
    const newJsonStr = jsonStr.replace(uuidRegexp, () => {
      return '"uuid":"' + uuidV4() + '"';
    });
    // return instance of this
    const Constructor = this.constructor;
    return new Constructor(JSON.parse(newJsonStr));
  }
  /**
   * Interface for dispatching events.
   * Currently alias for EventEmitter.emit. May change.
   * @param {String} eventType Event type key.
   * @param {...} args Arguments passed to listeners.
   * @return {Model} The Model object.
   */
  dispatchEvent(eventType, ...args) {
    this.emit(eventType, ...[eventType, this].concat(args));
    // Return
    return this;
  }
  /**
   * Dispatch change events.
   * @param {String} property Name of property.
   * @param {*} newValue Anything JSON serializable.
   * @param {*} oldValue Anything JSON serializable.
   * @return {Model} The Model object.
   */
  dispatchChange(property, newValue, oldValue) {
    if (property) {
      this.dispatchEvent('change ' + property, newValue, oldValue);
    }
    return this.dispatchEvent('change');
  }
  /**
   * Alias for EventEmitter.addListener
   */
  addEventListener(event, listener) {
    this.addListener(event, listener);
    // Return
    return this;
  }
  /**
   * Alias for EventEmitter.removeListener
   */
  removeEventListener(event, listener) {
    this.removeListener(event, listener);
    // Return
    return this;
  }
  /**
   * Dispose model and sub models recursively.
   * Remove event listeners and delete references.
   * @return {Model} The Model object.
   */
  dispose() {
    // Remove event listeners
    this.removeAllListeners();
    // delete refs
    this._deleteReferences();
    // Return
    return this;
  }
  /**
   * Parse data object for model.
   * @param {...} data object for model.
   * @return {Object} Default data (JSON serializable object) for Model.
   */
  _parseData(data) {
    return data;
  }
  /**
   * Return default data object for new instance.
   * @param {...} constructorArgs List of arguments passed in constructor.
   * @return {Object} Default data (JSON serializable object) for Model.
   */
  _getDefaults(...constructorArgs) {
    return {
      // Model polymorphic identity
      identity: Model.identity,
      // model uuid
      uuid: uuidV4()
    };
  }
  /**
   * Assign defaults to data argument.
   * @param {Object} defaultData JSON serializable object.
   * @param {...} constructorArgs List of arguments passed in constructor.
   * @return {Object} Default data (JSON serializable object) for Model.
   */
  _withDefaultData(data, ...constructorArgs) {
    // Get defaults
    const defaults = Object.entries(this._getDefaults(...constructorArgs))
      .filter(entry => this._shouldSetDefaultValue(entry[0], data[entry[0]]))
      .reduce((d, entry) => { d[entry[0]] = entry[1]; return d; }, {});
    // Assign to data
    Object.keys(defaults).forEach(key => {
      data[key] = defaults[key];
    });
    // Return
    return data;
  }
  /**
   * Return true if _withDefaultData should set the default
   * value for this property.
   * @param {String} property Name of property.
   * @param {*} value Anything JSON serializable.
   * @return {Boolean}
   */
  _shouldSetDefaultValue(property, value) {
    return typeof value === 'undefined';
  }
  /**
   * Delete references set on model.
   */
  _deleteReferences() {
    delete this._data;
    delete this._previousData;
  }

}
// Polymorphic identity
Model.identity = 'mozy.Model';

/**
 * Model identities
 */
export const identities = new Map();

// Register Model
identities.set(Model.identity, Model);
<|endoftext|>


<commit_before>'use strict'

class SynonymService {

  static get ALLOWABLE_FLAGS() {
    return ['preserveWordSyllableCount',
            'preserveLineSyllableCount',
            'preserveWordRhyme',
            'preserveLineRhyme',
            'preservePronouns',
            'preserveArticles']
  }

  filterFlags(flags) {
    // TODO: function should check to make sure only allowable flags are set
    return flags;
  }
}

module.exports = SynonymService;
<commit_msg>Add setFlags, most of synonymize<commit_after>'use strict'

import pluralize from 'pluralize';

const WordService = use('App/Services/WordService');

class SynonymService {

  static get DEFAULT_FLAGS() {
    return {
      preserveWordSyllableCount: false,
      preserveLineSyllableCount: false,
      preserveWordRhyme: false,
      preserveLineRhyme: false,
      preservePronouns: false,
      preserveArticles: false,
      preserveConjunctions: false
    }
  }
  static get ALLOWABLE_FLAGS() {
    return Object.keys(SynonymService.DEFAULT_FLAGS);
  }
  static get CLASS_FLAGS_AND_CHECKS() {
    return {
      preservePronouns: 'isPronoun',
      preserveArticles: 'isArticle',
      preserveConjunctions: 'isConjunction'
    };
  }

  constructor() {
    this._wordService = new WordService();
    this._flags = SynonymService.DEFAULT_FLAGS;
  }

  setFlags(flags) {
    // TODO: function should check to make sure only allowable flags are set
    this._flags = Object.assign({}, SynonymService.DEFAULT_FLAGS, flags);
  }

  synonymizeText(text) {
    let lines = this._splitTextIntoLines(text);

    lines.forEach(line => {
      let token = this._splitLineIntoTokens(line);

      tokens.map((token, tokenIdx) => {
        if (this._isPunctuation(token)) {
          return token;
        }

        let tokenIsPluralized = pluralize.isPluralized(token);
        if (tokenIsPluralized) {
          token = pluralize.singular(token);
        }

        if (this._isWordExcludedByClass(token)) {
          return token;
        }

        // TODO: Get syn using model (use a scope to limit by syllables if preserveWordSyllableCount)
        // TODO: When getting syn, should scope by preserveWordSyllableCount, preserveWordRhyme, and (if last word and !preserveWordRhyme) by preserveLineRhyme
        // TODO: This scope should also order by random
        let synonym = null; // tmp

        let replacement = synonym || token;

        // TODO: Need to add functionality for preserveLineRhyme
        if (tokenIsPluralized) {
          replacement = pluralize.plural(replacement);
        }

        return replacement;
      });
    });
  }

  _isPunctuation(token) {

  }

  _splitTextIntoLines(text) {

  }

  _splitLineIntoTokens(line) {

  }

  _isWordExcludedByClass(word) {
    for (flag in SynonymService.CLASS_FLAGS_AND_CHECKS) {
      let checkFunc = SynonymService.CLASS_FLAGS_AND_CHECKS[flag];
      if (this._flags[flag] && this._wordService[checkFunc](word)) {
        return true;
      }
    }
  }
}

module.exports = SynonymService;
<|endoftext|>


<commit_before>import {v4} from 'node-uuid';
import {Signal} from 'phosphor-signaling';

export class Model {
    static registerModelType(modelClass) {
        if (!Model.registeredModelTypes) {
            Model.registeredModelTypes = [];
        }

        let name = modelClass.constructor.name;
        if (Model.registeredModelTypes.indexOf(name) === -1) {
            Model.registeredModelTypes[name] = modelClass;
        } else {
            throw new Error('A class with the name "' + name + '" has already been registered.');
        }
    }

    constructor(id) {
        this.id = id || this._newId();
        this.changedLock = 0;
        this.keys = [];
    }

    get changed() {
        return Model.changedSignal.bind(this);
    }

    declare(key, getter, setter) {
        if (getter === undefined) throw new Error('getter not defined');
        if (setter === undefined) throw new Error('setter not defined');

        if (this.keys.indexOf(key) === -1) {
            this.keys.push(key);
        }

        Object.defineProperty(this, key, {
            get: getter,
            set: (x) => {
                let changed = x !== this[key];
                setter.call(this, x);
                if (changed) {
                    // TODO: Signal value change
                }
            }
        });
    }

    placeholder(key) {
        let barf = () => { throw new Error(key + ' not implemented'); };
        if (this.keys.indexOf(key) === -1) {
            this.declare(key, barf, barf);
        }
    }

    get state() {
        let state = { main: this.id };
        state[this.id] = {};

        for (let key of this.keys) {
            let modelState = this._packModels(state[key]);
            state[this.id][key] = modelState.state;

            for (let modelId of Object.keys(modelState.models)) {
                state[modelId] = modelState.models[modelId];
            }
        }
        return state;
    }
    set state() {

    }

    preventChanged(f) {
        this.changedLock += 1;
        try {
            f.call(this);
        } finally {
            this.changedLock -= 1;
        }
    }

    _packModels() {

    }

    _unpackModels() {

    }

    _newId() {
        return v4();
    }
}

Model.changedSignal = new Signal();
<commit_msg>Finish base model class<commit_after>import {v4} from 'node-uuid';
import {Signal} from 'phosphor-signaling';
import * as _ from 'underscore';

var SERIALIZATION_ID = 'model#';

var changed = Signal();

/**
 * Base model
 */
export class Model {

    /**
     * Register a model class.  Require for model serialization and
     * deserialization.
     * @param  {Model class} modelClass
     */
    static registerModelType(modelClass) {
        if (!Model.registeredModelTypes) {
            Model.registeredModelTypes = [];
        }

        let name = modelClass.constructor.name;
        if (Model.registeredModelTypes.indexOf(name) === -1) {
            Model.registeredModelTypes[name] = modelClass;
        } else {
            throw new Error('A class with the name "' + name + '" has already been registered.');
        }
    }

    /**
     * Public constructor
     * @param  {[string]} id - uuid
     */
    constructor(id) {
        if (!Model.weakMap) {
            Model.weakMap = new WeakMap();
        }

        this.id = id || this._newId();
        Model.weakMap.set(this.id, this);

        this._changedLock = 0;
        this._keys = [];
    }

    /**
     * Get the registered type name of the class.
     * @return {string}
     */
    get typeName() {
        return this.constructor.name;
    }

    /**
     * Changed signal
     * @return {Signal}
     */
    get changed() {
        return changed.bind(this);
    }

    /**
     * Declare a state key.
     * @param  {string} key
     * @param  {()=>object} getter
     * @param  {(object)=>void} setter
     */
    declare(key, getter, setter) {
        if (getter === undefined) throw new Error('getter not defined');
        if (setter === undefined) throw new Error('setter not defined');

        if (this._keys.indexOf(key) === -1) {
            this._keys.push(key);
        }

        Object.defineProperty(this, key, {
            get: getter,
            set: (x) => {
                let changed = x !== this[key];
                setter.call(this, x);
                if (changed) {
                    if (changedLock <= 0) {
                        this.changed.emit(key, v, this);
                    }

                    // Recursively listen to change signals.  Duck typing.
                    if (x.changed) {
                        x.changed.connect((k, v, sender) => {
                            if (changedLock <= 0) {
                                this.changed.emit(key + '.' + k, v, this);
                            }
                        }, this);
                    }
                }
            }
        });
    }

    /**
     * Declare a placeholder for a state key.
     * Useful for base class models
     * @param  {string} key
     */
    placeholder(key) {
        let barf = () => { throw new Error(key + ' not implemented'); };
        if (this._keys.indexOf(key) === -1) {
            this.declare(key, barf, barf);
        }
    }

    /**
     * Readonly copy of the internal keys array
     * @return {[type]} [description]
     */
    get keys() {
        return this._keys.slice();
    }

    /**
     * Model state - jsonable
     * @return {object}
     */
    get state() {
        return JSON.stringify(this.stateObject);
    }

    /**
     * Model state - jsonable
     * @param  {object} x
     */
    set state(x) {
        this.stateObject = JSON.parse(x, this.fromJSON);
    }

    /**
     * Model state - not jsonable
     * @return {object}
     */
    get stateObject() {
        let state = {};
        for (let key of this.keys) {
            state[key] = this[key];
        }
        return state;
    }

    /**
     * Model state - not jsonable
     * @param  {object} state
     */
    set stateObject(state) {
        for (let key of state) {
            this[key] = state[key];
        }
    }

    /**
     * Context handler that prevents state change signals from emitting.
     * @param  {function} f
     */
    preventChanged(f) {
        this._changedLock += 1;
        try {
            f.call(this);
        } finally {
            this._changedLock -= 1;
        }
    }

    /**
     * For serialization using JSON.stringify.
     * @return {string}
     */
    toJSON() {
        return SERIALIZATION_ID + this.typeName + ',' + this.id;
    }

    /**
     * For deserialization using JSON.parse
     * @return {any} value
     */
    fromJSON(k, v) {
        if (typeof v === 'string' && v.startsWith(SERIALIZATION_ID) && v.indexOf(',') !== -1) {
            let serialized = v.substring(SERIALIZATION_ID.length).split(',', 2);
            let className = serialized[0];
            let id = serialized[1];
            if (Model.weakMap.has(id)) {
                return Model.weakMap.get(id);
            } else {
                return new (Model.registeredModelTypes[className])(id);
            }
        } else {
            return v;
        }
    }

    /**
     * Generates a new id.
     * @return {string} id
     */
    _newId() {
        return v4();
    }
}
<|endoftext|>


<commit_before>/*
  Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/*jslint browser:true evil:true */

(function (global) {
    'use strict';

    var lookup;

    function id(i) {
        return document.getElementById(i);
    }

    function escaped(str) {
        return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
    }

    function setText(id, str) {
        var el = document.getElementById(id);
        if (typeof el.innerText === 'string') {
            el.innerText = str;
        } else {
            el.textContent = str;
        }
    }

    function isLineTerminator(ch) {
        return (ch === '\n' || ch === '\r' || ch === '\u2028' || ch === '\u2029');
    }

    global.traceInstrument = function () {
        var tracer, code, i, functionList, signature, pos;

        if (typeof window.editor === 'undefined') {
            code = document.getElementById('code').value;
        } else {
            code = window.editor.getValue();
        }

        // TODO: remove all existing instrumentation

        tracer = window.esmorph.Tracer.FunctionEntrance(function (fn) {
            signature = 'window.TRACE({ ';
            signature += 'name: "' + fn.name + '", ';
            signature += 'lineNumber: ' + fn.loc.start.line + ', ';
            signature += 'range: [' + fn.range[0] + ',' + fn.range[1] + ']';
            signature += ' })';
            return signature;
        });

        code = window.esmorph.modify(code, tracer);

        if (typeof window.editor === 'undefined') {
            document.getElementById('code').value = code;
        } else {
            window.editor.setValue(code);
        }

        // Enclose in IIFE.
        code = '(function() {\n' + code + '\n}())';

        return code;
    };

    function showResult() {
        var i, str, histogram, entry;

        histogram = window.TRACE.getHistogram();

        str = '

Function	Hits

';
        for (i = 0; i < histogram.length; i += 1) {
            entry = histogram[i];
            str += '
';
            str += '' + entry.name + '	';
            str += '' + entry.count + '	';
            str += '
';
        }
        str += '
';

        id('result').innerHTML = str;
    }

    function createTraceCollector() {
        global.TRACE = {
            hits: {},
            enterFunction: function (info) {
                var key = info.name + ' at line ' + info.lineNumber;
                if (this.hits.hasOwnProperty(key)) {
                    this.hits[key] = this.hits[key] + 1;
                } else {
                    this.hits[key] = 1;
                }
            },
            getHistogram: function () {
                var entry,
                    sorted = [];
                for (entry in this.hits) {
                    if (this.hits.hasOwnProperty(entry)) {
                        sorted.push({ name: entry, count: this.hits[entry]});
                    }
                }
                sorted.sort(function (a, b) {
                    return b.count - a.count;
                });
                return sorted;
            }
        };
    }

    global.traceRun = function () {
        var code;
        try {
            code = global.traceInstrument();
            createTraceCollector();
            eval(code);
            showResult();
        } catch (e) {
            id('result').innerText = e.toString();
        }
    };
}(window));
/* vim: set sw=4 ts=4 et tw=80 : */
<commit_msg>Fix wrong call in the function trace example.<commit_after>/*
  Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/*jslint browser:true evil:true */

(function (global) {
    'use strict';

    var lookup;

    function id(i) {
        return document.getElementById(i);
    }

    function escaped(str) {
        return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
    }

    function setText(id, str) {
        var el = document.getElementById(id);
        if (typeof el.innerText === 'string') {
            el.innerText = str;
        } else {
            el.textContent = str;
        }
    }

    function isLineTerminator(ch) {
        return (ch === '\n' || ch === '\r' || ch === '\u2028' || ch === '\u2029');
    }

    global.traceInstrument = function () {
        var tracer, code, i, functionList, signature, pos;

        if (typeof window.editor === 'undefined') {
            code = document.getElementById('code').value;
        } else {
            code = window.editor.getValue();
        }

        // TODO: remove all existing instrumentation

        tracer = window.esmorph.Tracer.FunctionEntrance(function (fn) {
            signature = 'window.TRACE.enterFunction({ ';
            signature += 'name: "' + fn.name + '", ';
            signature += 'lineNumber: ' + fn.loc.start.line + ', ';
            signature += 'range: [' + fn.range[0] + ',' + fn.range[1] + ']';
            signature += ' });';
            return signature;
        });

        code = window.esmorph.modify(code, tracer);

        if (typeof window.editor === 'undefined') {
            document.getElementById('code').value = code;
        } else {
            window.editor.setValue(code);
        }

        // Enclose in IIFE.
        code = '(function() {\n' + code + '\n}())';

        return code;
    };

    function showResult() {
        var i, str, histogram, entry;

        histogram = window.TRACE.getHistogram();

        str = '

Function	Hits

';
        for (i = 0; i < histogram.length; i += 1) {
            entry = histogram[i];
            str += '
';
            str += '' + entry.name + '	';
            str += '' + entry.count + '	';
            str += '
';
        }
        str += '
';

        id('result').innerHTML = str;
    }

    function createTraceCollector() {
        global.TRACE = {
            hits: {},
            enterFunction: function (info) {
                var key = info.name + ' at line ' + info.lineNumber;
                if (this.hits.hasOwnProperty(key)) {
                    this.hits[key] = this.hits[key] + 1;
                } else {
                    this.hits[key] = 1;
                }
            },
            getHistogram: function () {
                var entry,
                    sorted = [];
                for (entry in this.hits) {
                    if (this.hits.hasOwnProperty(entry)) {
                        sorted.push({ name: entry, count: this.hits[entry]});
                    }
                }
                sorted.sort(function (a, b) {
                    return b.count - a.count;
                });
                return sorted;
            }
        };
    }

    global.traceRun = function () {
        var code;
        try {
            code = global.traceInstrument();
            createTraceCollector();
            eval(code);
            showResult();
        } catch (e) {
            id('result').innerText = e.toString();
        }
    };
}(window));
/* vim: set sw=4 ts=4 et tw=80 : */
<|endoftext|>


<commit_before>module.exports = {
    getUTCDate: function (date) {
        var year = date.getYear();
        var month = date.getMonth();
        var currDate = date.getDate();
        var hours = date.getHours();
        var minutes = date.getMinutes();
        var seconds = date.getSeconds();

        return new Date(Date.UTC(year, month, currDate, hours, minutes, seconds));
    }
};<commit_msg>UTCDate extension fix.<commit_after>module.exports = {
    getUTCDate: function (date) {
        var year = date.getFullYear();
        var month = date.getMonth();
        var currDate = date.getDate();
        var hours = date.getHours();
        var minutes = date.getMinutes();
        var seconds = date.getSeconds();

        return new Date(Date.UTC(year, month, currDate, hours, minutes, seconds));
    }
};<|endoftext|>


<commit_before>"use strict";
const util = require('util');
const exec = require('child_process').exec;
const LoadBalancer = require('../db/models/loadbalancer.js');
const LoadBalancers = require('../db/collections/loadbalancers.js');
const Server = require('../db/models/client-server.js');
const Servers = require('../db/collections/client-server.js');
var requestP = require('request-promise');
var Promise = require('bluebird');

var log = function(error, stdout, stderr) {
  console.log(stdout);
};
const _ = require('underscore');

module.exports = {

  //NEED TO GET ID FOR REMOVE

  listParsed(nginxipandport, zone) {
    let options = {
      uri: 'http://' + nginxipandport + '/upstream_conf',
      qs: {
        upstream: zone,
        verbose: ''
      }
    };

    return requestP(options)
      .then((result) => {
        let servers = [];
        let parseServerInfo = /server ([0-9\.]+):([0-9]+).*id=([0-9]+)/g;
        let serverInfo = null;
        while (serverInfo = parseServerInfo.exec(result)) {
          servers.push({
            ip: serverInfo[1],
            port: serverInfo[2],
            id: serverInfo[3]
          });
        }

        return servers;
      })
      .catch((error) => {
        console.log(error);
        return;
      });
  },
  list(nginxipandport, zone) {
    exec("curl http://" + nginxipandport + "/upstream_conf?upstream=" + zone + "&verbose=", log);
  },
  enable(nginxipandport, targetipandport, zone) {
    exec("curl http://" + nginxipandport + "/upstream_conf?upstream=" + zone + "&server=" + targetipandport + "&up=", log);
  },
  disable(nginxipandport, targetipandport, zone) {
    exec("curl http://" + nginxipandport + "/upstream_conf?upstream=" + zone + "&server=" + targetipandport + "&down=", log);
  },
  add(nginxipandport, targetipandport, zone) {
    let options = {
      // don't use qs for this one since query string ascii convers the : in the server which nginx does not like
      uri: 'http://' + nginxipandport + '/upstream_conf?add=&upstream=' + zone + '&server=' + targetipandport,
    };
    return requestP(options);
    // exec("curl http://" + nginxipandport + "/upstream_conf?add=&upstream=" + zone + "&server=" + targetipandport, log);
  },
  remove(nginxipandport, zone, id) {
    // exec("curl http://" + nginxipandport + "/upstream_conf?remove=&upstream=" + zone + "&id=" + id, log);
    let options = {
      uri: 'http://' + nginxipandport + '/upstream_conf?remove=',
      qs: {
        upstream: zone,
        id: id
      }
    };

    return requestP(options)
    .then(function(result){
      let servers = [];
      let parseServerInfo = /server ([0-9\.]+):([0-9]+).*id=([0-9]+)/g;
      let serverInfo = null;
      while (serverInfo = parseServerInfo.exec(result)) {
        servers.push({
          ip: serverInfo[1],
          port: serverInfo[2],
          id: serverInfo[3]
        });
      }
      return servers;
    })
    .catch((error) => {
      console.log(error);
      return;
    });
  },

  newLoadBalancer(req, res) {
    const data = req.body;
    LoadBalancer.where({ users_id: req.user.id, ip: data.ip }).fetch()
      .then((lb) => {
        if (!lb) {
          new LoadBalancer({
            ip: data.ip,
            port: data.port,
            zone: data.zone,
            image: data.image,
            users_id: req.user.id,
            min_threshold: data.min_threshold || 10000,
            max_threshold: data.max_threshold || 50000,
            max_servers: data.max_servers || 5,
          })
          .save()
          .then((newlb) => {
            //DO AUTO DISCOVERY
            res.send('success');
            return internalTasks.syncServersToPlatforms(req.user.id);
          })
          .then(() => {
            return internalTasks.syncServersToLB(req.user.id);
          });
        } else {
          res.send('That server has already been added');
        }
      }).
      catch((error) => {
        console.error("Could not add load balancer", error);
      });
  },

  addSlave(req, res) {
    Server.where({ id: req.body.id }).fetch()
      .then((server) => {
        server.set('master', req.body.master)
        .save()
        .then(() => {
          res.send('success');
        })
        .catch((err) => {
          console.log(err);
          res.send('Error');
        });
      });
  },

  allSlaves(req, res) {
    LoadBalancer.where({users_id: req.user.id}).fetchAll()
    .then((LoadBalancers) => {
      var promises = _.map(LoadBalancers.models, (model) => {
        return  Servers.model.where({master: model.attributes.id})
                  .fetchAll()
                  .then((servers) => {
                    return servers;
                  })
                  .catch((error) => {
                    console.error("Error: Couldn't get slaves", error);
                  });
      });
      return Promise.all(promises).then((lbServers) => {
        return lbServers;
      })
      .then((lbServers) => {
        res.send(lbServers);
      });
    })
    .catch((error) => {
      console.error("Error: could not get all slaves", error);
    });
  },

  removeLoadBalancer(req, res) {
    LoadBalancer.where({ id: req.body.id }).fetch()
      .then((lb) => {
        const lbid = lb.id;
        if (!lb) {
          res.send('Load Balancer with id ' + req.body.id + ' not found');
        }
        lb.destroy()
          .then(() => {
            Servers.query('where', 'master', '=', lbid).fetch()
              .then((servers) => {
                _.each(servers.models, (item, index) => {
                  item.set('master', null)
                  .save();
                });
              })
              .then(() => {
                res.send('Great Success!');
              });
          });
      });
  },

  getLoadBalancers(req, res) {
    LoadBalancer.where({users_id: req.user.id}).fetchAll()
      .then((LoadBalancers) => {
        res.send(LoadBalancers);
      });
  },

  updateLoadBalancer(req, res) {
    let updatedFields = {}
    if (req.body.image) { updatedFields.image = req.body.image};
    if (req.body.min_threshold) { updatedFields.min_threshold = req.body.min_threshold};
    if (req.body.max_threshold) { updatedFields.max_threshold = req.body.max_threshold};
    if (req.body.max_servers) { updatedFields.max_servers = req.body.max_servers};
    LoadBalancer.where({users_id: req.user.id, id: req.body.loadBalancerId})
      .fetch()
      .then((lb) => {
        lb.set(updatedFields)
        .save()
        .then((updatedLb) => {
          res.send(updatedLb);
        });
      })
      .catch((error) => {
        console.error("Error: Could not update image", error)
      });
  }

};
<commit_msg>added require internal tasks to nginxController.<commit_after>"use strict";
const util = require('util');
const exec = require('child_process').exec;
const LoadBalancer = require('../db/models/loadbalancer.js');
const LoadBalancers = require('../db/collections/loadbalancers.js');
const Server = require('../db/models/client-server.js');
const Servers = require('../db/collections/client-server.js');
var requestP = require('request-promise');
var Promise = require('bluebird');
const internalTasks = require('./internal_tasks');

var log = function(error, stdout, stderr) {
  console.log(stdout);
};
const _ = require('underscore');

module.exports = {

  //NEED TO GET ID FOR REMOVE

  listParsed(nginxipandport, zone) {
    let options = {
      uri: 'http://' + nginxipandport + '/upstream_conf',
      qs: {
        upstream: zone,
        verbose: ''
      }
    };

    return requestP(options)
      .then((result) => {
        let servers = [];
        let parseServerInfo = /server ([0-9\.]+):([0-9]+).*id=([0-9]+)/g;
        let serverInfo = null;
        while (serverInfo = parseServerInfo.exec(result)) {
          servers.push({
            ip: serverInfo[1],
            port: serverInfo[2],
            id: serverInfo[3]
          });
        }

        return servers;
      })
      .catch((error) => {
        console.log(error);
        return;
      });
  },
  list(nginxipandport, zone) {
    exec("curl http://" + nginxipandport + "/upstream_conf?upstream=" + zone + "&verbose=", log);
  },
  enable(nginxipandport, targetipandport, zone) {
    exec("curl http://" + nginxipandport + "/upstream_conf?upstream=" + zone + "&server=" + targetipandport + "&up=", log);
  },
  disable(nginxipandport, targetipandport, zone) {
    exec("curl http://" + nginxipandport + "/upstream_conf?upstream=" + zone + "&server=" + targetipandport + "&down=", log);
  },
  add(nginxipandport, targetipandport, zone) {
    let options = {
      // don't use qs for this one since query string ascii convers the : in the server which nginx does not like
      uri: 'http://' + nginxipandport + '/upstream_conf?add=&upstream=' + zone + '&server=' + targetipandport,
    };
    return requestP(options);
    // exec("curl http://" + nginxipandport + "/upstream_conf?add=&upstream=" + zone + "&server=" + targetipandport, log);
  },
  remove(nginxipandport, zone, id) {
    // exec("curl http://" + nginxipandport + "/upstream_conf?remove=&upstream=" + zone + "&id=" + id, log);
    let options = {
      uri: 'http://' + nginxipandport + '/upstream_conf?remove=',
      qs: {
        upstream: zone,
        id: id
      }
    };

    return requestP(options)
    .then(function(result){
      let servers = [];
      let parseServerInfo = /server ([0-9\.]+):([0-9]+).*id=([0-9]+)/g;
      let serverInfo = null;
      while (serverInfo = parseServerInfo.exec(result)) {
        servers.push({
          ip: serverInfo[1],
          port: serverInfo[2],
          id: serverInfo[3]
        });
      }
      return servers;
    })
    .catch((error) => {
      console.log(error);
      return;
    });
  },

  newLoadBalancer(req, res) {
    const data = req.body;
    LoadBalancer.where({ users_id: req.user.id, ip: data.ip }).fetch()
      .then((lb) => {
        if (!lb) {
          new LoadBalancer({
            ip: data.ip,
            port: data.port,
            zone: data.zone,
            image: data.image,
            users_id: req.user.id,
            min_threshold: data.min_threshold || 10000,
            max_threshold: data.max_threshold || 50000,
            max_servers: data.max_servers || 5,
          })
          .save()
          .then((newlb) => {
            //DO AUTO DISCOVERY
            res.send('success');
            return internalTasks.syncServersToPlatforms(req.user.id);
          })
          .then(() => {
            return internalTasks.syncServersToLB(req.user.id);
          });
        } else {
          res.send('That server has already been added');
        }
      }).
      catch((error) => {
        console.error("Could not add load balancer", error);
      });
  },

  addSlave(req, res) {
    Server.where({ id: req.body.id }).fetch()
      .then((server) => {
        server.set('master', req.body.master)
        .save()
        .then(() => {
          res.send('success');
        })
        .catch((err) => {
          console.log(err);
          res.send('Error');
        });
      });
  },

  allSlaves(req, res) {
    LoadBalancer.where({users_id: req.user.id}).fetchAll()
    .then((LoadBalancers) => {
      var promises = _.map(LoadBalancers.models, (model) => {
        return  Servers.model.where({master: model.attributes.id})
                  .fetchAll()
                  .then((servers) => {
                    return servers;
                  })
                  .catch((error) => {
                    console.error("Error: Couldn't get slaves", error);
                  });
      });
      return Promise.all(promises).then((lbServers) => {
        return lbServers;
      })
      .then((lbServers) => {
        res.send(lbServers);
      });
    })
    .catch((error) => {
      console.error("Error: could not get all slaves", error);
    });
  },

  removeLoadBalancer(req, res) {
    LoadBalancer.where({ id: req.body.id }).fetch()
      .then((lb) => {
        const lbid = lb.id;
        if (!lb) {
          res.send('Load Balancer with id ' + req.body.id + ' not found');
        }
        lb.destroy()
          .then(() => {
            Servers.query('where', 'master', '=', lbid).fetch()
              .then((servers) => {
                _.each(servers.models, (item, index) => {
                  item.set('master', null)
                  .save();
                });
              })
              .then(() => {
                res.send('Great Success!');
              });
          });
      });
  },

  getLoadBalancers(req, res) {
    LoadBalancer.where({users_id: req.user.id}).fetchAll()
      .then((LoadBalancers) => {
        res.send(LoadBalancers);
      });
  },

  updateLoadBalancer(req, res) {
    let updatedFields = {}
    if (req.body.image) { updatedFields.image = req.body.image};
    if (req.body.min_threshold) { updatedFields.min_threshold = req.body.min_threshold};
    if (req.body.max_threshold) { updatedFields.max_threshold = req.body.max_threshold};
    if (req.body.max_servers) { updatedFields.max_servers = req.body.max_servers};
    LoadBalancer.where({users_id: req.user.id, id: req.body.loadBalancerId})
      .fetch()
      .then((lb) => {
        lb.set(updatedFields)
        .save()
        .then((updatedLb) => {
          res.send(updatedLb);
        });
      })
      .catch((error) => {
        console.error("Error: Could not update image", error)
      });
  }

};
<|endoftext|>


<commit_before>var Plurb = require('../db/dbconfig').Plurb;
var User = require('../db/dbconfig').User;

module.exports = {
  //currently not being used
  getAllPlurbs: function (req, res) {
    Plurb.findAll({})
    .then(function (plurbs) {
      res.status(200).json(plurbs);
    })
    .catch(function (err) {
      console.error(err);
    });
  },

  createPlurb: function (req, res) {
    var googId = req.session.user;
    var topicId = req.body.topicId;
    //make a db call using the googid and returns user data
    User.find({where:
      {googid: googId}
    })
    .then(function (user) {
      //set the values for first and last names, picture
      //put all data into an objected used to create plurb
      var plurbData = {
        text: req.body.text,
        lat: req.body.lat,
        long: req.body.long,
        firstName: user.dataValues.firstName,
        lastName: user.dataValues.lastName,
        picture: user.dataValues.picture
      };
      Plurb.create(plurbData)
      .then(function (plurb) {
        //sets the foreign key of googId and topicId
        plurb.setUser(googId);
        plurb.setTopic(topicId);
        res.status(201).json(plurb);
      })
      .catch(function (err) {
        console.error(err);
      });
    });
  },

  getPlurb: function (req, res) {
    var plurbId = req.params.plurbId;
    Plurb.findById(plurbId)
    .then(function (plurb) {
      res.status(200).json(plurb);
    })
    .catch(function (err) {
      console.error(err);
    });
  },

  deletePlurb: function (req, res) {
    var plurbId = req.params.plurbId;
    Plurb.destroy({where: {id: plurbId}})
    .then(function () {
      res.status(201);
    })
    .catch(function (err) {
      console.error(err);
    });
  },

  getPlurbsByGoogId: function (req, res) {
    var googId = req.params.googId;
    Plurb.findAll({where: {UserGoogid: googId}})
    .then(function (plurbs) {
      res.status(200).json(plurbs);
    })
    .catch(function (err) {
      console.error(err);
    });
  },

  getPlurbsByLocation: function (req, res) {
    var topicId = req.body.topicId;
    var minLat = req.body.mapBounds.minLat;
    var maxLat = req.body.mapBounds.maxLat;
    var minLng = req.body.mapBounds.minLng;
    var maxLng = req.body.mapBounds.maxLng;
    //if topic id is 0 send back all plurbs in that location regardless of topic
    if (topicId === 0) {
      //find all plurbs that fit within the min-max range
      Plurb.findAll({
        where: {
          lat: {$between: [minLat, maxLat]},
          long: {$between: [minLng, maxLng]}
        }
      })
      .then(function (plurbs) {
        res.status(200).json(plurbs);
      })
      .catch(function (err) {
        console.error (err);
      });
      //otherwise send back plurbs with that topic and location
    } else {
      Plurb.findAll({
        where: {
          lat: {$between: [minLat, maxLat]},
          long: {$between: [minLng, maxLng]},
          TopicId: topicId
        }
      })
      .then(function (plurbs) {
        res.status(200).json(plurbs);
      })
      .catch(function (err) {
        console.error(err);
      });
    }
  },

  getAllFriendsAllPlurbs: function (req, res) {
    var googId = req.session.user;
    var friendsGoogIds = [];
//Create array of all friends googIds

    User.find({where: {googid: googId}})
    .then(function(user) {
      user.getFriends({where: {UserGoogid: googId}})
    })
    .then(function(friends){
      console.log(friends);
    })
    .catch(function (err) {
      console.error(err);
    });

    // Plurb.findAll({
    //   where: {
    //     UserGoogid: friendsGoogIds
    //   }
    // })
    //   .then(function (plurbs) {
    //     res.status(200).json(plurbs);
    //   })
    //   .catch(function (err) {
    //     console.error(err);
    //   });
  }
};
<commit_msg>(feat) Pull all friends of user<commit_after>var Plurb = require('../db/dbconfig').Plurb;
var User = require('../db/dbconfig').User;

module.exports = {
  //currently not being used
  getAllPlurbs: function (req, res) {
    Plurb.findAll({})
    .then(function (plurbs) {
      res.status(200).json(plurbs);
    })
    .catch(function (err) {
      console.error(err);
    });
  },

  createPlurb: function (req, res) {
    var googId = req.session.user;
    var topicId = req.body.topicId;
    //make a db call using the googid and returns user data
    User.find({where:
      {googid: googId}
    })
    .then(function (user) {
      //set the values for first and last names, picture
      //put all data into an objected used to create plurb
      var plurbData = {
        text: req.body.text,
        lat: req.body.lat,
        long: req.body.long,
        firstName: user.dataValues.firstName,
        lastName: user.dataValues.lastName,
        picture: user.dataValues.picture
      };
      Plurb.create(plurbData)
      .then(function (plurb) {
        //sets the foreign key of googId and topicId
        plurb.setUser(googId);
        plurb.setTopic(topicId);
        res.status(201).json(plurb);
      })
      .catch(function (err) {
        console.error(err);
      });
    });
  },

  getPlurb: function (req, res) {
    var plurbId = req.params.plurbId;
    Plurb.findById(plurbId)
    .then(function (plurb) {
      res.status(200).json(plurb);
    })
    .catch(function (err) {
      console.error(err);
    });
  },

  deletePlurb: function (req, res) {
    var plurbId = req.params.plurbId;
    Plurb.destroy({where: {id: plurbId}})
    .then(function () {
      res.status(201);
    })
    .catch(function (err) {
      console.error(err);
    });
  },

  getPlurbsByGoogId: function (req, res) {
    var googId = req.params.googId;
    Plurb.findAll({where: {UserGoogid: googId}})
    .then(function (plurbs) {
      res.status(200).json(plurbs);
    })
    .catch(function (err) {
      console.error(err);
    });
  },

  getPlurbsByLocation: function (req, res) {
    var topicId = req.body.topicId;
    var minLat = req.body.mapBounds.minLat;
    var maxLat = req.body.mapBounds.maxLat;
    var minLng = req.body.mapBounds.minLng;
    var maxLng = req.body.mapBounds.maxLng;
    //if topic id is 0 send back all plurbs in that location regardless of topic
    if (topicId === 0) {
      //find all plurbs that fit within the min-max range
      Plurb.findAll({
        where: {
          lat: {$between: [minLat, maxLat]},
          long: {$between: [minLng, maxLng]}
        }
      })
      .then(function (plurbs) {
        res.status(200).json(plurbs);
      })
      .catch(function (err) {
        console.error (err);
      });
      //otherwise send back plurbs with that topic and location
    } else {
      Plurb.findAll({
        where: {
          lat: {$between: [minLat, maxLat]},
          long: {$between: [minLng, maxLng]},
          TopicId: topicId
        }
      })
      .then(function (plurbs) {
        res.status(200).json(plurbs);
      })
      .catch(function (err) {
        console.error(err);
      });
    }
  },

  getAllFriendsAllPlurbs: function (req, res) {
    var googId = req.body.user;
    // var googId = req.session.user;
    var friendsGoogIds = [];
//Create array of all friends googIds

    User.find({where: {googid: googId}})
    .then(function(user) {
      //this built in Sequelize method will pull all friends
      user.getFriends()
       .then(function(friends){
         console.log('friends: ', friends);
       });
    })
    .catch(function (err) {
      console.error(err);
    });

    // Plurb.findAll({
    //   where: {
    //     UserGoogid: friendsGoogIds
    //   }
    // })
    //   .then(function (plurbs) {
    //     res.status(200).json(plurbs);
    //   })
    //   .catch(function (err) {
    //     console.error(err);
    //   });
  }
};
<|endoftext|>