<commit_before>/*global define*/
define([
        '../Core/defined',
        '../Core/defineProperties',
        '../Core/DeveloperError',
        '../Core/Event',
        '../Core/EventHelper',
        './Property'
    ], function(
        defined,
        defineProperties,
        DeveloperError,
        Event,
        EventHelper,
        Property) {
    "use strict";

    /**
     * A {@link Property} whose value is an array whose items are the computed value
     * of other property instances.
     *
     * @alias PropertyArray
     * @constructor
     *
     * @param {Property[]} [value] An array of Property instances.
     */
    function PropertyArray(value) {
        this._value = undefined;
        this._definitionChanged = new Event();
        this._eventHelper = new EventHelper();
        this.setValue(value);
    }

    defineProperties(PropertyArray.prototype, {
        /**
         * Gets a value indicating if this property is constant.  This property
         * is considered constant if all property items in the array are constant.
         * @memberof PropertyArray.prototype
         *
         * @type {Boolean}
         * @readonly
         */
        isConstant : {
            get : function() {
                var value = this._value;
                if (!defined(value)) {
                    return true;
                }
                var length = value.length;
                for (var i = 0; i < length; i++) {
                    if (!Property.isConstant(value[i])) {
                        return false;
                    }
                }
                return true;
            }
        },
        /**
         * Gets the event that is raised whenever the definition of this property changes.
         * The definition is changed whenever setValue is called with data different
         * than the current value or one of the properties in the array also changes.
         * @memberof PropertyArray.prototype
         *
         * @type {Event}
         * @readonly
         */
        definitionChanged : {
            get : function() {
                return this._definitionChanged;
            }
        }
    });

    /**
     * Gets the value of the property.
     *
     * @param {JulianDate} [time] The time for which to retrieve the value.  This parameter is unused since the value does not change with respect to time.
     * @param {Object[]} [result] The object to store the value into, if omitted, a new instance is created and returned.
     * @returns {Object[]} The modified result parameter or a new instance if the result parameter was not supplied.
     */
    PropertyArray.prototype.getValue = function(time, result) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(time)) {
            throw new DeveloperError('time is required.');
        }
        //>>includeEnd('debug');

        var value = this._value;
        if (!defined(value)) {
            return undefined;
        }

        var length = value.length;
        if (!defined(result)) {
            result = new Array(length);
        }
        var i = 0;
        var x = 0;
        while (i < length) {
            var property = this._value[i];
            var itemValue = property.getValue(time, result[i]);
            if (defined(itemValue)) {
                result[x] = itemValue;
                x++;
            }
            i++;
        }
        result.length = x;
        return result;
    };

    /**
     * Sets the value of the property.
     *
     * @param {Property[]} value An array of Property instances.
     */
    PropertyArray.prototype.setValue = function(value) {
        var eventHelper = this._eventHelper;
        eventHelper.removeAll();

        if (defined(value)) {
            this._value = value.slice();
            var length = value.length;
            for (var i = 0; i < length; i++) {
                var property = value[i];
                if (defined(property)) {
                    eventHelper.add(property.definitionChanged, PropertyArray.prototype._raiseDefinitionChanged, this);
                }
            }
        } else {
            this._value = undefined;
        }
        this._definitionChanged.raiseEvent(this);
    };

    /**
     * Compares this property to the provided property and returns
     * true if they are equal, false otherwise.
     *
     * @param {Property} [other] The other property.
     * @returns {Boolean} true if left and right are equal, false otherwise.
     */
    PropertyArray.prototype.equals = function(other) {
        return this === other || //
               (other instanceof PropertyArray && //
                Property.arrayEquals(this._value, other._value));
    };

    PropertyArray.prototype._raiseDefinitionChanged = function() {
        this._definitionChanged.raiseEvent(this);
    };

    return PropertyArray;
});
<commit_msg>Update PropertyArray.js<commit_after>/*global define*/
define([
        '../Core/defined',
        '../Core/defineProperties',
        '../Core/DeveloperError',
        '../Core/Event',
        '../Core/EventHelper',
        './Property'
    ], function(
        defined,
        defineProperties,
        DeveloperError,
        Event,
        EventHelper,
        Property) {
    "use strict";

    /**
     * A {@link Property} whose value is an array whose items are the computed value
     * of other property instances.
     *
     * @alias PropertyArray
     * @constructor
     *
     * @param {Property[]} [value] An array of Property instances.
     */
    function PropertyArray(value) {
        this._value = undefined;
        this._definitionChanged = new Event();
        this._eventHelper = new EventHelper();
        this.setValue(value);
    }

    defineProperties(PropertyArray.prototype, {
        /**
         * Gets a value indicating if this property is constant.  This property
         * is considered constant if all property items in the array are constant.
         * @memberof PropertyArray.prototype
         *
         * @type {Boolean}
         * @readonly
         */
        isConstant : {
            get : function() {
                var value = this._value;
                if (!defined(value)) {
                    return true;
                }
                var length = value.length;
                for (var i = 0; i < length; i++) {
                    if (!Property.isConstant(value[i])) {
                        return false;
                    }
                }
                return true;
            }
        },
        /**
         * Gets the event that is raised whenever the definition of this property changes.
         * The definition is changed whenever setValue is called with data different
         * than the current value or one of the properties in the array also changes.
         * @memberof PropertyArray.prototype
         *
         * @type {Event}
         * @readonly
         */
        definitionChanged : {
            get : function() {
                return this._definitionChanged;
            }
        }
    });

    /**
     * Gets the value of the property.
     *
     * @param {JulianDate} time The time for which to retrieve the value.
     * @param {Object[]} [result] The object to store the value into, if omitted, a new instance is created and returned.
     * @returns {Object[]} The modified result parameter, which is an array of values produced by evaluating each of the contained properties at the given time or a new instance if the result parameter was not supplied.
     */
    PropertyArray.prototype.getValue = function(time, result) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(time)) {
            throw new DeveloperError('time is required.');
        }
        //>>includeEnd('debug');

        var value = this._value;
        if (!defined(value)) {
            return undefined;
        }

        var length = value.length;
        if (!defined(result)) {
            result = new Array(length);
        }
        var i = 0;
        var x = 0;
        while (i < length) {
            var property = this._value[i];
            var itemValue = property.getValue(time, result[i]);
            if (defined(itemValue)) {
                result[x] = itemValue;
                x++;
            }
            i++;
        }
        result.length = x;
        return result;
    };

    /**
     * Sets the value of the property.
     *
     * @param {Property[]} value An array of Property instances.
     */
    PropertyArray.prototype.setValue = function(value) {
        var eventHelper = this._eventHelper;
        eventHelper.removeAll();

        if (defined(value)) {
            this._value = value.slice();
            var length = value.length;
            for (var i = 0; i < length; i++) {
                var property = value[i];
                if (defined(property)) {
                    eventHelper.add(property.definitionChanged, PropertyArray.prototype._raiseDefinitionChanged, this);
                }
            }
        } else {
            this._value = undefined;
        }
        this._definitionChanged.raiseEvent(this);
    };

    /**
     * Compares this property to the provided property and returns
     * true if they are equal, false otherwise.
     *
     * @param {Property} [other] The other property.
     * @returns {Boolean} true if left and right are equal, false otherwise.
     */
    PropertyArray.prototype.equals = function(other) {
        return this === other || //
               (other instanceof PropertyArray && //
                Property.arrayEquals(this._value, other._value));
    };

    PropertyArray.prototype._raiseDefinitionChanged = function() {
        this._definitionChanged.raiseEvent(this);
    };

    return PropertyArray;
});
<|endoftext|>


