<commit_before>roleSpawner = {

    run: function() {
	    var store = {
	        'worker': 6,
	        'harvester': 2
	    };

	    for(role in store) {
	        var count = store[role];
	        var creeps = _.filter(Game.creeps, (creep) => creep.memory.role == role);
	        if(creeps.length < count) {

	            var build = undefined;
	            switch (role) {
                    case 'harvester':
                        build = roleSpawner.currentHarvesterBuild();
                        break;
//	                case 'worker':
//	                    build = roleSpawner.currentWorkerBuild();
//	                    break;
	            }

		        var newName = Game.spawns['Spawn1'].createCreep(build, undefined, {role: role});
		        console.log('spawning new ' + role + ': ' + newName);
		        return;
	        }
	    }
    },

    assembleBuild: function(stats) {
        var build = [];
        for(part in stats) {
            for(var i=0; i < stats[part]; i++) {
                build.push(part);
            }
        }
    },

    currentWorkerBuild: function() {
        var spawnRoomCapacity = Game.rooms[Memory.home].energyCapacityAvailable;
        if(spawnRoomCapacity >= 1300) {
            return roleSpawner.assembleBuild({
                WORK: 4,
                CARRY: 7,
                MOVE: 11,
            })
        } else if(spawnRoomCapacity >= 800) {
            return roleSpawner.assembleBuild({
                WORK: 2,
                CARRY: 5,
                MOVE: 7,
            })
        } else if(spawnRoomCapacity >= 550) {
            return roleSpawner.assembleBuild({
                WORK: 2,
                CARRY: 3,
                MOVE: 4,
            })
        } else {
            return [WORK,CARRY,MOVE];
        }
    },

    currentHarvesterBuild: function() {
        var spawnRoomCapacity = Game.rooms[Memory.home].energyCapacityAvailable;
        if(spawnRoomCapacity >= 1300) {
            return roleSpawner.assembleBuild({
                WORK: 8,
                CARRY: 4,
                MOVE: 6,
            })
        } else if(spawnRoomCapacity >= 800) {
            return roleSpawner.assembleBuild({
                WORK: 4,
                CARRY: 4,
                MOVE: 4,
            })
        } else if(spawnRoomCapacity >= 550) {
            return roleSpawner.assembleBuild({
                WORK: 3,
                CARRY: 2,
                MOVE: 3,
            })
        } else {
            return [WORK,CARRY,MOVE];
        }
    },
}

module.exports = roleSpawner;
<commit_msg>fixed<commit_after>roleSpawner = {

    run: function() {
	    var store = {
	        //'worker': 6,
	        'harvester': 2
	    };

	    for(role in store) {
	        var count = store[role];
	        var creeps = _.filter(Game.creeps, (creep) => creep.memory.role == role);
	        if(creeps.length < count) {

	            var build = undefined;
	            switch (role) {
                    case 'harvester':
                        build = roleSpawner.currentHarvesterBuild();
                        break;
	                case 'worker':
	                    build = roleSpawner.currentWorkerBuild();
	                    break;
	            }

		        var newName = Game.spawns['Spawn1'].createCreep(build, undefined, {role: role});
		        console.log('spawning new ' + role + ': ' + newName);
	        }
	    }
    },

    assembleBuild: function(stats) {
        var build = [];
        for(part in stats) {
            for(var i=0; i < stats[part]; i++) {
                build.push(part);
            }
        }
    },

    currentWorkerBuild: function() {
        var spawnRoomCapacity = Game.rooms[Memory.home].energyCapacityAvailable;
        if(spawnRoomCapacity >= 1300) {
            return roleSpawner.assembleBuild({
                WORK: 4,
                CARRY: 7,
                MOVE: 11,
            })
        } else if(spawnRoomCapacity >= 800) {
            return roleSpawner.assembleBuild({
                WORK: 2,
                CARRY: 5,
                MOVE: 7,
            })
        } else if(spawnRoomCapacity >= 550) {
            return roleSpawner.assembleBuild({
                WORK: 2,
                CARRY: 3,
                MOVE: 4,
            })
        } else {
            return [WORK,CARRY,MOVE];
        }
    },

    currentHarvesterBuild: function() {
        var spawnRoomCapacity = Game.rooms[Memory.home].energyCapacityAvailable;
        if(spawnRoomCapacity >= 1300) {
            return roleSpawner.assembleBuild({
                WORK: 8,
                CARRY: 4,
                MOVE: 6,
            })
        } else if(spawnRoomCapacity >= 800) {
            return roleSpawner.assembleBuild({
                WORK: 4,
                CARRY: 4,
                MOVE: 4,
            })
        } else if(spawnRoomCapacity >= 550) {
            return roleSpawner.assembleBuild({
                WORK: 3,
                CARRY: 2,
                MOVE: 3,
            })
        } else {
            return [WORK,CARRY,MOVE];
        }
    },
}

module.exports = roleSpawner;
<|endoftext|>


<commit_before>/*
 * Copyright 2014 XWiki SAS
 *
 * 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/>.
 */
define([
    '/common/common-util.js',
    '/customize/application_config.js',
    '/bower_components/chainpad/chainpad.dist.js'
], function (Util, AppConfig) {
    var ChainPad = window.ChainPad;
    var module = { exports: {} };

    var badStateTimeout = typeof(AppConfig.badStateTimeout) === 'number' ?
        AppConfig.badStateTimeout : 30000;

    var verbose = function (x) { console.log(x); };
    verbose = function () {}; // comment out to enable verbose logging

    module.exports.start = function (config) {
        var onConnectionChange = config.onConnectionChange || function () { };
        var onRemote = config.onRemote || function () { };
        var onInit = config.onInit || function () { };
        var onLocal = config.onLocal || function () { };
        var setMyID = config.setMyID || function () { };
        var onReady = config.onReady || function () { };
        var userName = config.userName;
        var initialState = config.initialState;
        var transformFunction = config.transformFunction;
        var validateContent = config.validateContent;
        var avgSyncMilliseconds = config.avgSyncMilliseconds;
        var logLevel = typeof(config.logLevel) !== 'undefined'? config.logLevel : 1;
        var readOnly = config.readOnly || false;
        var sframeChan = config.sframeChan;
        var metadataMgr = config.metadataMgr;
        config = undefined;

        var chainpad;
        var myID;
        var isReady = false;
        var evConnected = Util.mkEvent(true);
        var evInfiniteSpinner = Util.mkEvent(true);

        window.setInterval(function () {
            if (!chainpad || !myID) { return; }
            var l;
            try {
                l = chainpad.getLag();
            } catch (e) {
                throw new Error("ChainPad.getLag() does not exist, please `bower update`");
            }
            if (l.lag < badStateTimeout) { return; }
            chainpad.abort();
            evInfiniteSpinner.fire();
        }, 2000);

        sframeChan.on('EV_RT_DISCONNECT', function () {
            isReady = false;
            if (chainpad) { chainpad.abort(); }
            onConnectionChange({ state: false });
        });
        sframeChan.on('EV_RT_CONNECT', function (content) {
            //content.members.forEach(userList.onJoin);
            myID = content.myID;
            isReady = false;
            if (chainpad) {
                // it's a reconnect
                if (chainpad) { chainpad.start(); }
                onConnectionChange({ state: true, myId: myID });
                return;
            }
            chainpad = ChainPad.create({
                userName: userName,
                initialState: initialState,
                transformFunction: transformFunction,
                validateContent: validateContent,
                avgSyncMilliseconds: avgSyncMilliseconds,
                logLevel: logLevel
            });
            chainpad.onMessage(function(message, cb) {
                sframeChan.query('Q_RT_MESSAGE', message, cb);
            });
            chainpad.onPatch(function () {
                onRemote({ realtime: chainpad });
            });
            onInit({
                myID: myID,
                realtime: chainpad,
                readOnly: readOnly
            });
            evConnected.fire();
        });
        sframeChan.on('Q_RT_MESSAGE', function (content, cb) {
            if (isReady) {
                onLocal(); // should be onBeforeMessage
            }
            chainpad.message(content);
            cb('OK');
        });
        sframeChan.on('EV_RT_READY', function () {
            if (isReady) { return; }
            isReady = true;
            chainpad.start();
            setMyID({ myID: myID });
            onReady({ realtime: chainpad });
        });

        var whenRealtimeSyncs = function (cb) {
            evConnected.reg(function () {
                if (chainpad.getAuthDoc() === chainpad.getUserDoc()) {
                    return void cb();
                } else {
                    chainpad.onSettle(cb);
                }
            });
        };

        return Object.freeze({
            getMyID: function () { return myID; },
            metadataMgr: metadataMgr,
            whenRealtimeSyncs: whenRealtimeSyncs,
            onInfiniteSpinner: evInfiniteSpinner.reg
        });
    };
    return Object.freeze(module.exports);
});<commit_msg>Refactor sframe-cpnf-inner to export chainpad<commit_after>/*
 * Copyright 2014 XWiki SAS
 *
 * 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/>.
 */
define([
    '/common/common-util.js',
    '/customize/application_config.js',
    '/bower_components/chainpad/chainpad.dist.js'
], function (Util, AppConfig) {
    var ChainPad = window.ChainPad;
    var module = { exports: {} };

    var badStateTimeout = typeof(AppConfig.badStateTimeout) === 'number' ?
        AppConfig.badStateTimeout : 30000;

    var verbose = function (x) { console.log(x); };
    verbose = function () {}; // comment out to enable verbose logging

    module.exports.start = function (config) {
        var onConnectionChange = config.onConnectionChange || function () { };
        var onRemote = config.onRemote || function () { };
        var onInit = config.onInit || function () { };
        var onLocal = config.onLocal || function () { };
        var setMyID = config.setMyID || function () { };
        var onReady = config.onReady || function () { };
        var userName = config.userName;
        var initialState = config.initialState;
        var transformFunction = config.transformFunction;
        var validateContent = config.validateContent;
        var avgSyncMilliseconds = config.avgSyncMilliseconds;
        var logLevel = typeof(config.logLevel) !== 'undefined'? config.logLevel : 1;
        var readOnly = config.readOnly || false;
        var sframeChan = config.sframeChan;
        var metadataMgr = config.metadataMgr;
        config = undefined;

        var chainpad = ChainPad.create({
            userName: userName,
            initialState: initialState,
            transformFunction: transformFunction,
            validateContent: validateContent,
            avgSyncMilliseconds: avgSyncMilliseconds,
            logLevel: logLevel
        });
        chainpad.onMessage(function(message, cb) {
            sframeChan.query('Q_RT_MESSAGE', message, cb);
        });
        chainpad.onPatch(function () {
            onRemote({ realtime: chainpad });
        });

        var myID;
        var isReady = false;
        var evConnected = Util.mkEvent(true);
        var evInfiniteSpinner = Util.mkEvent(true);

        window.setInterval(function () {
            if (!chainpad || !myID) { return; }
            var l;
            try {
                l = chainpad.getLag();
            } catch (e) {
                throw new Error("ChainPad.getLag() does not exist, please `bower update`");
            }
            if (l.lag < badStateTimeout) { return; }
            chainpad.abort();
            evInfiniteSpinner.fire();
        }, 2000);

        sframeChan.on('EV_RT_DISCONNECT', function () {
            isReady = false;
            chainpad.abort();
            onConnectionChange({ state: false });
        });
        sframeChan.on('EV_RT_CONNECT', function (content) {
            //content.members.forEach(userList.onJoin);
            isReady = false;
            if (myID) {
                // it's a reconnect
                myID = content.myID;
                chainpad.start();
                onConnectionChange({ state: true, myId: myID });
                return;
            }
            myID = content.myID;
            onInit({
                myID: myID,
                realtime: chainpad,
                readOnly: readOnly
            });
            evConnected.fire();
        });
        sframeChan.on('Q_RT_MESSAGE', function (content, cb) {
            if (isReady) {
                onLocal(); // should be onBeforeMessage
            }
            chainpad.message(content);
            cb('OK');
        });
        sframeChan.on('EV_RT_READY', function () {
            if (isReady) { return; }
            isReady = true;
            chainpad.start();
            setMyID({ myID: myID });
            onReady({ realtime: chainpad });
        });

        var whenRealtimeSyncs = function (cb) {
            evConnected.reg(function () {
                if (chainpad.getAuthDoc() === chainpad.getUserDoc()) {
                    return void cb();
                } else {
                    chainpad.onSettle(cb);
                }
            });
        };

        return Object.freeze({
            getMyID: function () { return myID; },
            metadataMgr: metadataMgr,
            whenRealtimeSyncs: whenRealtimeSyncs,
            onInfiniteSpinner: evInfiniteSpinner.reg,
            chainpad: chainpad,
        });
    };
    return Object.freeze(module.exports);
});<|endoftext|>


