<commit_before>/*global define*/
define([
        '../Core/defined',
        '../Core/TimeInterval',
        '../Core/TimeIntervalCollection',
        '../Core/Iso8601',
        './DynamicColorMaterial',
        './DynamicImageMaterial',
        './DynamicGridMaterial'
    ], function(
        defined,
        TimeInterval,
        TimeIntervalCollection,
        Iso8601,
        DynamicColorMaterial,
        DynamicImageMaterial,
        DynamicGridMaterial) {
    "use strict";

    var potentialMaterials = [DynamicColorMaterial, DynamicImageMaterial, DynamicGridMaterial];

    /**
     * A dynamic property which stores data for multiple types of materials
     * associated with the same property over time. Rather than creating instances
     * of this object directly, it's typically created and managed via loading CZML
     * data into a DynamicObjectCollection.
     *
     * @alias DynamicMaterialProperty
     * @internalconstructor
     *
     * @see DynamicObject
     * @see DynamicProperty
     * @see ReferenceProperty
     * @see DynamicDirectionsProperty
     * @see DynamicVertexPositionsProperty
     */
    var DynamicMaterialProperty = function() {
        this._intervals = new TimeIntervalCollection();
    };

    /**
     * Processes the provided CZML interval or intervals into this property.
     * @memberof DynamicMaterialProperty
     *
     * @param {Object} czmlIntervals The CZML data to process.
     * @param {TimeInterval} [constrainedInterval] Constrains the processing so that any times outside of this interval are ignored.
     * @param {String} [sourceUri] The originating url of the CZML being processed.
     */
    DynamicMaterialProperty.prototype.processCzmlIntervals = function(czmlIntervals, constrainedInterval, sourceUri) {
        if (Array.isArray(czmlIntervals)) {
            for ( var i = 0, len = czmlIntervals.length; i < len; i++) {
                addCzmlInterval(this, czmlIntervals[i], constrainedInterval, sourceUri);
            }
        } else {
            addCzmlInterval(this, czmlIntervals, constrainedInterval, sourceUri);
        }
    };

    /**
     * Returns the value of the property at the specified time.
     * @memberof DynamicMaterialProperty
     *
     * @param {JulianDate} time The time for which to retrieve the value.
     * @param {Context} [context] The context in which the material exists.
     * @param {Object} [result] The object to store the value into, if omitted, a new instance is created and returned.
     * @returns The modified result parameter or a new instance if the result parameter was not supplied.
     */
    DynamicMaterialProperty.prototype.getValue = function(time, context, existingMaterial) {
        var value = this._intervals.findIntervalContainingDate(time);
        var material = defined(value) ? value.data : undefined;
        if (defined(material)) {
            return material;
        }
        return existingMaterial;
    };

    function addCzmlInterval(dynamicMaterialProperty, czmlInterval, constrainedInterval, sourceUri) {
        var iso8601Interval = czmlInterval.interval;
        if (!defined(iso8601Interval)) {
            iso8601Interval = Iso8601.MAXIMUM_INTERVAL.clone();
        } else {
            iso8601Interval = TimeInterval.fromIso8601(iso8601Interval);
        }

        if (defined(constrainedInterval)) {
            iso8601Interval = iso8601Interval.intersect(constrainedInterval);
        }

        //See if we already have data at that interval.
        var thisIntervals = dynamicMaterialProperty._intervals;
        var existingInterval = thisIntervals.findInterval(iso8601Interval.start, iso8601Interval.stop);
        var foundMaterial = false;
        var existingMaterial;

        if (defined(existingInterval)) {
            //We have an interval, but we need to make sure the
            //new data is the same type of material as the old data.
            existingMaterial = existingInterval.data;
            foundMaterial = existingMaterial.isMaterial(czmlInterval);
        } else {
            //If not, create it.
            existingInterval = iso8601Interval;
            thisIntervals.addInterval(existingInterval);
        }

        //If the new data was a different type, look for a handler for this type.
        if (foundMaterial === false) {
            for ( var i = 0, len = potentialMaterials.length; i < len; i++) {
                var PotentialMaterial = potentialMaterials[i];
                foundMaterial = PotentialMaterial.isMaterial(czmlInterval);
                if (foundMaterial) {
                    existingInterval.data = existingMaterial = new PotentialMaterial();
                    break;
                }
            }
        }

        //We could handle the data, prcess it.
        if (foundMaterial) {
            existingMaterial.processCzmlIntervals(czmlInterval, sourceUri);
        }
    }

    return DynamicMaterialProperty;
});<commit_msg>Delete DynamicMaterialProperty.js<commit_after><|endoftext|>