<commit_before>//
//  attachmentItemScript.js
//
//  This script is a simplified version of the original attachmentItemScript.js
//  Copyright 2017 High Fidelity, Inc.
//
//  Distributed under the Apache License, Version 2.0.
//  See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
(function() {
    var shared = Script.require('attachmentZoneShared.js');

    var GRAB_SOUND = SoundCache.getSound(Script.resolvePath('sounds/sound1.wav'));
    var ATTACH_SOUND = SoundCache.getSound(Script.resolvePath('sounds/sound2.wav'));
    var DETACH_SOUND = SoundCache.getSound(Script.resolvePath('sounds/sound7.wav'));

    var LEFT_RIGHT_PLACEHOLDER = '[LR]';
    var ATTACH_DISTANCE = 0.35;
    var RELEASE_LIFETIME = 10;

    var TRIGGER_INTENSITY = 1.0;
    var TRIGGER_TIME = 0.2;

    var EMPTY_PARENT_ID = "{00000000-0000-0000-0000-000000000000}";

    var _entityID;
    var _attachmentData;
    var _supportedJoints = [];
    var isAttached;

    var attachDistance = HMD.active ? (MyAvatar.getHeadPosition().y - MyAvatar.getLeftHandPosition().y) / 2 : ATTACH_DISTANCE;

    function AttachableItem() {

    }

    var attachFunction = function(){
        if (HMD.active) {
            attachDistance = (MyAvatar.getHeadPosition().y - MyAvatar.getLeftHandPosition().y)/2;
        }
    };

    AttachableItem.prototype = {
        preload : function(entityID) {
            _entityID = entityID;
            var properties = Entities.getEntityProperties(entityID, ['parentID', 'userData']);
            var userData = JSON.parse(properties.userData);
            _attachmentData = userData.Attachment;
            var _marketplaceID = userData.marketplaceID;

            if (_attachmentData.joint.indexOf(LEFT_RIGHT_PLACEHOLDER) !== -1) {
                var baseJoint = _attachmentData.joint.substring(4);
                _supportedJoints.push("Left".concat(baseJoint));
                _supportedJoints.push("Right".concat(baseJoint));
            } else {
                _supportedJoints.push(_attachmentData.joint);
            }

            isAttached = _attachmentData.attached;
            Entities.editEntity(entityID, {marketplaceID: _marketplaceID});
            MyAvatar.skeletonChanged.connect(attachFunction);
        },
        unload: function() {
            MyAvatar.skeletonChanged.disconnect(attachFunction);
        },
        startNearGrab: function(entityID, args) {
            if (GRAB_SOUND.downloaded) {
                Audio.playSound(GRAB_SOUND, {
                    position: MyAvatar.position,
                    volume: shared.AUDIO_VOLUME_LEVEL,
                    localOnly: true
                });
            }
            if (Entities.getEntityProperties(entityID, 'visible').visible === false) {
                Entities.editEntity(entityID, {'visible' : true});
            }
        },

        releaseGrab: function(entityID, args) {
            var hand = args[0];
            var properties = Entities.getEntityProperties(entityID, ['parentID', 'userData', 'position']);
            var userData = properties.userData;
            var position = properties.position;
            var attachmentData = JSON.parse(userData).Attachment;
            isAttached = attachmentData.attached;
            if (isAttached) {
                var jointPosition = (properties.parentID === MyAvatar.sessionUUID) ?
                    MyAvatar.getJointPosition(properties.parentJointIndex) :
                    AvatarList.getAvatar(properties.parentID).getJointPosition(properties.parentJointIndex);
                if (Vec3.distance(position, jointPosition) > attachDistance) {
                    var newDetachEntityProperties = Entities.getEntityProperties(entityID);
                    shared.touchJSONUserData(newDetachEntityProperties, function(userData) {
                        userData.Attachment.attached = false;
                    });
                    Entities.editEntity(_entityID, {
                        parentID: EMPTY_PARENT_ID,
                        lifetime: Entities.getEntityProperties(_entityID, 'age').age + RELEASE_LIFETIME,
                        userData: newDetachEntityProperties.userData
                    });
                    if (DETACH_SOUND.downloaded) {
                        Audio.playSound(DETACH_SOUND, {
                            position: MyAvatar.position,
                            volume: shared.AUDIO_VOLUME_LEVEL,
                            localOnly: true
                        });
                    }
                    Controller.triggerHapticPulse(TRIGGER_INTENSITY, TRIGGER_TIME, hand);
                    isAttached = false;
                }
            } else if (!isAttached) {
                _supportedJoints.forEach(function(joint) {
                    var jointPosition = MyAvatar.getJointPosition(joint);
                    if (Vec3.distance(position, jointPosition) <= attachDistance) {
                        // Check that we are not holding onto an arm attachment in a hand
                        if (joint.toLowerCase().indexOf(hand) !== -1) {
                            return;
                        }
                        var newEntityProperties = Entities.getEntityProperties(_entityID, 'userData');
                        shared.touchJSONUserData(newEntityProperties, function(userData) {
                            userData.Attachment.attached = true;
                        });
                        Entities.editEntity(_entityID, {
                            parentID: MyAvatar.sessionUUID,
                            parentJointIndex: MyAvatar.getJointIndex(joint),
                            userData: newEntityProperties.userData,
                            lifetime: -1
                        });
                        if (ATTACH_SOUND.downloaded) {
                            Audio.playSound(ATTACH_SOUND, {
                                position: MyAvatar.position,
                                volume: shared.AUDIO_VOLUME_LEVEL,
                                localOnly: true
                            });
                        }
                        isAttached = true;
                        Controller.triggerHapticPulse(TRIGGER_INTENSITY, TRIGGER_TIME, hand);
                    }
                });
            }
        }
    };
    return new AttachableItem();
});
<commit_msg>Update attachmentItemScript.js<commit_after>//
//  attachmentItemScript.js
//
//  This script is a simplified version of the original attachmentItemScript.js
//  Copyright 2017 High Fidelity, Inc.
//
//  Distributed under the Apache License, Version 2.0.
//  See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
(function() {
    var shared = Script.require('./attachmentZoneShared.js');

    var GRAB_SOUND = SoundCache.getSound(Script.resolvePath('sounds/sound1.wav'));
    var ATTACH_SOUND = SoundCache.getSound(Script.resolvePath('sounds/sound2.wav'));
    var DETACH_SOUND = SoundCache.getSound(Script.resolvePath('sounds/sound7.wav'));

    var LEFT_RIGHT_PLACEHOLDER = '[LR]';
    var ATTACH_DISTANCE = 0.35;
    var RELEASE_LIFETIME = 10;

    var TRIGGER_INTENSITY = 1.0;
    var TRIGGER_TIME = 0.2;

    var EMPTY_PARENT_ID = "{00000000-0000-0000-0000-000000000000}";

    var _entityID;
    var _attachmentData;
    var _supportedJoints = [];
    var isAttached;

    var attachDistance = HMD.active ? (MyAvatar.getHeadPosition().y - MyAvatar.getLeftHandPosition().y) / 2 : ATTACH_DISTANCE;

    function AttachableItem() {

    }

    var attachFunction = function(){
        if (HMD.active) {
            attachDistance = (MyAvatar.getHeadPosition().y - MyAvatar.getLeftHandPosition().y)/2;
        }
    };

    AttachableItem.prototype = {
        preload : function(entityID) {
            _entityID = entityID;
            var properties = Entities.getEntityProperties(entityID, ['parentID', 'userData']);
            var userData = JSON.parse(properties.userData);
            _attachmentData = userData.Attachment;
            var _marketplaceID = userData.marketplaceID;

            if (_attachmentData.joint.indexOf(LEFT_RIGHT_PLACEHOLDER) !== -1) {
                var baseJoint = _attachmentData.joint.substring(4);
                _supportedJoints.push("Left".concat(baseJoint));
                _supportedJoints.push("Right".concat(baseJoint));
            } else {
                _supportedJoints.push(_attachmentData.joint);
            }

            isAttached = _attachmentData.attached;
            Entities.editEntity(entityID, {marketplaceID: _marketplaceID});
            MyAvatar.skeletonChanged.connect(attachFunction);
        },
        unload: function() {
            MyAvatar.skeletonChanged.disconnect(attachFunction);
        },
        startNearGrab: function(entityID, args) {
            if (GRAB_SOUND.downloaded) {
                Audio.playSound(GRAB_SOUND, {
                    position: MyAvatar.position,
                    volume: shared.AUDIO_VOLUME_LEVEL,
                    localOnly: true
                });
            }
            if (Entities.getEntityProperties(entityID, 'visible').visible === false) {
                Entities.editEntity(entityID, {'visible' : true});
            }
        },

        releaseGrab: function(entityID, args) {
            var hand = args[0];
            var properties = Entities.getEntityProperties(entityID, ['parentID', 'userData', 'position']);
            var userData = properties.userData;
            var position = properties.position;
            var attachmentData = JSON.parse(userData).Attachment;
            isAttached = attachmentData.attached;
            if (isAttached) {
                var jointPosition = (properties.parentID === MyAvatar.sessionUUID) ?
                    MyAvatar.getJointPosition(properties.parentJointIndex) :
                    AvatarList.getAvatar(properties.parentID).getJointPosition(properties.parentJointIndex);
                if (Vec3.distance(position, jointPosition) > attachDistance) {
                    var newDetachEntityProperties = Entities.getEntityProperties(entityID);
                    shared.touchJSONUserData(newDetachEntityProperties, function(userData) {
                        userData.Attachment.attached = false;
                    });
                    Entities.editEntity(_entityID, {
                        parentID: EMPTY_PARENT_ID,
                        lifetime: Entities.getEntityProperties(_entityID, 'age').age + RELEASE_LIFETIME,
                        userData: newDetachEntityProperties.userData
                    });
                    if (DETACH_SOUND.downloaded) {
                        Audio.playSound(DETACH_SOUND, {
                            position: MyAvatar.position,
                            volume: shared.AUDIO_VOLUME_LEVEL,
                            localOnly: true
                        });
                    }
                    Controller.triggerHapticPulse(TRIGGER_INTENSITY, TRIGGER_TIME, hand);
                    isAttached = false;
                }
            } else if (!isAttached) {
                _supportedJoints.forEach(function(joint) {
                    var jointPosition = MyAvatar.getJointPosition(joint);
                    if (Vec3.distance(position, jointPosition) <= attachDistance) {
                        // Check that we are not holding onto an arm attachment in a hand
                        if (joint.toLowerCase().indexOf(hand) !== -1) {
                            return;
                        }
                        var newEntityProperties = Entities.getEntityProperties(_entityID, 'userData');
                        shared.touchJSONUserData(newEntityProperties, function(userData) {
                            userData.Attachment.attached = true;
                        });
                        Entities.editEntity(_entityID, {
                            parentID: MyAvatar.sessionUUID,
                            parentJointIndex: MyAvatar.getJointIndex(joint),
                            userData: newEntityProperties.userData,
                            lifetime: -1
                        });
                        if (ATTACH_SOUND.downloaded) {
                            Audio.playSound(ATTACH_SOUND, {
                                position: MyAvatar.position,
                                volume: shared.AUDIO_VOLUME_LEVEL,
                                localOnly: true
                            });
                        }
                        isAttached = true;
                        Controller.triggerHapticPulse(TRIGGER_INTENSITY, TRIGGER_TIME, hand);
                    }
                });
            }
        }
    };
    return new AttachableItem();
});
<|endoftext|>


<commit_before>//
// raffleWheel.js
//
// Created by Rebecca Stankus on 07/05/2018
// Copyright High Fidelity 2018
//
// Licensed under the Apache 2.0 License
// See accompanying license file or http://apache.org/
//
/* global Avatar, AccountServices */

(function() {
    var ANGULAR_VELOCITY = {
        x: 10,
        y: 0,
        z: 0
    };
    var ANGULAR_VELOCITY_CHECK_MS = 50;
    var ANGULAR_VELOCITY_DECREMENT = 0.09;
    var CHECKING_INTERVAL_DELAY = 100;
    var USERS_ALLOWED_TO_SPIN_WHEEL = ['philip', 'ryan', 'Becky', 'MissLiviRose', 'Firebird25', 'Alan_'];
    var MAX_CHAR_PER_LINE = 9;
    var CUT_OFF_1 = 13;
    var CUT_OFF_2 = 18;
    var CUT_OFF_3 = 24;
    var CUT_OFF_4 = 32;
    var LINE_HEIGHT_1 =0.21;
    var LINE_HEIGHT_2 =0.15;
    var LINE_HEIGHT_3 =0.115;
    var LINE_HEIGHT_4 =0.075;
    var DEFAULT_LINE_HEIGHT = 0.3;
    var SHUFFLE_DELAY = 200;

    var _this;

    function shuffle(array) {
        var currentIndex = array.length, temporaryValue, randomIndex;

        while (0 !== currentIndex) {
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
        }
        return array;
    }

    var Wheel = function() {
        _this = this;
    };

    Wheel.prototype = {
        interval: null,
        angularVelocityLimit: 10,
        nameText: null,
        avatarList: [],
        usernameList: [],
        listCounter: 0,

        preload: function(entityID) {
            _this.entityID = entityID;
            Users.usernameFromIDReply.connect(_this.usernameFromIDReply);
        },

        mousePressOnEntity: function(entityID, mouseEvent) {
            if (!mouseEvent.button === "Primary") {
                return;
            }
            var position = Entities.getEntityProperties(_this.entityID, 'position').position;
            var winnerTextEntitiesArray = Entities.findEntitiesByName("Raffle Wheel Winner", position, 1);
            _this.usernameList = [];
            if (USERS_ALLOWED_TO_SPIN_WHEEL.indexOf(AccountServices.username) >= 0) {
                _this.angularVelocityLimit = 10;
                _this.avatarList = AvatarList.getAvatarIdentifiers();
                _this.avatarList.forEach(function(id) {
                    Users.requestUsernameFromID(id);
                });
                Entities.editEntity(_this.entityID, {
                    angularVelocity: ANGULAR_VELOCITY
                });
                Script.setTimeout(function() {
                    shuffle(_this.usernameList);
                }, SHUFFLE_DELAY);
                Script.setTimeout(function() {
                    if (_this.interval) {
                        Script.clearInterval(_this.interval);
                    }
                    var winner;
                    _this.interval = Script.setInterval(function() {
                        var lineHeight;
                        var currentAngularVelocity = Entities.getEntityProperties(
                            _this.entityID, 'angularVelocity').angularVelocity;
                        if (currentAngularVelocity.x <= _this.angularVelocityLimit && currentAngularVelocity.x > 0) {
                            winner = _this.usernameList[_this.listCounter];
                            if (winner.length <= MAX_CHAR_PER_LINE) {
                                lineHeight = DEFAULT_LINE_HEIGHT;
                            } else if (winner.length <= CUT_OFF_1) {
                                lineHeight = LINE_HEIGHT_1;
                            } else if (winner.length <= CUT_OFF_2) {
                                lineHeight = LINE_HEIGHT_2;
                            } else if (winner.length <= CUT_OFF_3) {
                                lineHeight = LINE_HEIGHT_3;
                            } else if (winner.length <= CUT_OFF_4) {
                                lineHeight = LINE_HEIGHT_4;
                            } else {
                                winner = winner.slice(0, CUT_OFF_4 + 1);
                            }
                            Entities.editEntity(winnerTextEntitiesArray[0], {
                                lineHeight: lineHeight,
                                text: winner
                            });
                            _this.listCounter += 1;
                            _this.listCounter = _this.listCounter >= _this.usernameList.length ? 0 : _this.listCounter;
                            _this.angularVelocityLimit -= ANGULAR_VELOCITY_DECREMENT;
                        } else if (currentAngularVelocity.x === 0) {
                            if (_this.interval) {
                                // this print is purposely left as a backup way to see winner via logs
                                print("-------------RAFFLE WINNER IS: ", winner);
                                Script.clearInterval(_this.interval);
                            }
                        }
                    }, ANGULAR_VELOCITY_CHECK_MS);
                }, CHECKING_INTERVAL_DELAY);
            }
        },

        usernameFromIDReply: function(nodeID, userName, machineFingerprint, isAdmin) {
            _this.usernameList.push(userName);
        },

        unload: function(entityID) {
            if (_this.interval) {
                Script.clearInterval(_this.interval);
            }
        }
    };

    return new Wheel();
});
<commit_msg>fixed order of shuffle comparison<commit_after>//
// raffleWheel.js
//
// Created by Rebecca Stankus on 07/05/2018
// Copyright High Fidelity 2018
//
// Licensed under the Apache 2.0 License
// See accompanying license file or http://apache.org/
//
/* global Avatar, AccountServices */