<commit_before>
import THREE from 'three';

//This file defines the set of primitives that programs written in the IDE can use.

const PrimitiveProp = Symbol("PrimitiveName");

const r = {
	primitives: [],
	provide: function(name, value) {
		this.primitives.push({
			[PrimitiveProp]: name,
			value: value
		});
	},
	defPrimitive: function(name, args) {
		return function() {
			var realArguments = arguments;
			var callArgs = {};
			args.forEach(function(paramName, i){
				callArgs[paramName] = i<realArguments.length ? realArguments[i] : undefined;
			});
			return {
				[PrimitiveProp]: name,
				args: callArgs
			};
		};
	},
	defPrimitiveAndProvide: function(name, args) {
		let primitive = this.defPrimitive(name, args);
		this.provide(name, primitive);
		return primitive;
	}
};

//No points when creating things
//Functional behavior

const matrix = {};
matrix.identity = new THREE.Matrix4();
matrix.translation = function(x, y, z) {
	return (new THREE.Matrix4()).makeTranslation(x, y, z);
};
matrix.rotation = function(axisVector, radians) {
	return (new THREE.Matrix4()).makeRotationAxis(axisVector, radians);
};
matrix.scaling = function(xFactor, yFactor, zFactor) {
	return (new THREE.Matrix4()).makeScale(xFactor, yFactor, zFactor);
};
matrix.multiply = function(m1, m2) {
	return m1.clone().multiply(m2);
};
matrix.basis = function(xVector, yVector, zVector) {
	let tmp = new THREE.Matrix4();
	tmp.makeBasis(xVector, yVector, zVector);
	return tmp;
};

const transform = {};
transform.translation = {};
transform.translation.byVector = function(vector) {
	return matrix.translation(vector.x, vector.y, vector.z);
};
transform.rotation = {};
transform.rotation.aroundAxisVectorByAngle = function(axisVector, radians) {
	let normalizedAxis = axisVector.clone().normalize();
	return matrix.rotation(normalizedAxis, radians);
};
transform.scaling = {};
transform.scaling.byFactor = function(scaleFactor) {
	return matrix.scaling(scaleFactor, scaleFactor, scaleFactor);
};
transform.compose = function(t1, t2) {
	return matrix.multiply(t1, t2);
};

r.provide("transform", transform);

const coordinates = {};
coordinates.world = matrix.identity; //TODO getter
coordinates.current = coordinates.world; //TODO getter
coordinates.with = function(coordinateSystem, callback) {
	const oldCoordinateSystem = coordinates.current;
	coordinates.current = coordinateSystem;
	let ret = callback();
	coordinates.current = oldCoordinateSystem;
	return ret;
}

const vector = {};
vector.byXYZ = function(x, y, z) {
	return (new THREE.Vector4(x, y, z, 0.0)).applyMatrix4(coordinates.current);
};
vector.add = function(v1, v2) {
	return v1.clone().add(v2);
};
vector.sub = function(v1, v2) {
	return v1.clone().sub(v2);
};
vector.dot = function(v1, v2) {
	return v1.dot(v2);
};
vector.cross = function(v1, v2) {
	let vec3Result = (new THREE.Vector3()).crossVectors(v1, v2);
	return new THREE.Vector4(vec3Result.x, vec3Result.y, vec3Result.z, 0.0);
};
vector.scale = function(vec, scalar) {
	return vec.clone().multiplyScalar(scalar);
};
vector.length = function(vec) {
	return vec.length();
}
vector.normalized = function(vec) {
	return vec.clone().normalize();
};

r.provide("vector", vector);

const point = {};
point.byXYZ = function(x, y, z) {
	return (new THREE.Vector4(x, y, z, 1.0)).applyMatrix4(coordinates.current);
};
point.origin = function() {
	return point.byXYZ(0, 0, 0);
}
point.pointPlusVector = function(point, vec) {
	return point.clone().add(vec);
};
point.pointMinusPoint = function(p1, p2) {
	return p1.clone().sub(p2);
};

r.provide("point", point);
//TODO Check if all vector operations are implemented and available.
// vectors
//r.defPrimitive("xyz", ["x", "y", "z"], function(x,y,z) {
//	return new THREE.Vector3(x,y,z);
//});
//r.defPrimitive("polar", ["radius", "phi"]);
//r.defPrimitive("cylindrical", ["radius", "phi", "z"]);
//r.defPrimitive("spherical", ["radius", "longitude", "azimuth"]);
//
//r.defPrimitive("point_distance", ["p1", "p2"], function(p1, p2){
//	return p2.clone().sub( p1 ).length();
//});
//r.defPrimitive("dot", ["v1", "v2"], function(v1, v2) {
//	return v1.dot(v2);
//});
//r.defPrimitive("cross", ["v1", "v2"], function(v0, v1){
//	return v0.clone().cross( v1 );
//});
//r.defPrimitive("direction_from_to", ["p0", "p1"], function(p0, p1){
//	return p1.clone().sub( p0 ).normalize();
//});
//r.defPrimitive("linear_interpolation", ["p0", "p1", "t"], function(p0, p1, t) {
//	return p0.clone().lerp( p1, t );
//});
//r.defPrimitive("add", ["v1", "v2"], function(v1, v2){
//	return v1.clone().add(v2);
//});
//r.defPrimitive("sub", ["v1", "v2"], function(v1, v2) {
//	return v1.clone().sub(v2);
//});
//r.defPrimitive("mult", ["v1", "v2"], function(v1, v2) {
//	return v1.clone().multiply(v2);
//});
//r.defPrimitive("multScalar", ["v", "s"], function(v, s) {
//	return v.clone().multiplyScalar(s);
//});
//r.defPrimitive("normalize", ["v"], function(v) {
//	return v.clone().normalize();
//});
//r.defPrimitive("length", ["v"], function(v) {
//	return v.length();
//});
/*
vec = {};
{_threeVec: new THREE.Vector3(0,0,0),
 cartesianCoords: [x,y,z],
 dir: [alpha, beta],
 magntitude: num
 }
vec.byXYZ = vecbyXYZ;
vec.byCylindrical = vecbyCylindrical;
vec.byPolar
vec.bySpherical
vec.add
vec.sub
vec.scale
vec.mul
vec.dot
vec.cross
vec.length
vec.lengthSqr
*/

//TODO Define more primitives.
//primitives
const boxPrimitive = r.defPrimitive("box", ["width", "height", "depth"]);
const spherePrimitive = r.defPrimitive("sphere", ["radius"]);
const cylinderPrimitive = r.defPrimitive("cylinder", ["radius", "height"]);
const transformObjectPrimitive = r.defPrimitiveAndProvide("transformObjectWith", ["object", "transform"]);
//r.defPrimitiveAndProvide("cone", ["radius", "height"]);
//r.defPrimitiveAndProvide("coneFrustum", ["bottomRadius", "topRadius", "height"]);
//r.defPrimitiveAndProvide("regularPyramid", ["sides", "height"]);

//r.defPrimitiveAndProvide("line", ["origin", "direction"]);
//r.defPrimitiveAndProvide("polyline", ["coordinates", "closed"]);
//r.defPrimitiveAndProvide("spline", ["coordinates", "closed"]);
//r.defPrimitiveAndProvide("arc", ["radius", "angle"]);

//r.defPrimitiveAndProvide("circle", ["radius"]);
//r.defPrimitiveAndProvide("plane", ["origin", "normal"]);
//r.defPrimitiveAndProvide("polygon", ["coordinates"]);
//r.defPrimitiveAndProvide("regularPolygon", ["radius", "sides"]);

// shapes
const box = {};
box.byWidthHeightDepth = function(width, height, depth) {
	return boxPrimitive(width, height, depth);
};
box.byCentersAxes = function([baseCenter, topCenter], [xVector, yVector]) {
	//let boxCenter = point.pointPlusVector(
	//	baseCenter,
	//	vector.scale(
	//		point.pointMinusPoint(topCenter, baseCenter),
	//		0.5));
	//let translationTransform = matrix.translation(boxCenter.x, boxCenter.y, boxCenter.z);
	let translateBaseToOrigin = matrix.translation(0.0, 0.0, 0.5);

	let zVector = point.pointMinusPoint(topCenter, baseCenter);
	let basisTransform = matrix.basis(xVector, yVector, zVector);

	let translateToBaseCenter = matrix.translation(baseCenter.x, baseCenter.y, baseCenter.z);

	let completeTransform = matrix.multiply(
		translateToBaseCenter,
		matrix.multiply(basisTransform, translateBaseToOrigin));
	//let completeTransform = matrix.multiply(basisTransform, translateBaseToOrigin);
	//transform: move base to wanted base * apply basis * move base to origin

	return transformObjectPrimitive(boxPrimitive(1.0, 1.0, 1.0), completeTransform);
};
box.byCentersWidthHeight = function([baseCenter, topCenter], [width, height]) {
	let boxAxis = point.pointMinusPoint(topCenter, baseCenter);
	let worldZAxis = coordinates.with(coordinates.world, ()=>vector.byXYZ(0.0,0.0,1.0));
	let angleBetweenAxes = Math.acos(vector.dot(worldZAxis, vector.normalized(boxAxis)));
	let rotationAxis = vector.normalized(vector.cross(worldZAxis, boxAxis));
	let rotationTransform = transform.rotation.aroundAxisVectorByAngle(rotationAxis, angleBetweenAxes);

	let worldOrigin = coordinates.with(coordinates.world, ()=>point.byXYZ(0.0,0.0,0.0));
	let midPoint = point.pointPlusVector(
		baseCenter,
		vector.scale(
			point.pointMinusPoint(topCenter, baseCenter),
			0.5));
	let translationVector = point.pointMinusPoint(midPoint, worldOrigin);
	let translationTransform = transform.translation.byVector(translationVector);

	let transformation = transform.compose(translationTransform, rotationTransform);
	let box = boxPrimitive(width, height, vector.length(boxAxis));
	return transformObjectPrimitive(box, transformation);
};
r.provide("box", box);

const sphere = {};
sphere.byCenterRadius = function(vec, radius) {
	let translation = transform.translation.byVector(vec);
	return transformObjectPrimitive(spherePrimitive(radius), translation);
};
r.provide("sphere", sphere);