<commit_before>/*global define*/
define([
        '../Core/DeveloperError',
        '../Core/Color',
        '../Core/destroyObject',
        '../Core/Math',
        '../Core/Matrix4',
        '../Renderer/BufferUsage',
        './Material',
        './CustomSensorVolume'
    ], function(
        DeveloperError,
        Color,
        destroyObject,
        CesiumMath,
        Matrix4,
        BufferUsage,
        Material,
        CustomSensorVolume) {
    "use strict";

    /**
     * DOC_TBA
     *
     * @alias RectangularPyramidSensorVolume
     * @constructor
     *
     * @see SensorVolumeCollection#addRectangularPyramid
     */
    var RectangularPyramidSensorVolume = function(template) {
        var t = template || {};

        /**
         * true if this sensor will be shown; otherwise, false
         *
         * @type Boolean
         */
        this.show = (typeof t.show === 'undefined') ? true : t.show;

        /**
         * When true, a polyline is shown where the sensor outline intersections the central body.  The default is true.
         *
         * @type Boolean
         *
         * @see RectangularPyramidSensorVolume#intersectionColor
         */
        this.showIntersection = (typeof t.showIntersection === 'undefined') ? true : t.showIntersection;

        /**
         *

         * Determines if a sensor intersecting the ellipsoid is drawn through the ellipsoid and potentially out
         * to the other side, or if the part of the sensor intersecting the ellipsoid stops at the ellipsoid.
         *

         *

         * The default is false, meaning the sensor will not go through the ellipsoid.
         *

         *
         * @type Boolean
         */
        this.showThroughEllipsoid = (typeof t.showThroughEllipsoid === 'undefined') ? false : t.showThroughEllipsoid;

        /**
         * The 4x4 transformation matrix that transforms this sensor from model to world coordinates.  In it's model
         * coordinates, the sensor's principal direction is along the positive z-axis.  Half angles measured from the
         * principal direction and in the direction of the x-axis and y-axis define the extent of the rectangular
         * cross section.  This matrix is available to GLSL vertex and fragment shaders via
         * {@link czm_model} and derived uniforms.
         *

         *

         *

         * Model coordinate system for a sensor
         *

         *
         * @type Matrix4
         *
         * @see czm_model
         *
         * @example
         * // The sensor's vertex is located on the surface at -75.59777 degrees longitude and 40.03883 degrees latitude.
         * // The sensor's opens upward, along the surface normal.
         * var center = ellipsoid.cartographicToCartesian(Cartographic.fromDegrees(-75.59777, 40.03883));
         * sensor.modelMatrix = Transforms.eastNorthUpToFixedFrame(center);
         */
        this.modelMatrix = t.modelMatrix || Matrix4.IDENTITY.clone();

        /**
         * DOC_TBA
         *
         * @type BufferUsage
         */
        this.bufferUsage = t.bufferUsage || BufferUsage.STATIC_DRAW;

        /**
         * DOC_TBA
         *
         * @type Number
         */
        this.radius = (typeof t.radius === 'undefined') ? Number.POSITIVE_INFINITY : t.radius;

        /**
         * DOC_TBA
         *
         * @type Number
         *
         * @see RectangularPyramidSensorVolume#yHalfAngle
         */
        this.xHalfAngle = (typeof t.xHalfAngle === 'undefined') ? CesiumMath.PI_OVER_TWO : t.xHalfAngle;
        this._xHalfAngle = undefined;

        /**
         * DOC_TBA
         *
         * @type Number
         *
         * @see RectangularPyramidSensorVolume#xHalfAngle
         */
        this.yHalfAngle = (typeof t.yHalfAngle === 'undefined') ? CesiumMath.PI_OVER_TWO : t.yHalfAngle;
        this._yHalfAngle = undefined;

        /**
         * The surface appearance of the sensor.  This can be one of several built-in {@link Material} objects or a custom material, scripted with
         * Fabric.
         *

         * The default material is Material.ColorType.
         *

         *
         * @type Material
         *
         * @example
         * // 1. Change the color of the default material to yellow
         * sensor.material.uniforms.color = new Color(1.0, 1.0, 0.0, 1.0);
         *
         * // 2. Change material to horizontal stripes
         * sensor.material = Material.fromType(scene.getContext(), Material.StripeType);
         *
         * @see Fabric
         */
        this.material = (typeof t.material !== 'undefined') ? t.material : Material.fromType(undefined, Material.ColorType);

        /**
         * The color of the polyline where the sensor outline intersects the central body.  The default is {@link Color.WHITE}.
         *
         * @type Color
         *
         * @see RectangularPyramidSensorVolume#showIntersection
         */
        this.intersectionColor = (typeof t.intersectionColor !== 'undefined') ? Color.clone(t.intersectionColor) : Color.clone(Color.WHITE);

        t._pickIdThis = t._pickIdThis || this;
        this._customSensor = new CustomSensorVolume(t);
    };

    /**
     * DOC_TBA
     *
     * @memberof RectangularPyramidSensorVolume
     *
     * @exception {DeveloperError} this.xHalfAngle and this.yHalfAngle must each be less than 90 degrees.
     * @exception {DeveloperError} this.radius must be greater than or equal to zero.
     */
    RectangularPyramidSensorVolume.prototype.update = function(context, frameState, commandList) {
        if ((this.xHalfAngle > CesiumMath.PI_OVER_TWO) || (this.yHalfAngle > CesiumMath.PI_OVER_TWO)) {
            throw new DeveloperError('this.xHalfAngle and this.yHalfAngle must each be less than or equal to 90 degrees.');
        }

        var s = this._customSensor;

        s.show = this.show;
        s.showIntersection = this.showIntersection;
        s.showThroughEllipsoid = this.showThroughEllipsoid;
        s.modelMatrix = this.modelMatrix;
        s.bufferUsage = this.bufferUsage;
        s.radius = this.radius;
        s.material = this.material;
        s.intersectionColor = this.intersectionColor;

        if ((this._xHalfAngle !== this.xHalfAngle) || (this._yHalfAngle !== this.yHalfAngle)) {

            this._xHalfAngle = this.xHalfAngle;
            this._yHalfAngle = this.yHalfAngle;

            // At 90 degrees the sensor is completely open, and tan() goes to infinity.
            var tanX = Math.tan(Math.min(this.xHalfAngle, CesiumMath.toRadians(89.0)));
            var tanY = Math.tan(Math.min(this.yHalfAngle, CesiumMath.toRadians(89.0)));
            var theta = Math.atan(tanX / tanY);
            var cone = Math.atan(Math.sqrt(tanX * tanX + tanY * tanY));

            s.setDirections([{
                clock : theta,
                cone : cone
            }, {
                clock : CesiumMath.toRadians(180.0) - theta,
                cone : cone
            }, {
                clock : CesiumMath.toRadians(180.0) + theta,
                cone : cone
            }, {
                clock : -theta,
                cone : cone
            }]);
        }

        s.update(context, frameState, commandList);
    };

    /**
     * DOC_TBA
     * @memberof RectangularPyramidSensorVolume
     */
    RectangularPyramidSensorVolume.prototype.isDestroyed = function() {
        return false;
    };

    /**
     * DOC_TBA
     * @memberof RectangularPyramidSensorVolume
     */
    RectangularPyramidSensorVolume.prototype.destroy = function() {
        this._customSensor = this._customSensor && this._customSensor.destroy();
        return destroyObject(this);
    };

    return RectangularPyramidSensorVolume;
});<commit_msg>fixing rectangularpyramidsensorvolume<commit_after>/*global define*/
define([
        '../Core/defaultValue',
        '../Core/DeveloperError',
        '../Core/Color',
        '../Core/destroyObject',
        '../Core/Math',
        '../Core/Matrix4',
        '../Renderer/BufferUsage',
        './Material',
        './CustomSensorVolume'
    ], function(
        defaultValue,
        DeveloperError,
        Color,
        destroyObject,
        CesiumMath,
        Matrix4,
        BufferUsage,
        Material,
        CustomSensorVolume) {
    "use strict";

    /**
     * DOC_TBA
     *
     * @alias RectangularPyramidSensorVolume
     * @constructor
     *
     * @see SensorVolumeCollection#addRectangularPyramid
     */
    var RectangularPyramidSensorVolume = function(template) {
        var t = defaultValue(template, {});

        /**
         * true if this sensor will be shown; otherwise, false
         *
         * @type Boolean
         */
        this.show = (typeof t.show === 'undefined') ? true : t.show;

        /**
         * When true, a polyline is shown where the sensor outline intersections the central body.  The default is true.
         *
         * @type Boolean
         *
         * @see RectangularPyramidSensorVolume#intersectionColor
         */
        this.showIntersection = (typeof t.showIntersection === 'undefined') ? true : t.showIntersection;

        /**
         *

         * Determines if a sensor intersecting the ellipsoid is drawn through the ellipsoid and potentially out
         * to the other side, or if the part of the sensor intersecting the ellipsoid stops at the ellipsoid.
         *

         *

         * The default is false, meaning the sensor will not go through the ellipsoid.
         *

         *
         * @type Boolean
         */
        this.showThroughEllipsoid = (typeof t.showThroughEllipsoid === 'undefined') ? false : t.showThroughEllipsoid;

        /**
         * The 4x4 transformation matrix that transforms this sensor from model to world coordinates.  In it's model
         * coordinates, the sensor's principal direction is along the positive z-axis.  Half angles measured from the
         * principal direction and in the direction of the x-axis and y-axis define the extent of the rectangular
         * cross section.  This matrix is available to GLSL vertex and fragment shaders via
         * {@link czm_model} and derived uniforms.
         *

         *

         *

         * Model coordinate system for a sensor
         *

         *
         * @type Matrix4
         *
         * @see czm_model
         *
         * @example
         * // The sensor's vertex is located on the surface at -75.59777 degrees longitude and 40.03883 degrees latitude.
         * // The sensor's opens upward, along the surface normal.
         * var center = ellipsoid.cartographicToCartesian(Cartographic.fromDegrees(-75.59777, 40.03883));
         * sensor.modelMatrix = Transforms.eastNorthUpToFixedFrame(center);
         */
        this.modelMatrix = defaultValue(t.modelMatrix, Matrix4.IDENTITY.clone());

        /**
         * DOC_TBA
         *
         * @type BufferUsage
         */
        this.bufferUsage = defaultValue(t.bufferUsage, BufferUsage.STATIC_DRAW);

        /**
         * DOC_TBA
         *
         * @type Number
         */
        this.radius = (typeof t.radius === 'undefined') ? Number.POSITIVE_INFINITY : t.radius;

        /**
         * DOC_TBA
         *
         * @type Number
         *
         * @see RectangularPyramidSensorVolume#yHalfAngle
         */
        this.xHalfAngle = (typeof t.xHalfAngle === 'undefined') ? CesiumMath.PI_OVER_TWO : t.xHalfAngle;
        this._xHalfAngle = undefined;

        /**
         * DOC_TBA
         *
         * @type Number
         *
         * @see RectangularPyramidSensorVolume#xHalfAngle
         */
        this.yHalfAngle = (typeof t.yHalfAngle === 'undefined') ? CesiumMath.PI_OVER_TWO : t.yHalfAngle;
        this._yHalfAngle = undefined;

        /**
         * The surface appearance of the sensor.  This can be one of several built-in {@link Material} objects or a custom material, scripted with
         * Fabric.
         *

         * The default material is Material.ColorType.
         *

         *
         * @type Material
         *
         * @example
         * // 1. Change the color of the default material to yellow
         * sensor.material.uniforms.color = new Color(1.0, 1.0, 0.0, 1.0);
         *
         * // 2. Change material to horizontal stripes
         * sensor.material = Material.fromType(scene.getContext(), Material.StripeType);
         *
         * @see Fabric
         */
        this.material = (typeof t.material !== 'undefined') ? t.material : Material.fromType(undefined, Material.ColorType);

        /**
         * The color of the polyline where the sensor outline intersects the central body.  The default is {@link Color.WHITE}.
         *
         * @type Color
         *
         * @see RectangularPyramidSensorVolume#showIntersection
         */
        this.intersectionColor = (typeof t.intersectionColor !== 'undefined') ? Color.clone(t.intersectionColor) : Color.clone(Color.WHITE);

        t._pickIdThis = defaultValue(t._pickIdThis, this);
        this._customSensor = new CustomSensorVolume(t);
    };

    /**
     * DOC_TBA
     *
     * @memberof RectangularPyramidSensorVolume
     *
     * @exception {DeveloperError} this.xHalfAngle and this.yHalfAngle must each be less than 90 degrees.
     * @exception {DeveloperError} this.radius must be greater than or equal to zero.
     */
    RectangularPyramidSensorVolume.prototype.update = function(context, frameState, commandList) {
        if ((this.xHalfAngle > CesiumMath.PI_OVER_TWO) || (this.yHalfAngle > CesiumMath.PI_OVER_TWO)) {
            throw new DeveloperError('this.xHalfAngle and this.yHalfAngle must each be less than or equal to 90 degrees.');
        }

        var s = this._customSensor;

        s.show = this.show;
        s.showIntersection = this.showIntersection;
        s.showThroughEllipsoid = this.showThroughEllipsoid;
        s.modelMatrix = this.modelMatrix;
        s.bufferUsage = this.bufferUsage;
        s.radius = this.radius;
        s.material = this.material;
        s.intersectionColor = this.intersectionColor;

        if ((this._xHalfAngle !== this.xHalfAngle) || (this._yHalfAngle !== this.yHalfAngle)) {

            this._xHalfAngle = this.xHalfAngle;
            this._yHalfAngle = this.yHalfAngle;

            // At 90 degrees the sensor is completely open, and tan() goes to infinity.
            var tanX = Math.tan(Math.min(this.xHalfAngle, CesiumMath.toRadians(89.0)));
            var tanY = Math.tan(Math.min(this.yHalfAngle, CesiumMath.toRadians(89.0)));
            var theta = Math.atan(tanX / tanY);
            var cone = Math.atan(Math.sqrt(tanX * tanX + tanY * tanY));

            s.setDirections([{
                clock : theta,
                cone : cone
            }, {
                clock : CesiumMath.toRadians(180.0) - theta,
                cone : cone
            }, {
                clock : CesiumMath.toRadians(180.0) + theta,
                cone : cone
            }, {
                clock : -theta,
                cone : cone
            }]);
        }

        s.update(context, frameState, commandList);
    };

    /**
     * DOC_TBA
     * @memberof RectangularPyramidSensorVolume
     */
    RectangularPyramidSensorVolume.prototype.isDestroyed = function() {
        return false;
    };

    /**
     * DOC_TBA
     * @memberof RectangularPyramidSensorVolume
     */
    RectangularPyramidSensorVolume.prototype.destroy = function() {
        this._customSensor = this._customSensor && this._customSensor.destroy();
        return destroyObject(this);
    };

    return RectangularPyramidSensorVolume;
});<|endoftext|>


<commit_before>/*
* @Author: manrajsingh
* @Date:   2016-04-06 15:58:03
* @Last Modified by:   Manraj Singh
* @Last Modified time: 2016-04-07 20:55:54
*/

(function(root, factory){
	if (typeof define === 'function' && define.amd) {
		define(factory);
	} else if (typeof exports === 'object') {
		module.exports = factory();
	} else {
		root.microbar = factory();
	}
})(this, function(){
	var css = '.microbar{width: 100%;height: 2px;z-index: 9999;top:0;background-color: transparent;} .progress{width: 0;height: 100%;background-color: #000000;}';

	function addStyleSheet(){
		if(document.getElementById('microbarstyles') != undefined){
			return;
		}
		var style = document.createElement('style');
		style.type = 'text/css';
		style.id = 'microbarstyles';
		if(style.styleSheet){
			style.styleSheet.cssText = css;
		}
		else{
			style.appendChild(document.createTextNode(css));
		}
		document.head.insertBefore(style, null);
	}

	return function microbar(args){
		args = args || {};
		var current = 0,
			color = args.color || '#000000',
			speed = args.speed || 0.3,
			looping = args.looping || false,
			position = args.position || 'top';
		addStyleSheet();
		var microbar = {
			element : '',
			moveTo: function(percentage){

			},
			setColor: function(color){

			},
			getSpeed: function(){
				return speed;
			},
			setSpeed: function(s){
				speed = s;
			},
			getLooping: function(){
				return looping;
			},
			setLooping: function(loop){
				looping = loop;
			},
			getPosition: function(){
				return position;
			},
			setPosition: function(pos){
				position = pos;
			}
		};
		return microbar;
	};
});<commit_msg>Minor changes<commit_after>/*
* @Author: manrajsingh
* @Date:   2016-04-06 15:58:03
* @Last Modified by:   Manraj Singh
* @Last Modified time: 2016-04-07 22:16:38
*/

(function(root, factory){
	if (typeof define === 'function' && define.amd) {
		define(factory);
	} else if (typeof exports === 'object') {
		module.exports = factory();
	} else {
		root.microbar = factory();
	}
})(this, function(){
	var css = '.microbar{width: 100%;height: 2px;z-index: 9999;top:0;background-color: transparent;} .microbar #progress{width: 0;height: 100%;background-color: #000000;}';
	var ctr = 0;
	function addStyleSheet(){
		if(document.getElementById('microbarstyles') != undefined){
			return;
		}
		var style = document.createElement('style');
		style.type = 'text/css';
		style.id = 'microbarstyles';
		if(style.styleSheet){
			style.styleSheet.cssText = css;
		}
		else{
			style.appendChild(document.createTextNode(css));
		}
		document.head.insertBefore(style, null);
	}

	return function microbar(args){
		args = args || {};
		if(!args.hasOwnProperty("id")){
			throw new Error('You need to provide an ID for your microbar');
		}
		var current = 0,
			color = args.color || '#000000',
			speed = args.speed || 1,
			looping = args.looping || false,
			position = args.position || 'top';
		addStyleSheet();
		var microbar = {
			id : args.id,
			moveTo: function(percentage){

			},
			getSpeed: function(){
				return speed;
			},
			setSpeed: function(s){
				speed = s;
			},
			getLooping: function(){
				return looping;
			},
			setLooping: function(loop){
				looping = loop;
			},
			getPosition: function(){
				return position;
			},
			setPosition: function(pos){
				position = pos;
			}
		};
		return microbar;
	};
});<|endoftext|>