(function() {
    var ANGULAR_VELOCITY = {
        x: 10,
        y: 0,
        z: 0
    };
    var ANGULAR_VELOCITY_CHECK_MS = 50;
    var ANGULAR_VELOCITY_DECREMENT = 0.09;
    var CHECKING_INTERVAL_DELAY = 100;
    var USERS_ALLOWED_TO_SPIN_WHEEL = ['philip', 'ryan', 'Becky', 'MissLiviRose', 'Firebird25', 'Alan_'];
    var MAX_CHAR_PER_LINE = 9;
    var CUT_OFF_1 = 13;
    var CUT_OFF_2 = 18;
    var CUT_OFF_3 = 24;
    var CUT_OFF_4 = 32;
    var LINE_HEIGHT_1 =0.21;
    var LINE_HEIGHT_2 =0.15;
    var LINE_HEIGHT_3 =0.115;
    var LINE_HEIGHT_4 =0.075;
    var DEFAULT_LINE_HEIGHT = 0.3;
    var SHUFFLE_DELAY = 200;

    var _this;

    function shuffle(array) {
        var currentIndex = array.length, temporaryValue, randomIndex;

        while (currentIndex !== 0) {
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
        }
        return array;
    }

    var Wheel = function() {
        _this = this;
    };

    Wheel.prototype = {
        interval: null,
        angularVelocityLimit: 10,
        nameText: null,
        avatarList: [],
        usernameList: [],
        listCounter: 0,

        preload: function(entityID) {
            _this.entityID = entityID;
            Users.usernameFromIDReply.connect(_this.usernameFromIDReply);
        },

        mousePressOnEntity: function(entityID, mouseEvent) {
            if (!mouseEvent.button === "Primary") {
                return;
            }
            var position = Entities.getEntityProperties(_this.entityID, 'position').position;
            var winnerTextEntitiesArray = Entities.findEntitiesByName("Raffle Wheel Winner", position, 1);
            _this.usernameList = [];
            if (USERS_ALLOWED_TO_SPIN_WHEEL.indexOf(AccountServices.username) >= 0) {
                _this.angularVelocityLimit = 10;
                _this.avatarList = AvatarList.getAvatarIdentifiers();
                _this.avatarList.forEach(function(id) {
                    Users.requestUsernameFromID(id);
                });
                Entities.editEntity(_this.entityID, {
                    angularVelocity: ANGULAR_VELOCITY
                });
                Script.setTimeout(function() {
                    shuffle(_this.usernameList);
                }, SHUFFLE_DELAY);
                Script.setTimeout(function() {
                    if (_this.interval) {
                        Script.clearInterval(_this.interval);
                    }
                    var winner;
                    _this.interval = Script.setInterval(function() {
                        var lineHeight;
                        var currentAngularVelocity = Entities.getEntityProperties(
                            _this.entityID, 'angularVelocity').angularVelocity;
                        if (currentAngularVelocity.x <= _this.angularVelocityLimit && currentAngularVelocity.x > 0) {
                            winner = _this.usernameList[_this.listCounter];
                            if (winner.length <= MAX_CHAR_PER_LINE) {
                                lineHeight = DEFAULT_LINE_HEIGHT;
                            } else if (winner.length <= CUT_OFF_1) {
                                lineHeight = LINE_HEIGHT_1;
                            } else if (winner.length <= CUT_OFF_2) {
                                lineHeight = LINE_HEIGHT_2;
                            } else if (winner.length <= CUT_OFF_3) {
                                lineHeight = LINE_HEIGHT_3;
                            } else if (winner.length <= CUT_OFF_4) {
                                lineHeight = LINE_HEIGHT_4;
                            } else {
                                winner = winner.slice(0, CUT_OFF_4 + 1);
                            }
                            Entities.editEntity(winnerTextEntitiesArray[0], {
                                lineHeight: lineHeight,
                                text: winner
                            });
                            _this.listCounter += 1;
                            _this.listCounter = _this.listCounter >= _this.usernameList.length ? 0 : _this.listCounter;
                            _this.angularVelocityLimit -= ANGULAR_VELOCITY_DECREMENT;
                        } else if (currentAngularVelocity.x === 0) {
                            if (_this.interval) {
                                // this print is purposely left as a backup way to see winner via logs
                                print("-------------RAFFLE WINNER IS: ", winner);
                                Script.clearInterval(_this.interval);
                            }
                        }
                    }, ANGULAR_VELOCITY_CHECK_MS);
                }, CHECKING_INTERVAL_DELAY);
            }
        },

        usernameFromIDReply: function(nodeID, userName, machineFingerprint, isAdmin) {
            _this.usernameList.push(userName);
        },

        unload: function(entityID) {
            if (_this.interval) {
                Script.clearInterval(_this.interval);
            }
        }
    };

    return new Wheel();
});
<|endoftext|>


<commit_before>// Test the widget framework.
casper.notebook_test(function () {
    var index;

    // Test widget dependencies ////////////////////////////////////////////////
    this.then(function () {

        // Check if the WidgetManager class is defined.
        this.test.assert(this.evaluate(function() {
            return IPython.WidgetManager != undefined;
        }), 'WidgetManager class is defined');
    });

    index = append_cell(
        'from IPython.html import widgets\n' +
        'from IPython.display import display, clear_output\n' +
        'print("Success")');
    execute_cell_then(index);

    this.wait(500); // Wait for require.js async callbacks to load dependencies.

    this.then(function () {
        // Check if the widget manager has been instanciated.
        this.test.assert(this.evaluate(function() {
            return IPython.widget_manager != undefined;
        }), 'Notebook widget manager instanciated');
    });

    // Check widget mapping ////////////////////////////////////////////////////
    index = append_cell(
        'names = [name for name in dir(widgets)' +
        ' if name.endswith("Widget") and name!= "Widget"]\n' +
        'for name in names:\n' +
        '    print(name)\n');
    execute_cell_then(index, function(index){

        // Get the widget names that are registered with the widget manager.  Assume
        // a 1 to 1 mapping of model and widgets names (model names just have 'model'
        // suffixed).
        var javascript_names = this.evaluate(function () {
            names = [];
            for (var name in IPython.widget_manager.widget_model_types) {
                names.push(name.replace('Model',''));
            }
            return names;
        });

        // Get the widget names registered in python.
        var python_names = this.get_output_cell(index).text.split('\n');

        // Make sure the two lists have the same items.
        for (var i in javascript_names) {
            var javascript_name = javascript_names[i];
            var found = false;
            for (var j in python_names) {
                var python_name = python_names[j];
                if (python_name==javascript_name) {
                    found = true;
                    break;
                }
            }
            this.test.assert(found, javascript_name + ' exists in python');
        }
        for (var i in python_names) {
            var python_name = python_names[i];
            if (python_name.length > 0) {
                var found = false;
                for (var j in javascript_names) {
                    var javascript_name = javascript_names[j];
                    if (python_name==javascript_name) {
                        found = true;
                        break;
                    }
                }
                this.test.assert(found, python_name + ' exists in javascript');
            }
        }
    });

    // Test button widget //////////////////////////////////////////////////////
    var button_cell_index = append_cell(
        'button = widgets.ButtonWidget(description="Title")\n' +
        'display(button)\n'+
        'print("Success")\n' +
        'def handle_click(sender):\n' +
        '    print("Clicked")\n' +
        'button.on_click(handle_click)');
    execute_cell_then(button_cell_index, function(index){

        var button_output = this.get_output_cell(index).text;
        this.test.assert(button_output == 'Success\n',
            'Create button widget, cell executed with correct output.');

        this.test.assert(cell_element_exists(index,
            '.widget-area .widget-subarea'),
            'Create button widget, widget subarea exist.');

        this.test.assert(cell_element_exists(index,
            '.widget-area .widget-subarea button'),
            'Create button widget, widget button exist.');

        this.test.assert(cell_element_function(index,
            '.widget-area .widget-subarea button', 'html')=='Title',
            'Set button description.');

        cell_element_function(index,
            '.widget-area .widget-subarea button', 'click');
    });

    this.wait(500); // Wait for click to execute in kernel and write output

    this.then(function () {
        this.test.assert(this.get_output_cell(button_cell_index, 1).text == 'Clicked\n',
            'Button click event fires.');
    });

    index = append_cell(
        'button.close()\n'+
        'print("Success")\n');
    execute_cell_then(index, function(index){

        var button_output = this.get_output_cell(index).text;
        this.test.assert(button_output == 'Success\n',
            'Close button, cell executed with correct output.');

        this.test.assert(! cell_element_exists(button_cell_index,
            '.widget-area .widget-subarea button'),
            'Remove button, widget button doesn\'t exist.');
    });
});

<commit_msg>Make widget tests use new casper util functions<commit_after>// Test the widget framework.
casper.notebook_test(function () {
    var index;

    // Test widget dependencies ////////////////////////////////////////////////
    this.then(function () {

        // Check if the WidgetManager class is defined.
        this.test.assert(this.evaluate(function() {
            return IPython.WidgetManager != undefined;
        }), 'WidgetManager class is defined');
    });

    index = this.append_cell(
        'from IPython.html import widgets\n' +
        'from IPython.display import display, clear_output\n' +
        'print("Success")');
    this.execute_cell_then(index);

    this.wait(500); // Wait for require.js async callbacks to load dependencies.

    this.then(function () {
        // Check if the widget manager has been instanciated.
        this.test.assert(this.evaluate(function() {
            return IPython.widget_manager != undefined;
        }), 'Notebook widget manager instanciated');
    });

    // Check widget mapping ////////////////////////////////////////////////////
    index = this.append_cell(
        'names = [name for name in dir(widgets)' +
        ' if name.endswith("Widget") and name!= "Widget"]\n' +
        'for name in names:\n' +
        '    print(name)\n');
    this.execute_cell_then(index, function(index){

        // Get the widget names that are registered with the widget manager.  Assume
        // a 1 to 1 mapping of model and widgets names (model names just have 'model'
        // suffixed).
        var javascript_names = this.evaluate(function () {
            names = [];
            for (var name in IPython.widget_manager.widget_model_types) {
                names.push(name.replace('Model',''));
            }
            return names;
        });

        // Get the widget names registered in python.
        var python_names = this.get_output_cell(index).text.split('\n');

        // Make sure the two lists have the same items.
        for (var i in javascript_names) {
            var javascript_name = javascript_names[i];
            var found = false;
            for (var j in python_names) {
                var python_name = python_names[j];
                if (python_name==javascript_name) {
                    found = true;
                    break;
                }
            }
            this.test.assert(found, javascript_name + ' exists in python');
        }
        for (var i in python_names) {
            var python_name = python_names[i];
            if (python_name.length > 0) {
                var found = false;
                for (var j in javascript_names) {
                    var javascript_name = javascript_names[j];
                    if (python_name==javascript_name) {
                        found = true;
                        break;
                    }
                }
                this.test.assert(found, python_name + ' exists in javascript');
            }
        }
    });

    // Test button widget //////////////////////////////////////////////////////
    var button_index = this.append_cell(
        'button = widgets.ButtonWidget(description="Title")\n' +
        'display(button)\n'+
        'print("Success")\n' +
        'def handle_click(sender):\n' +
        '    print("Clicked")\n' +
        'button.on_click(handle_click)');
    this.execute_cell_then(button_index, function(index){

        var button_output = this.get_output_cell(index).text;
        this.test.assert(button_output == 'Success\n',
            'Create button widget, cell executed with correct output.');

        this.test.assert(this.cell_element_exists(index,
            '.widget-area .widget-subarea'),
            'Create button widget, widget subarea exist.');

        this.test.assert(this.cell_element_exists(index,
            '.widget-area .widget-subarea button'),
            'Create button widget, widget button exist.');

        this.test.assert(this.cell_element_function(index,
            '.widget-area .widget-subarea button', 'html')=='Title',
            'Set button description.');

        this.cell_element_function(index,
            '.widget-area .widget-subarea button', 'click');
    });

    this.wait(500); // Wait for click to execute in kernel and write output

    this.then(function () {
        this.test.assert(this.get_output_cell(button_index, 1).text == 'Clicked\n',
            'Button click event fires.');
    });

    index = this.append_cell(
        'button.close()\n'+
        'print("Success")\n');
    this.execute_cell_then(index, function(index){

        var button_output = this.get_output_cell(index).text;
        this.test.assert(button_output == 'Success\n',
            'Close button, cell executed with correct output.');

        this.test.assert(! this.cell_element_exists(button_index,
            '.widget-area .widget-subarea button'),
            'Remove button, widget button doesn\'t exist.');
    });
});