const cylinder = {};
cylinder.byRadiusHeight = function(radius, height) {
	return cylinderPrimitive(radius, height);
};
cylinder.byCentersRadius = function([baseCenter, topCenter], radius) {
	let cylinderAxis = point.pointMinusPoint(topCenter, baseCenter);
	let worldZAxis = coordinates.with(coordinates.world, ()=>vector.byXYZ(0.0,0.0,1.0));
	let angleBetweenAxes = Math.acos(vector.dot(worldZAxis, vector.normalized(cylinderAxis)));
	let rotationAxis = vector.normalized(vector.cross(worldZAxis, cylinderAxis));
	let rotationTransform = transform.rotation.aroundAxisVectorByAngle(rotationAxis, angleBetweenAxes);

	let worldOrigin = coordinates.with(coordinates.world, ()=>point.byXYZ(0.0,0.0,0.0));
	let midPoint = point.pointPlusVector(
		baseCenter,
		vector.scale(
			point.pointMinusPoint(topCenter, baseCenter),
			0.5));
	let translationVector = point.pointMinusPoint(midPoint, worldOrigin);
	let translationTransform = transform.translation.byVector(translationVector);

	let transformation = transform.compose(translationTransform, rotationTransform);
	let cylinder = cylinderPrimitive(radius, vector.length(cylinderAxis));
	return transformObjectPrimitive(cylinder, transformation);
};
r.provide("cylinder", cylinder);

const sequence = {};
sequence.map = function(fn, seq) {
	return seq.map(fn);
};
sequence.division = function(start, end, divisions) {
	var arr = [];
	var stepSize = (end-start) / divisions;
	var i = 0;
	while(i<divisions+1) {
		arr.push(stepSize*i);
		i++;
	}
	return arr;
};
sequence.count = function(n) {
	var arr = [];
	var i = 0;
	while(i<n) {
		arr.push(i);
		i++;
	}
	return arr;
};
sequence.zip = function(l1, l2) {
	var arr = [];
	var i = 0;
	while(i<l1.length) {
		arr.push([l1[i], l2[i]]);
		i++;
	}
	return arr;
};
sequence.cartesianProduct = function(l1, l2) {
	var arr = [];
	for(let i=0; i<l1.length; i++) {
		for(let j=0; j<l2.length; j++) {
			arr.push([l1[i], l2[j]]);
		}
	}
	return arr;
};
sequence.rotate = function(lst, offset) {
	function posModulo(dividend, divisor) {
		return ((dividend%divisor)+divisor)%divisor;
	}
	var arr = [];
	for(let i=0; i<lst.length; i++) {
		arr.push(lst[posModulo(i+offset, lst.length)]);
	}
	return arr;
};
sequence.repeatTimes = function(elem, n) {
	let i=0;
	let arr = [];
	while(i<n) {
		arr.push(elem);
		i++;
	}
	return arr;
}
sequence.concat = function(lst1, lst2) {
	return lst1.concat(lst2);
}

r.provide("sequence", sequence);

/*
shape.move.byXYZ(x,y,z)
shape.move.byZ(z)
shape.move.byVector(vector)
shape.rotate.byAxisAngle(axis,angle)
shape.scale.uniform(scale)
shape.mirror.byPlane
*/

export default r.primitives;
export {PrimitiveProp};
<commit_msg>Implemented generation of rotation matrix from one axis to another that is resistant to colinear axes.<commit_after>
import THREE from 'three';

//This file defines the set of primitives that programs written in the IDE can use.

const PrimitiveProp = Symbol("PrimitiveName");

const r = {
	primitives: [],
	provide: function(name, value) {
		this.primitives.push({
			[PrimitiveProp]: name,
			value: value
		});
	},
	defPrimitive: function(name, args) {
		return function() {
			var realArguments = arguments;
			var callArgs = {};
			args.forEach(function(paramName, i){
				callArgs[paramName] = i<realArguments.length ? realArguments[i] : undefined;
			});
			return {
				[PrimitiveProp]: name,
				args: callArgs
			};
		};
	},
	defPrimitiveAndProvide: function(name, args) {
		let primitive = this.defPrimitive(name, args);
		this.provide(name, primitive);
		return primitive;
	}
};

//No points when creating things
//Functional behavior

const matrix = {};
matrix.identity = new THREE.Matrix4();
matrix.translation = function(x, y, z) {
	return (new THREE.Matrix4()).makeTranslation(x, y, z);
};
matrix.rotation = function(axisVector, radians) {
	return (new THREE.Matrix4()).makeRotationAxis(axisVector, radians);
};
matrix.scaling = function(xFactor, yFactor, zFactor) {
	return (new THREE.Matrix4()).makeScale(xFactor, yFactor, zFactor);
};
matrix.multiply = function(m1, m2) {
	return m1.clone().multiply(m2);
};
matrix.basis = function(xVector, yVector, zVector) {
	let tmp = new THREE.Matrix4();
	tmp.makeBasis(xVector, yVector, zVector);
	return tmp;
};
matrix.axisCosSinAngle = function(axisVector, cosAngle, sinAngle) {
	//Based on http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToMatrix/index.htm
	let a = axisVector, c = cosAngle, s = sinAngle;
	let t = 1.0 - c;

	let tmp1 = a.x*a.y*t,
		tmp2 = a.z*s,
		tmp3 = a.x*a.z*t,
		tmp4 = a.y*s,
		tmp5 = a.y*a.z*t,
		tmp6 = a.x*s;

	let matr = new THREE.Matrix4();
	matr.set(
		c + a.x*a.x*t, tmp1 - tmp2,   tmp3 + tmp4,   0.0,
		tmp1 + tmp2,   c + a.y*a.y*t, tmp5 - tmp6,   0.0,
		tmp3 - tmp4,   tmp5 + tmp6,   c + a.z*a.z*t, 0.0,
		0.0,           0.0,           0.0,           1.0);

	return matr;
};
matrix.alignFromAxisToAxis = function(fromAxis, toAxis) {
	let dot = fromAxis.dot(toAxis),
		cross = (new THREE.Vector3()).crossVectors(fromAxis, toAxis),
		crossLength = cross.length();
	//TODO Improve vector colinearity check. Use approximate equality.
	let areColinear = crossLength === 0.0;
	if(areColinear) {
		let axis = new THREE.Vector4(1.0, 0.0, 0.0, 0.0);
		return dot < 0.0
			?	matrix.axisCosSinAngle(axis, -1.0, 0.0)
			: matrix.axisCosSinAngle(axis, 1.0, 0.0);
	}	else {
		let axis = cross.clone().multiplyScalar(1.0/crossLength);
		return matrix.axisCosSinAngle(axis, dot, crossLength);
	}
};

const transform = {};
transform.translation = {};
transform.translation.byVector = function(vector) {
	return matrix.translation(vector.x, vector.y, vector.z);
};
transform.rotation = {};
transform.rotation.aroundAxisVectorByAngle = function(axisVector, radians) {
	let normalizedAxis = axisVector.clone().normalize();
	return matrix.rotation(normalizedAxis, radians);
};
transform.scaling = {};
transform.scaling.byFactor = function(scaleFactor) {
	return matrix.scaling(scaleFactor, scaleFactor, scaleFactor);
};
transform.compose = function(t1, t2) {
	return matrix.multiply(t1, t2);
};

r.provide("transform", transform);

const coordinates = {};
coordinates.world = matrix.identity; //TODO getter
coordinates.current = coordinates.world; //TODO getter
coordinates.with = function(coordinateSystem, callback) {
	const oldCoordinateSystem = coordinates.current;
	coordinates.current = coordinateSystem;
	let ret = callback();
	coordinates.current = oldCoordinateSystem;
	return ret;
}

const vector = {};
vector.byXYZ = function(x, y, z) {
	return (new THREE.Vector4(x, y, z, 0.0)).applyMatrix4(coordinates.current);
};
vector.add = function(v1, v2) {
	return v1.clone().add(v2);
};
vector.sub = function(v1, v2) {
	return v1.clone().sub(v2);
};
vector.dot = function(v1, v2) {
	return v1.dot(v2);
};
vector.cross = function(v1, v2) {
	let vec3Result = (new THREE.Vector3()).crossVectors(v1, v2);
	return new THREE.Vector4(vec3Result.x, vec3Result.y, vec3Result.z, 0.0);
};
vector.scale = function(vec, scalar) {
	return vec.clone().multiplyScalar(scalar);
};
vector.length = function(vec) {
	return vec.length();
}
vector.normalized = function(vec) {
	return vec.clone().normalize();
};

r.provide("vector", vector);

const point = {};
point.byXYZ = function(x, y, z) {
	return (new THREE.Vector4(x, y, z, 1.0)).applyMatrix4(coordinates.current);
};
point.origin = function() {
	return point.byXYZ(0, 0, 0);
}
point.pointPlusVector = function(point, vec) {
	return point.clone().add(vec);
};
point.pointMinusPoint = function(p1, p2) {
	return p1.clone().sub(p2);
};

r.provide("point", point);
//TODO Check if all vector operations are implemented and available.
// vectors
//r.defPrimitive("xyz", ["x", "y", "z"], function(x,y,z) {
//	return new THREE.Vector3(x,y,z);
//});
//r.defPrimitive("polar", ["radius", "phi"]);
//r.defPrimitive("cylindrical", ["radius", "phi", "z"]);
//r.defPrimitive("spherical", ["radius", "longitude", "azimuth"]);
//
//r.defPrimitive("point_distance", ["p1", "p2"], function(p1, p2){
//	return p2.clone().sub( p1 ).length();
//});
//r.defPrimitive("dot", ["v1", "v2"], function(v1, v2) {
//	return v1.dot(v2);
//});
//r.defPrimitive("cross", ["v1", "v2"], function(v0, v1){
//	return v0.clone().cross( v1 );
//});
//r.defPrimitive("direction_from_to", ["p0", "p1"], function(p0, p1){
//	return p1.clone().sub( p0 ).normalize();
//});
//r.defPrimitive("linear_interpolation", ["p0", "p1", "t"], function(p0, p1, t) {
//	return p0.clone().lerp( p1, t );
//});
//r.defPrimitive("add", ["v1", "v2"], function(v1, v2){
//	return v1.clone().add(v2);
//});
//r.defPrimitive("sub", ["v1", "v2"], function(v1, v2) {
//	return v1.clone().sub(v2);
//});
//r.defPrimitive("mult", ["v1", "v2"], function(v1, v2) {
//	return v1.clone().multiply(v2);
//});
//r.defPrimitive("multScalar", ["v", "s"], function(v, s) {
//	return v.clone().multiplyScalar(s);
//});
//r.defPrimitive("normalize", ["v"], function(v) {
//	return v.clone().normalize();
//});
//r.defPrimitive("length", ["v"], function(v) {
//	return v.length();
//});
/*
vec = {};
{_threeVec: new THREE.Vector3(0,0,0),
 cartesianCoords: [x,y,z],
 dir: [alpha, beta],
 magntitude: num
 }
vec.byXYZ = vecbyXYZ;
vec.byCylindrical = vecbyCylindrical;
vec.byPolar
vec.bySpherical
vec.add
vec.sub
vec.scale
vec.mul
vec.dot
vec.cross
vec.length
vec.lengthSqr
*/

//TODO Define more primitives.
//primitives
const boxPrimitive = r.defPrimitive("box", ["width", "height", "depth"]);
const spherePrimitive = r.defPrimitive("sphere", ["radius"]);
const cylinderPrimitive = r.defPrimitive("cylinder", ["radius", "height"]);
const transformObjectPrimitive = r.defPrimitiveAndProvide("transformObjectWith", ["object", "transform"]);
//r.defPrimitiveAndProvide("cone", ["radius", "height"]);
//r.defPrimitiveAndProvide("coneFrustum", ["bottomRadius", "topRadius", "height"]);
//r.defPrimitiveAndProvide("regularPyramid", ["sides", "height"]);