<commit_before>function Liquid(attrs) {
	//driving force convention: positive -> into liquid, neg -> into vapor
	this.type = 'Liquid';
	this.wallInfo = attrs.wallInfo;
	this.wallGas = walls[this.wallInfo];
	this.wallPts = attrs.wallPts || [this.wallGas[this.wallGas.length - 2], this.wallGas[this.wallGas.length - 3]];
	this.handle = attrs.handle;
	this.cleanUpWith = attrs.cleanUpWith || currentSetupType;
	var actCoeffType = attrs.actCoeffType; //twoSfxMrg for two suffix margules,
	var actCoeffInfo = attrs.actCoeffInfo;

	var tempInit = attrs.tempInit;
	this.spcInfo = this.makeSpcInfo(attrs.spcInfo); //formatted as {spc1: {count: #, spcVol: #, cp: #, antoineCoeffs: {a: #,b: #,c: #}, hVap: #} ... } spcVol in L/mol
	this.drivingForce = this.makeDrivingForce(spcInfo);
	this.dotMgrLiq = new DotManager();
	this.wallLiq = this.makeWallLiq(this.spcInfo, this.wallGas, this.wallPts, this.dotMgrLiq);
	var dataGas = this.initData(this.wallGas, this.spcInfo, ['pInt']);
	var dataLiq = this.initData(this.wallLiq, this.spcInfo, ['temp']);
	this.makeDots(this.wallLiq, this.spcInfo, tempInit, this.dotMgrLiq) && this.deleteCount(this.spcInfo);
	this.drawList = this.makeDrawList(this.dotMgrLiq); //need to make draw list in random order otherwise dots drawn on top will look more prominant than they are.
	this.actCoeffFuncs = this.makeActCoeffFuncs(actCoeffType, actCoeffInfo, spcList);

	this.updateListenerName = this.type + this.handle;
	this.setupUpdate(this.spcInfo, this.dataGas, this.dataLiq, this.actCoeffFuncs, this.drivingForce, this.updateListenerName, this.drawList, this.dotMgrLiq)

	//this.setupStd();
}

_.extend(Liquid.prototype, objectFuncs, {
	makeActCoeffFuncs: function(type, info, spcList) {
		if (type == 'twoSfxMrg') {
			var coeff = info.a
			return this.makeTwoSfxMrgFuncs(spcList, coeff);
		}
	},
	makeTwoSfxMrgFuncs: function(spcList, coeff) {
		var funcs = {};
		var gasConst = R;
		for (var spcIdx=0; spcIdx<spcList.length; spcIdx++) {
			var spcName = spcList[spcIdx];
			funcs[spcName] = function(x, T) {
				return Math.exp(coeff * x * x / (gasConst * T));
			}
		}
		return funcs;
	},
	makeWallLiq: function(spcInfo, wallGas, wallPts, dotMgrLiq) {
		var vol = this.getLiqWallVol(spcInfo);
		//liq wall needs to go in opposite direction of gas wall
		var pts = this.getWallLiqPts(wallGas, wallGasPts, vol);
		var handler = {func: this.hit, obj: this};
		window.walls.addWall({pts:pts, handler:handler, handle: 'liquid' + this.handle, record: false, show: false, dotManager: dotMgrLiq});
		return window.walls[window.walls.length - 1];
	},
	getLiqWallVol: function(spcInfo) {
		var vol = 0;
		for (var spcName in spcInfo) {
			vol += spcInfo[spcName].spcVol * spcInfo[spcName].count / N;
		}
		return vol;
	},
	getWallLiqPts: function(wallGas, wallGasPts, vol) {
		var a = wallGas[wallGasPts[0]];
		var b = wallGas[wallGasPts[1]];
		var bottomLeft = a.x < b.x ? a : b;
		var bottomRight = bottomLeft == a ? b : a;
		var height = this.getWallHeight(bottomRight.x - bottomLeft.x, vol);
		var topLeft = bottomLeft.copy().movePt(V(0, -height));
		var topRight = bottomRight.copy().movePt(V(0, -height));
		return [topLeft, bottomLeft, bottomRight, topRight];
	},
	getWallHeight: function(width, vol) {
		return vol/(vConst*width);
	},
	makeDots: function(wallLiq, makeOrder, temp, dotMgrLiq) {
		var pos = wallLiq[0].copy();
		var dims = wallLiq[0].VTo(wallLiq[2]);

		for (var spcName in makeOrder) {
			var order = makeOrder[spcName]
			spcs[spcName].populate(pos, dims, order.count, temp, wallLiq.handle, wallLiq.handle, dotMgrLiq);
		}
	},
	initData: function(wall, spcInfo, extras) {
		var data = {};
		for (var extraIdx=0; extraIdx<extras.length; extraIdx++) {
			var extra = extras[extraIdx];
			var dataObj = wall.getDataObj(extra);
			if (dataObj === false) {
				var recordFunc = 'record' + extra.toCapitalCamelCase();
				wall[recordFunc]();
				data[extra] = wall.getDataObj(extra).src();
			} else {
				data[extra] = dataObj.src();
			}
		}
		for (var spcName in spcInfo) {
			var attrs = {spcName: spcName, tag: wall.handle};
			wall.recordFrac(attrs)
			data[spcName] = wall.getDataObj('frac', attrs).src();
		}
		return data;
	},
	makeSpcInfo: function(spcInfo) {
		var reformat = {};
		for (var infolet in spcInfo) {
			var spc = spcInfo[infolet];
			reformat[infolet] = new this.Species(infolet, spc.count, spc.hVap, spc.cP, spc.spcVol, spc.antoineCoeffs);
		}
		return reformat;
	},
	makeDrivingForce: function(spcInfo) {
		var force = {};
		for (var spcName in spcInfo) {
			force[spcName] = 0;
		}
		return force;
	},
	setupUpdate: function(spcInfo, dataGas, dataLiq, actCoeffFuncs, drivingForce, listenerName, drawList, dotMgrLiq) {
		this.setupUpdateEquil(spcInfo, dataGas, dataLiq, actCoeffFuncs, drivingForce, listenerName);
		this.setupUpdateDraw(drawList);
		this.setupUpdateMove(dotMgrLiq.ALLDOTS); //need to send list of each species.  Need to make velocity vectors for *each* group of dots. whew

	},
	setupUpdateEquil: function(spcInfo, dataGas, dataLiq, actCoeffFuncs, drivingForce, listenerName) {
		addListener(curLevel, 'update', listenerName + 'Equil', function() {
			for (var spcName in spcInfo) {
				var spc = spcInfo[spcName];
				var gasFrac = dataGas[spcName];
				var liqFrac = dataLiq[spcName];
				var liqTemp = dataLiq.temp;
				var actCoeff = actCoeffFuncs[spcName](liqFrac, liqTemp);
				var antCoeffs = spcInfo.antoineCoeffs;
				var pPure = this.getPPure(antCoeffs.a, antCoeffs.b, antCoeffs.c, liqTemp);
				var pEq = pPure * actCoeff * liqFrac;
				var pGas = gasFrac * dataGas.pInt;
				drivingForce[spcName] = pGas - pEq;
			}
		})
	},
	setupUpdateDraw: function(drawList) {
		addListener(curLevel, 'update', listenerName + 'Draw', function() {
			window.drawingTools.dotsAsst(drawList);
		});
	},
	setupUpdateMove: function(dots) {
		var stepSize = Math.max(1, dots.length / 50)
		var numSteps = Math.max(dots.length / stepSize);
		for (var i=0; i<numSteps; i++) {
			var
		}

	},
	getPPure: function(a, b, c, T) {
		Math.pow(10, a - b / (T + c));
	},
	deleteCount: function(spcInfo) {
		for (var a in spcInfo) {
			delete spcInfo[a].count;
		}
	},
	makeDrawList: function(dotMgr) {
		var sacArray = dotMgr.ALLDOTS.concat();
		var draw = [];
		for (var i=0; i<dotMgr.ALLDOTS.length; i++) {
			var spliceIdx = Math.floor(Math.random() * dotMgr.ALLDOTS.length);
			draw.push(sacArray[spliceIdx]);
			sacArray.splice(spiceIdx, 1);
		}
		return draw;

	}

})

Liquid.prototype.Species = function(spcName, count, hVap, cP, spcVol, antoineCoeffs) {
	this.spcName = spcName;
	this.count = count;
	this.hVap = hVap;
	this.cP = cP;
	this.spcVol = spcVol;
	this.antoineCoeffs = antoineCoeffs;
}
<commit_msg>debugged liquid<commit_after>function Liquid(attrs) {
	//driving force convention: positive -> into liquid, neg -> into vapor
	this.type = 'Liquid';
	this.wallInfo = attrs.wallInfo;
	this.wallGas = walls[this.wallInfo];
	this.wallPtIdxs = attrs.wallPts || [this.wallGas.length - 2, this.wallGas.length - 3];
	this.handle = attrs.handle;
	this.cleanUpWith = attrs.cleanUpWith || currentSetupType;
	this.actCoeffType = attrs.actCoeffType; //twoSfxMrg for two suffix margules,
	this.actCoeffInfo = attrs.actCoeffInfo;

	var tempInit = attrs.tempInit;
	this.spcInfo = this.makeSpcInfo(attrs.spcInfo); //formatted as {spc1: {count: #, spcVol: #, cP: #, antoineCoeffs: {a: #,b: #,c: #}, hVap: #} ... } spcVol in L/mol
	this.drivingForce = this.makeDrivingForce(this.spcInfo);
	this.dotMgrLiq = this.makeDotManager(this.spcInfo);
	this.wallLiq = this.makeWallLiq(this.spcInfo, this.wallGas, this.wallPtIdxs, this.dotMgrLiq);
	var dataGas = this.initData(this.wallGas, this.spcInfo, ['pInt']);
	var dataLiq = this.initData(this.wallLiq, this.spcInfo, ['temp']);
	this.makeDots(this.wallLiq, this.spcInfo, tempInit, this.dotMgrLiq) && this.deleteCount(this.spcInfo);
	this.drawList = this.makeDrawList(this.dotMgrLiq); //need to make draw list in random order otherwise dots drawn on top will look more prominant than they are.
	this.actCoeffFuncs = this.makeActCoeffFuncs(this.actCoeffType, this.actCoeffInfo, this.spcInfo);

	this.updateListenerName = this.type + this.handle;
	this.setupUpdate(this.spcInfo, this.dataGas, this.dataLiq, this.actCoeffFuncs, this.drivingForce, this.updateListenerName, this.drawList, this.dotMgrLiq)

	//this.setupStd();
}