<|endoftext|>


<commit_before>import React from 'react';
import { Dimensions, AppRegistry, StyleSheet, View } from 'react-native';
import { SceneNavigator, spring } from 'navigation-react-native';
import createStateNavigator from './createStateNavigator';

const stateNavigator = createStateNavigator();

const getStyle = (translate, scale, opacity) => ({
  translate: spring(translate),
  scale: spring(scale),
  opacity: spring(opacity)
});

export default Twitter = () => (
  <View>
    <SceneNavigator
      startStateKey="home"
      unmountedStyle={getStyle(1, 1, 1)}
      mountedStyle={getStyle(0, 1, 1)}
      crumbStyle={getStyle(0.05, 0.9, 0)}
      stateNavigator={stateNavigator}>
      {({translate, scale, opacity}, scene, active) => (
          <Scene
            scale={scale}
            translate={translate}
            opacity={opacity}
            pointerEvents={active ? 'auto' : 'none'}
            dimensions={Dimensions.get('window')}>
            {scene}
          </Scene>
      )}
    </SceneNavigator>
  </View>
);

const Scene = ({translate, scale, opacity, pointerEvents,
  dimensions: {width, height}, children}) => (
  <View
    pointerEvents={pointerEvents}
    style={[
      styles.scene,
      {
        width: width,
        height: height,
        opacity: opacity,
        transform: [
          {translateX: width * translate},
          {scale: scale},
        ]
      }
    ]}>
    {children}
  </View>
);

const styles = StyleSheet.create({
  scene: {
    backgroundColor: 'white',
    position: 'absolute',
  }
});

AppRegistry.registerComponent('twitter', () => Twitter);
<commit_msg>Rendered a permanent, fixed height footer<commit_after>import React from 'react';
import { Dimensions, AppRegistry, StyleSheet, View } from 'react-native';
import { SceneNavigator, spring } from 'navigation-react-native';
import createStateNavigator from './createStateNavigator';

const stateNavigator = createStateNavigator();

const getStyle = (translate, scale, opacity) => ({
  translate: spring(translate),
  scale: spring(scale),
  opacity: spring(opacity)
});

export default Twitter = () => (
  <View style={styles.app}>
    <SceneNavigator
      startStateKey="home"
      unmountedStyle={getStyle(1, 1, 1)}
      mountedStyle={getStyle(0, 1, 1)}
      crumbStyle={getStyle(0.05, 0.9, 0)}
      stateNavigator={stateNavigator}>
      {({translate, scale, opacity}, scene, active) => (
          <Scene
            scale={scale}
            translate={translate}
            opacity={opacity}
            pointerEvents={active ? 'auto' : 'none'}
            dimensions={Dimensions.get('window')}>
            {scene}
          </Scene>
      )}
    </SceneNavigator>
    <Footer />
  </View>
);

const Scene = ({translate, scale, opacity, pointerEvents,
  dimensions: {width, height}, children}) => (
  <View
    pointerEvents={pointerEvents}
    style={[
      styles.scene,
      {
        width: width,
        height: height -70,
        opacity: opacity,
        transform: [
          {translateX: width * translate},
          {scale: scale},
        ]
      }
    ]}>
    {children}
  </View>
);

const Footer = () => (
  <View style={styles.footer}>
  </View>
);

const styles = StyleSheet.create({
  app: {
    flexDirection: 'row',
    flex: 1,
  },
  scene: {
    backgroundColor: 'white',
    position: 'absolute',
  },
  footer: {
    alignSelf: 'flex-end',
    flex: 1,
    height: 70,
    backgroundColor: 'white',
  },
});

AppRegistry.registerComponent('twitter', () => Twitter);
<|endoftext|>


<commit_before>/**
 * Created by ksinger on 10.05.2016.
 */

import angular from "angular";
import postShareLinkModule from "./post-share-link.js";
import { attach } from "../utils.js";
import won from "../won-es6.js";
import { labels, relativeTime } from "../won-label-utils.js";
import { connect2Redux } from "../won-utils.js";
import { selectLastUpdateTime } from "../selectors.js";
import { actionCreators } from "../actions/actions.js";

const serviceDependencies = ["$ngRedux", "$scope", "$element"];
function genComponentConf() {
  let template = `

              Created

              {{ self.friendlyTimestamp }}

              Type

              {{self.labels.type[self.post.get('type')]}}{{self.post.get('matchingContexts')? ' in '+ self.post.get('matchingContexts').join(', ') : '' }}

              Flags

              {{ self.labels.flags[flag]? self.labels.flags[flag] : flag }}

      <won-post-share-link
        ng-if="!(self.post.get('state') === self.WON.InactiveCompacted || self.post.get('isWhatsAround') || self.post.get('isWhatsNew'))"
        post-uri="self.post.get('uri')">
      </won-post-share-link>
    `;

  class Controller {
    constructor() {
      attach(this, serviceDependencies, arguments);

      this.labels = labels;

      const selectFromState = state => {
        const post = this.postUri && state.getIn(["needs", this.postUri]);
        const hasFlags = post && post.get("hasFlags");

        return {
          WON: won.WON,
          post,
          type: post && post.get("type"),
          hasFlags,
          friendlyTimestamp:
            post &&
            relativeTime(selectLastUpdateTime(state), post.get("creationDate")),
        };
      };
      connect2Redux(selectFromState, actionCreators, ["self.postUri"], this);
    }
  }

  Controller.$inject = serviceDependencies;
  return {
    restrict: "E",
    controller: Controller,
    controllerAs: "self",
    bindToController: true, //scope-bindings -> ctrl
    template: template,
    scope: {
      postUri: "=",
    },
  };
}

export default angular
  .module("won.owner.components.postContentGeneral", [postShareLinkModule])
  .directive("wonPostContentGeneral", genComponentConf).name;
<commit_msg>prevent sharing of posts that have NoHintForCounterpart (as they would probably not ever be found with a matcher either)<commit_after>/**
 * Created by ksinger on 10.05.2016.
 */

import angular from "angular";
import postShareLinkModule from "./post-share-link.js";
import { attach } from "../utils.js";
import won from "../won-es6.js";
import { labels, relativeTime } from "../won-label-utils.js";
import { connect2Redux } from "../won-utils.js";
import { selectLastUpdateTime } from "../selectors.js";
import { actionCreators } from "../actions/actions.js";

const serviceDependencies = ["$ngRedux", "$scope", "$element"];
function genComponentConf() {
  let template = `

              Created

              {{ self.friendlyTimestamp }}

              Type

              {{self.labels.type[self.post.get('type')]}}{{self.post.get('matchingContexts')? ' in '+ self.post.get('matchingContexts').join(', ') : '' }}

 0">

              Flags

              {{ self.labels.flags[flag]? self.labels.flags[flag] : flag }}

      <won-post-share-link
        ng-if="!self.preventSharing"
        post-uri="self.post.get('uri')">
      </won-post-share-link>
    `;

  class Controller {
    constructor() {
      attach(this, serviceDependencies, arguments);
      window.pcg4dbg = this;
      this.labels = labels;

      const selectFromState = state => {
        const post = this.postUri && state.getIn(["needs", this.postUri]);
        const hasFlags = post && post.get("hasFlags");

        return {
          WON: won.WON,
          post,
          type: post && post.get("type"),
          hasFlags,
          preventSharing:
            (post && post.get("state") === won.WON.InactiveCompacted) ||
            (hasFlags &&
              hasFlags.filter(
                flag => flag === won.WON.NoHintForCounterpartCompacted
              ).size > 0),
          friendlyTimestamp:
            post &&
            relativeTime(selectLastUpdateTime(state), post.get("creationDate")),
        };
      };
      connect2Redux(selectFromState, actionCreators, ["self.postUri"], this);
    }
  }

  Controller.$inject = serviceDependencies;
  return {
    restrict: "E",
    controller: Controller,
    controllerAs: "self",
    bindToController: true, //scope-bindings -> ctrl
    template: template,
    scope: {
      postUri: "=",
    },
  };
}

export default angular
  .module("won.owner.components.postContentGeneral", [postShareLinkModule])
  .directive("wonPostContentGeneral", genComponentConf).name;
<|endoftext|>