//r.defPrimitiveAndProvide("line", ["origin", "direction"]);
//r.defPrimitiveAndProvide("polyline", ["coordinates", "closed"]);
//r.defPrimitiveAndProvide("spline", ["coordinates", "closed"]);
//r.defPrimitiveAndProvide("arc", ["radius", "angle"]);

//r.defPrimitiveAndProvide("circle", ["radius"]);
//r.defPrimitiveAndProvide("plane", ["origin", "normal"]);
//r.defPrimitiveAndProvide("polygon", ["coordinates"]);
//r.defPrimitiveAndProvide("regularPolygon", ["radius", "sides"]);

// shapes
const box = {};
box.byWidthHeightDepth = function(width, height, depth) {
	return boxPrimitive(width, height, depth);
};
box.byCentersAxes = function([baseCenter, topCenter], [xVector, yVector]) {
	//let boxCenter = point.pointPlusVector(
	//	baseCenter,
	//	vector.scale(
	//		point.pointMinusPoint(topCenter, baseCenter),
	//		0.5));
	//let translationTransform = matrix.translation(boxCenter.x, boxCenter.y, boxCenter.z);
	let translateBaseToOrigin = matrix.translation(0.0, 0.0, 0.5);

	let zVector = point.pointMinusPoint(topCenter, baseCenter);
	let basisTransform = matrix.basis(xVector, yVector, zVector);

	let translateToBaseCenter = matrix.translation(baseCenter.x, baseCenter.y, baseCenter.z);

	let completeTransform = matrix.multiply(
		translateToBaseCenter,
		matrix.multiply(basisTransform, translateBaseToOrigin));
	//let completeTransform = matrix.multiply(basisTransform, translateBaseToOrigin);
	//transform: move base to wanted base * apply basis * move base to origin

	return transformObjectPrimitive(boxPrimitive(1.0, 1.0, 1.0), completeTransform);
};
box.byCentersWidthHeight = function([baseCenter, topCenter], [width, height]) {
	let boxAxis = point.pointMinusPoint(topCenter, baseCenter);
	let worldZAxis = coordinates.with(coordinates.world, ()=>vector.byXYZ(0.0,0.0,1.0));
	let angleBetweenAxes = Math.acos(vector.dot(worldZAxis, vector.normalized(boxAxis)));
	let rotationAxis = vector.normalized(vector.cross(worldZAxis, boxAxis));
	let rotationTransform = transform.rotation.aroundAxisVectorByAngle(rotationAxis, angleBetweenAxes);

	let worldOrigin = coordinates.with(coordinates.world, ()=>point.byXYZ(0.0,0.0,0.0));
	let midPoint = point.pointPlusVector(
		baseCenter,
		vector.scale(
			point.pointMinusPoint(topCenter, baseCenter),
			0.5));
	let translationVector = point.pointMinusPoint(midPoint, worldOrigin);
	let translationTransform = transform.translation.byVector(translationVector);

	let transformation = transform.compose(translationTransform, rotationTransform);
	let box = boxPrimitive(width, height, vector.length(boxAxis));
	return transformObjectPrimitive(box, transformation);
};
r.provide("box", box);

const sphere = {};
sphere.byCenterRadius = function(vec, radius) {
	let translation = transform.translation.byVector(vec);
	return transformObjectPrimitive(spherePrimitive(radius), translation);
};
r.provide("sphere", sphere);

const cylinder = {};
cylinder.byRadiusHeight = function(radius, height) {
	return cylinderPrimitive(radius, height);
};
cylinder.byCentersRadius = function([baseCenter, topCenter], radius) {
	let cylinderAxis = point.pointMinusPoint(topCenter, baseCenter);
	let worldZAxis = coordinates.with(coordinates.world, ()=>vector.byXYZ(0.0,0.0,1.0));
	let angleBetweenAxes = Math.acos(vector.dot(worldZAxis, vector.normalized(cylinderAxis)));
	let rotationAxis = vector.normalized(vector.cross(worldZAxis, cylinderAxis));
	let rotationTransform = transform.rotation.aroundAxisVectorByAngle(rotationAxis, angleBetweenAxes);

	let worldOrigin = coordinates.with(coordinates.world, ()=>point.byXYZ(0.0,0.0,0.0));
	let midPoint = point.pointPlusVector(
		baseCenter,
		vector.scale(
			point.pointMinusPoint(topCenter, baseCenter),
			0.5));
	let translationVector = point.pointMinusPoint(midPoint, worldOrigin);
	let translationTransform = transform.translation.byVector(translationVector);

	let transformation = transform.compose(translationTransform, rotationTransform);
	let cylinder = cylinderPrimitive(radius, vector.length(cylinderAxis));
	return transformObjectPrimitive(cylinder, transformation);
};
r.provide("cylinder", cylinder);

const sequence = {};
sequence.map = function(fn, seq) {
	return seq.map(fn);
};
sequence.division = function(start, end, divisions) {
	var arr = [];
	var stepSize = (end-start) / divisions;
	var i = 0;
	while(i<divisions+1) {
		arr.push(stepSize*i);
		i++;
	}
	return arr;
};
sequence.count = function(n) {
	var arr = [];
	var i = 0;
	while(i<n) {
		arr.push(i);
		i++;
	}
	return arr;
};
sequence.zip = function(l1, l2) {
	var arr = [];
	var i = 0;
	while(i<l1.length) {
		arr.push([l1[i], l2[i]]);
		i++;
	}
	return arr;
};
sequence.cartesianProduct = function(l1, l2) {
	var arr = [];
	for(let i=0; i<l1.length; i++) {
		for(let j=0; j<l2.length; j++) {
			arr.push([l1[i], l2[j]]);
		}
	}
	return arr;
};
sequence.rotate = function(lst, offset) {
	function posModulo(dividend, divisor) {
		return ((dividend%divisor)+divisor)%divisor;
	}
	var arr = [];
	for(let i=0; i<lst.length; i++) {
		arr.push(lst[posModulo(i+offset, lst.length)]);
	}
	return arr;
};
sequence.repeatTimes = function(elem, n) {
	let i=0;
	let arr = [];
	while(i<n) {
		arr.push(elem);
		i++;
	}
	return arr;
}
sequence.concat = function(lst1, lst2) {
	return lst1.concat(lst2);
}

r.provide("sequence", sequence);

/*
shape.move.byXYZ(x,y,z)
shape.move.byZ(z)
shape.move.byVector(vector)
shape.rotate.byAxisAngle(axis,angle)
shape.scale.uniform(scale)
shape.mirror.byPlane
*/

export default r.primitives;
export {PrimitiveProp};
<|endoftext|>


<commit_before>import 'fetch';
import url from 'url';
import sass from 'sass.js';
import fs from 'fs';

let urlBase;

// intercept file loading requests (@import directive) from libsass
sass.importer((request, done) => {
  const importUrl = url.resolve(urlBase, request.current + '.scss');
  fetch(importUrl)
    .then(response => response.text())
    .then(content => done({ content }));
});

const compile = scss => {
  return new Promise((resolve, reject) => {
    sass.compile(scss, result => {
      if (result.status === 0) {
        const style = document.createElement('style');
        style.textContent = result.text;
        style.setAttribute('type', 'text/css');
        document.getElementsByTagName('head')[0].appendChild(style);
        resolve('');
      } else {
        reject(result.formatted);
      }
    });
  });
};

const scssFetch = load => {
    urlBase = load.address;

    if (urlBase.indexOf('file://') > -1) {
        return new Promise((resolve, reject) => {
            let url = urlBase.slice('file://'.length);
            fs.readFile(url, 'utf8', (err, data) => {
                if (err) {
                    reject(err);
                }
                else {
                    resolve(data);
                }
            });
        }).then(compile);
    }
    else {
        // fetch initial scss file
        return fetch(urlBase)
        .then(response => response.text())
        .then(compile);
    }
};

export default scssFetch;
<commit_msg>- lint it<commit_after>import 'fetch';
import url from 'url';
import sass from 'sass.js';
import fs from 'fs';

let urlBase;

// intercept file loading requests (@import directive) from libsass
sass.importer((request, done) => {
  const importUrl = url.resolve(urlBase, request.current + '.scss');
  fetch(importUrl)
    .then(response => response.text())
    .then(content => done({ content }));
});

const compile = scss => {
  return new Promise((resolve, reject) => {
    sass.compile(scss, result => {
      if (result.status === 0) {
        const style = document.createElement('style');
        style.textContent = result.text;
        style.setAttribute('type', 'text/css');
        document.getElementsByTagName('head')[0].appendChild(style);
        resolve('');
      } else {
        reject(result.formatted);
      }
    });
  });
};

const scssFetch = load => {
    urlBase = load.address;

    if (urlBase.indexOf('file://') > -1) {
      return new Promise((resolve, reject) => {
        const fileUrl = urlBase.slice('file://'.length);
        fs.readFile(fileUrl, 'utf8', (err, data) => {
          if (err) {
            reject(err);
          } else {
            resolve(data);
          }
        });
      }).then(compile);
    }
    // fetch initial scss file
    return fetch(urlBase)
    .then(response => response.text())
    .then(compile);
  };

export default scssFetch;
<|endoftext|>


<commit_before>/**
 * @namespace Lyria
 * Lyria namespace decleration
 */
define('lyria/scene', ['jquery', 'mixin', 'lyria/eventmap', 'lyria/gameobject'], function($, mixin, EventMap, GameObject) {
  'use strict';

  var sceneCache = {};

  var Scene = (function() {

    var Scene = function(sceneName, sceneFunction, options) {
      if (!sceneName) {
        return;
      }

      // Mixin event map into Scene
      mixin(Scene.prototype, new EventMap('scene:' + sceneName));

      // We need a reference to the scene not being this
      var self = this;

      // Collect all template values
      var templateVals = {};

      // Set name
      this.name = sceneName;

      // Default values
      this.localization = {};

      // Expose function for template values
      this.expose = function(obj) {
        if (!obj || $.isEmptyObject(obj)) {
          return;
        }

        templateVals = $.extend(true, templateVals, obj);
      };

      // Set a context object for sceneFunction to be called in
      var context = {};

      // Call scene
      var retValue = sceneFunction.call(this, this);

      if (retValue && !$.isEmptyObject(retValue)) {
        this.expose(retValue);
      }

      // Mix in keys from context to the scene object
      $.each(context, function(key, value) {
        if (self[key]) {

        } else {
          self[key] = value;
        }
      });

      /*if (this.localization) {
        var currentLocalization = this.localization['de'];

        retValue = $.extend(retValue, currentLocalization);
      }*/

      if (this.template) {
        this.content = this.template(templateVals);
      }

      if (this.events) {
        if (options && options.isPrefab) {
          this.events.delegate = (options.target) ? options.target : 'body';
        } else {
          this.events.delegate = '#' + sceneName;
        }
      }

    };

    Scene.prototype.add = function(gameObject) {
      if (gameObject instanceof GameObject) {

      }
    };

    return Scene;

  })();

  return Scene;

});<commit_msg>Added function to re-compile scene template<commit_after>/**
 * @namespace Lyria
 * Lyria namespace decleration
 */