_.extend(Liquid.prototype, objectFuncs, {
	makeActCoeffFuncs: function(type, info, spcInfo) {
		if (type == 'twoSfxMrg') {
			var coeff = info.a
			return this.makeTwoSfxMrgFuncs(spcInfo, coeff);
		}
	},
	makeTwoSfxMrgFuncs: function(spcInfo, coeff) {
		var funcs = {};
		var gasConst = R;
		for (var spcName in spcInfo) {
			funcs[spcName] = function(x, T) {
				return Math.exp(coeff * x * x / (gasConst * T));
			}
		}
		return funcs;
	},
	makeWallLiq: function(spcInfo, wallGas, wallPtIdxs, dotMgrLiq) {
		var vol = this.getLiqWallVol(spcInfo);
		//liq wall needs to go in opposite direction of gas wall
		var pts = this.getWallLiqPts(wallGas, wallPtIdxs, vol);
		var handler = {func: this.hit, obj: this};
		window.walls.addWall({pts:pts, handler:handler, handle: 'liquid' + this.handle, record: false, show: false, dotManager: dotMgrLiq});
		return window.walls[window.walls.length - 1];
	},
	getLiqWallVol: function(spcInfo) {
		var vol = 0;
		for (var spcName in spcInfo) {
			vol += spcInfo[spcName].spcVol * spcInfo[spcName].count / N;
		}
		return vol;
	},
	getWallLiqPts: function(wallGas, wallGasPts, vol) {
		var a = wallGas[wallGasPts[0]];
		var b = wallGas[wallGasPts[1]];
		var bottomLeft = a.x < b.x ? a : b;
		var bottomRight = bottomLeft == a ? b : a;
		var height = this.getWallHeight(bottomRight.x - bottomLeft.x, vol);
		var topLeft = bottomLeft.copy().movePt(V(0, -height));
		var topRight = bottomRight.copy().movePt(V(0, -height));
		return [topLeft, bottomLeft, bottomRight, topRight];
	},
	getWallHeight: function(width, vol) {
		return vol/(vConst*width);
	},
	makeDotManager: function(spcInfo) {
		var dotMgr = new DotManager();
		for (var spcName in spcInfo) {
			dotMgr.addSpcs(spcName);
		}
		return dotMgr;
	},
	makeDots: function(wallLiq, makeOrder, temp, dotMgrLiq) {
		var pos = wallLiq[0].copy();
		var dims = wallLiq[0].VTo(wallLiq[2]);

		for (var spcName in makeOrder) {
			var order = makeOrder[spcName]
			spcs[spcName].populate(pos, dims, order.count, temp, wallLiq.handle, wallLiq.handle, dotMgrLiq);
		}
	},
	initData: function(wall, spcInfo, extras) {
		var data = {};
		for (var extraIdx=0; extraIdx<extras.length; extraIdx++) {
			var extra = extras[extraIdx];
			var dataObj = wall.getDataObj(extra);
			if (dataObj === false) {
				var recordFunc = 'record' + extra.toCapitalCamelCase();
				wall[recordFunc]();
				data[extra] = wall.getDataObj(extra).src();
			} else {
				data[extra] = dataObj.src();
			}
		}
		for (var spcName in spcInfo) {
			var attrs = {spcName: spcName, tag: wall.handle};
			wall.recordFrac(attrs)
			data[spcName] = wall.getDataObj('frac', attrs).src();
		}
		return data;
	},
	makeSpcInfo: function(spcInfo) {
		var reformat = {};
		for (var infolet in spcInfo) {
			var spc = spcInfo[infolet];
			reformat[infolet] = new this.Species(infolet, spc.count, spc.hVap, spc.cP, spc.spcVol, spc.antoineCoeffs);
		}
		return reformat;
	},
	makeDrivingForce: function(spcInfo) {
		var force = {};
		for (var spcName in spcInfo) {
			force[spcName] = 0;
		}
		return force;
	},
	setupUpdate: function(spcInfo, dataGas, dataLiq, actCoeffFuncs, drivingForce, listenerName, drawList, dotMgrLiq) {
		this.setupUpdateEquil(spcInfo, dataGas, dataLiq, actCoeffFuncs, drivingForce, listenerName);
		this.setupUpdateDraw(drawList);
		this.setupUpdateMove(dotMgrLiq.lists.ALLDOTS); //need to send list of each species.  Need to make velocity vectors for *each* group of dots. whew

	},
	setupUpdateEquil: function(spcInfo, dataGas, dataLiq, actCoeffFuncs, drivingForce, listenerName) {
		addListener(curLevel, 'update', listenerName + 'Equil', function() {
			for (var spcName in spcInfo) {
				var spc = spcInfo[spcName];
				var gasFrac = dataGas[spcName];
				var liqFrac = dataLiq[spcName];
				var liqTemp = dataLiq.temp;
				var actCoeff = actCoeffFuncs[spcName](liqFrac, liqTemp);
				var antCoeffs = spcInfo.antoineCoeffs;
				var pPure = this.getPPure(antCoeffs.a, antCoeffs.b, antCoeffs.c, liqTemp);
				var pEq = pPure * actCoeff * liqFrac;
				var pGas = gasFrac * dataGas.pInt;
				drivingForce[spcName] = pGas - pEq;
			}
		})
	},
	setupUpdateDraw: function(drawList) {
		addListener(curLevel, 'update', listenerName + 'Draw', function() {
			window.drawingTools.dotsAsst(drawList);
		});
	},
	setupUpdateMove: function(dots) {
		var stepSize = Math.max(1, dots.length / 50)
		var numSteps = Math.max(dots.length / stepSize);
		for (var i=0; i<numSteps; i++) {
			//var
		}

	},
	getPPure: function(a, b, c, T) {
		Math.pow(10, a - b / (T + c));
	},
	deleteCount: function(spcInfo) {
		for (var a in spcInfo) {
			delete spcInfo[a].count;
		}
	},
	makeDrawList: function(dotMgr) {
		var sacArray = dotMgr.lists.ALLDOTS.concat();
		var draw = [];
		for (var i=0; i<dotMgr.lists.ALLDOTS.length; i++) {
			var spliceIdx = Math.floor(Math.random() * sacArray.length);
			draw.push(sacArray[spliceIdx]);
			sacArray.splice(spliceIdx, 1);
		}
		return draw;

	}

})

Liquid.prototype.Species = function(spcName, count, hVap, cP, spcVol, antoineCoeffs) {
	this.spcName = spcName;
	this.count = count;
	this.hVap = hVap;
	this.cP = cP;
	this.spcVol = spcVol;
	this.antoineCoeffs = antoineCoeffs;
}
<|endoftext|>


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

foam.CLASS({
  package: 'foam.classloader',
  name: 'WebModelDisplayer',

  documentation: `
     Load and display a model using class-loader support.

     Sample Usage:
     http://localhost:8000/index.html?model=com.google.foam.demos.lifestar.Disk
  `,

  requires: [
    'foam.u2.stack.Stack',
    'foam.u2.stack.StackView',
    'foam.classloader.OrDAO',
    'foam.classloader.WebModelFileDAO'
  ],

  imports: [
    'arequire',
    'window'
  ],

  exports: [
    'stack',
    foam.String.daoize(foam.core.Model.name)
  ],

  properties: [
    {
      name: 'model',
    },
    {
      name: 'view',
    },
    {
      name: 'stack',
      factory: function() { return this.Stack.create() },
    },
    {
      name: 'locale',
      postSet: function(_, n) { foam.locale = n; }
    },
    {
      class: 'String',
      name: 'classpath'
    },
    {
      name: foam.String.daoize(foam.core.Model.name),
      expression: function(classpath) {
        var prefix   = this.window.location.protocol + '//' + this.window.location.host;
        var paths    = classpath.split(',');
        var modelDao = this.WebModelFileDAO.create({
          url: prefix + paths[0],
        });

        for ( var i = 1, classpath ; classpath = paths[i] ; i++ ) {
          modelDao = this.OrDAO.create({
            delegate: modelDao,
            primary: this.WebModelFileDAO.create({
              url: prefix + classpath
            })
          });
        }
        return modelDao;
      }
    }
  ],

  methods: [
    function fromQuery(opt_query) {
      var search = /([^&=]+)=?([^&]*)/g;
      var query  = opt_query || window.location.search.substring(1);
      var decode = function(s) {
        return decodeURIComponent(s.replace(/\+/g, ' '));
      };
      var params = {};
      var match;

      while ( match = search.exec(query) ) {
        // TODO: move this to Window
        params[decode(match[1])] = decode(match[2]);
      }

      if ( params.model ) {
        this.copyFrom({
          classpath: params.classpath || '/src/',
          model:     params.model,
          view:      params.view
        });
      } else {
        alert('Please specify model. Ex.: ?model=com.acme.MyModel');
      }

      return this;
    },

    function execute() {
      var self     = this;
      var X        = this.__subContext__;
      var promises = [X.arequire(this.model)];

      if (this.view) promises.push(X.arequire(this.view));

      Promise.all(promises).then(function() {
        var model = X.lookup(self.model).create(null, self);
        window.__foam_obj__ = model;
        var view = self.view ?
            X.lookup(self.view).create({data: model}, self) :
            model.toE(null, model);
        self.stack.push(view);
        self.StackView.create({data: self.stack}, model).write();
      })
    }
  ]
});
<commit_msg>Fix usage of StackView in WebModelDisplayer to push a view spec.<commit_after>/**
 * @license
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.CLASS({
  package: 'foam.classloader',
  name: 'WebModelDisplayer',

  documentation: `
     Load and display a model using class-loader support.

     Sample Usage:
     http://localhost:8000/index.html?model=com.google.foam.demos.lifestar.Disk
  `,

  requires: [
    'foam.u2.stack.Stack',
    'foam.u2.stack.StackView',
    'foam.classloader.OrDAO',
    'foam.classloader.WebModelFileDAO'
  ],

  imports: [
    'arequire',
    'window'
  ],

  exports: [
    'stack',
    foam.String.daoize(foam.core.Model.name)
  ],

  properties: [
    {
      name: 'model',
    },
    {
      name: 'view',
    },
    {
      name: 'stack',
      factory: function() { return this.Stack.create() },
    },
    {
      name: 'locale',
      postSet: function(_, n) { foam.locale = n; }
    },
    {
      class: 'String',
      name: 'classpath'
    },
    {
      name: foam.String.daoize(foam.core.Model.name),
      expression: function(classpath) {
        var prefix   = this.window.location.protocol + '//' + this.window.location.host;
        var paths    = classpath.split(',');
        var modelDao = this.WebModelFileDAO.create({
          url: prefix + paths[0],
        });

        for ( var i = 1, classpath ; classpath = paths[i] ; i++ ) {
          modelDao = this.OrDAO.create({
            delegate: modelDao,
            primary: this.WebModelFileDAO.create({
              url: prefix + classpath
            })
          });
        }
        return modelDao;
      }
    }
  ],

  methods: [
    function fromQuery(opt_query) {
      var search = /([^&=]+)=?([^&]*)/g;
      var query  = opt_query || window.location.search.substring(1);
      var decode = function(s) {
        return decodeURIComponent(s.replace(/\+/g, ' '));
      };
      var params = {};
      var match;

      while ( match = search.exec(query) ) {
        // TODO: move this to Window
        params[decode(match[1])] = decode(match[2]);
      }

      if ( params.model ) {
        this.copyFrom({
          classpath: params.classpath || '/src/',
          model:     params.model,
          view:      params.view
        });
      } else {
        alert('Please specify model. Ex.: ?model=com.acme.MyModel');
      }

      return this;
    },

    function execute() {
      var self     = this;
      var X        = this.__subContext__;
      var promises = [X.arequire(this.model)];

      if (this.view) promises.push(X.arequire(this.view));

      Promise.all(promises).then(function() {
        var model = X.lookup(self.model).create(null, self);
        window.__foam_obj__ = model;

        var viewSpec = self.view ? { class: self.view, data: model } : model.toE.bind(model);

        self.stack.push(viewSpec);
        self.StackView.create({data: self.stack}).write();
      })
    }
  ]
});
<|endoftext|>


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

const moment = require('moment');
const repoLicense = require('./config').config.repoLicense;

const Utils = {};

const CryptoJS = require('crypto-js');

Utils.hashCode = (s) => CryptoJS.MD5(s).toString();

Utils.exitApplication = (errCode = -1) => {
	// eslint-disable-next-line no-process-exit
	process.exit(errCode);
};

Utils.sleep = (ms) => new Promise((resolve) => {
	setTimeout(resolve, ms);
});

Utils.getCurrentDateTimeAsString = () => moment().format('YYYY-MM-DD_HH[h]mm[m]ss[s]');

Utils.gatherProcessInformation = (
	owner,
	model,
	database,
	queue,
	filetype,
	filesize,
) => (
	{
		DateTime: Date.now(),
		Owner: owner,
		Model: model,
		Database: database,
		Queue: queue, // logLabel.label,
		FileType: filetype, // file.split('.').pop().toString(),
		FileSize: filesize, // fileStats.size,
		licenseKey: repoLicense
	});

module.exports = Utils;
<commit_msg>#552 satisfy lint<commit_after>/**
 * Copyright (C) 2020 3D Repo Ltd
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 */