<commit_before>define(["Tone/core/Tone", "Tone/component/ScaledEnvelope", "Tone/component/Envelope"],
	function(Tone){

	"use strict";

	/**
	 *  @class Tone.FrequencyEnvelope is a Tone.ScaledEnvelope, but instead of `min` and `max`
	 *         it's got a `baseFrequency` and `octaves` parameter. Also the exponent is
	 *         hard-coded at 2.
	 *
	 *  @extends {Tone.Envelope}
	 *  @constructor
	 *  @param {Time|Object} [attack]	the attack time in seconds
	 *  @param {Time} [decay]	the decay time in seconds
	 *  @param {number} [sustain] 	a percentage (0-1) of the full amplitude
	 *  @param {Time} [release]	the release time in seconds
	 *  @example
	 *  var env = new Tone.FrequencyEnvelope({
	 *  	"attack" : 0.2,
	 *  	"baseFrequency" : "C2",
	 *  	"octaves" : 4
	 *  });
	 *  scaledEnv.connect(oscillator.frequency);
	 */
	Tone.FrequencyEnvelope = function(){

		var options = this.optionsObject(arguments, ["attack", "decay", "sustain", "release"], Tone.Envelope.defaults);
		options.exponent = 2;
		Tone.ScaledEnvelope.call(this, options);
		options = this.defaultArg(options, Tone.FrequencyEnvelope.defaults);

		/**
		 *  Stores the octave value
		 *  @type {Positive}
		 *  @private
		 */
		this._octaves = options.octaves;

		//setup
		this.baseFrequency = options.baseFrequency;
		this.octaves = options.octaves;
	};

	Tone.extend(Tone.FrequencyEnvelope, Tone.Envelope);

	/**
	 *  the default parameters
	 *  @static
	 */
	Tone.FrequencyEnvelope.defaults = {
		"baseFrequency" : 200,
		"octaves" : 4,
	};

	/**
	 * The envelope's mininum output value. This is the value which it
	 * starts at.
	 * @memberOf Tone.FrequencyEnvelope#
	 * @type {Frequencye}
	 * @name baseFrequency
	 */
	Object.defineProperty(Tone.FrequencyEnvelope.prototype, "baseFrequency", {
		get : function(){
			return this._scale.min;
		},
		set : function(min){
			this._scale.min = this.toFrequency(min);
		}
	});

	/**
	 * The number of octaves above the baseFrequency that the
	 * envelope will scale to.
	 * @memberOf Tone.FrequencyEnvelope#
	 * @type {Positive}
	 * @name octaves
	 */
	Object.defineProperty(Tone.FrequencyEnvelope.prototype, "octaves", {
		get : function(){
			return this._octaves;
		},
		set : function(octaves){
			this._octaves = octaves;
			this._scale.max = this.baseFrequency * Math.pow(2, octaves);
		}
	});

	/**
	 *  clean up
	 *  @returns {Tone.FrequencyEnvelope} this
	 */
	Tone.FrequencyEnvelope.prototype.dispose = function(){
		Tone.ScaledEnvelope.prototype.dispose.call(this);
		return this;
	};

	return Tone.FrequencyEnvelope;
});<commit_msg>exposing exponent value<commit_after>define(["Tone/core/Tone", "Tone/component/ScaledEnvelope", "Tone/component/Envelope"],
	function(Tone){

	"use strict";

	/**
	 *  @class Tone.FrequencyEnvelope is a Tone.ScaledEnvelope, but instead of `min` and `max`
	 *         it's got a `baseFrequency` and `octaves` parameter.
	 *
	 *  @extends {Tone.Envelope}
	 *  @constructor
	 *  @param {Time|Object} [attack]	the attack time in seconds
	 *  @param {Time} [decay]	the decay time in seconds
	 *  @param {number} [sustain] 	a percentage (0-1) of the full amplitude
	 *  @param {Time} [release]	the release time in seconds
	 *  @example
	 *  var env = new Tone.FrequencyEnvelope({
	 *  	"attack" : 0.2,
	 *  	"baseFrequency" : "C2",
	 *  	"octaves" : 4
	 *  });
	 *  scaledEnv.connect(oscillator.frequency);
	 */
	Tone.FrequencyEnvelope = function(){

		var options = this.optionsObject(arguments, ["attack", "decay", "sustain", "release"], Tone.Envelope.defaults);
		Tone.ScaledEnvelope.call(this, options);
		options = this.defaultArg(options, Tone.FrequencyEnvelope.defaults);

		/**
		 *  Stores the octave value
		 *  @type {Positive}
		 *  @private
		 */
		this._octaves = options.octaves;

		//setup
		this.baseFrequency = options.baseFrequency;
		this.octaves = options.octaves;
	};

	Tone.extend(Tone.FrequencyEnvelope, Tone.Envelope);

	/**
	 *  the default parameters
	 *  @static
	 */
	Tone.FrequencyEnvelope.defaults = {
		"baseFrequency" : 200,
		"octaves" : 4,
		"exponent" : 2
	};

	/**
	 * The envelope's mininum output value. This is the value which it
	 * starts at.
	 * @memberOf Tone.FrequencyEnvelope#
	 * @type {Frequency}
	 * @name baseFrequency
	 */
	Object.defineProperty(Tone.FrequencyEnvelope.prototype, "baseFrequency", {
		get : function(){
			return this._scale.min;
		},
		set : function(min){
			this._scale.min = this.toFrequency(min);
		}
	});

	/**
	 * The number of octaves above the baseFrequency that the
	 * envelope will scale to.
	 * @memberOf Tone.FrequencyEnvelope#
	 * @type {Positive}
	 * @name octaves
	 */
	Object.defineProperty(Tone.FrequencyEnvelope.prototype, "octaves", {
		get : function(){
			return this._octaves;
		},
		set : function(octaves){
			this._octaves = octaves;
			this._scale.max = this.baseFrequency * Math.pow(2, octaves);
		}
	});

	/**
	 * The envelope's exponent value.
	 * @memberOf Tone.FrequencyEnvelope#
	 * @type {number}
	 * @name exponent
	 */
	Object.defineProperty(Tone.FrequencyEnvelope.prototype, "exponent", {
		get : function(){
			return this._exp.value;
		},
		set : function(exp){
			this._exp.value = exp;
		}
	});

	/**
	 *  clean up
	 *  @returns {Tone.FrequencyEnvelope} this
	 */
	Tone.FrequencyEnvelope.prototype.dispose = function(){
		Tone.ScaledEnvelope.prototype.dispose.call(this);
		return this;
	};

	return Tone.FrequencyEnvelope;
});<|endoftext|>


<commit_before>Ext.define('devilry.extjshelpers.studentsmanager.StudentsManager', {
    extend: 'Ext.panel.Panel',
    alias: 'widget.studentsmanager',
    cls: 'studentsmanager',
    layout: 'border',

    requires: [
        'devilry.extjshelpers.studentsmanager.FilterSelector',
        'devilry.extjshelpers.studentsmanager.StudentsGrid',
        'devilry.extjshelpers.SearchField'
    ],

    config: {
        assignmentgroupstore: undefined,
        assignmentid: undefined
    },

    constructor: function(config) {
        this.callParent([config]);
        this.initConfig(config);
    },

    initComponent: function() {
        Ext.apply(this, {
            items: [{
                region: 'north',     // position for region
                xtype: 'panel',
                height: 100,
                //html: 'Search will go here'
                layout: { //Layout spec of underlying components
                    type: 'vbox',
                    align: 'center'
                },
                items: [{
                    xtype: 'searchfield',
                    width: 600,
                    height: 40,
                    padding: '30 0 0 0'

                }]
            },{
                region:'west',
                xtype: 'panel',
                width: 200,
                layout: 'fit',
                tbar: [{
                    xtype: 'button',
                    text: 'Add more students',
                    iconCls: 'icon-add-32',
                    scale: 'large'
                }],
                items: [{
                    xtype: 'studentsmanager_filterselector'
                }]
            },{
                region: 'center',     // center region is required, no width/height specified
                xtype: 'panel',
                layout: 'fit',
                items: [{
                    xtype: 'studentsmanager_studentsgrid',
                    store: this.assignmentgroupstore,
                    assignmentid: this.assignmentid
                }],

                bbar: ['->', {
                    xtype: 'button',
                    scale: 'medium',
                    text: 'Give feedback to selected'
                }, {
                    xtype: 'button',
                    scale: 'medium',
                    text: 'Statistics'
                }]
            }],

        });
        this.callParent(arguments);
    }
});
<commit_msg>C:/Program Files (x86)/Git/devilry/apps/extjshelpers/ added events<commit_after>Ext.define('devilry.extjshelpers.studentsmanager.StudentsManager', {
    extend: 'Ext.panel.Panel',
    alias: 'widget.studentsmanager',
    cls: 'studentsmanager',
    layout: 'border',

    requires: [
        'devilry.extjshelpers.studentsmanager.FilterSelector',
        'devilry.extjshelpers.studentsmanager.StudentsGrid',
        'devilry.extjshelpers.SearchField'
    ],

    config: {
        assignmentgroupstore: undefined,
        assignmentid: undefined
    },

    constructor: function(config) {
        this.callParent([config]);
        this.initConfig(config);
    },

    initComponent: function() {
        Ext.apply(this, {
            items: [{
                region: 'north',     // position for region
                xtype: 'panel',
                height: 100,
                //html: 'Search will go here'
                layout: { //Layout spec of underlying components
                    type: 'vbox',
                    align: 'center'
                },
                items: [{
                    xtype: 'searchfield',
                    id: 'foo',
                    width: 600,
                    height: 40,
                    padding: '30 0 0 0'

                }]
            },{
                region:'west',
                xtype: 'panel',
                width: 200,
                layout: 'fit',
                tbar: [{
                    xtype: 'button',
                    text: 'Add more students',
                    iconCls: 'icon-add-32',
                    scale: 'large'
                }],
                items: [{
                    xtype: 'studentsmanager_filterselector'
                }]
            },{
                region: 'center',     // center region is required, no width/height specified
                xtype: 'panel',
                layout: 'fit',
                items: [{
                    xtype: 'studentsmanager_studentsgrid',
                    store: this.assignmentgroupstore,
                    assignmentid: this.assignmentid
                }],

                bbar: ['->', {
                    xtype: 'button',
                    scale: 'medium',
                    text: 'Give feedback to selected'
                }, {
                    xtype: 'button',
                    scale: 'medium',
                    text: 'Statistics'
                }]
            }],

        });
        this.callParent(arguments);
        this.setSearchfieldAttributes();
    },

    setSearchfieldAttributes: function() {
        var search_field = this.down('searchfield');

        search_field.addListener('newSearchValue', function(value) {
            console.log("StudentManager: " + value);
        });

        search_field.addListener('emptyInput', function() {
            console.log("StudentManager: Nil");
        });

    }

});
<|endoftext|>