define('lyria/scene', ['jquery', 'mixin', 'lyria/eventmap', 'lyria/gameobject'], function($, mixin, EventMap, GameObject) {
  'use strict';

  var sceneCache = {};

  var Scene = (function() {

    var Scene = function(sceneName, sceneFunction, options) {
      if (!sceneName) {
        return;
      }

      // Mixin event map into Scene
      mixin(Scene.prototype, new EventMap('scene:' + sceneName));

      // We need a reference to the scene not being this
      var self = this;

      // Collect all template values
      var templateVals = {};

      // Set name
      this.name = sceneName;

      // Default values
      this.localization = {};

      // Expose function for template values
      this.expose = function(obj) {
        if (!obj || $.isEmptyObject(obj)) {
          return;
        }

        templateVals = $.extend(true, templateVals, obj);
      };

      // Set a context object for sceneFunction to be called in
      var context = {};

      // Call scene
      var retValue = sceneFunction.call(this, this);

      if (retValue && !$.isEmptyObject(retValue)) {
        this.expose(retValue);
      }

      // Mix in keys from context to the scene object
      $.each(context, function(key, value) {
        if (self[key]) {

        } else {
          self[key] = value;
        }
      });

      /*if (this.localization) {
        var currentLocalization = this.localization['de'];

        retValue = $.extend(retValue, currentLocalization);
      }*/

      if (this.template) {
        this.content = this.template(templateVals);
      }

      if (this.events) {
        if (options && options.isPrefab) {
          this.events.delegate = (options.target) ? options.target : 'body';
        } else {
          this.events.delegate = '#' + sceneName;
        }
      }

    };

    Scene.prototype.add = function(gameObject) {
      if (gameObject instanceof GameObject) {

      }
    };

    Scene.prototype.compileTemplate = function(val) {
      this.content = this.template(val);
    };

    return Scene;

  })();

  return Scene;

});<|endoftext|>


<commit_before>import DocumentTitle from 'react-document-title'
import HTML5Backend from 'react-dnd-html5-backend'
import React, { Component, PropTypes, cloneElement } from 'react'
import { DragDropContext } from 'react-dnd'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { ActionCreators as UndoableActionCreators } from 'redux-undo'
import * as actionCreators from '../ducks/actions/students'
import omit from 'lodash/object/omit'

import '../index.scss'

export class App extends Component {
	static propTypes = {
		actions: PropTypes.objectOf(PropTypes.func).isRequired,
		areas: PropTypes.array.isRequired,
		canRedo: PropTypes.bool.isRequired,
		canUndo: PropTypes.bool.isRequired,
		children: PropTypes.node.isRequired,
		students: PropTypes.object.isRequired,
	}

	render() {
		return (
			<DocumentTitle title='Gobbldygook'>
				{cloneElement(this.props.children, omit(this.props, 'children'))}
			</DocumentTitle>
		)
	}
}

function mapStateToProps(state) {
	// selects some state that is relevant to this component, and returns it.
	// redux-react will bind it to props.
	return {
		areas: state.areas,
		canRedo: state.students.future.length !== 0,
		canUndo: state.students.past.length !== 0,
		students: state.students.present,
	}
}

function mapDispatchToProps(dispatch) {
	// binds the actions creators to this dispatch function.
	// then passes the keys of the returned object as props to the connect()-ed component
	return {
		actions: {
			...bindActionCreators(actionCreators, dispatch),
			undo: () => dispatch(UndoableActionCreators.undo()),
			redo: () => dispatch(UndoableActionCreators.redo()),
		},
	}
}

const draggable = DragDropContext(HTML5Backend)(App)
const connected = connect(mapStateToProps, mapDispatchToProps)(draggable)
export default connected
<commit_msg>render CourseSearcherSheet in App<commit_after>import DocumentTitle from 'react-document-title'
import HTML5Backend from 'react-dnd-html5-backend'
import React, { Component, PropTypes, cloneElement } from 'react'
import { DragDropContext } from 'react-dnd'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { ActionCreators as UndoableActionCreators } from 'redux-undo'
import * as actionCreators from '../ducks/actions/students'
import omit from 'lodash/object/omit'
import CourseSearcherSheet from './course-searcher-sheet'

import '../index.scss'

export class App extends Component {
	static propTypes = {
		actions: PropTypes.objectOf(PropTypes.func).isRequired,
		areas: PropTypes.array.isRequired,
		canRedo: PropTypes.bool.isRequired,
		canUndo: PropTypes.bool.isRequired,
		children: PropTypes.node.isRequired,
		students: PropTypes.object.isRequired,
	}

	static contextTypes = {
		location: PropTypes.object,
	}

	render() {
		return (
			<DocumentTitle title='Gobbldygook'>
				<div>
					{cloneElement(this.props.children, omit(this.props, 'children'))}
					{'search-overlay' in this.context.location.query &&
						<CourseSearcherSheet actions={this.props.actions} />}
				</div>
			</DocumentTitle>
		)
	}
}

function mapStateToProps(state) {
	// selects some state that is relevant to this component, and returns it.
	// redux-react will bind it to props.
	return {
		areas: state.areas,
		canRedo: state.students.future.length !== 0,
		canUndo: state.students.past.length !== 0,
		students: state.students.present,
	}
}

function mapDispatchToProps(dispatch) {
	// binds the actions creators to this dispatch function.
	// then passes the keys of the returned object as props to the connect()-ed component
	return {
		actions: {
			...bindActionCreators(actionCreators, dispatch),
			undo: () => dispatch(UndoableActionCreators.undo()),
			redo: () => dispatch(UndoableActionCreators.redo()),
		},
	}
}

const draggable = DragDropContext(HTML5Backend)(App)
const connected = connect(mapStateToProps, mapDispatchToProps)(draggable)
export default connected
<|endoftext|>


<commit_before>(function() {
    var lang = localStorage.getItem('lang') || 'en-us';
    require.config({
        locale: lang,
        paths: {
            text:'../vendors/require/text',
            i18n:'../vendors/require/i18n',
            Framework7:'../vendors/framework7/framework7',
            mustache:'../vendors/mustache/mustache',
            GTPL:'../page/global.tpl.html',
            GS:'services/globalService'
        },
        shim: {
            'Framework7':{exports: 'Framework7'}
        }
    });

    require(['Framework7','router','i18n!nls/lang','utils/appFunc'], function(Framework7,router,i18n,appFunc) {

        var app = {
            initialize: function() {
                this.bindEvents();
            },
            bindEvents: function() {
                if(appFunc.isPhonegap()) {
                    document.addEventListener('deviceready', this.onDeviceReady, false);
                }else{
                    window.onload = this.onDeviceReady();
                }
            },
            onDeviceReady: function() {
                app.receivedEvent('deviceready');
            },
            receivedEvent: function(event) {
                switch (event) {
                    case 'deviceready':
                        app.initMainView();
                        break;
                }
            },
            initMainView:function(){
                window.$$ = Dom7;

                window.hiApp = new Framework7({
                    pushState: false,
                    popupCloseByOutside:false,
                    animateNavBackIcon: true,
                    modalTitle: i18n.global.modal_title,
                    modalButtonOk: i18n.global.modal_button_ok,
                    modalButtonCancel: i18n.global.cancel,
                    preprocess:router.preprocess
                });

                window.mainView = hiApp.addView('#ourView', {
                    dynamicNavbar: true
                });

                window.contatcView = hiApp.addView('#contatcView', {
                    dynamicNavbar: true
                });

                window.settingView = hiApp.addView('#settingView', {
                    dynamicNavbar: true
                });

                router.init();
            }
        };

        app.initialize();

    });
})();
<commit_msg>Use Template7 instead mustache<commit_after>(function() {
    var lang = localStorage.getItem('lang') || 'en-us';
    require.config({
        locale: lang,
        paths: {
            text:'../vendors/require/text',
            i18n:'../vendors/require/i18n',
            Framework7:'../vendors/framework7/framework7',
            GTPL:'../page/global.tpl.html',
            GS:'services/globalService'
        },
        shim: {
            'Framework7':{exports: 'Framework7'}
        }
    });

    require(['Framework7','router','i18n!nls/lang','utils/appFunc'], function(Framework7,router,i18n,appFunc) {

        var app = {
            initialize: function() {
                this.bindEvents();
            },
            bindEvents: function() {
                if(appFunc.isPhonegap()) {
                    document.addEventListener('deviceready', this.onDeviceReady, false);
                }else{
                    window.onload = this.onDeviceReady();
                }
            },
            onDeviceReady: function() {
                app.receivedEvent('deviceready');
            },
            receivedEvent: function(event) {
                switch (event) {
                    case 'deviceready':
                        app.initMainView();
                        break;
                }
            },
            initMainView:function(){
                window.$$ = Dom7;

                window.hiApp = new Framework7({
                    pushState: false,
                    popupCloseByOutside:false,
                    animateNavBackIcon: true,
                    modalTitle: i18n.global.modal_title,
                    modalButtonOk: i18n.global.modal_button_ok,
                    modalButtonCancel: i18n.global.cancel,
                    preprocess:router.preprocess
                });

                window.mainView = hiApp.addView('#ourView', {
                    dynamicNavbar: true
                });

                window.contatcView = hiApp.addView('#contatcView', {
                    dynamicNavbar: true
                });

                window.settingView = hiApp.addView('#settingView', {
                    dynamicNavbar: true
                });

                router.init();
            }
        };

        app.initialize();

    });
})();
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012-2015 S-Core Co., Ltd.
 *
 * 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.
 */

/**
 * @example Using fileloc transformer. "<fileloc>" is fileloc transformer and
 *      transforms the next element to a link to the file.
 * require(['plugins/output/plugin'],
 *      function (c) {
 *          c.log("<fileloc>", "/ws1/settings.json:15");
 *          c.log("<fileloc>", "/ws1/settings.json:15:comment);
 *      });
 */

/* global timedLogger: true */