const CryptoJS = require('crypto-js');
const moment = require('moment');
const { repoLicense } = require('./config').config;

const Utils = {};

Utils.hashCode = (s) => CryptoJS.MD5(s).toString();

Utils.exitApplication = (errCode = -1) => {
	// eslint-disable-next-line no-process-exit
	process.exit(errCode);
};

Utils.sleep = (ms) => new Promise((resolve) => {
	setTimeout(resolve, ms);
});

Utils.getCurrentDateTimeAsString = () => moment().format('YYYY-MM-DD_HH[h]mm[m]ss[s]');

Utils.gatherProcessInformation = (
	owner,
	model,
	database,
	queue,
	filetype,
	filesize,
) => (
	{
		DateTime: Date.now(),
		Owner: owner,
		Model: model,
		Database: database,
		Queue: queue, // logLabel.label,
		FileType: filetype, // file.split('.').pop().toString(),
		FileSize: filesize, // fileStats.size,
		licenseKey: repoLicense,
	});

module.exports = Utils;
<|endoftext|>


<commit_before>function(doc){
    if (doc.django_type == "users.hquserprofile")
    	for (var i=0;i<doc.domain_accounts.length;i++)
    	{
            emit([doc.django_user.username,
                  doc.domain_accounts[i].domain],
                  doc);
    	}
}

<commit_msg>fix by_username_domain map function<commit_after>function(doc){
    if (doc.django_type == "users.hquserprofile")
    	for (var i=0;i<doc.domain_memberships.length;i++)
    	{
            emit([doc.django_user.username,
                  doc.domain_memberships[i].domain],
                  doc);
    	}
}

<|endoftext|>


<commit_before>/**
 *  KitScript - A User Script Safari Extension
 */

 /**
  *  KSUtils (KitScript Utilitary Class)
  */
 var KSUtils = Class.create({

     initialize: function () {

         this._vl = 0;
     },
     /**
      *  @param int verboseLevel (0=Silenced,1=Console,2=BrowserAlert)
      */
     setVerboseLevel: function (verboseLevel) {

         this._vl = verboseLevel;
     },
     log: function (msg) {

         switch (this._vl) {

             case 2:
                 alert(msg);
             case 1:
                 console.log(msg);
                 break;
             case 0:
             default:
                 // Silence
         }
     }
 });

/**
*  KSBase (KitScript Base Object Class)
*/
var KSBase = Class.create({

    initialize: function () {

        this._isTabOpen = false;

        this.defaultPage = 'MainPanel.html';

        this._previousPage = null;
        this._currentPage = this.defaultPage;

        this._tab = null;
        this._url = null;

        this._isEnabled = true;
    },
    openPage: function (page) {

        if (this._isTabOpen === false)
            this.openTab();

        this.setTabPage(page);
    },
    closePage: function () {

        this.setTabPage(this.defaultPage);
        this.closeTab();
    },
    setTabPage: function (page) {

        this._previousPage = this._currentPage;
        this._currentPage = page;

        this._tab.url = location.href.replace(this._previousPage, this._currentPage);
    },
    openTab: function () {

        this._tab = safari.application.activeBrowserWindow.openTab('foreground',-1);
        this._isTabOpen = true;
    },
    closeTab: function () {

        if (this._tab !== null) {

            this._tab.close();
            this._tab = null;
            this._isTabOpen = false;
        }
    },
    isTabOpen: function () {

        return this._isTabOpen;
    },
    isEnabled: function () {

        return this._isEnabled;
    },
    toggleEnable: function () {

        this._isEnabled = !this._isEnabled;

        //_triggerNotEnabled();
    }
});

/**
 *  KSContentManager (KitScript Content Manager for the Main Panel)
 */
var KSContentManager = Class.create({

    initialize: function () {

        this.contents = [
            {
                id: "userscript-manager",
                title: "User Script Manager"
            },
            {
                id: "global-settings",
                title: "Global Settings"
            },
            {
                id: "new-userscript",
                title: "User Script Editor"
            },
            {
                id: "about",
                title: "About KitScript"
            }
        ];

        this.defaultContentId = this.contents[0].id;

        this._currentContentId = this.defaultContentId;
        this._previousContentId = null;
    },
    _hideContent: function (contentId) {

        ks.$('#'+contentId).css('display','none');
    },
    _showContent: function (contentId) {

        ks.$('#'+contentId).css('display','block');
    },
    _setDocumentTitle: function (newTitle) {

        document.title = "KitScript | "+newTitle;
    },
    _cleanContentIdStr: function (contentId) {

        if (contentId.substr(0,1) == '#')
            return contentId.substr(1,contentId.length);
        else
            return contentId;
    },
    getTitleByContentId: function (contentId) {

        _contentId = this._cleanContentIdStr(contentId);

        for (var i=0; i < this.contents.length; i++) {

            if (this.contents[i].id == _contentId)
                return this.contents[i].title;
        }
    },
    initContent: function () {

        this._setDocumentTitle(this.getTitleByContentId(this.defaultContentId));
    },
    transitContent: function (newContentId) {

        _contentId = this._cleanContentIdStr(newContentId);

        this._previousContentId = this._currentContentId;
        this._currentContentId = _contentId;

        this._hideContent(this._previousContentId);
        this._showContent(this._currentContentId);

        this._setDocumentTitle(this.getTitleByContentId(_contentId));
    }
});

/**
 *  KSMainPanel (KitScript User Scripts Main Panel Class)
 */
var KSMainPanel = Class.create(KSBase, {

    initialize: function ($super) {

        this._pageName = "MainPanel.html";
        this.contentManager = null;
        this.globalSettingsForm = null;

        $super();
    },
    openPage: function ($super) {

        $super(this._pageName);
    }
});

var KSGlobalSettingsForm = Class.create({

    initialize: function () {

    },
    addExclude: function () {

        ks.$('#ks-gs-add-modal').modal('show');
    },
    editExclude: function () {

    },
    removeExclude: function () {

    }
});

/*

openUserScriptSettings: function (id) {

    //ks.scriptSettingsPanel.openPage(id);
},
disableUserScript: function (id) {

    //db.disableScript(id);

    //$('#user-script-'+id).addClass('disabled');
    //$('button','#us-list tbody tr td').attr('disabled','disabled');
},
deleteUserScript: function (id) {

    //db.remove(id);

    //$('#user-script-'+id).remove();
}

*/

/**
 *  KSNewPanel (KitScript New User Script Panel Class)
 *
var KSNewPanel = Class.create(KSBase, {

    initialize: function () {

        this._pageName = "newUserScriptPanel.html";
    },
    openPage: function ($super) {

        $super(this._pageName);
    },
    save: function (newUserScriptForm) {
        /*
        code = newUserScriptForm.us-code;

        us = new UserScript(code);

        name = us.getName();
        desc = us.getDescription();
        includes = us.getIncludes().join(",");
        excludes = us.getExcludes().join(",");
        disabled = 0;

        db.create(name, desc, includes, excludes, code, disabled);
        *
    },
    autoSave: function () {

    }
});
*/

/**
 *  KSSettingsPanel (KitScript User Script Settings Panel Class)
 *
var KSSettingsPanel = Class.create(KSBase, {

    initialize: function () {

        this._pageName = "scriptSettingsPanel.html";
    },
    openPage: function ($super, scriptId) {

        this._scriptId = scriptId;

        $super(this._pageName);

        //this.showUserSettings();
    },
    close: function ($super) {

        //$super();
    },
    showUserSettings: function () {

    },
    showScriptSettings: function () {

    },
    showScriptEdition: function () {

    },
    saveUserSettings: function () {

    },
    saveScriptSettings: function () {

    },
    saveScriptEdition: function (userScriptForm) {
        /*
        id = userScriptForm.us-id;

        code = userScriptForm.us-code;

        us = new UserScript(code);

        name = us.getName();
        desc = us.getDescription();
        includes = us.getIncludes().join(",");
        excludes = us.getExcludes().join(",");
        disabled = userScriptForm.isDisabled;

        db.update(name, desc, includes, excludes, code, disabled, id);
        *
    }
});
*/

/**
 *  KSStorage (KitScript Storage Class)
 */