<commit_before>function CreateRequisitionController($scope, requisition, currency, rnrColumns, $location, Requisitions, $routeParams, $rootScope) {

  $scope.showNonFullSupply = $routeParams.supplyType == 'non-full-supply';
  $scope.baseUrl = "/create-rnr/" + $routeParams.facility + '/' + $routeParams.program + '/' + $routeParams.period;
  $scope.fullSupplyLink = $scope.baseUrl + "?supplyType=full-supply&page=1";
  $scope.nonFullSupplyLink = $scope.baseUrl + "?supplyTpe=non-full-supply&page=1";
  $scope.pageSize = 10;

  $scope.fillPagedGridData = function () {
    var gridLineItems = $scope.showNonFullSupply ? $scope.rnr.nonFullSupplyLineItems : $scope.rnr.lineItems;
    $scope.numberOfPages = Math.ceil(gridLineItems.length / $scope.pageSize)? Math.ceil(gridLineItems.length / $scope.pageSize): 1;
    $scope.currentPage = (utils.isValidPage($routeParams.page, $scope.numberOfPages)) ? parseInt($routeParams.page, 10) : 1;
    $scope.pageLineItems = gridLineItems.slice(($scope.pageSize * ($scope.currentPage - 1)), $scope.pageSize * $scope.currentPage);
  };

  $scope.rnr = requisition;
  $scope.visibleColumns = _.where(rnrColumns, {'visible':true});
  $scope.programRnrColumnList = rnrColumns;
  $scope.addNonFullSupplyLineItemButtonShown = _.findWhere($scope.programRnrColumnList, {'name':'quantityRequested'});

  prepareRnr();

  $scope.currency = currency;

  if ($scope.programRnrColumnList && $scope.programRnrColumnList.length > 0) {
  } else {
    $scope.error = "rnr.template.not.defined.error";
    $location.path("/init-rnr");
  }

  $scope.currentPage = ($routeParams.page) ? parseInt($routeParams.page) || 1 : 1;

  $scope.switchSupplyType = function (supplyType) {
    $scope.showNonFullSupply = supplyType == 'non-full-supply';
    $location.search('page', 1);
    $location.search('supplyType', supplyType);
  };

  $scope.$on('$routeUpdate', function () {
    $scope.fillPagedGridData();
    if ($scope.saveRnrForm.$dirty) $scope.saveRnr();
  });

  $scope.$watch("currentPage", function () {
    $location.search("page", $scope.currentPage);
  });

  $scope.periodDisplayName = function () {
    if (!$scope.rnr) return;

    var startDate = new Date($scope.rnr.period.startDate);

    var endDate = new Date($scope.rnr.period.endDate);
    return utils.getFormattedDate(startDate) + ' - ' + utils.getFormattedDate(endDate);
  };

  $scope.saveRnr = function () {
    resetFlags();
    var rnr = removeExtraDataForPostFromRnr();
    Requisitions.update({id:$scope.rnr.id, operation:"save"}, rnr, function (data) {
      $scope.message = data.success;
      setTimeout(function () {
        $scope.$apply(function () {
          angular.element("#saveSuccessMsgDiv").fadeOut('slow', function () {
            $scope.message = '';
          });
        });
      }, 3000);
      $scope.saveRnrForm.$dirty = false;
    }, function (data) {
      $scope.error = data.error;
    });
  };

  $scope.submitRnr = function () {
    resetFlags();
    if (!valid()) return;
    var rnr = removeExtraDataForPostFromRnr();
    Requisitions.update({id:$scope.rnr.id, operation:"submit"},
      rnr, function (data) {
        $scope.rnr.status = "SUBMITTED";
        $scope.formDisabled = !$rootScope.hasPermission('AUTHORIZE_REQUISITION');
        $scope.submitMessage = data.success;
      }, function (data) {
        $scope.submitError = data.data.error;
      });
  };

  $scope.authorizeRnr = function () {
    resetFlags();
    if (!valid()) return;
    var rnr = removeExtraDataForPostFromRnr();
    Requisitions.update({id:$scope.rnr.id, operation:"authorize"}, rnr, function (data) {
      $scope.rnr.status = "AUTHORIZED";
      $scope.formDisabled = true;
      $scope.submitMessage = data.success;
    }, function (data) {
      $scope.submitError = data.data.error;
    });
  };

  $scope.hide = function () {
    return "";
  };

  $scope.highlightRequired = function (value) {
    if ($scope.inputClass == 'required' && (isUndefined(value) || value.toString().trim().length == 0)) {
      return "required-error";
    }
    return null;
  };

  $scope.highlightRequiredFieldInModal = function (value) {
    if (isUndefined(value)) return "required-error";
    return null;
  };

  $scope.highlightWarningBasedOnField = function (value, field) {
    if ((isUndefined(value) || value.trim().length == 0 || value == false) && $scope.inputClass == 'required' && field) {
      return "warning-error";
    }
    return null;
  };

  $scope.highlightWarning = function (value) {
    if ((isUndefined(value) || value.trim().length == 0 || value == false) && $scope.inputClass == 'required') {
      return "warning-error";
    }
    return null;
  };

  $scope.totalCost = function () {
    if (!$scope.rnr) return;
    return parseFloat(parseFloat($scope.rnr.fullSupplyItemsSubmittedCost) + parseFloat($scope.rnr.nonFullSupplyItemsSubmittedCost)).toFixed(2);
  };

  $scope.getCellErrorClass = function (rnrLineItem) {
    return (typeof(rnrLineItem.getErrorMessage) != "undefined" && rnrLineItem.getErrorMessage()) ? 'cell-error-highlight' : '';
  };

  $scope.getRowErrorClass = function (rnrLineItem) {
    return $scope.getCellErrorClass(rnrLineItem) ? 'row-error-highlight' : '';
  };

  function resetCostsIfNull() {
    var rnr = $scope.rnr;
    if (rnr == null) return;
    if (!rnr.fullSupplyItemsSubmittedCost)
      rnr.fullSupplyItemsSubmittedCost = 0;
    if (!rnr.nonFullSupplyItemsSubmittedCost)
      rnr.nonFullSupplyItemsSubmittedCost = 0;
  }

  function prepareRnr() {
    var rnr = $scope.rnr;

    var lineItemsJson = rnr.lineItems;
    rnr.lineItems = [];
    $(lineItemsJson).each(function (i, lineItem) {
      rnr.lineItems.push(new RnrLineItem(lineItem, $scope.rnr, $scope.programRnrColumnList));
    });

    var nonFullSupplyLineItemsJson = rnr.nonFullSupplyLineItems;
    rnr.nonFullSupplyLineItems = [];
    $(nonFullSupplyLineItemsJson).each(function (i, lineItem) {
      rnr.nonFullSupplyLineItems.push(new RnrLineItem(lineItem, $scope.rnr, $scope.programRnrColumnList))
    });

    resetCostsIfNull();
    $scope.fillPagedGridData();
    $scope.formDisabled = (function () {
      if ($scope.rnr) {
        var status = $scope.rnr.status;
        if (status == 'INITIATED' && $rootScope.hasPermission('CREATE_REQUISITION')) return false;
        if (status == 'SUBMITTED' && $rootScope.hasPermission('AUTHORIZE_REQUISITION')) return false;
      }
      return true;
    })();
  }

  function valid() {
    if ($scope.saveRnrForm.$error.required) {
      $scope.saveRnr(null);
      $scope.inputClass = "required";
      $scope.submitMessage = "";
      $scope.submitError = 'Please complete the highlighted fields on the R&R form before submitting';
      return false;
    }
    if (!formulaValid()) {
      $scope.saveRnr(null);
      $scope.submitError = "Please correct the errors on the R&R form before submitting";
      $scope.submitMessage = "";
      return false;
    }
    return true;
  }

  function resetFlags() {
    $scope.inputClass = "";
    $scope.submitError = "";
    $rootScope.submitMessage = "";
    $scope.error = "";
    $scope.message = "";
  }

  // TODO: Push this method to rnr-line-item
  function formulaValid() {
    var valid = true;
    $($scope.rnr.lineItems).each(function (index, lineItem) {
      if (lineItem.arithmeticallyInvalid() || lineItem.stockInHand < 0 || lineItem.quantityDispensed < 0) {
        valid = false;
        return false;
      }
    });
    return valid;
  }

  function removeExtraDataForPostFromRnr() {
    var rnr = {"id":$scope.rnr.id, "lineItems":[], "nonFullSupplyLineItems":[]};

    _.each($scope.rnr.lineItems, function (lineItem) {
      rnr.lineItems.push(_.omit(lineItem, ['rnr', 'programRnrColumnList']));
    });
    _.each($scope.rnr.nonFullSupplyLineItems, function (lineItem) {
      rnr.nonFullSupplyLineItems.push(_.omit(lineItem, ['rnr', 'programRnrColumnList']));
    });
    return rnr;
  }
}

CreateRequisitionController.resolve = {

  requisition:function ($q, $timeout, Requisition, $route) {
    var deferred = $q.defer();
    $timeout(function () {

      Requisition.get({facilityId:$route.current.params.facility, programId:$route.current.params.program, periodId:$route.current.params.period}, function (data) {
        deferred.resolve(data.rnr);
      }, {});
    }, 100);
    return deferred.promise;
  },

  rnrColumns:function ($q, $timeout, ProgramRnRColumnList, $route) {
    var deferred = $q.defer();
    $timeout(function () {
      ProgramRnRColumnList.get({programId:$route.current.params.program}, function (data) {
        deferred.resolve(data.rnrColumnList);
      }, {});
    }, 100);
    return deferred.promise;
  },

  currency:function ($q, $timeout, ReferenceData) {
    var deferred = $q.defer();
    $timeout(function () {
      ReferenceData.get({}, function (data) {
        deferred.resolve(data.currency);
      }, {});
    }, 100);
    return deferred.promise;
  }
};