var time;
define([(time = timedLogger.getLoggerTime(), 'webida-lib/plugins/workbench/plugin'),
    'other-lib/underscore/lodash.min',
    'dojo/topic',
    'dijit/form/CheckBox',
    'dijit/form/Button',
    'text!./output-view.html',
    'text!./templates/_tmplToolbar.html',
    'webida-lib/widgets/views/view'
],
function (workbench, _, topic, CheckBox, Button, consoleViewHtml, toolbarTmpl, View) {
    'use strict';

    time = timedLogger.log('loaded modules required by output. initializing output plugin\'s module', time);

    var consoleMgr;
    var mod = {};
    var defaultConsoleId = 'Output';
    var tabs;

    function transformerFileLoc(filelocInfo) {
        if (filelocInfo) {
            if (filelocInfo.hasOwnProperty('path')) {
                var path = filelocInfo.path;
                var pos = {row: 0, col: 0};
                var text = '';
                if (filelocInfo.hasOwnProperty('line')) {
                    pos.row = filelocInfo.line - 1;
                }
                if (filelocInfo.hasOwnProperty('text')) {
                    text = filelocInfo.text;
                }

                var elm = $('').addClass('fileloc_link pre_whitespace').text(text);
                elm.on('click', function () {
                    topic.publish('#REQUEST.openFile', path, { pos: pos });
                    elm.addClass('fileloc_link_clicked');
                });

                return elm;
            }
            return null;
        }
    }

    function transformerUri(text) {
        var myRe = new RegExp(
            '(http|ftp|https)://[\\w-]+(\\.[\\w-]+)+([\\w-.,@?^=%&:/~+#-]*[\\w@?^=%&;/~+#-])?', 'ig');
        var myArray;

        var uriList = [];
        while ((myArray = myRe.exec(text)) !== null) {
            console.log(myArray);
            var msg = 'Found ' + myArray[0] + '.  ';
            msg += 'Next match starts at ' + myRe.lastIndex;
            var item = {text: myArray[0], index: myArray.index, lastIndex: myRe.lastIndex};
            uriList.push(item);
            console.log(msg);
        }

        _.each(uriList, function (uri) {
            uri.text = uri.text.replace(myRe, '$&');
            console.log(uri);
        });

        var result = [];
        var edLoc;
        var stLoc = 0;
        _.each(uriList, function (uri, index) {
            edLoc = uri.index;
            if (edLoc !== stLoc) {
                result.push($('').text(text.substr(stLoc, edLoc - stLoc)));
            }
            result.push(uri.text);
            stLoc = uri.lastIndex;
            if (index === uriList.length - 1) {
                result.push($('').text(text.substr(stLoc, text.length - stLoc)));
            }
        });

        if (result.length > 0) {
            var elm = $('');
            _.each(result, function (value) {
                elm.append(value);
            });

            return elm;
        } else {
            return text;
        }

    }

    mod.TRANSFORMERS_MAP = {
//        'htmlescape': transformerHtmlEscape,
        'fileloc': transformerFileLoc,
        'uri': transformerUri,
//        'error': transformerError
    };

    function getTransformer(type) {
        if (mod.TRANSFORMERS_MAP.hasOwnProperty(type)) {
            return mod.TRANSFORMERS_MAP[type];
        }
    }

    /**
     *  @class ConsoleManager
     */
    function ConsoleManager() {
        this.consoles = {};
        this.consoles[defaultConsoleId] = new Console(defaultConsoleId);
    }
    ConsoleManager.prototype.getConsole = function (consoleId) {
        if (this.consoles.hasOwnProperty(consoleId)) {
            return this.consoles[consoleId];
        } else {
            return this.addNewConsole(consoleId);
        }
    };
    ConsoleManager.prototype.addNewConsole = function (consoleId, opt) {
        if (this.consoles.hasOwnProperty(consoleId)) {
            return null;
        } else {
            var con = new Console(consoleId, opt);
            this.consoles[consoleId] = con;
            return this.consoles[consoleId];
        }
    };

    /**
     * @class Console
     */
    function Console(consoleId, opt) {
        var self = this;
        self.consoleId = consoleId;
        if (!opt) {
            opt = {};
        }
        self.scrollLocked = opt.scrollLocked || false;
        self.showLineNumber = opt.showLineNumber || false; // TODO
        self.lineNumber = 0; // TODO
        self.showOnNewMessage = opt.showOnNewMessage || true;
        self.showOnNewMessage = true;
        self.defaultTransformers = opt.defaultTransformers ||
//            [mod.TRANSFORMERS_MAP.htmlescape, mod.TRANSFORMERS_MAP.uri]; TODO : FIXME
                        [mod.TRANSFORMERS_MAP.uri];

        self.elemId = this.getContentElemId();
        self.contentElem = null;
        self.logQueue = [];
        self.interval = null;

        var topContent = $('

');

        var contentHtml =
            '

';

        topContent.append(toolbarTmpl);
        topContent.append(contentHtml);

        var view = new View(consoleId, consoleId);
        self.view = view;
        view.setContent(topContent[0]);

        self.$titleElem = $(this.getTitleElem());
        var chkNewMeaasge = new CheckBox({
            checked: self.showOnNewMessage,
            onChange: function (value) {
                self.setShowOnMeaasge(value);
            }
        }, self.$titleElem.find('.chk-showonmessage')[0]);

        var chkScrollLock = new CheckBox({
            checked: self.scrollLocked,
            onChange: function (value) {
                self.scrollLock(value);
            }
        }, self.$titleElem.find('.chk-scrolllock')[0]);

        void new Button({
            label: 'Clear',
            style: 'position:absolute; right:5px',
            onClick: function () {
                self.clearContents();
            }
        }, self.$titleElem.find('.btn-clear')[0]);

        chkNewMeaasge.set('checked', self.showOnNewMessage);
        chkScrollLock.set('checked', self.scrollLocked);

        if (consoleId !== defaultConsoleId) {
            workbench.appendView(view, 'bottom');
        }
    }

    Console.prototype.log = function () {
        var self = this;
        var args = Array.prototype.slice.call(arguments);

        self.logQueue.push({type : 'log', args : args});
        self.startTimer();
    };

    Console.prototype.logs = function () {
        var self = this;
        var args = Array.prototype.slice.call(arguments);

        self.logQueue.push({type : 'log', args : args});
        self.startTimer();
    };

    Console.prototype.startTimer = function (rotateCount, maxItemCount) {
        var self = this;
        if (self.interval === null) {
            var rCount = 1;
            var MAX_COUNT = 50;

            if (rotateCount) {
                rCount = rotateCount;
            }

            if (maxItemCount) {
                MAX_COUNT = maxItemCount;
            }

            var processQueue = function () {
                _.range(rCount).forEach(function () {
                    if (self.logQueue.length > 0) {
                        var args, i;
                        var $contentElem = $(self.getContentElem());
                        var $groupContent = $('
');
                        var $messageElem;
                        var type;

                        try {
                            _.range(self.logQueue.length).forEach(function (i) {
                                if (i >= MAX_COUNT) {
                                    throw 'break';
                                }
                                args = self.logQueue[i].args;
                                type = self.logQueue[i].type;
                                $messageElem = $('
');
                                _.each(args, function (arg) {
                                    var transformer = null;
                                    var data = null;
                                    if (typeof(arg) === 'object') {
                                        if (arg.hasOwnProperty('type')) {
                                            transformer = getTransformer(arg.type);
                                        }
                                    } else if (typeof(arg) === 'string') {
                                        transformer = getTransformer('uri');
                                    }

                                    if (transformer) {
                                        data = transformer(arg);
                                    } else {
                                        data = arg;
                                    }

                                    if (data) {
                                        $messageElem.append(data);
                                        $messageElem.append(' ');
                                        if (type === 'err') {
                                            $messageElem.addClass('console_error_message');
                                        }
                                    }
                                });

                                $messageElem.append('
');
                                $groupContent.append($messageElem);
                            });
                        } catch (e) {
                            if (e !== 'break') {
                                throw e;
                            }
                        }

                        if (i === MAX_COUNT) {
                            self.logQueue.splice(0, MAX_COUNT);
                        } else {
                            self.logQueue = [];
                            clearInterval(self.interval);
                            self.interval = null;
                        }

                        $contentElem.append($groupContent);

                        if (!self.scrollLocked) {
                            self.scrollBot();
                        }

                        if (self.showOnNewMessage && self.view) {
                            self.view.select();
                        }
                    }
                });
            };

            self.interval = setInterval(function () {
                processQueue();
                return false;
            }, 100);
        }
    };

    Console.prototype.err = function () {
        var self = this;
        var args = Array.prototype.slice.call(arguments);
        self.logQueue.push({type : 'err', args : args});
    };
    Console.prototype.getTitleElemId = function () {
        return 'consoleTitle_' + this.consoleId;
    };
    Console.prototype.getContentElemId = function () {
        return 'consoleContent_' + this.consoleId;
    };
    Console.prototype.getContentElem = function () {
        if (!this.contentElem) {
            var elemId = this.getContentElemId();
            if (this.view) {
                this.contentElem = $(this.view.contentPane.domNode).find('#' + elemId)[0];
            }
        }

        return this.contentElem;
    };
    Console.prototype.getTitleElem = function () {
        var content = this.view.getContent();
        if (content) {
            return content.children[0];
        }
        //return $('#' + elemId)[0];
    };
    Console.prototype.scrollBot = function () {
        var elem = $(this.getContentElem());
        var tab = elem.parent();
        tab.scrollTop(elem[0].scrollHeight);
    };
    Console.prototype.addTransformer = function (transformer) {
        this.transformers.push(transformer);
    };
    Console.prototype.show = function () {
        this.view.select();
    };
    Console.prototype.setShowOnMeaasge = function (value) {
        if (value === false) {
            this.showOnNewMessage = false;
        } else {
            this.showOnNewMessage = true;
        }
    };
    Console.prototype.scrollLock = function (value) {
        if (value === false) {
            this.scrollLocked = false;
        } else {
            this.scrollLocked = true;
        }
    };
    Console.prototype.clearContents = function () {
        $(this.getContentElem()).empty();
        this.logQueue = [];
    };

    mod.getConsole = function () {
        if (!consoleMgr) {
            consoleMgr = mod.consoleMgr = new ConsoleManager();
        }

        if (consoleMgr) {
            return consoleMgr.getConsole.apply(consoleMgr, arguments);
        } else {
            return null;
        }
    };
    mod.addNewConsole = function () {
        if (consoleMgr) {
            return consoleMgr.addNewConsole.bind(consoleMgr);
        } else {
            return null;
        }
    };
    mod.Console = Console;

    mod.openConsole = function () {
        workbench.horzSplitter.expand();
    };

    mod.getDefaultConsole = function () {
        return consoleMgr.getConsole(defaultConsoleId);
    };

    mod.addTransformer = function (name, tfm) {
        if (mod.TRANSFORMERS_MAP.hasOwnProperty(name)) {
            return false;
        } else {
            mod.TRANSFORMERS_MAP[name] = tfm;
            return true;
        }
    };

    mod.removeTransformer = function (name) {
        if (mod.TRANSFORMERS_MAP.hasOwnProperty(name)) {
            delete mod.TRANSFORMERS_MAP[name];
            return true;
        } else {
            return false;
        }
    };

    mod.log = function () {
        var defaultConsole = mod.getDefaultConsole();
        defaultConsole.log.apply(defaultConsole, arguments);
    };

    mod.err = function () {
        var defaultConsole = mod.getDefaultConsole();
        defaultConsole.err.apply(defaultConsole, arguments);
    };

    mod.getView = function () {
        consoleMgr = mod.consoleMgr = new ConsoleManager();
        var defaultConsole = mod.getDefaultConsole();
        return defaultConsole.view;
    };

    mod.onViewAppended = function () {
        var view = this.getDefaultConsole().view;
        if (view) {
            var opt = {};
            opt.title = 'Output';
            opt.key = 'O';
            workbench.registToViewFocusList(view, opt);
        }
    };

    mod.getTabs = function () {
        return tabs;
    };

    topic.subscribe('#REQUEST.log', mod.log);

    timedLogger.log('initialized output plugin\'s module', time);

    return mod;
});
<commit_msg>[BUGFIX] (ODP-317) fix output logging bug (the logger could not write more than 50 rows in Output view)<commit_after>/*
 * Copyright (c) 2012-2015 S-Core Co., Ltd.
 *
 * 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.
 */

/**
 * @example Using fileloc transformer. "<fileloc>" is fileloc transformer and
 *      transforms the next element to a link to the file.
 * require(['plugins/output/plugin'],
 *      function (c) {
 *          c.log("<fileloc>", "/ws1/settings.json:15");
 *          c.log("<fileloc>", "/ws1/settings.json:15:comment);
 *      });
 */

/* global timedLogger: true */

var time;
define([(time = timedLogger.getLoggerTime(), 'webida-lib/plugins/workbench/plugin'),
    'other-lib/underscore/lodash.min',
    'dojo/topic',
    'dijit/form/CheckBox',
    'dijit/form/Button',
    'text!./output-view.html',
    'text!./templates/_tmplToolbar.html',
    'webida-lib/widgets/views/view'
],
function (workbench, _, topic, CheckBox, Button, consoleViewHtml, toolbarTmpl, View) {
    'use strict';

    time = timedLogger.log('loaded modules required by output. initializing output plugin\'s module', time);

    var consoleMgr;
    var mod = {};
    var defaultConsoleId = 'Output';
    var tabs;

    function transformerFileLoc(filelocInfo) {
        if (filelocInfo) {
            if (filelocInfo.hasOwnProperty('path')) {
                var path = filelocInfo.path;
                var pos = {row: 0, col: 0};
                var text = '';
                if (filelocInfo.hasOwnProperty('line')) {
                    pos.row = filelocInfo.line - 1;
                }
                if (filelocInfo.hasOwnProperty('text')) {
                    text = filelocInfo.text;
                }

                var elm = $('').addClass('fileloc_link pre_whitespace').text(text);
                elm.on('click', function () {
                    topic.publish('#REQUEST.openFile', path, { pos: pos });
                    elm.addClass('fileloc_link_clicked');
                });

                return elm;
            }
            return null;
        }
    }

    function transformerUri(text) {
        var myRe = new RegExp(
            '(http|ftp|https)://[\\w-]+(\\.[\\w-]+)+([\\w-.,@?^=%&:/~+#-]*[\\w@?^=%&;/~+#-])?', 'ig');
        var myArray;

        var uriList = [];
        while ((myArray = myRe.exec(text)) !== null) {
            console.log(myArray);
            var msg = 'Found ' + myArray[0] + '.  ';
            msg += 'Next match starts at ' + myRe.lastIndex;
            var item = {text: myArray[0], index: myArray.index, lastIndex: myRe.lastIndex};
            uriList.push(item);
            console.log(msg);
        }

        _.each(uriList, function (uri) {
            uri.text = uri.text.replace(myRe, '$&');
            console.log(uri);
        });

        var result = [];
        var edLoc;
        var stLoc = 0;
        _.each(uriList, function (uri, index) {
            edLoc = uri.index;
            if (edLoc !== stLoc) {
                result.push($('').text(text.substr(stLoc, edLoc - stLoc)));
            }
            result.push(uri.text);
            stLoc = uri.lastIndex;
            if (index === uriList.length - 1) {
                result.push($('').text(text.substr(stLoc, text.length - stLoc)));
            }
        });

        if (result.length > 0) {
            var elm = $('');
            _.each(result, function (value) {
                elm.append(value);
            });

            return elm;
        } else {
            return text;
        }

    }

    mod.TRANSFORMERS_MAP = {
//        'htmlescape': transformerHtmlEscape,
        'fileloc': transformerFileLoc,
        'uri': transformerUri
//        'error': transformerError
    };

    function getTransformer(type) {
        if (mod.TRANSFORMERS_MAP.hasOwnProperty(type)) {
            return mod.TRANSFORMERS_MAP[type];
        }
    }

    /**
     *  @class ConsoleManager
     */
    function ConsoleManager() {
        this.consoles = {};
        this.consoles[defaultConsoleId] = new Console(defaultConsoleId);
    }
    ConsoleManager.prototype.getConsole = function (consoleId) {
        if (this.consoles.hasOwnProperty(consoleId)) {
            return this.consoles[consoleId];
        } else {
            return this.addNewConsole(consoleId);
        }
    };
    ConsoleManager.prototype.addNewConsole = function (consoleId, opt) {
        if (this.consoles.hasOwnProperty(consoleId)) {
            return null;
        } else {
            var con = new Console(consoleId, opt);
            this.consoles[consoleId] = con;
            return this.consoles[consoleId];
        }
    };

    /**
     * @class Console
     */
    function Console(consoleId, opt) {
        var self = this;
        self.consoleId = consoleId;
        if (!opt) {
            opt = {};
        }
        self.scrollLocked = opt.scrollLocked || false;
        self.showLineNumber = opt.showLineNumber || false; // TODO
        self.lineNumber = 0; // TODO
        self.showOnNewMessage = opt.showOnNewMessage || true;
        self.showOnNewMessage = true;
        self.defaultTransformers = opt.defaultTransformers ||
//            [mod.TRANSFORMERS_MAP.htmlescape, mod.TRANSFORMERS_MAP.uri]; TODO : FIXME
                        [mod.TRANSFORMERS_MAP.uri];

        self.elemId = this.getContentElemId();
        self.contentElem = null;
        self.logQueue = [];
        self.interval = null;

        var topContent = $('

');

        var contentHtml =
            '

';

        topContent.append(toolbarTmpl);
        topContent.append(contentHtml);

        var view = new View(consoleId, consoleId);
        self.view = view;
        view.setContent(topContent[0]);

        self.$titleElem = $(this.getTitleElem());
        var chkNewMeaasge = new CheckBox({
            checked: self.showOnNewMessage,
            onChange: function (value) {
                self.setShowOnMeaasge(value);
            }
        }, self.$titleElem.find('.chk-showonmessage')[0]);

        var chkScrollLock = new CheckBox({
            checked: self.scrollLocked,
            onChange: function (value) {
                self.scrollLock(value);
            }
        }, self.$titleElem.find('.chk-scrolllock')[0]);

        void new Button({
            label: 'Clear',
            style: 'position:absolute; right:5px',
            onClick: function () {
                self.clearContents();
            }
        }, self.$titleElem.find('.btn-clear')[0]);

        chkNewMeaasge.set('checked', self.showOnNewMessage);
        chkScrollLock.set('checked', self.scrollLocked);

        if (consoleId !== defaultConsoleId) {
            workbench.appendView(view, 'bottom');
        }
    }

    Console.prototype.log = function () {
        var self = this;
        var args = Array.prototype.slice.call(arguments);

        self.logQueue.push({type : 'log', args : args});
        self.startTimer();
    };

    Console.prototype.logs = function () {
        var self = this;
        var args = Array.prototype.slice.call(arguments);

        self.logQueue.push({type : 'log', args : args});
        self.startTimer();
    };

    Console.prototype.startTimer = function (rotateCount, maxItemCount) {
        var self = this;
        if (self.interval === null) {
            var rCount = 1;
            var MAX_COUNT = 50;

            if (rotateCount) {
                rCount = rotateCount;
            }

            if (maxItemCount) {
                MAX_COUNT = maxItemCount;
            }

            var processQueue = function () {
                _.range(rCount).forEach(function () {
                    if (self.logQueue.length > 0) {
                        var args;
                        var $contentElem = $(self.getContentElem());
                        var $groupContent = $('
');
                        var $messageElem;
                        var type;

                        var range = Math.min(self.logQueue.length, MAX_COUNT);
                        _.range(range).forEach(function (i) {
                            args = self.logQueue[i].args;
                            type = self.logQueue[i].type;
                            $messageElem = $('
');
                            _.each(args, function (arg) {
                                var transformer = null;
                                var data = null;
                                if (typeof(arg) === 'object') {
                                    if (arg.hasOwnProperty('type')) {
                                        transformer = getTransformer(arg.type);
                                    }
                                } else if (typeof(arg) === 'string') {
                                    transformer = getTransformer('uri');
                                }

                                if (transformer) {
                                    data = transformer(arg);
                                } else {
                                    data = arg;
                                }

                                if (data) {
                                    $messageElem.append(data);
                                    $messageElem.append(' ');
                                    if (type === 'err') {
                                        $messageElem.addClass('console_error_message');
                                    }
                                }
                            });

                            $messageElem.append('
');
                            $groupContent.append($messageElem);
                        });

                        self.logQueue.splice(0, MAX_COUNT);
                        if(range < MAX_COUNT){
                            clearInterval(self.interval);
                            self.interval = null;
                        }

                        $contentElem.append($groupContent);

                        if (!self.scrollLocked) {
                            self.scrollBot();
                        }

                        if (self.showOnNewMessage && self.view) {
                            self.view.select();
                        }
                    }
                });
            };

            self.interval = setInterval(function () {
                processQueue();
                return false;
            }, 100);
        }
    };

    Console.prototype.err = function () {
        var self = this;
        var args = Array.prototype.slice.call(arguments);
        self.logQueue.push({type : 'err', args : args});
    };
    Console.prototype.getTitleElemId = function () {
        return 'consoleTitle_' + this.consoleId;
    };
    Console.prototype.getContentElemId = function () {
        return 'consoleContent_' + this.consoleId;
    };
    Console.prototype.getContentElem = function () {
        if (!this.contentElem) {
            var elemId = this.getContentElemId();
            if (this.view) {
                this.contentElem = $(this.view.contentPane.domNode).find('#' + elemId)[0];
            }
        }

        return this.contentElem;
    };
    Console.prototype.getTitleElem = function () {
        var content = this.view.getContent();
        if (content) {
            return content.children[0];
        }
        //return $('#' + elemId)[0];
    };
    Console.prototype.scrollBot = function () {
        var elem = $(this.getContentElem());
        var tab = elem.parent();
        tab.scrollTop(elem[0].scrollHeight);
    };
    Console.prototype.addTransformer = function (transformer) {
        this.transformers.push(transformer);
    };
    Console.prototype.show = function () {
        this.view.select();
    };
    Console.prototype.setShowOnMeaasge = function (value) {
        if (value === false) {
            this.showOnNewMessage = false;
        } else {
            this.showOnNewMessage = true;
        }
    };
    Console.prototype.scrollLock = function (value) {
        if (value === false) {
            this.scrollLocked = false;
        } else {
            this.scrollLocked = true;
        }
    };
    Console.prototype.clearContents = function () {
        $(this.getContentElem()).empty();
        this.logQueue = [];
    };

    mod.getConsole = function () {
        if (!consoleMgr) {
            consoleMgr = mod.consoleMgr = new ConsoleManager();
        }

        if (consoleMgr) {
            return consoleMgr.getConsole.apply(consoleMgr, arguments);
        } else {
            return null;
        }
    };
    mod.addNewConsole = function () {
        if (consoleMgr) {
            return consoleMgr.addNewConsole.bind(consoleMgr);
        } else {
            return null;
        }
    };
    mod.Console = Console;

    mod.openConsole = function () {
        workbench.horzSplitter.expand();
    };

    mod.getDefaultConsole = function () {
        return consoleMgr.getConsole(defaultConsoleId);
    };

    mod.addTransformer = function (name, tfm) {
        if (mod.TRANSFORMERS_MAP.hasOwnProperty(name)) {
            return false;
        } else {
            mod.TRANSFORMERS_MAP[name] = tfm;
            return true;
        }
    };

    mod.removeTransformer = function (name) {
        if (mod.TRANSFORMERS_MAP.hasOwnProperty(name)) {
            delete mod.TRANSFORMERS_MAP[name];
            return true;
        } else {
            return false;
        }
    };

    mod.log = function () {
        var defaultConsole = mod.getDefaultConsole();
        defaultConsole.log.apply(defaultConsole, arguments);
    };

    mod.err = function () {
        var defaultConsole = mod.getDefaultConsole();
        defaultConsole.err.apply(defaultConsole, arguments);
    };

    mod.getView = function () {
        consoleMgr = mod.consoleMgr = new ConsoleManager();
        var defaultConsole = mod.getDefaultConsole();
        return defaultConsole.view;
    };

    mod.onViewAppended = function () {
        var view = this.getDefaultConsole().view;
        if (view) {
            var opt = {};
            opt.title = 'Output';
            opt.key = 'O';
            workbench.registToViewFocusList(view, opt);
        }
    };

    mod.getTabs = function () {
        return tabs;
    };

    topic.subscribe('#REQUEST.log', mod.log);

    timedLogger.log('initialized output plugin\'s module', time);

    return mod;
});
<|endoftext|>


<commit_before>define(function (require, exports, module) {
  'use strict';

  var AppInit = app.getModule('utils/AppInit');
  var Core = app.getModule('core/Core');
  var PreferenceManager = app.getModule('core/PreferenceManager');

  var preferenceId = 'ruby';

  var rubyPreferences = {
    'ruby.gen': {
      text: 'Ruby Code Generation',
      type: 'Section',
    },
    'ruby.gen.useTab': {
      text: 'Use Tab',
      description: 'Use tab for indentation instead of spaces.',
      type: 'Check',
      default: false,
    },
    'ruby.gen.indentSpaces': {
      text: 'Indent Spaces',
      description: 'Number of spaces for indentation.',
      type: 'Number',
      default: 2,
    },
    'ruby.gen.initializeMethod': {
      text: 'The initialize method',
      description: 'Generate initialize method that works almost same way as constructor.',
      type: 'Check',
      default: true,
    },
    'ruby.gen.useAttributeAccessor': {
      text: 'Attribute accessor',
      description: 'Use attribute accessor rather than set and get attribute methods.',
      type: 'Check',
      default: false,
    },
    'ruby.gen.toStringMethod': {
      text: 'The to_s method',
      description: 'Generate to_s method that returns a string representation of the object.',
      type: 'Check',
      default: true,
    },
  };

  function getId() {
    return preferenceId;
  }

  function getGenerateOptions() {
    return {
      useTab: PreferenceManager.get('ruby.gen.useTab'),
      indentSpaces: PreferenceManager.get('ruby.gen.indentSpaces'),
      initializeMethod: PreferenceManager.get('ruby.gen.initializeMethod'),
      useAttributeAccessor: PreferenceManager.get('ruby.gen.useAttributeAccessor'),
      rubyToStringMethod: PreferenceManager.get('ruby.gen.toStringMethod'),
    };
  }

  AppInit.htmlReady(function () {
    PreferenceManager.register(preferenceId, 'Ruby', rubyPreferences);
  });

  exports.getId = getId;
  exports.getGenerateOptions = getGenerateOptions;
});
<commit_msg>Add documentation of class elements preference<commit_after>define(function (require, exports, module) {
  'use strict';

  var AppInit = app.getModule('utils/AppInit');
  var Core = app.getModule('core/Core');
  var PreferenceManager = app.getModule('core/PreferenceManager');

  var preferenceId = 'ruby';

  var rubyPreferences = {
    'ruby.gen': {
      text: 'Ruby Code Generation',
      type: 'Section',
    },
    'ruby.gen.useTab': {
      text: 'Use Tab',
      description: 'Use tab for indentation instead of spaces.',
      type: 'Check',
      default: false,
    },
    'ruby.gen.indentSpaces': {
      text: 'Indent Spaces',
      description: 'Number of spaces for indentation.',
      type: 'Number',
      default: 2,
    },
    'ruby.gen.initializeMethod': {
      text: 'The initialize method',
      description: 'Generate initialize method that works almost same way as constructor.',
      type: 'Check',
      default: true,
    },
    'ruby.gen.useAttributeAccessor': {
      text: 'Attribute accessor',
      description: 'Use attribute accessor rather than set and get attribute methods.',
      type: 'Check',
      default: false,
    },
    'ruby.gen.toStringMethod': {
      text: 'The to_s method',
      description: 'Generate to_s method that returns a string representation of the object.',
      type: 'Check',
      default: true,
    },
    'ruby.gen.documentation': {
      text: 'Documentation',
      description: 'Generate documentation of class elements.',
      type: 'Check',
      default: true,
    },
  };

  function getId() {
    return preferenceId;
  }

  function getGenerateOptions() {
    return {
      useTab: PreferenceManager.get('ruby.gen.useTab'),
      indentSpaces: PreferenceManager.get('ruby.gen.indentSpaces'),
      initializeMethod: PreferenceManager.get('ruby.gen.initializeMethod'),
      useAttributeAccessor: PreferenceManager.get('ruby.gen.useAttributeAccessor'),
      rubyToStringMethod: PreferenceManager.get('ruby.gen.toStringMethod'),
      documentation: PreferenceManager.get('ruby.gen.documentation'),
    };
  }

  AppInit.htmlReady(function () {
    PreferenceManager.register(preferenceId, 'Ruby', rubyPreferences);
  });

  exports.getId = getId;
  exports.getGenerateOptions = getGenerateOptions;
});
<|endoftext|>


<commit_before>function (user, context, callback) {
  if ((context.connection === 'github') && (!user.two_factor_authentication)) {
    console.log('GitHub user not allowed to log in because 2FA was disabled on the account: '+user.user_id);
    context.redirect = {
     url: "https://sso.mozilla.com/forbidden?reason=githubmfa"
    };
    return callback(null, null, context);
  } else {
    return callback(null, user, context);
  }
}
<commit_msg>Better message with link for the user<commit_after>function (user, context, callback) {
  if ((context.connection === 'github') && (!user.two_factor_authentication)) {
    console.log('GitHub user not allowed to log in because 2FA was disabled on the account: '+user.user_id);
    var reason = 'You must setup a security device ("MFA", "2FA") for your GitHub account in order to access ' +
      'this service. Please follow the ' +
      ' ' +
      'GitHub documentation to setup the device and try logging in again.';

    context.redirect = {
     url: "https://sso.mozilla.com/forbidden?reason="+encodeURIComponent(reason)
    };
    return callback(null, null, context);
  } else {
    return callback(null, user, context);
  }
}
<|endoftext|>


<commit_before>

function setupPOC(form, selectEleId) {
	var selectEle = document.getElementById(selectEleId);
	var otext = selectEle.options[selectEle.options.selectedIndex].text;
	if(otext == "[Other]") {
		form.action = "submitNanoparticleSample.do?dispatch=setupPointOfContact&page=0&location=local";
		form.submit();
	}
	return false;
}

function setupOrgDetailView(form, selectEleId) {
	var selectEle = document.getElementById(selectEleId);
	var org = selectEle.options[selectEle.options.selectedIndex].text;
	if(org != "[Other]") {
		form.action = "submitPointOfContact.do?dispatch=detailView&page=0&location=local" +
			"&organizationName=" + org;
		form.submit();
	}
	return false;
}

function setPOCDetailLink(selectEleId, linkId) {
	var selectEle = document.getElementById(selectEleId);
	var linkEle = document.getElementById(linkId);
	var org = selectEle.options[selectEle.options.selectedIndex].text;
	if(org != "[Other]" && org != "") {
		linkEle.style.display = "inline";
	} else {
		linkEle.style.display = "none";
	}
}

function setSecondaryPOC(form, selectEleId, pocIndex) {
	var selectEle = document.getElementById(selectEleId);
	var pocId = selectEle.options[selectEle.options.selectedIndex].value;
	if(pocId != "other" && pocId != "") {
		form.action = "submitPointOfContact.do?dispatch=getPointOfContact&pocIndex=" + pocIndex + "&pocId=" + pocId;
		form.submit();
	}
}
/*
function setSecondaryPOC(selectEleId, pocIndex) {
	var selectEle = document.getElementById(selectEleId);
	var pocId = selectEle.options[selectEle.options.selectedIndex].value;
	CommonManager.getPointOfContact(pocIndex + "_" + pocId, function (data) {
			dwr.util.removeAllOptions("nanoparticleEntityTypes");
			dwr.util.addOptions("nanoparticleEntityTypes", data);
		});
}

function setSecondaryPOC(selectEleId, pocIndex) {
	var selectEle = document.getElementById(selectEleId);
	var pocId = selectEle.options[selectEle.options.selectedIndex].value;
    var request;

	var url = "/caNanoLab/submitPointOfContact.do?dispatch=getPointOfContact&pocIndex=" + pocIndex + "&pocId=" + pocId;

    // Perform the AJAX request using a non-IE browser.
	if (window.XMLHttpRequest) {
		request = new XMLHttpRequest();

      // Register callback function that will be called when
      // the response is generated from the server.
		//request.onreadystatechange = function(){ updateCount(request, countType); };
		try {
			request.open("GET", url, true);
		}
		catch (e) {
			alert("Unable to connect to server to retrieve counts.");
		}
		request.send(null);
    // Perform the AJAX request using an IE browser.
	} else {
		if (window.ActiveXObject) {
			request = new ActiveXObject("Microsoft.XMLHTTP");
			if (request) {
				//request.onreadystatechange = function(){ updateCount(request, countType); };
				request.open("GET", url, true);
				request.send();
			}
		}
	}
}

*/
<commit_msg>add particleId to detail view URL<commit_after>

function setupPOC(form, selectEleId) {
	var selectEle = document.getElementById(selectEleId);
	var otext = selectEle.options[selectEle.options.selectedIndex].text;
	if(otext == "[Other]") {
		form.action = "submitNanoparticleSample.do?dispatch=setupPointOfContact&page=0&location=local";
		form.submit();
	}
	return false;
}

function setupOrgDetailView(form, selectEleId, particleIdEle) {
	var selectEle = document.getElementById(selectEleId);
	var particleId = document.getElementById(particleIdEle).value;
	var org = selectEle.options[selectEle.options.selectedIndex].text;
	if(org != "[Other]") {
		form.action = "submitPointOfContact.do?dispatch=detailView&page=0&location=local" +
			"&particleId="+particleId+"&organizationName=" + org;
		form.submit();
	}
	return false;
}

function setPOCDetailLink(selectEleId, linkId) {
	var selectEle = document.getElementById(selectEleId);
	var linkEle = document.getElementById(linkId);
	var org = selectEle.options[selectEle.options.selectedIndex].text;
	if(org != "[Other]" && org != "") {
		linkEle.style.display = "inline";
	} else {
		linkEle.style.display = "none";
	}
}

function setSecondaryPOC(form, selectEleId, pocIndex) {
	var selectEle = document.getElementById(selectEleId);
	var pocId = selectEle.options[selectEle.options.selectedIndex].value;
	if(pocId != "other" && pocId != "") {
		form.action = "submitPointOfContact.do?dispatch=getPointOfContact&pocIndex=" + pocIndex + "&pocId=" + pocId;
		form.submit();
	}
}
/*
function setSecondaryPOC(selectEleId, pocIndex) {
	var selectEle = document.getElementById(selectEleId);
	var pocId = selectEle.options[selectEle.options.selectedIndex].value;
	CommonManager.getPointOfContact(pocIndex + "_" + pocId, function (data) {
			dwr.util.removeAllOptions("nanoparticleEntityTypes");
			dwr.util.addOptions("nanoparticleEntityTypes", data);
		});
}

function setSecondaryPOC(selectEleId, pocIndex) {
	var selectEle = document.getElementById(selectEleId);
	var pocId = selectEle.options[selectEle.options.selectedIndex].value;
    var request;

	var url = "/caNanoLab/submitPointOfContact.do?dispatch=getPointOfContact&pocIndex=" + pocIndex + "&pocId=" + pocId;

    // Perform the AJAX request using a non-IE browser.
	if (window.XMLHttpRequest) {
		request = new XMLHttpRequest();

      // Register callback function that will be called when
      // the response is generated from the server.
		//request.onreadystatechange = function(){ updateCount(request, countType); };
		try {
			request.open("GET", url, true);
		}
		catch (e) {
			alert("Unable to connect to server to retrieve counts.");
		}
		request.send(null);
    // Perform the AJAX request using an IE browser.
	} else {
		if (window.ActiveXObject) {
			request = new ActiveXObject("Microsoft.XMLHTTP");
			if (request) {
				//request.onreadystatechange = function(){ updateCount(request, countType); };
				request.open("GET", url, true);
				request.send();
			}
		}
	}
}

*/
<|endoftext|>