var KSStorage = Class.create(Storage, {

    initialize: function ($super) {

        this._dbName = 'KitScript';
        this._dbVersion = '1.0';
        this._dbDisplayName = 'KitScript';
        this._dbSize = 10 * 1024 * 1024; // 10 MB in bytes

        this._dbTable = "UserScripts";

        this._isDbExistant = false;

        $super(this._dbName, this._dbVersion, this._dbDisplayName, this._dbSize);
    },
    connect: function ($super) {

        _db = $super();

        this._verifyDb();

        return _db;
    },
    isDbExistant: function () {

        return this._isDbExistant;
    },
    _verifyDb: function () {

        this._isDbExistant = false;

        _fH = function (transaction, resultSet) {

            var _db = transaction.storageInstance;

            _statementCallback(transaction, resultSet);

            if (resultSet.rows.length > 0) {

                var _row = resultSet.rows.item(0);

                if (_row['name'] == _db._dbTable) {

                    _db._isDbExistant = true;
                }
            }

            return this._isDbExistant;
        }

        sqlArray = new SQLStatementsArray();

        sqlArray.push(this, "SELECT name FROM sqlite_master WHERE type=? AND name=?;", ["table",this._dbTable], _fH, _errorHandler);

        this.transact(sqlArray);
    },
    createTable: function (isDropAllowed) {

        if (isDropAllowed === true) {

            _fH = function () { console.log("Table dropped."); };

            sqlArray = new SQLStatementsArray();

            sqlArray.push(this, 'DROP TABLE '+this._dbTable+';', [], _fH, _errorHandler);

            this.transact(sqlArray);
        }

        _fH = function () { console.log("Table created."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push(this, 'CREATE TABLE IF NOT EXISTS '+this._dbTable+' (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, description TEXT NOT NULL, whitelist TEXT NOT NULL, blacklist TEXT NOT NULL, script TEXT NOT NULL, disabled INT NOT NULL DEFAULT 0);', [], _fH, _errorHandler);

        this.transact(sqlArray);
    },
    insert: function (name, desc, includes, excludes, code, disabled) {

        _fH = function () { console.log("Data inserted."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push(this, "INSERT INTO "+this._dbTable+" (name, description, whitelist, blacklist, script, disabled) VALUES (?, ?, ?, ?, ?, ?);", [name, desc, includes, excludes, code, disabled], _fH, _errorHandler);

        this.transact(sqlArray);
    },
    update: function (id, name, desc, includes, excludes, code, disabled) {

        _fH = function () { console.log("Data updated."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push(this, "UPDATE "+this._dbTable+" SET name = ?, description = ?, whitelist = ?, blacklist = ?, script = ?, disabled = ? WHERE id = ?;", [name, desc, includes, excludes, code, disabled, id], _fH, _errorHandler);

        this.transact(sqlArray);
    },
    fetch: function (id, fetchCallback) {

        sqlArray = new SQLStatementsArray();

        sqlArray.push(this, "SELECT * FROM "+this._dbTable+" WHERE id = ?;", [id], fetchCallback, _errorHandler);

        this.transact(sqlArray);
    },
    fetchAll: function (offset, limit, fetchCallback) {

        sqlArray = new SQLStatementsArray();

        sqlArray.push(this, "SELECT * FROM "+this._dbTable+" LIMIT ?, ?;", [offset, limit], fetchCallback, _errorHandler);

        this.transact(sqlArray);
    },
    remove: function (id) {

        _fH = function () { console.log("Data deleted."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push(this, "DELETE FROM "+this._dbTable+" WHERE id = ?;", [id], _fH, _killTransaction);

        this.transact(sqlArray);
    },
    disableScript: function (id) {

        _fH = function () { console.log("Script disabled."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push(this, "UPDATE "+this._dbTable+" SET disabled = 1 WHERE id = ?;", [id], _fH, _errorHandler);

        this.transact(sqlArray);
    }
});

var KitScript = Class.create(KSUtils, {

    initialize: function ($super) {

        this._isEnabled = true;

        this.db = new KSStorage();
        this.$ = jQuery;
        this.mainPanel = new KSMainPanel();
        this.mainPanel.contentManager = new KSContentManager();

        this.mainPanel.globalSettingsForm = new KSGlobalSettingsForm();

        try {

            this.db.connect();
        } catch (e) {

            ks.log(e.getMessage());
        }

        $super();

        this.setVerboseLevel(1);
    },
    isEnabled: function () {

        return this._isEnabled;
    },
    setEnable: function () {

        if (!this.isEnabled()) {

            this._isEnabled = true;
            this.$('#toggle-enable-dropdown').text("KitScript is Enabled!");
        }
    },
    setDisable: function () {

        if (this.isEnabled()) {

            this._isEnabled = false;
            this.$('#toggle-enable-dropdown').text("KitScript is Disabled!");
        }
    }
});

function _ksCommandHandler(event) {

    switch (event.command)
    {
        case "close":

            ks.log("Something closed.");
            //ks.mainPanel.close();
            break;
        case "toggle_enable":

            alert("command toggle_enable");
            break;
        case "open_tab":

            ks.mainPanel.openTab();
            ks.mainPanel.setTabPage(ks.mainPanel.defaultPage);
            //ks.mainPanel.contentManager.initContent();
            break;
        case "goto_manage":

            break;
        case "goto_new":

            break;
        case "goto_globsettings":

            break;
    }
}

function _ksValidateHandler(event) {

    switch (event.command)
    {
        case "close":

            break;
        case "toggle_enable":

            alert("validate toggle_enable");
            break;
        case "open_tab":

            //if (ks.mainPanel.isTabOpen() === true) {

            //    ks.mainPanel.openPage(ks.mainPanel.defaultPage);
            //}
            break;
        case "goto_manage":

            break;
        case "goto_new":

            break;
        case "goto_globsettings":

            break;
    }
}

safari.application.addEventListener("command", _ksCommandHandler, false);
safari.application.addEventListener("validate", _ksValidateHandler, false);

<commit_msg>cleanup of old comments & added database classes<commit_after>/**
 *  KitScript - A User Script Safari Extension
 */

 /**
  *  KSUtils (KitScript Utilitary Class)
  */
 var KSUtils = Class.create({

     initialize: function () {

         this._vl = 0;
     },
     /**
      *  @param int verboseLevel (0=Silenced,1=Console,2=BrowserAlert)
      */
     setVerboseLevel: function (verboseLevel) {

         this._vl = verboseLevel;
     },
     log: function (msg) {

         switch (this._vl) {

             case 2:
                 alert(msg);
             case 1:
                 console.log(msg);
                 break;
             case 0:
             default:
                 // Silence
         }
     }
 });

/**
*  KSBase (KitScript Base Object Class)
*/
var KSBase = Class.create({

    initialize: function () {

        this._isTabOpen = false;

        this.defaultPage = 'MainPanel.html';

        this._previousPage = null;
        this._currentPage = this.defaultPage;

        this._tab = null;
        this._url = null;

        this._isEnabled = true;
    },
    openPage: function (page) {

        if (this._isTabOpen === false)
            this.openTab();

        this.setTabPage(page);
    },
    closePage: function () {

        this.setTabPage(this.defaultPage);
        this.closeTab();
    },
    setTabPage: function (page) {

        this._previousPage = this._currentPage;
        this._currentPage = page;

        this._tab.url = location.href.replace(this._previousPage, this._currentPage);
    },
    openTab: function () {

        this._tab = safari.application.activeBrowserWindow.openTab('foreground',-1);
        this._isTabOpen = true;
    },
    closeTab: function () {

        if (this._tab !== null) {

            this._tab.close();
            this._tab = null;
            this._isTabOpen = false;
        }
    },
    isTabOpen: function () {

        return this._isTabOpen;
    },
    isEnabled: function () {

        return this._isEnabled;
    },
    toggleEnable: function () {

        this._isEnabled = !this._isEnabled;

        //_triggerNotEnabled();
    }
});

/**
 *  KSContentManager (KitScript Content Manager for the Main Panel)
 */
var KSContentManager = Class.create({

    initialize: function () {

        this.contents = [
            {
                id: "userscript-manager",
                title: "User Script Manager"
            },
            {
                id: "global-settings",
                title: "Global Settings"
            },
            {
                id: "new-userscript",
                title: "User Script Editor"
            },
            {
                id: "about",
                title: "About KitScript"
            }
        ];

        this.defaultContentId = this.contents[0].id;

        this._currentContentId = this.defaultContentId;
        this._previousContentId = null;
    },
    _hideContent: function (contentId) {

        ks.$('#'+contentId).css('display','none');
    },
    _showContent: function (contentId) {

        ks.$('#'+contentId).css('display','block');
    },
    _setDocumentTitle: function (newTitle) {

        document.title = "KitScript | "+newTitle;
    },
    _cleanContentIdStr: function (contentId) {

        if (contentId.substr(0,1) == '#')
            return contentId.substr(1,contentId.length);
        else
            return contentId;
    },
    getTitleByContentId: function (contentId) {

        _contentId = this._cleanContentIdStr(contentId);

        for (var i=0; i < this.contents.length; i++) {

            if (this.contents[i].id == _contentId)
                return this.contents[i].title;
        }
    },
    initContent: function () {

        this._setDocumentTitle(this.getTitleByContentId(this.defaultContentId));
    },
    transitContent: function (newContentId) {

        _contentId = this._cleanContentIdStr(newContentId);

        this._previousContentId = this._currentContentId;
        this._currentContentId = _contentId;

        this._hideContent(this._previousContentId);
        this._showContent(this._currentContentId);

        this._setDocumentTitle(this.getTitleByContentId(_contentId));
    }
});

/**
 *  KSMainPanel (KitScript User Scripts Main Panel Class)
 */
var KSMainPanel = Class.create(KSBase, {

    initialize: function ($super) {

        this._pageName = "MainPanel.html";
        this.contentManager = null;
        this.globalSettingsForm = null;

        $super();
    },
    openPage: function ($super) {

        $super(this._pageName);
    }
});

var KSGlobalSettingsForm = Class.create({

    initialize: function () {

    },
    addExclude: function () {

        ks.$('#ks-gs-add-modal').modal('show');
    },
    editExclude: function () {

    },
    removeExclude: function () {

    }
});

/*

openUserScriptSettings: function (id) {

    //ks.scriptSettingsPanel.openPage(id);
},
disableUserScript: function (id) {

    //db.disableScript(id);

    //$('#user-script-'+id).addClass('disabled');
    //$('button','#us-list tbody tr td').attr('disabled','disabled');
},
deleteUserScript: function (id) {

    //db.remove(id);

    //$('#user-script-'+id).remove();
}

*/

/**
 *  KSStorage (KitScript Storage Class)
 */
var KSStorage = Class.create(Storage, {

    initialize: function ($super) {

        this._dbName = 'KitScript';
        this._dbVersion = '1.0';
        this._dbDisplayName = 'KitScript';
        this._dbSize = 10 * 1024 * 1024; // 10 MB in bytes

        this._isDbExistant = false;

        $super(this._dbName, this._dbVersion, this._dbDisplayName, this._dbSize);
    },
    connect: function ($super) {

        _db = $super();

        this._verifyDb();

        return _db;
    },
    isDbExistant: function () {

        return this._isDbExistant;
    },
    _verifyDb: function () {

        this._isDbExistant = false;

        _fH = function (transaction, resultSet) {

            var _db = transaction.storageInstance;

            _statementCallback(transaction, resultSet);

            if (resultSet.rows.length > 0) {

                var _row = resultSet.rows.item(0);

                if (_row['name'] == _db._dbTable) {

                    _db._isDbExistant = true;
                }
            }

            return this._isDbExistant;
        }

        sqlArray = new SQLStatementsArray();

        sqlArray.push(this, "SELECT name FROM sqlite_master WHERE type=? AND name=?;", ["table",this._dbTable], _fH, _errorHandler);

        this.transact(sqlArray);
    },
    createTables: function (isDropAllowed) {

        if (isDropAllowed === true) {

            _fH = function () { console.log("Table dropped."); };

            sqlArray = new SQLStatementsArray();

            sqlArray.push(this, 'DROP TABLE '+this._dbTable+';', [], _fH, _errorHandler);

            this.transact(sqlArray);
        }

        _fH1 = function () { console.log("Table created."); };
        _fH2 = function () { console.log("Data inserted."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push(this, 'CREATE TABLE IF NOT EXISTS UserScripts (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, description TEXT NOT NULL, whitelist TEXT NOT NULL, blacklist TEXT NOT NULL, script TEXT NOT NULL, disabled INT NOT NULL DEFAULT 0);', [], _fH1, _errorHandler);
        sqlArray.push(this, 'CREATE TABLE IF NOT EXISTS GlobalExcludes (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, url TEXT NOT NULL);', [], _fH1, _errorHandler);
        sqlArray.push(this, 'CREATE TABLE IF NOT EXISTS KitScript (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, enabled INT NOT NULL DEFAULT 1);', [], _fH1, _errorHandler);
        sqlArray.push(this, "INSERT INTO KitScript (enabled) VALUES (1);", [], _fH2, _errorHandler);

        this.transact(sqlArray);
    }
});

var KSUserScriptStorage = Class.create({

    initialize: function () {

        this._dbTable = "UserScripts";
    },
    insert: function (name, desc, includes, excludes, code, disabled) {

        _fH = function () { console.log("Data inserted."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push(this, "INSERT INTO "+this._dbTable+" (name, description, whitelist, blacklist, script, disabled) VALUES (?, ?, ?, ?, ?, ?);", [name, desc, includes, excludes, code, disabled], _fH, _errorHandler);

        this.transact(sqlArray);
    },
    update: function (id, name, desc, includes, excludes, code, disabled) {

        _fH = function () { console.log("Data updated."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push(this, "UPDATE "+this._dbTable+" SET name = ?, description = ?, whitelist = ?, blacklist = ?, script = ?, disabled = ? WHERE id = ?;", [name, desc, includes, excludes, code, disabled, id], _fH, _errorHandler);

        this.transact(sqlArray);
    },
    fetch: function (id, fetchCallback) {

        sqlArray = new SQLStatementsArray();

        sqlArray.push(this, "SELECT * FROM "+this._dbTable+" WHERE id = ?;", [id], fetchCallback, _errorHandler);

        this.transact(sqlArray);
    },
    fetchAll: function (offset, limit, fetchCallback) {

        sqlArray = new SQLStatementsArray();

        sqlArray.push(this, "SELECT * FROM "+this._dbTable+" LIMIT ?, ?;", [offset, limit], fetchCallback, _errorHandler);

        this.transact(sqlArray);
    },
    remove: function (id) {

        _fH = function () { console.log("Data deleted."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push(this, "DELETE FROM "+this._dbTable+" WHERE id = ?;", [id], _fH, _killTransaction);

        this.transact(sqlArray);
    },
    disableScript: function (id) {

        _fH = function () { console.log("Script disabled."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push(this, "UPDATE "+this._dbTable+" SET disabled = 1 WHERE id = ?;", [id], _fH, _errorHandler);

        this.transact(sqlArray);
    }
});

var KSGlobalExcludesStorage = Class.create({

    initialize: function () {

        this._dbTable = "GlobalExcludes";
    },
    insert: function (url) {

        _fH = function () { console.log("Data inserted."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push(this, "INSERT INTO "+this._dbTable+" (url) VALUES (?);", [url], _fH, _errorHandler);

        this.transact(sqlArray);
    },
    update: function (id, url) {

        _fH = function () { console.log("Data updated."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push(this, "UPDATE "+this._dbTable+" SET url = ? WHERE id = ?;", [url, id], _fH, _errorHandler);

        this.transact(sqlArray);
    },
    fetch: function (id, fetchCallback) {

        sqlArray = new SQLStatementsArray();

        sqlArray.push(this, "SELECT * FROM "+this._dbTable+" WHERE id = ?;", [id], fetchCallback, _errorHandler);

        this.transact(sqlArray);
    },
    fetchAll: function (offset, limit, fetchCallback) {

        sqlArray = new SQLStatementsArray();

        sqlArray.push(this, "SELECT * FROM "+this._dbTable+" LIMIT ?, ?;", [offset, limit], fetchCallback, _errorHandler);

        this.transact(sqlArray);
    },
    remove: function (id) {

        _fH = function () { console.log("Data deleted."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push(this, "DELETE FROM "+this._dbTable+" WHERE id = ?;", [id], _fH, _killTransaction);

        this.transact(sqlArray);
    }
});

var KSKitScriptStorage = Class.create({

    initialize: function () {

        this._dbTable = "KitScript";
    },
    enableKitScript: function () {

        _fH = function () { console.log("KitScript is enabled."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push(this, "UPDATE "+this._dbTable+" SET enabled = 1 WHERE id = 1;", [], _fH, _errorHandler);

        this.transact(sqlArray);
    },
    disableKitScript: function () {

        _fH = function () { console.log("KitScript is disabled."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push(this, "UPDATE "+this._dbTable+" SET enabled = 0 WHERE id = 1;", [], _fH, _errorHandler);

        this.transact(sqlArray);
    }
});

var KitScript = Class.create(KSUtils, {

    initialize: function ($super) {

        this._isEnabled = true;

        this.db = new KSStorage();
        this.$ = jQuery;
        this.mainPanel = new KSMainPanel();
        this.mainPanel.contentManager = new KSContentManager();

        this.mainPanel.globalSettingsForm = new KSGlobalSettingsForm();

        try {

            this.db.connect();
        } catch (e) {

            ks.log(e.getMessage());
        }

        $super();

        this.setVerboseLevel(1);
    },
    isEnabled: function () {

        return this._isEnabled;
    },
    setEnable: function () {

        if (!this.isEnabled()) {

            this._isEnabled = true;
            this.$('#toggle-enable-dropdown').text("KitScript is Enabled!");
        }
    },
    setDisable: function () {

        if (this.isEnabled()) {

            this._isEnabled = false;
            this.$('#toggle-enable-dropdown').text("KitScript is Disabled!");
        }
    }
});

function _ksCommandHandler(event) {

    switch (event.command)
    {
        case "close":

            ks.log("Something closed.");
            //ks.mainPanel.close();
            break;
        case "toggle_enable":

            alert("command toggle_enable");
            break;
        case "open_tab":

            ks.mainPanel.openTab();
            ks.mainPanel.setTabPage(ks.mainPanel.defaultPage);
            //ks.mainPanel.contentManager.initContent();
            break;
        case "goto_manage":

            break;
        case "goto_new":

            break;
        case "goto_globsettings":

            break;
    }
}

function _ksValidateHandler(event) {

    switch (event.command)
    {
        case "close":

            break;
        case "toggle_enable":

            alert("validate toggle_enable");
            break;
        case "open_tab":

            //if (ks.mainPanel.isTabOpen() === true) {

            //    ks.mainPanel.openPage(ks.mainPanel.defaultPage);
            //}
            break;
        case "goto_manage":

            break;
        case "goto_new":

            break;
        case "goto_globsettings":

            break;
    }
}

safari.application.addEventListener("command", _ksCommandHandler, false);
safari.application.addEventListener("validate", _ksValidateHandler, false);

<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';

import Events, { STORIES_CONFIGURED } from '@storybook/core-events';

import initProviderApi from './init-provider-api';

import Store from './store';
import getInitialState from './initial-state';

import initAddons from './addons';
import initChannel from './channel';
import initNotifications from './notifications';
import initStories from './stories';
import initLayout from './layout';
import initShortcuts from './shortcuts';
import initURL from './url';
import initVersions from './versions';

const Context = React.createContext({ api: undefined, state: getInitialState({}) });

const { STORY_CHANGED, SET_STORIES, SELECT_STORY } = Events;

export class Provider extends Component {
  static propTypes = {
    navigate: PropTypes.func.isRequired,
    provider: PropTypes.shape({}).isRequired,
    location: PropTypes.shape({}).isRequired,
    path: PropTypes.string,
    viewMode: PropTypes.oneOf(['story', 'info']),
    storyId: PropTypes.string,
    children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]).isRequired,
  };

  static defaultProps = {
    viewMode: undefined,
    storyId: undefined,
    path: undefined,
  };

  constructor(props) {
    super(props);
    const { provider, location, path, viewMode, storyId, navigate } = props;

    const store = new Store({
      getState: () => this.state,
      setState: (a, b) => this.setState(a, b),
    });

    // Initialize the state to be the initial (persisted) state of the store.
    // This gives the modules the chance to read the persisted state, apply their defaults
    // and override if necessary
    this.state = store.getInitialState();

    const apiData = {
      navigate,
      store,
      provider,
      location,
      path,
      viewMode,
      storyId,
    };

    this.modules = [
      initChannel,
      initAddons,
      initLayout,
      initNotifications,
      initShortcuts,
      initStories,
      initURL,
      initVersions,
    ].map(initModule => initModule(apiData));

    // Create our initial state by combining the initial state of all modules, then overlaying any saved state
    const state = getInitialState(...this.modules.map(m => m.state));

    // Get our API by combining the APIs exported by each module
    const combo = Object.assign({ navigate }, ...this.modules.map(m => m.api));

    const api = initProviderApi({ provider, store, api: combo });

    api.on(STORY_CHANGED, id => {
      const options = api.getParameters(id, 'options');

      api.setOptions(options);
    });

    api.on(SET_STORIES, data => {
      api.setStories(data.stories);

      const options = storyId
        ? api.getParameters(storyId, 'options')
        : api.getParameters(Object.keys(data.stories)[0], 'options');

      api.setOptions(options);
    });
    api.on(STORIES_CONFIGURED, () => {
      store.setState({ storiesConfigured: true });
    });
    api.on(SELECT_STORY, ({ kind, story, ...rest }) => {
      api.selectStory(kind, story, rest);
    });

    // TODO: cleanup into the module
    // TODO: animation isn't serializing succesfully, should use telejson
    const {
      theme: { animation, ...rest },
      // eslint-disable-next-line react/destructuring-assignment
    } = this.state.ui;
    this.state = Object.assign({}, state, {
      ui: { ...state.ui, theme: { ...state.ui.theme, ...rest } },
    });
    this.api = api;
  }

  componentDidMount() {
    // Now every module has had a chance to set its API, call init on each module which gives it
    // a chance to do things that call other modules' APIs.
    this.modules.forEach(({ init }) => {
      if (init) {
        init({ api: this.api });
      }
    });
  }

  shouldComponentUpdate(nextProps, nextState) {
    const { state: prevState, props: prevProps } = this;

    if (prevState !== nextState) {
      return true;
    }
    if (prevProps.path !== nextProps.path) {
      return true;
    }
    return false;
  }

  static getDerivedStateFromProps = (props, state) => {
    if (state.path !== props.path) {
      return {
        ...state,
        location: props.location,
        path: props.path,
        viewMode: props.viewMode,
        storyId: props.storyId,
      };
    }
    return null;
  };

  render() {
    const { children } = this.props;
    const value = {
      state: this.state,
      api: this.api,
    };

    return (
      <Context.Provider value={value}>
        {typeof children === 'function' ? children(value) : children}
      </Context.Provider>
    );
  }
}
Provider.displayName = 'Manager';

export const { Consumer } = Context;
<commit_msg>FIX problem with loading empty localStorage to theme<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';

import Events, { STORIES_CONFIGURED } from '@storybook/core-events';

import initProviderApi from './init-provider-api';

import Store from './store';
import getInitialState from './initial-state';

import initAddons from './addons';
import initChannel from './channel';
import initNotifications from './notifications';
import initStories from './stories';
import initLayout from './layout';
import initShortcuts from './shortcuts';
import initURL from './url';
import initVersions from './versions';

const Context = React.createContext({ api: undefined, state: getInitialState({}) });

const { STORY_CHANGED, SET_STORIES, SELECT_STORY } = Events;

export class Provider extends Component {
  static propTypes = {
    navigate: PropTypes.func.isRequired,
    provider: PropTypes.shape({}).isRequired,
    location: PropTypes.shape({}).isRequired,
    path: PropTypes.string,
    viewMode: PropTypes.oneOf(['story', 'info']),
    storyId: PropTypes.string,
    children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]).isRequired,
  };

  static defaultProps = {
    viewMode: undefined,
    storyId: undefined,
    path: undefined,
  };

  constructor(props) {
    super(props);
    const { provider, location, path, viewMode, storyId, navigate } = props;

    const store = new Store({
      getState: () => this.state,
      setState: (a, b) => this.setState(a, b),
    });

    // Initialize the state to be the initial (persisted) state of the store.
    // This gives the modules the chance to read the persisted state, apply their defaults
    // and override if necessary
    this.state = store.getInitialState();

    const apiData = {
      navigate,
      store,
      provider,
      location,
      path,
      viewMode,
      storyId,
    };

    this.modules = [
      initChannel,
      initAddons,
      initLayout,
      initNotifications,
      initShortcuts,
      initStories,
      initURL,
      initVersions,
    ].map(initModule => initModule(apiData));

    // Create our initial state by combining the initial state of all modules, then overlaying any saved state
    const state = getInitialState(...this.modules.map(m => m.state));

    // Get our API by combining the APIs exported by each module
    const combo = Object.assign({ navigate }, ...this.modules.map(m => m.api));

    const api = initProviderApi({ provider, store, api: combo });

    api.on(STORY_CHANGED, id => {
      const options = api.getParameters(id, 'options');

      api.setOptions(options);
    });

    api.on(SET_STORIES, data => {
      api.setStories(data.stories);

      const options = storyId
        ? api.getParameters(storyId, 'options')
        : api.getParameters(Object.keys(data.stories)[0], 'options');

      api.setOptions(options);
    });
    api.on(STORIES_CONFIGURED, () => {
      store.setState({ storiesConfigured: true });
    });
    api.on(SELECT_STORY, ({ kind, story, ...rest }) => {
      api.selectStory(kind, story, rest);
    });

    // TODO: cleanup into the module
    // TODO: animation isn't serializing succesfully, should use telejson
    const {
      theme: { animation, ...rest },
      // eslint-disable-next-line react/destructuring-assignment
    } = this.state.ui || { theme: {} };
    this.state = Object.assign({}, state, {
      ui: { ...state.ui, theme: { ...state.ui.theme, ...rest } },
    });
    this.api = api;
  }

  componentDidMount() {
    // Now every module has had a chance to set its API, call init on each module which gives it
    // a chance to do things that call other modules' APIs.
    this.modules.forEach(({ init }) => {
      if (init) {
        init({ api: this.api });
      }
    });
  }

  shouldComponentUpdate(nextProps, nextState) {
    const { state: prevState, props: prevProps } = this;

    if (prevState !== nextState) {
      return true;
    }
    if (prevProps.path !== nextProps.path) {
      return true;
    }
    return false;
  }

  static getDerivedStateFromProps = (props, state) => {
    if (state.path !== props.path) {
      return {
        ...state,
        location: props.location,
        path: props.path,
        viewMode: props.viewMode,
        storyId: props.storyId,
      };
    }
    return null;
  };

  render() {
    const { children } = this.props;
    const value = {
      state: this.state,
      api: this.api,
    };

    return (
      <Context.Provider value={value}>
        {typeof children === 'function' ? children(value) : children}
      </Context.Provider>
    );
  }
}
Provider.displayName = 'Manager';

export const { Consumer } = Context;
<|endoftext|>


<commit_before>var Promise = require('bluebird');
var _ = require('underscore');
var constants = require('./constants.js');
var requestLogger = require('./requestLogger');
var packageJson = require('../../package.json');

exports.create = function(requestorConfig) {
  var logger = requestorConfig.logger
    ? requestLogger.create(requestorConfig.logger)
    : requestLogger.empty;

  var request = requestorConfig.request ||
                Promise.promisifyAll(require("request"), {multiArgs: true});

  var handleResponse = requestorConfig.handleResponse ||
                       require('./responseHandler');

  var defaultCalcBackoff = numRetries => (Math.pow(2, numRetries) + Math.random()) * 1000;
  var defaultRetryOptions = {
    maxRetryDurationMillis: requestorConfig.maxRetryDurationMillis ||
                            constants.maxRetryDurationMillis,
    calcRetryBackoff: requestorConfig.calcRetryBackoff || defaultCalcBackoff
  };

  var buildHeaders = options => {
    var headers = {
      Accept: options.accept || 'application/json',
      'Content-Type': options.contentType || 'application/json',
      'User-Agent': `smartsheet-javascript-sdk/${packageJson.version}`
    };
    if(options.accessToken) {
      headers.Authorization = 'Bearer ' + options.accessToken;
    }
    if(options.assumeUser) {
      headers['Assume-User'] = encodeURIComponent(options.assumeUser);
    }
    if (options.fileName) {
      headers['Content-Disposition'] = `attachment; filename="${options.fileName}"`;
      headers['Content-Length'] = options.fileSize;
    }
    if(options.apiScenario) {
      headers['Api-Scenario'] = options.apiScenario;
    }
    if(options.changeAgent) {
      headers['Smartsheet-Change-Agent'] = options.changeAgent;
    }
    return headers;
  };

  var buildUrl = options => {
    var baseUrl = process.env.SMARTSHEET_API_HOST || 'https://api.smartsheet.com/2.0/';
    if (options.id) {
      return baseUrl + options.url + options.id;
    } else {
      return baseUrl + (options.url || '');
    }
  };

  var get = (options, callback) =>
    methodRequest(options, request.getAsync, 'GET', callback);

  var post = (options, callback) => {
    var requestExtension = { body: JSON.stringify(options.body) };

    return methodRequest(options, request.postAsync, 'POST', callback, requestExtension);
  };

  var postFile = (options, callback) => {
    var requestExtension = { body: options.fileStream };

    return methodRequest(options, request.postAsync, 'POST', callback, requestExtension);
  };

  var deleteFunc = (options, callback)  =>
    methodRequest(options, request.delAsync, 'DELETE', callback);

  var put = (options, callback) => {
    var requestExtension = { body: JSON.stringify(options.body) };

    return methodRequest(options, request.putAsync, 'PUT', callback, requestExtension);
  };

  var methodRequest = (options, method, methodName, callback, requestExtension) => {
    var baseRequestOptions = {
      url: buildUrl(options),
      headers: buildHeaders(options),
      qs: options.queryParameters,
      encoding: options.encoding
    };
    var requestOptions = _.extend(baseRequestOptions, requestExtension);

    var retryOptions = _.pick(options, 'maxRetryDurationMillis', 'calcRetryBackoff');

    logger.logRequest(methodName, requestOptions);

    return makeRequestWithRetries(method, methodName, requestOptions, retryOptions, callback);
  };

  var makeRequestWithRetries = (method, methodName, requestOptions, retryOptions, callback) => {
    var effectiveRetryOptions = _.defaults(retryOptions, defaultRetryOptions);

    effectiveRetryOptions.endRetryTime = Date.now() + effectiveRetryOptions.maxRetryDurationMillis;

    return retryHelper(method, methodName, requestOptions, effectiveRetryOptions, 0)
      .tap(logger.logSuccessfulResponse)
      .tapCatch(error => logger.logErrorResponse(methodName, requestOptions, error))
      .get('content')
      .catch(error => Promise.reject(_.omit(error, 'headers', 'body')))
      .nodeify(callback);
  };

  var retryHelper = (method, methodName, requestOptions, retryOptions, numRetries) =>
    makeRequest(method, methodName, requestOptions)
      .catch(retryWithBackoffHelper(method, methodName, requestOptions, retryOptions, numRetries));

  var makeRequest = (method, methodName, requestOptions) =>
    method(requestOptions).spread(handleResponse);

  var retryWithBackoffHelper = (method, methodName, requestOptions, retryOptions, numRetries) => {
    return error => {
      var backoffMillis = retryOptions.calcRetryBackoff(numRetries, error);

      var shouldExitRetry =
        !shouldRetry(error) ||
        backoffMillis < 0 ||
        Date.now() + backoffMillis >= retryOptions.endRetryTime;

      if (shouldExitRetry) {
        logger.logRetryFailure(methodName, requestOptions, numRetries);
        return new Promise.reject(error);
      }

      var nextRetry = numRetries + 1;
      logger.logRetryAttempt(methodName, requestOptions, error, nextRetry);
      return Promise.delay(backoffMillis)
        .then(() => retryHelper(method, methodName, requestOptions, retryOptions, nextRetry));
    };
  };

  var shouldRetry = error =>
    error.errorCode === 4001 ||
    error.errorCode === 4002 ||
    error.errorCode === 4003 ||
    error.errorCode === 4004;

  return {
    get: get,
    put: put,
    post: post,
    postFile: postFile,
    delete: deleteFunc,
    internal: {
      buildHeaders: buildHeaders,
      buildUrl: buildUrl
    }
  };
};
<commit_msg>Add gzip encoding to RequestJS call<commit_after>var Promise = require('bluebird');
var _ = require('underscore');
var constants = require('./constants.js');
var requestLogger = require('./requestLogger');
var packageJson = require('../../package.json');

exports.create = function(requestorConfig) {
  var logger = requestorConfig.logger
    ? requestLogger.create(requestorConfig.logger)
    : requestLogger.empty;

  var request = requestorConfig.request ||
                Promise.promisifyAll(require("request"), {multiArgs: true});

  var handleResponse = requestorConfig.handleResponse ||
                       require('./responseHandler');

  var defaultCalcBackoff = numRetries => (Math.pow(2, numRetries) + Math.random()) * 1000;
  var defaultRetryOptions = {
    maxRetryDurationMillis: requestorConfig.maxRetryDurationMillis ||
                            constants.maxRetryDurationMillis,
    calcRetryBackoff: requestorConfig.calcRetryBackoff || defaultCalcBackoff
  };

  var buildHeaders = options => {
    var headers = {
      Accept: options.accept || 'application/json',
      'Content-Type': options.contentType || 'application/json',
      'User-Agent': `smartsheet-javascript-sdk/${packageJson.version}`
    };
    if(options.accessToken) {
      headers.Authorization = 'Bearer ' + options.accessToken;
    }
    if(options.assumeUser) {
      headers['Assume-User'] = encodeURIComponent(options.assumeUser);
    }
    if (options.fileName) {
      headers['Content-Disposition'] = `attachment; filename="${options.fileName}"`;
      headers['Content-Length'] = options.fileSize;
    }
    if(options.apiScenario) {
      headers['Api-Scenario'] = options.apiScenario;
    }
    if(options.changeAgent) {
      headers['Smartsheet-Change-Agent'] = options.changeAgent;
    }
    return headers;
  };

  var buildUrl = options => {
    var baseUrl = process.env.SMARTSHEET_API_HOST || 'https://api.smartsheet.com/2.0/';
    if (options.id) {
      return baseUrl + options.url + options.id;
    } else {
      return baseUrl + (options.url || '');
    }
  };

  var get = (options, callback) =>
    methodRequest(options, request.getAsync, 'GET', callback);

  var post = (options, callback) => {
    var requestExtension = { body: JSON.stringify(options.body) };

    return methodRequest(options, request.postAsync, 'POST', callback, requestExtension);
  };

  var postFile = (options, callback) => {
    var requestExtension = { body: options.fileStream };

    return methodRequest(options, request.postAsync, 'POST', callback, requestExtension);
  };

  var deleteFunc = (options, callback)  =>
    methodRequest(options, request.delAsync, 'DELETE', callback);

  var put = (options, callback) => {
    var requestExtension = { body: JSON.stringify(options.body) };

    return methodRequest(options, request.putAsync, 'PUT', callback, requestExtension);
  };

  var methodRequest = (options, method, methodName, callback, requestExtension) => {
    var baseRequestOptions = {
      url: buildUrl(options),
      headers: buildHeaders(options),
      qs: options.queryParameters,
      encoding: options.encoding,
      gzip: true
    };
    var requestOptions = _.extend(baseRequestOptions, requestExtension);

    var retryOptions = _.pick(options, 'maxRetryDurationMillis', 'calcRetryBackoff');

    logger.logRequest(methodName, requestOptions);

    return makeRequestWithRetries(method, methodName, requestOptions, retryOptions, callback);
  };

  var makeRequestWithRetries = (method, methodName, requestOptions, retryOptions, callback) => {
    var effectiveRetryOptions = _.defaults(retryOptions, defaultRetryOptions);

    effectiveRetryOptions.endRetryTime = Date.now() + effectiveRetryOptions.maxRetryDurationMillis;

    return retryHelper(method, methodName, requestOptions, effectiveRetryOptions, 0)
      .tap(logger.logSuccessfulResponse)
      .tapCatch(error => logger.logErrorResponse(methodName, requestOptions, error))
      .get('content')
      .catch(error => Promise.reject(_.omit(error, 'headers', 'body')))
      .nodeify(callback);
  };

  var retryHelper = (method, methodName, requestOptions, retryOptions, numRetries) =>
    makeRequest(method, methodName, requestOptions)
      .catch(retryWithBackoffHelper(method, methodName, requestOptions, retryOptions, numRetries));

  var makeRequest = (method, methodName, requestOptions) =>
    method(requestOptions).spread(handleResponse);

  var retryWithBackoffHelper = (method, methodName, requestOptions, retryOptions, numRetries) => {
    return error => {
      var backoffMillis = retryOptions.calcRetryBackoff(numRetries, error);

      var shouldExitRetry =
        !shouldRetry(error) ||
        backoffMillis < 0 ||
        Date.now() + backoffMillis >= retryOptions.endRetryTime;

      if (shouldExitRetry) {
        logger.logRetryFailure(methodName, requestOptions, numRetries);
        return new Promise.reject(error);
      }

      var nextRetry = numRetries + 1;
      logger.logRetryAttempt(methodName, requestOptions, error, nextRetry);
      return Promise.delay(backoffMillis)
        .then(() => retryHelper(method, methodName, requestOptions, retryOptions, nextRetry));
    };
  };

  var shouldRetry = error =>
    error.errorCode === 4001 ||
    error.errorCode === 4002 ||
    error.errorCode === 4003 ||
    error.errorCode === 4004;

  return {
    get: get,
    put: put,
    post: post,
    postFile: postFile,
    delete: deleteFunc,
    internal: {
      buildHeaders: buildHeaders,
      buildUrl: buildUrl
    }
  };
};
<|endoftext|>