<commit_msg>#000|+Rahul | Changing create rnr resolve to look for rnr in parent before making a call again.<commit_after>function CreateRequisitionController($scope, requisition, currency, rnrColumns, $location, Requisitions, $routeParams, $rootScope) {

  $scope.showNonFullSupply = $routeParams.supplyType == 'non-full-supply';
  $scope.baseUrl = "/create-rnr/" + $routeParams.facility + '/' + $routeParams.program + '/' + $routeParams.period;
  $scope.fullSupplyLink = $scope.baseUrl + "?supplyType=full-supply&page=1";
  $scope.nonFullSupplyLink = $scope.baseUrl + "?supplyTpe=non-full-supply&page=1";
  $scope.pageSize = 10;

  $scope.fillPagedGridData = function () {
    var gridLineItems = $scope.showNonFullSupply ? $scope.rnr.nonFullSupplyLineItems : $scope.rnr.lineItems;
    $scope.numberOfPages = Math.ceil(gridLineItems.length / $scope.pageSize)? Math.ceil(gridLineItems.length / $scope.pageSize): 1;
    $scope.currentPage = (utils.isValidPage($routeParams.page, $scope.numberOfPages)) ? parseInt($routeParams.page, 10) : 1;
    $scope.pageLineItems = gridLineItems.slice(($scope.pageSize * ($scope.currentPage - 1)), $scope.pageSize * $scope.currentPage);
  };
  $scope.rnr = requisition;
  $scope.visibleColumns = _.where(rnrColumns, {'visible':true});
  $scope.programRnrColumnList = rnrColumns;
  $scope.addNonFullSupplyLineItemButtonShown = _.findWhere($scope.programRnrColumnList, {'name':'quantityRequested'});

  prepareRnr();

  $scope.currency = currency;

  if ($scope.programRnrColumnList && $scope.programRnrColumnList.length > 0) {
  } else {
    $scope.error = "rnr.template.not.defined.error";
    $location.path("/init-rnr");
  }

  $scope.currentPage = ($routeParams.page) ? parseInt($routeParams.page) || 1 : 1;

  $scope.switchSupplyType = function (supplyType) {
    $scope.showNonFullSupply = supplyType == 'non-full-supply';
    $location.search('page', 1);
    $location.search('supplyType', supplyType);
  };

  $scope.$on('$routeUpdate', function () {
    $scope.fillPagedGridData();
    if ($scope.saveRnrForm.$dirty) $scope.saveRnr();
  });

  $scope.$watch("currentPage", function () {
    $location.search("page", $scope.currentPage);
  });

  $scope.periodDisplayName = function () {
    if (!$scope.rnr) return;

    var startDate = new Date($scope.rnr.period.startDate);

    var endDate = new Date($scope.rnr.period.endDate);
    return utils.getFormattedDate(startDate) + ' - ' + utils.getFormattedDate(endDate);
  };

  $scope.saveRnr = function () {
    resetFlags();
    var rnr = removeExtraDataForPostFromRnr();
    Requisitions.update({id:$scope.rnr.id, operation:"save"}, rnr, function (data) {
      $scope.message = data.success;
      setTimeout(function () {
        $scope.$apply(function () {
          angular.element("#saveSuccessMsgDiv").fadeOut('slow', function () {
            $scope.message = '';
          });
        });
      }, 3000);
      $scope.saveRnrForm.$dirty = false;
    }, function (data) {
      $scope.error = data.error;
    });
  };

  $scope.submitRnr = function () {
    resetFlags();
    if (!valid()) return;
    var rnr = removeExtraDataForPostFromRnr();
    Requisitions.update({id:$scope.rnr.id, operation:"submit"},
      rnr, function (data) {
        $scope.rnr.status = "SUBMITTED";
        $scope.formDisabled = !$rootScope.hasPermission('AUTHORIZE_REQUISITION');
        $scope.submitMessage = data.success;
      }, function (data) {
        $scope.submitError = data.data.error;
      });
  };

  $scope.authorizeRnr = function () {
    resetFlags();
    if (!valid()) return;
    var rnr = removeExtraDataForPostFromRnr();
    Requisitions.update({id:$scope.rnr.id, operation:"authorize"}, rnr, function (data) {
      $scope.rnr.status = "AUTHORIZED";
      $scope.formDisabled = true;
      $scope.submitMessage = data.success;
    }, function (data) {
      $scope.submitError = data.data.error;
    });
  };

  $scope.hide = function () {
    return "";
  };

  $scope.highlightRequired = function (value) {
    if ($scope.inputClass == 'required' && (isUndefined(value) || value.toString().trim().length == 0)) {
      return "required-error";
    }
    return null;
  };

  $scope.highlightRequiredFieldInModal = function (value) {
    if (isUndefined(value)) return "required-error";
    return null;
  };

  $scope.highlightWarningBasedOnField = function (value, field) {
    if ((isUndefined(value) || value.trim().length == 0 || value == false) && $scope.inputClass == 'required' && field) {
      return "warning-error";
    }
    return null;
  };

  $scope.highlightWarning = function (value) {
    if ((isUndefined(value) || value.trim().length == 0 || value == false) && $scope.inputClass == 'required') {
      return "warning-error";
    }
    return null;
  };

  $scope.totalCost = function () {
    if (!$scope.rnr) return;
    return parseFloat(parseFloat($scope.rnr.fullSupplyItemsSubmittedCost) + parseFloat($scope.rnr.nonFullSupplyItemsSubmittedCost)).toFixed(2);
  };

  $scope.getCellErrorClass = function (rnrLineItem) {
    return (typeof(rnrLineItem.getErrorMessage) != "undefined" && rnrLineItem.getErrorMessage()) ? 'cell-error-highlight' : '';
  };

  $scope.getRowErrorClass = function (rnrLineItem) {
    return $scope.getCellErrorClass(rnrLineItem) ? 'row-error-highlight' : '';
  };

  function resetCostsIfNull() {
    var rnr = $scope.rnr;
    if (rnr == null) return;
    if (!rnr.fullSupplyItemsSubmittedCost)
      rnr.fullSupplyItemsSubmittedCost = 0;
    if (!rnr.nonFullSupplyItemsSubmittedCost)
      rnr.nonFullSupplyItemsSubmittedCost = 0;
  }

  function prepareRnr() {
    var rnr = $scope.rnr;

    var lineItemsJson = rnr.lineItems;
    rnr.lineItems = [];
    $(lineItemsJson).each(function (i, lineItem) {
      rnr.lineItems.push(new RnrLineItem(lineItem, $scope.rnr, $scope.programRnrColumnList));
    });

    var nonFullSupplyLineItemsJson = rnr.nonFullSupplyLineItems;
    rnr.nonFullSupplyLineItems = [];
    $(nonFullSupplyLineItemsJson).each(function (i, lineItem) {
      rnr.nonFullSupplyLineItems.push(new RnrLineItem(lineItem, $scope.rnr, $scope.programRnrColumnList))
    });

    resetCostsIfNull();
    $scope.fillPagedGridData();
    $scope.formDisabled = (function () {
      if ($scope.rnr) {
        var status = $scope.rnr.status;
        if (status == 'INITIATED' && $rootScope.hasPermission('CREATE_REQUISITION')) return false;
        if (status == 'SUBMITTED' && $rootScope.hasPermission('AUTHORIZE_REQUISITION')) return false;
      }
      return true;
    })();
  }

  function valid() {
    if ($scope.saveRnrForm.$error.required) {
      $scope.saveRnr(null);
      $scope.inputClass = "required";
      $scope.submitMessage = "";
      $scope.submitError = 'Please complete the highlighted fields on the R&R form before submitting';
      return false;
    }
    if (!formulaValid()) {
      $scope.saveRnr(null);
      $scope.submitError = "Please correct the errors on the R&R form before submitting";
      $scope.submitMessage = "";
      return false;
    }
    return true;
  }

  function resetFlags() {
    $scope.inputClass = "";
    $scope.submitError = "";
    $rootScope.submitMessage = "";
    $scope.error = "";
    $scope.message = "";
  }

  // TODO: Push this method to rnr-line-item
  function formulaValid() {
    var valid = true;
    $($scope.rnr.lineItems).each(function (index, lineItem) {
      if (lineItem.arithmeticallyInvalid() || lineItem.stockInHand < 0 || lineItem.quantityDispensed < 0) {
        valid = false;
        return false;
      }
    });
    return valid;
  }

  function removeExtraDataForPostFromRnr() {
    var rnr = {"id":$scope.rnr.id, "lineItems":[], "nonFullSupplyLineItems":[]};

    _.each($scope.rnr.lineItems, function (lineItem) {
      rnr.lineItems.push(_.omit(lineItem, ['rnr', 'programRnrColumnList']));
    });
    _.each($scope.rnr.nonFullSupplyLineItems, function (lineItem) {
      rnr.nonFullSupplyLineItems.push(_.omit(lineItem, ['rnr', 'programRnrColumnList']));
    });
    return rnr;
  }
}

CreateRequisitionController.resolve = {

  requisition:function ($q, $timeout, Requisition, $route, $rootScope) {
    var deferred = $q.defer();
    $timeout(function () {
      var rnr = $rootScope.rnr;
      if(rnr){
        deferred.resolve(rnr);
        $rootScope.rnr=undefined;
        return;
      }
      Requisition.get({facilityId:$route.current.params.facility, programId:$route.current.params.program, periodId:$route.current.params.period}, function (data) {
        deferred.resolve(data.rnr);
      }, {});
    }, 100);
    return deferred.promise;
  },

  rnrColumns:function ($q, $timeout, ProgramRnRColumnList, $route) {
    var deferred = $q.defer();
    $timeout(function () {
      ProgramRnRColumnList.get({programId:$route.current.params.program}, function (data) {
        deferred.resolve(data.rnrColumnList);
      }, {});
    }, 100);
    return deferred.promise;
  },

  currency:function ($q, $timeout, ReferenceData) {
    var deferred = $q.defer();
    $timeout(function () {
      ReferenceData.get({}, function (data) {
        deferred.resolve(data.currency);
      }, {});
    }, 100);
    return deferred.promise;
  }
};

<|endoftext|>


<commit_before>/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

import 'semantic-ui-css/components/dropdown';
import $ from 'jquery';

const getNextIndex = function getNextIndex() {
  return $('#attributesContainer').attr('data-count');
};

const addAttributesNumber = function addAttributesNumber(number) {
  const currentIndex = parseInt(getNextIndex(), 10);
  $('#attributesContainer').attr('data-count', currentIndex + number);
};

const controlAttributesList = function controlAttributesList() {
  $('#attributesContainer .attribute').each((index, element) => {
    const value = $(element).attr('data-id');
    $('#sylius_product_attribute_choice').dropdown('set selected', value);
  });
};

const modifyAttributesListOnSelectorElementDelete = function modifyAttributesListOnSelectorElementDelete(removedValue) {
  $(`#attributesContainer .attributes-group[data-attribute-code="${removedValue}"]`).remove();
};

const modifySelectorOnAttributesListElementDelete = function modifySelectorOnAttributesListElementDelete() {
  $('.attributes-group button[data-attribute="delete"]').off('click').on('click', (event) => {
    const attributeId = $(event.currentTarget).parents('.attributes-group').attr('data-attribute-code');

    $('div#attributeChoice > .ui.dropdown.search').dropdown('remove selected', attributeId);
    modifyAttributesListOnSelectorElementDelete(attributeId);
  });
};

const modifyAttributeFormElements = function modifyAttributeFormElements($response) {
  $response.find('input,select,textarea').each((index, element) => {
    if ($(element).attr('data-name') != null) {
      $(element).attr('name', $(element).attr('data-name'));
    }
  });

  return $response;
};

const isInTheAttributesContainer = function isInTheAttributesContainer(attributeId) {
  let result = false;
  $('#attributesContainer .attribute').each((index, element) => {
    const dataId = $(element).attr('data-id');
    if (dataId === attributeId) {
      result = true;
    }
  });

  return result;
};

const copyValueToAllLanguages = function copyValueToAllLanguages() {
  $('#attributesContainer').on('click', '.attribute [data-attribute="copy"]', (event) => {
    event.preventDefault();

    const $attributesContainer = $('#attributesContainer');
    const $masterAttribute = $(event.currentTarget).closest('.attribute');
    const attributeID = $masterAttribute.attr('data-id');
    const $attributeCollection = $attributesContainer.find(`[data-id="${attributeID}"]`);

    const $masterAttributeInputs = $masterAttribute.find('input:visible, select, textarea');

    $attributeCollection.each((index, attr) => {
      const $inputs = $(attr).find('input:visible, select, textarea');

      $inputs.each((i, input) => {
        if (input.getAttribute('type') === 'checkbox') {
          input.checked = $masterAttributeInputs[i].checked;
        } else {
          input.value = $masterAttributeInputs[i].value;
        }
      });
    });
  });
};

const setAttributeChoiceListener = function setAttributeChoiceListener() {
  const $attributeChoice = $('#attributeChoice');
  $attributeChoice.find('button').on('click', (event) => {
    event.preventDefault();

    const $attributeChoiceSelect = $attributeChoice.find('select');
    let queryData = '';
    const $newAttributes = $attributeChoiceSelect.val();

    if ($newAttributes != null) {
      $attributeChoiceSelect.val().forEach((item) => {
        if (!isInTheAttributesContainer(item)) {
          queryData += `${$attributeChoiceSelect.prop('name')}=${item}&`;
        }
      });
    }
    queryData += `count=${getNextIndex()}`;

    $('form').addClass('loading');

    $.ajax({
      type: 'GET',
      url: $(event.currentTarget).parent().attr('data-action'),
      data: queryData,
      dataType: 'html',
      error() {
        $('form').removeClass('loading');
      },
      success(response) {
        const attributeFormElements = modifyAttributeFormElements($(response));

        attributeFormElements.each((index, element) => {
          const localeCode = $(element).find('input[type="hidden"]').last().val();
          $(`#attributesContainer > div`).append(element);
        });

        $('#sylius_product_attribute_choice').val('');

        addAttributesNumber($.grep(attributeFormElements, a => $(a).hasClass('attribute')).length);
        modifySelectorOnAttributesListElementDelete();

        $('form').removeClass('loading');
      },
    });
  });
};

$.fn.extend({
  productAttributes() {
    setAttributeChoiceListener();

    this.dropdown({
      onRemove(removedValue) {
        modifyAttributesListOnSelectorElementDelete(removedValue);
      },
      forceSelection: false,
    });

    controlAttributesList();
    modifySelectorOnAttributesListElementDelete();
    copyValueToAllLanguages();
  },
});
<commit_msg>[Admin] multiple selection applying button fixed to apply all the selected options<commit_after>/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

import 'semantic-ui-css/components/dropdown';
import $ from 'jquery';

const getNextIndex = function getNextIndex() {
  return $('#attributesContainer').attr('data-count');
};

const addAttributesNumber = function addAttributesNumber(number) {
  const currentIndex = parseInt(getNextIndex(), 10);
  $('#attributesContainer').attr('data-count', currentIndex + number);
};

const controlAttributesList = function controlAttributesList() {
  $('#attributesContainer .attribute').each((index, element) => {
    const value = $(element).attr('data-id');
    $('#sylius_product_attribute_choice').dropdown('set selected', value);
  });
};

const modifyAttributesListOnSelectorElementDelete = function modifyAttributesListOnSelectorElementDelete(removedValue) {
  $(`#attributesContainer .attributes-group[data-attribute-code="${removedValue}"]`).remove();
};

const modifySelectorOnAttributesListElementDelete = function modifySelectorOnAttributesListElementDelete() {
  $('.attributes-group button[data-attribute="delete"]').off('click').on('click', (event) => {
    const attributeId = $(event.currentTarget).parents('.attributes-group').attr('data-attribute-code');

    $('div#attributeChoice > .ui.dropdown.search').dropdown('remove selected', attributeId);
    modifyAttributesListOnSelectorElementDelete(attributeId);
  });
};

const modifyAttributeFormElements = function modifyAttributeFormElements($response) {
  $response.find('input,select,textarea').each((index, element) => {
    if ($(element).attr('data-name') != null) {
      $(element).attr('name', $(element).attr('data-name'));
    }
  });

  return $response;
};

const isInTheAttributesContainer = function isInTheAttributesContainer(attributeId) {
  let result = false;
  $('#attributesContainer .attribute').each((index, element) => {
    const dataId = $(element).attr('data-id');
    if (dataId === attributeId) {
      result = true;
    }
  });

  return result;
};

const copyValueToAllLanguages = function copyValueToAllLanguages() {
  $('#attributesContainer').on('click', '.attribute [data-attribute="copy"]', (event) => {
    event.preventDefault();

    const $attributesContainer = $('#attributesContainer');
    const $masterAttribute = $(event.currentTarget).closest('.attribute');
    const attributeID = $masterAttribute.attr('data-id');
    const $attributeCollection = $attributesContainer.find(`[data-id="${attributeID}"]`);

    const $masterAttributeInputs = $masterAttribute.find('input:visible, select, textarea');

    $attributeCollection.each((index, attr) => {
      const $inputs = $(attr).find('input:visible, select, textarea');

      $inputs.each((i, input) => {
        if (input.getAttribute('type') === 'checkbox') {
          input.checked = $masterAttributeInputs[i].checked;
        } else if (input.nodeName === 'SELECT') {
          for (let x = 0; x < $inputs[i].length; x++) {
            input[x].selected = $masterAttributeInputs[i][x].selected;
          }
        } else {
          input.value = $masterAttributeInputs[i].value;
        }
      });
    });
  });
};

const setAttributeChoiceListener = function setAttributeChoiceListener() {
  const $attributeChoice = $('#attributeChoice');
  $attributeChoice.find('button').on('click', (event) => {
    event.preventDefault();

    const $attributeChoiceSelect = $attributeChoice.find('select');
    let queryData = '';
    const $newAttributes = $attributeChoiceSelect.val();

    if ($newAttributes != null) {
      $attributeChoiceSelect.val().forEach((item) => {
        if (!isInTheAttributesContainer(item)) {
          queryData += `${$attributeChoiceSelect.prop('name')}=${item}&`;
        }
      });
    }
    queryData += `count=${getNextIndex()}`;

    $('form').addClass('loading');

    $.ajax({
      type: 'GET',
      url: $(event.currentTarget).parent().attr('data-action'),
      data: queryData,
      dataType: 'html',
      error() {
        $('form').removeClass('loading');
      },
      success(response) {
        const attributeFormElements = modifyAttributeFormElements($(response));

        attributeFormElements.each((index, element) => {
          const localeCode = $(element).find('input[type="hidden"]').last().val();
          $(`#attributesContainer > div`).append(element);
        });

        $('#sylius_product_attribute_choice').val('');

        addAttributesNumber($.grep(attributeFormElements, a => $(a).hasClass('attribute')).length);
        modifySelectorOnAttributesListElementDelete();

        $('form').removeClass('loading');
      },
    });
  });
};

$.fn.extend({
  productAttributes() {
    setAttributeChoiceListener();

    this.dropdown({
      onRemove(removedValue) {
        modifyAttributesListOnSelectorElementDelete(removedValue);
      },
      forceSelection: false,
    });

    controlAttributesList();
    modifySelectorOnAttributesListElementDelete();
    copyValueToAllLanguages();
  },
});
<|endoftext|>


<commit_before>//All the questoin in a survey
function ResponsesNewView(surveyID) {
	var _ = require('lib/underscore')._;
	var Question = require('models/question');
	var Survey = require('models/survey');
	var Response = require('models/response');
	var QuestionView = require('ui/common/questions/QuestionView');
	var ResponseViewHelper = require('ui/common/responses/ResponseViewHelper');
	var responseViewHelper = new ResponseViewHelper;

	//Number of questions in a page
	var PAGE_SIZE = 5;

	var self = Ti.UI.createView({
		layout : 'vertical'
	})

	var scrollableView = Ti.UI.createScrollableView({
		showPagingControl : true
	});
	self.add(scrollableView);

	var survey = Survey.findOneById(surveyID);
	var questions = survey.firstLevelQuestions();

	var pagedQuestions = _.chain(questions).groupBy(function(a, b) {
		return Math.floor(b / PAGE_SIZE);
	}).toArray().value();

	var saveButton = Ti.UI.createButton({
		title : 'Save',
		width : '48%'
	});

	var completeButton = Ti.UI.createButton({
		title : 'Complete',
		width : '48%'
	});

	_(pagedQuestions).each(function(questions, pageNumber) {
		var questionsView = Ti.UI.createView({
			layout : 'vertical'
		});

		_(questions).each(function(question) {
			var questionView = new QuestionView(question);
			questionsView.add(questionView);
		})

		if(pageNumber + 1 === pagedQuestions.length){
			questionsView.add(completeButton);
			questionsView.add(saveButton);
		}

		scrollableView.addView(questionsView);
	});

	var validateAndSaveAnswers = function(e, status) {
		var questionViews = responseViewHelper.getQuestionViews(self);
		var answersData = _(questionViews).map(function(fields, questionID) {
			Ti.API.info("questionid:" + questionID);
			Ti.API.info("content:" + fields['valueField'].getValue());
			return {
				'question_id' : questionID,
				'content' : fields.valueField.getValue()
			}
		});
		responseErrors = Response.validate(answersData, status);
		if (!_.isEmpty(responseErrors)) {
			responseViewHelper.displayErrors(responseErrors, questionViews);
			alert("There were some errors in the response.");
		} else {
			Response.createRecord(surveyID, status, answersData);
			self.fireEvent('ResponsesNewView:savedResponse');
		}
	};

	completeButton.addEventListener('click', function(event) {
		validateAndSaveAnswers(event, "complete");
	});
	saveButton.addEventListener('click', function(event) {
		validateAndSaveAnswers(event, "incomplete");
	});

	return self;
}

module.exports = ResponsesNewView;
<commit_msg>Save all the questionViews from all pages.<commit_after>//All the questoin in a survey
function ResponsesNewView(surveyID) {
	var _ = require('lib/underscore')._;
	var Question = require('models/question');
	var Survey = require('models/survey');
	var Response = require('models/response');
	var QuestionView = require('ui/common/questions/QuestionView');
	var ResponseViewHelper = require('ui/common/responses/ResponseViewHelper');
	var responseViewHelper = new ResponseViewHelper;

	//Number of questions in a page
	var PAGE_SIZE = 5;

	var self = Ti.UI.createView({
		layout : 'vertical'
	})

	var scrollableView = Ti.UI.createScrollableView({
		showPagingControl : true
	});
	self.add(scrollableView);

	var survey = Survey.findOneById(surveyID);
	var questions = survey.firstLevelQuestions();

	var allQuestionViews = Ti.UI.createView();

	var pagedQuestions = _.chain(questions).groupBy(function(a, b) {
		return Math.floor(b / PAGE_SIZE);
	}).toArray().value();

	var saveButton = Ti.UI.createButton({
		title : 'Save',
		width : '48%'
	});

	var completeButton = Ti.UI.createButton({
		title : 'Complete',
		width : '48%'
	});

	_(pagedQuestions).each(function(questions, pageNumber) {
		var questionsView = Ti.UI.createView({
			layout : 'vertical'
		});

		_(questions).each(function(question) {
			var questionView = new QuestionView(question);
			allQuestionViews.add(questionView);
			questionsView.add(questionView);
		})

		if(pageNumber + 1 === pagedQuestions.length){
			questionsView.add(completeButton);
			questionsView.add(saveButton);
		}

		scrollableView.addView(questionsView);
	});

	var validateAndSaveAnswers = function(e, status) {
		var questionViews = responseViewHelper.getQuestionViews(allQuestionViews);
		var answersData = _(questionViews).map(function(fields, questionID) {
			Ti.API.info("questionid:" + questionID);
			Ti.API.info("content:" + fields['valueField'].getValue());
			return {
				'question_id' : questionID,
				'content' : fields.valueField.getValue()
			}
		});
		responseErrors = Response.validate(answersData, status);
		if (!_.isEmpty(responseErrors)) {
			responseViewHelper.displayErrors(responseErrors, questionViews);
			alert("There were some errors in the response.");
		} else {
			Response.createRecord(surveyID, status, answersData);
			self.fireEvent('ResponsesNewView:savedResponse');
		}
	};

	completeButton.addEventListener('click', function(event) {
		validateAndSaveAnswers(event, "complete");
	});
	saveButton.addEventListener('click', function(event) {
		validateAndSaveAnswers(event, "incomplete");
	});

	return self;
}

module.exports = ResponsesNewView;
<|endoftext|>


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

    function showValidationOnSubmit(serverValidationManager) {
        return {
            require: ["ngMessages", "^^?valFormManager"],
            restrict: "A",
            scope: {
                form: "=?"
            },
            link: function (scope, element, attr, ctrl) {

                var formMgr = ctrl.length > 1 ? ctrl[1] : null;

                //We can either get the form submitted status by the parent directive valFormManager
                //or we can check upwards in the DOM for the css class... lets try both :)
                //The initial hidden state can't always be hidden because when we switch variants in the content editor we cannot
                //reset the status.
                var submitted = element.closest(".show-validation").length > 0 || (formMgr && formMgr.showValidation);
                if (!submitted) {
                    element.hide();
                }

                var unsubscribe = [];

                unsubscribe.push(scope.$on("formSubmitting", function (ev, args) {
                    element.show();
                }));

                unsubscribe.push(scope.$on("formSubmitted", function (ev, args) {
                    element.hide();
                }));

                //no isolate scope to listen to element destroy
                element.on('$destroy', function () {
                    for (var u in unsubscribe) {
                        unsubscribe[u]();
                    }
                });

            }
        };
    }

    angular.module('umbraco.directives.validation').directive("showValidationOnSubmit", showValidationOnSubmit);

})();
<commit_msg>toggle ng-hide class instead of using .hide()<commit_after>(function () {
    "use strict";

    function showValidationOnSubmit(serverValidationManager) {
        return {
            require: ["ngMessages", "^^?valFormManager"],
            restrict: "A",
            scope: {
                form: "=?"
            },
            link: function (scope, element, attr, ctrl) {

                var formMgr = ctrl.length > 1 ? ctrl[1] : null;
                const hiddenClass = 'ng-hide';

                //We can either get the form submitted status by the parent directive valFormManager
                //or we can check upwards in the DOM for the css class... lets try both :)
                //The initial hidden state can't always be hidden because when we switch variants in the content editor we cannot
                //reset the status.
                var submitted = element.closest(".show-validation").length > 0 || (formMgr && formMgr.showValidation);
                if (!submitted) {
                    element[0].classList.add(hiddenClass);
                }

                var unsubscribe = [];

                unsubscribe.push(scope.$on("formSubmitting", function (ev, args) {
                    element[0].classList.remove(hiddenClass);
                }));

                unsubscribe.push(scope.$on("formSubmitted", function (ev, args) {
                    element[0].classList.add(hiddenClass);
                }));

                //no isolate scope to listen to element destroy
                element.on('$destroy', function () {
                    for (var u in unsubscribe) {
                        unsubscribe[u]();
                    }
                });

            }
        };
    }

    angular.module('umbraco.directives.validation').directive("showValidationOnSubmit", showValidationOnSubmit);

})();
<|endoftext|>