<commit_before>define(
	[
		'jsorrery/NameSpace',
		'jquery',
		'jsorrery/data/Constellations',
		'jsorrery/graphics3d/loaders/ResourceLoader',
		'_'
	],
	function(ns, $, Constellations, ResourceLoader){
		'use strict';

		var rendered;

		var pxRatio = (window.devicePixelRatio || 1);

		//keys of the loaded array
		var NAME = 0;
		var X = 1;
		var Y = 2;
		var Z = 3;
		var MAG = 4;
		var SPECT = 5;

		var MIN_MAG = -1.44;

		var spectralColors = [
			0xfbf8ff,
			0xc8d5ff,
			0xd8e2ff,
			0xe6ecfc,
			0xfbf8ff,
			0xfff4e8,
			0xffeeda,
			0xfeead3,
			0xfccecb,
			0xebd3da,
			0xe7dbf3
		];

		var namedStars = {};

		var starTexture;

		var lightenDarkenColor = function (hex, amount) {
			var col = [hex >> 16, (hex >> 8) & 0x00FF,  hex & 0x0000FF];
			col = _.map(col, function(part, i){
				part *= amount;
				return part < 0 ? 0 : (part > 255 ? 255 : part);
			});
			return (col[0] | (col[1] << 8) | (col[2] << 16));
		};

		var drawConstellations = function(){

			var material = new THREE.LineBasicMaterial({
		        color: pxRatio === 1 ? 0x111111 : 0x222222
		    });

			$.each(Constellations, function(fromName, toArr){
				var fromPoint = namedStars[fromName];

				$.each(toArr, function(i, toName){
					var toPoint = namedStars[toName];
					if(!toPoint || !fromPoint) return;

					var orbitGeom = new THREE.Geometry();
				    orbitGeom.vertices = [fromPoint, toPoint];
				    var line = new THREE.Line(orbitGeom, material);
				    rendered.add(line);
				});
			});
		};

		var getShaderAttr = function(){

			return {
				uniforms : {
					color:     { type: "c", value: new THREE.Color( 0xffffff ) },
					starTexture:   { type: "t", value: starTexture },
				},

				attributes : {
					size: 			{ type: 'f', value: [] },
					customColor: 	{ type: 'c', value: [] },
				}
			};
		};

		var generateStars = function(shaders, stars, size) {

			var shaderAttr = getShaderAttr();
			var container = new THREE.Object3D();

			var pGeo = new THREE.Geometry();
			var count = stars.length;

			var star;
			var starVect;
			var mag;
			var name;
			var spectralType;
			var starColor;

			for( var i=0; i<count; i++ ){
				star = stars[i];

				starVect = new THREE.Vector3(star[X], star[Y], star[Z]);
				if(starVect.x === 0) continue;//dont add the sun
				starVect.normalize().multiplyScalar(size);

				mag = starVect.mag = (star[MAG] - MIN_MAG) + 1;
				name = star[NAME];
				spectralType = String(star[SPECT]).toUpperCase();
				starColor  = spectralColors[spectralType] || spectralColors.F;

				if(name) namedStars[name] = starVect;

				if(starVect.mag < 7) {
					//starVect.size = 2 + Math.pow((2 / starVect.mag), 1.2);
					starColor = lightenDarkenColor(starColor, Math.pow(1/starVect.mag, 0.5));
				} else {
					//starVect.size = 2;
					starColor = lightenDarkenColor(starColor, Math.pow(1/starVect.mag, 1.1));
				}
				/**/
				starVect.size = 2 * pxRatio;//Math.floor(10 * (2 + (1 / mag))) / 10;
				//starColor = lightenDarkenColor(starColor, Math.pow(1.5/mag, 1.1));

				pGeo.vertices.push( starVect );
				pGeo.colors.push( new THREE.Color(starColor) );
			}

			var shaderMaterial = new THREE.ShaderMaterial( {
				uniforms: 		shaderAttr.uniforms,
				attributes:     shaderAttr.attributes,
				vertexShader:   shaders.vertex,
				fragmentShader: shaders.fragment,
				blending: 		THREE.AdditiveBlending,
				transparent:	true,
			});

			var particleSystem = new THREE.ParticleSystem( pGeo, shaderMaterial );

			//	set the values to the shader
			var values_size = shaderAttr.attributes.size.value;
			var values_color = shaderAttr.attributes.customColor.value;

			for( var v = 0; v < pGeo.vertices.length; v++ ) {
				values_size[ v ] = pGeo.vertices[v].size;
				values_color[ v ] = pGeo.colors[v];
			}

			rendered.add( particleSystem );
			//rendered.add( container );
			drawConstellations();
		};

		var MilkyWay = {
			dataSrc : 'js/orbit/data/milkyway.json',
			//dataSrc : 'js/orbit/data/milkyway_heasarc_468k.json',
			init : function(size){

				// create the particle system
				rendered = this.displayObj = new THREE.Object3D();
				//var particleSystem = new THREE.ParticleSystem(particles, pMaterial);
				rendered.rotation.x = -((23+(26/60)+(21/3600)) * ns.DEG_TO_RAD);

				var onDataLoaded = ResourceLoader.loadJSON(this.dataSrc);
				var onShaderLoaded = ResourceLoader.loadShaders('stars');

				starTexture = ResourceLoader.loadTexture( "img/star.png" );

				var onReady = $.Deferred();
				$.when(onShaderLoaded, onDataLoaded).then(function(shaderResponse, dataResponse){
					generateStars(shaderResponse, dataResponse[0], size);
					onReady.resolve();
				});

				return onReady.promise();

			},

			getDisplayObject : function(){
				return this.displayObj;
			},

			setPosition : function(pos){
				this.displayObj && this.displayObj.position.copy(pos);
			}
		};

		return MilkyWay;
	}
);<commit_msg>Fixed error in stars data path<commit_after>define(
	[
		'jsorrery/NameSpace',
		'jquery',
		'jsorrery/data/Constellations',
		'jsorrery/graphics3d/loaders/ResourceLoader',
		'_'
	],
	function(ns, $, Constellations, ResourceLoader){
		'use strict';

		var rendered;

		var pxRatio = (window.devicePixelRatio || 1);

		//keys of the loaded array
		var NAME = 0;
		var X = 1;
		var Y = 2;
		var Z = 3;
		var MAG = 4;
		var SPECT = 5;

		var MIN_MAG = -1.44;

		var spectralColors = [
			0xfbf8ff,
			0xc8d5ff,
			0xd8e2ff,
			0xe6ecfc,
			0xfbf8ff,
			0xfff4e8,
			0xffeeda,
			0xfeead3,
			0xfccecb,
			0xebd3da,
			0xe7dbf3
		];

		var namedStars = {};

		var starTexture;

		var lightenDarkenColor = function (hex, amount) {
			var col = [hex >> 16, (hex >> 8) & 0x00FF,  hex & 0x0000FF];
			col = _.map(col, function(part, i){
				part *= amount;
				return part < 0 ? 0 : (part > 255 ? 255 : part);
			});
			return (col[0] | (col[1] << 8) | (col[2] << 16));
		};

		var drawConstellations = function(){

			var material = new THREE.LineBasicMaterial({
		        color: pxRatio === 1 ? 0x111111 : 0x222222
		    });

			$.each(Constellations, function(fromName, toArr){
				var fromPoint = namedStars[fromName];

				$.each(toArr, function(i, toName){
					var toPoint = namedStars[toName];
					if(!toPoint || !fromPoint) return;

					var orbitGeom = new THREE.Geometry();
				    orbitGeom.vertices = [fromPoint, toPoint];
				    var line = new THREE.Line(orbitGeom, material);
				    rendered.add(line);
				});
			});
		};

		var getShaderAttr = function(){

			return {
				uniforms : {
					color:     { type: "c", value: new THREE.Color( 0xffffff ) },
					starTexture:   { type: "t", value: starTexture },
				},

				attributes : {
					size: 			{ type: 'f', value: [] },
					customColor: 	{ type: 'c', value: [] },
				}
			};
		};

		var generateStars = function(shaders, stars, size) {

			var shaderAttr = getShaderAttr();
			var container = new THREE.Object3D();

			var pGeo = new THREE.Geometry();
			var count = stars.length;

			var star;
			var starVect;
			var mag;
			var name;
			var spectralType;
			var starColor;

			for( var i=0; i<count; i++ ){
				star = stars[i];

				starVect = new THREE.Vector3(star[X], star[Y], star[Z]);
				if(starVect.x === 0) continue;//dont add the sun
				starVect.normalize().multiplyScalar(size);

				mag = starVect.mag = (star[MAG] - MIN_MAG) + 1;
				name = star[NAME];
				spectralType = String(star[SPECT]).toUpperCase();
				starColor  = spectralColors[spectralType] || spectralColors.F;

				if(name) namedStars[name] = starVect;

				if(starVect.mag < 7) {
					//starVect.size = 2 + Math.pow((2 / starVect.mag), 1.2);
					starColor = lightenDarkenColor(starColor, Math.pow(1/starVect.mag, 0.5));
				} else {
					//starVect.size = 2;
					starColor = lightenDarkenColor(starColor, Math.pow(1/starVect.mag, 1.1));
				}
				/**/
				starVect.size = 2 * pxRatio;//Math.floor(10 * (2 + (1 / mag))) / 10;
				//starColor = lightenDarkenColor(starColor, Math.pow(1.5/mag, 1.1));

				pGeo.vertices.push( starVect );
				pGeo.colors.push( new THREE.Color(starColor) );
			}

			var shaderMaterial = new THREE.ShaderMaterial( {
				uniforms: 		shaderAttr.uniforms,
				attributes:     shaderAttr.attributes,
				vertexShader:   shaders.vertex,
				fragmentShader: shaders.fragment,
				blending: 		THREE.AdditiveBlending,
				transparent:	true,
			});

			var particleSystem = new THREE.ParticleSystem( pGeo, shaderMaterial );

			//	set the values to the shader
			var values_size = shaderAttr.attributes.size.value;
			var values_color = shaderAttr.attributes.customColor.value;

			for( var v = 0; v < pGeo.vertices.length; v++ ) {
				values_size[ v ] = pGeo.vertices[v].size;
				values_color[ v ] = pGeo.colors[v];
			}

			rendered.add( particleSystem );
			//rendered.add( container );
			drawConstellations();
		};

		var MilkyWay = {
			dataSrc : 'js/jsorrery/data/milkyway.json',
			//dataSrc : 'js/jsorrery/data/milkyway_heasarc_468k.json',
			init : function(size){

				// create the particle system
				rendered = this.displayObj = new THREE.Object3D();
				//var particleSystem = new THREE.ParticleSystem(particles, pMaterial);
				rendered.rotation.x = -((23+(26/60)+(21/3600)) * ns.DEG_TO_RAD);

				var onDataLoaded = ResourceLoader.loadJSON(this.dataSrc);
				var onShaderLoaded = ResourceLoader.loadShaders('stars');

				starTexture = ResourceLoader.loadTexture( "img/star.png" );

				var onReady = $.Deferred();
				$.when(onShaderLoaded, onDataLoaded).then(function(shaderResponse, dataResponse){
					generateStars(shaderResponse, dataResponse[0], size);
					onReady.resolve();
				});

				return onReady.promise();

			},

			getDisplayObject : function(){
				return this.displayObj;
			},

			setPosition : function(pos){
				this.displayObj && this.displayObj.position.copy(pos);
			}
		};

		return MilkyWay;
	}
);<|endoftext|>


<commit_before>var x11 = require('../lib/x11');
var Exposure = x11.eventMask.Exposure;
var PointerMotion = x11.eventMask.PointerMotion;

var EventEmitter = require('events').EventEmitter;
var util = require('util'); // util.inherits

function GraphicContext(win)
{
    this.win = win;
    this.xclient = win.xclient;
    this.id = this.xclient.AllocID();
    win.xclient.CreateGC(this.id, win.id);
}

GraphicContext.prototype.polyLine = function(points)
{
    this.xclient.PolyLine(0, this.win.id, this.id, points);
}

GraphicContext.prototype.noop = function()
{
    //testing triggering gc creation
}

GraphicContext.prototype.drawText = function(x, y, text)
{
    //console.log([0, this.win.id, this.id, x, y, [text]]);
    this.xclient.PolyText8(this.win.id, this.id, x, y, [text]);
}

function Window(parent, x, y, w, h)
{
    if (parent.constructor && parent.constructor.name == 'XClient')
    {
        this.xclient = parent;
        if (!this.xclient.rootWindow)
        {
            // quick hack
            var rootWnd = {
                id: this.xclient.display.screen[0].root,
                xclient: this.xclient
            };
            rootWnd.parent = null;
            this.parent = this.xclient.rootWnd;
            this.xclient.rootWindow = rootWnd;
        }
        this.parent = this.xclient.rootWindow;
    } else {
        this.parent = parent;
        this.xclient = parent.xclient;
    }

    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.black = this.xclient.display.screen[0].black_pixel;
    this.white = this.xclient.display.screen[0].white_pixel;
    this.id = this.xclient.AllocID();

    var borderWidth = 1;
    var _class = 1; // InputOutput
    var visual = 0; // CopyFromParent
    this.xclient.CreateWindow(
        this.id, this.parent.id, this.x, this.y, this.w, this.h,
        borderWidth, _class, visual,
        {
            backgroundPixel: this.white,
            eventMask: Exposure|PointerMotion
        }
    );

    //this.map();
    var wnd = this;
    eventType2eventName = {
        6: 'mousemove',
       12: 'expose'
    };

    var ee = new EventEmitter();
    this.xclient.event_consumers[wnd.id] = ee;
    // TODO: do we need to have wnd as EventEmitter AND EventEmitter stored in event_consumers ?
    ee.on('event', function( ev )
    {
        if (ev.type == 12) //Expose
            ev.gc = wnd.gc;

        wnd.emit(eventType2eventName[ev.type], ev); // convert to mousemove? (ev is already event-spacific)
    });
    // TODO: track delete events and remove wmd from consumers list

    this.__defineSetter__('title', function(title) {
        this._title = title;
        this.xclient.ChangeProperty(0, this.id, this.xclient.atoms.WM_NAME, this.xclient.atoms.STRING, 8, title);
    });

    this.__defineGetter__('title', function() {
        return this._title;
    });

    this.__defineGetter__('gc', function()
    {
       if (!this._gc)
       {
           this._gc = new GraphicContext(this);
       }
       return this._gc;
    });
}
util.inherits(Window, EventEmitter);

Window.prototype.map = function() {
    this.xclient.MapWindow(this.id);
}

Window.prototype.unmap = function() {
    this.xclient.UnmapWindow(this.id);
}

module.exports = Window;<commit_msg>drawing requests wrappers, set/get title, 'handle' helper<commit_after>var x11 = require('../lib/x11');
var Exposure = x11.eventMask.Exposure;
var PointerMotion = x11.eventMask.PointerMotion;

var EventEmitter = require('events').EventEmitter;
var util = require('util'); // util.inherits

function GraphicContext(win)
{
    this.win = win;
    this.xclient = win.xclient;
    this.id = this.xclient.AllocID();
    win.xclient.CreateGC(this.id, win.id);
}

GraphicContext.prototype.polyLine = function(points)
{
    this.xclient.PolyLine(0, this.win.id, this.id, points);
}

GraphicContext.prototype.noop = function()
{
    //testing triggering gc creation
}

GraphicContext.prototype.rectangles = function(x, y, xyWHpoints)
{
    this.xclient.PolyFillRectangle(this.win.id, this.id, xyWHpoints);
}

GraphicContext.prototype.text = function(x, y, text)
{
    this.xclient.PolyText8(this.win.id, this.id, x, y, [text]);
}

GraphicContext.prototype.polyLine = function(points, opts)
{
    var coordinateMode = 0;
    if (opts && opts.coordinateMode === 'previous')
        coordinateMode = 1;
    this.xclient.PolyLine(coordinateMode, this.win.id, this.id, points);
}

GraphicContext.prototype.points = function(points, opts)
{
    var coordinateMode = 0;
    if (opts && opts.coordinateMode === 'previous')
        coordinateMode = 1;
    this.xclient.PolyPoint(coordinateMode, this.win.id, this.id, points);
}

function Window(parent, x, y, w, h)
{
    if (parent.constructor && parent.constructor.name == 'XClient')
    {
        this.xclient = parent;
        if (!this.xclient.rootWindow)
        {
            // quick hack
            var rootWnd = {
                id: this.xclient.display.screen[0].root,
                xclient: this.xclient
            };
            rootWnd.parent = null;
            this.parent = this.xclient.rootWnd;
            this.xclient.rootWindow = rootWnd;
        }
        this.parent = this.xclient.rootWindow;
    } else {
        this.parent = parent;
        this.xclient = parent.xclient;
    }

    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.black = this.xclient.display.screen[0].black_pixel;
    this.white = this.xclient.display.screen[0].white_pixel;
    this.id = this.xclient.AllocID();

    var borderWidth = 1;
    var _class = 1; // InputOutput
    var visual = 0; // CopyFromParent
    this.xclient.CreateWindow(
        this.id, this.parent.id, this.x, this.y, this.w, this.h,
        borderWidth, _class, visual,
        {
            backgroundPixel: this.white,
            eventMask: Exposure|PointerMotion
        }
    );

    //this.map();
    var wnd = this;
    eventType2eventName = {
        6: 'mousemove',
       12: 'expose'
    };

    var ee = new EventEmitter();
    this.xclient.event_consumers[wnd.id] = ee;
    // TODO: do we need to have wnd as EventEmitter AND EventEmitter stored in event_consumers ?
    ee.on('event', function( ev )
    {
        if (ev.type == 12) //Expose
            ev.gc = wnd.gc;

        wnd.emit(eventType2eventName[ev.type], ev); // convert to mousemove? (ev is already event-spacific)
    });
    // TODO: track delete events and remove wmd from consumers list

    this.__defineSetter__('title', function(title) {
        this._title = title;
        this.xclient.ChangeProperty(0, this.id, this.xclient.atoms.WM_NAME, this.xclient.atoms.STRING, 8, title);
    });

    this.__defineGetter__('title', function() {
        return this._title;
    });

    this.__defineGetter__('gc', function()
    {
       if (!this._gc)
       {
           this._gc = new GraphicContext(this);
       }
       return this._gc;
    });
}
util.inherits(Window, EventEmitter);

Window.prototype.map = function() {
    this.xclient.MapWindow(this.id);
}

Window.prototype.unmap = function() {
    this.xclient.UnmapWindow(this.id);
}

Window.prototype.handle = function(handlers) {
    for (var eventName in handlers) {
        this.on(eventName, handlers[eventName]);
    }
}

module.exports = Window;<|endoftext|>


<commit_before>// View model for the page
function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.app  = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("WorksheetNameRapport");}, gvm);
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("HomeRapportTitle");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName");}, gvm);
    gvm.homeManual = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("WorksheetRapportManual");}, gvm);

    gvm.availableCourses = ko.observableArray([]);

    gvm.selectCourse = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SelectCourse");}, gvm);
    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);
    gvm.tabledata = ko.observableArray([]);

     // Table i18n bindings
    gvm.werkficheID = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("werkficheID");}, gvm);
    gvm.werkficheName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("werkficheName");}, gvm);
    gvm.werkficheAction = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("werkficheAction");}, gvm);

    gvm.currentCourseId = null;

    gvm.updateCourseRapport = function() {
        $.getJSON('/api/coursefromteacher' + gvm.userId, function(data) {
            gvm.availableCourses.removeAll();
            $.each(data, function(i, item) {
                //  Put item in list
                gvm.availableCourses.push(item);

                // Add listener to listitem
                $("#coursebtn-" + item.id).click(function(){
                    gvm.currentCourseId = item.id;
                    $(".btn-courseRapport span:first").text($(this).text());
                    loadTablePage(1);
                });
            });
        });
    };

    gvm.addTableData = function(id, name) {
        // Push data
        var tblOject = {tid: id, tname: name};
        gvm.tabledata.push(tblOject);

        $('#removebtn-' + id).bind('click', function(event, data){
            deleteTableItem(id, tblOject);
            event.stopPropagation();
        });

        $('#editbtn-' + id).bind('click', function(event, data){
            showEditWorksheetModal(id, name);
            event.stopPropagation();
        });

        $('#copybtn-' + id).bind('click', function(event, data){
            copyTableItem(id, tblOject);
            event.stopPropagation();
        });
    }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }
}

function addNewWorksheet(serialData, courseid, callback) {
    $.ajax({
        url: "/api/addworksheet/" + courseid,
        type: "POST",
        data: serialData,
        success: function(data) {
            callback(true);
            window.location = "/api/worksheet/" + data['id'] + "/" + data['name'] + '/' + courseid;
        },
        error: function(data) {
            callback(false);
        }
    });
}

function updateWorksheet(id, serialData, callback) {
    $.ajax({
        url: "/api/updateworksheet/" + id,
        type: "PUT",
        data: serialData,
        success: function(data) {
            loadTablePage(1);
            callback(true);
        },
        error: function(data) {
            callback(false);
        }
    });
}

function copyTableItem(id, tblObject) {
    /*showYesNoModal("Bent u zeker dat u dit item wil kopiëren? ", function(val){
        if(val){
            $.ajax({
                url: "/api/coursecopy/" + id,
                type: "post"

            });
        }
    });*/
}

function deleteTableItem(id, tblOject) {
    showYesNoModal("Bent u zeker dat u dit item wil verwijderen? \r\n Let op: verwijderde items blijven in het systeem en kunnen weer actief gezet worden door een administrator. \r\n Gelieve de administrator te contacteren om een vak definitief te verwijderen.", function(val){
        if(val){
            $.ajax({
                url: "/api/deleteworksheet/" + id,
                type: "DELETE",
                success: function() {
                    viewModel.tabledata.remove(tblOject);
                }
            });
        }
    });
}

function showNewWorksheetModal() {
    resetGeneralModal();
    setGeneralModalTitle(i18n.__("AddNewWorksheet"));
    setGeneralModalBody('<form id="newworksheetform"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('NameTableTitle') + '" " name="name"> \

 \
            </form>' );

    addGeneralModalButton(i18n.__("AddBtn"), function(){
       addNewWorksheet($('#newworksheetform').serialize(), viewModel.currentCourseId, function(result){
            hideModal();
        });
    });

    showGeneralModal();
}

function showEditWorksheetModal(id, name)
{
    resetGeneralModal();
    setGeneralModalTitle(i18n.__("EditWorksheet"));
    setGeneralModalBody('<form id="updateworksheetform"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('NameTableTitle') + '" " name="name" value="' + name + '"> \

 \
        </form>');
    $.getJSON()

    addGeneralModalButton(i18n.__("SaveBtn"), function(){
        updateWorksheet(id, $('#updateworksheetform').serialize(), function(result){
            hideModal();
        });
    });

    addGeneralModalButton(i18n.__("CancelBtn"), function(){
        hideModal();
    })

    showGeneralModal();
}

function loadTablePage(pagenr)
{
    $.getJSON('/api/worksheets/page/' + pagenr + '/' + viewModel.currentCourseId, function(data){

        /* Clear current table page */
        viewModel.clearTable();

        // Load table data
        $.each(data.data, function(i, item) {
            viewModel.addTableData(item.id, item.Name);
        });

        /* Let previous en next buttons work */
        if(data.prev == "none"){
            $('#pager-prev-btn').addClass('disabled');
        } else {
            $('#pager-prev-btn').removeClass('disabled');
            $('#pager-prev-btn a').click(function(){
                loadTablePage(data.prev);
            });
        }

        if(data.next == "none"){
            $('#pager-next-btn').addClass('disabled');
        } else {
            $('#pager-next-btn').removeClass('disabled');
            $('#pager-next-btn a').click(function(){
                loadTablePage(data.next);
            });
        }

        // Number of pager buttons
        var numItems = $('.pager-nr-btn').length;

        /* Calculate for the pager buttons */
        var lowPage = Math.floor(pagenr/numItems) + 1;

        $('.pager-nr-btn').each(function() {
            /* calculate current page number */
            var thispagenr = lowPage++;

            /* Add the page number */
            $(this).html('' + thispagenr + '');

            /* Add active class to current page */
            if(thispagenr == pagenr) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }

            /* Disable inactive classes and bind handlers to active classes */
            if(thispagenr > data.pagecount) {
                $(this).addClass('disabled');
            } else {
                /* Add click listener for button */
                $(this).click(function() {
                    loadTablePage(thispagenr);
                });
            }
        });
    });
}

function initPage() {
    $('#addWorksheetBtn').click(function() {
        showNewWorksheetModal();
    });

    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        viewModel.updateCourseRapport();
    });
}
<commit_msg>werkfiche tabel<commit_after>// View model for the page
function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.app  = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("WorksheetNameRapport");}, gvm);
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("HomeRapportTitle");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName");}, gvm);
    gvm.homeManual = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("WorksheetRapportManual");}, gvm);

    gvm.availableCourses = ko.observableArray([]);

    gvm.selectCourse = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SelectCourse");}, gvm);
    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);
    gvm.tabledata = ko.observableArray([]);

     // Table i18n bindings
    gvm.werkficheID = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("werkficheID");}, gvm);
    gvm.werkficheName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("werkficheName");}, gvm);
    gvm.werkficheAction = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("werkficheAction");}, gvm);

    gvm.currentCourseId = null;

    gvm.updateCourseRapport = function() {
        $.getJSON('api/coursefromteacher/' + gvm.userId, function(data) {
            gvm.availableCourses.removeAll();
            $.each(data, function(i, item) {
                //  Put item in list
                gvm.availableCourses.push(item);

                // Add listener to listitem
                $("#coursebtn-" + item.id).click(function(){
                    gvm.currentCourseId = item.id;
                    $(".btn-courseRapport span:first").text($(this).text());
                    loadTablePage(1);
                });
            });
        });
    };

    gvm.addTableData = function(id, name) {
        // Push data
        var tblOject = {tid: id, tname: name};
        gvm.tabledata.push(tblOject);

        $('#removebtn-' + id).bind('click', function(event, data){
            deleteTableItem(id, tblOject);
            event.stopPropagation();
        });

        $('#editbtn-' + id).bind('click', function(event, data){
            showEditWorksheetModal(id, name);
            event.stopPropagation();
        });

        $('#copybtn-' + id).bind('click', function(event, data){
            copyTableItem(id, tblOject);
            event.stopPropagation();
        });
    }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }
}

function addNewWorksheet(serialData, courseid, callback) {
    $.ajax({
        url: "/api/addworksheet/" + courseid,
        type: "POST",
        data: serialData,
        success: function(data) {
            callback(true);
            window.location = "/api/worksheet/" + data['id'] + "/" + data['name'] + '/' + courseid;
        },
        error: function(data) {
            callback(false);
        }
    });
}

function updateWorksheet(id, serialData, callback) {
    $.ajax({
        url: "/api/updateworksheet/" + id,
        type: "PUT",
        data: serialData,
        success: function(data) {
            loadTablePage(1);
            callback(true);
        },
        error: function(data) {
            callback(false);
        }
    });
}

function copyTableItem(id, tblObject) {
    /*showYesNoModal("Bent u zeker dat u dit item wil kopiëren? ", function(val){
        if(val){
            $.ajax({
                url: "/api/coursecopy/" + id,
                type: "post"

            });
        }
    });*/
}

function deleteTableItem(id, tblOject) {
    showYesNoModal("Bent u zeker dat u dit item wil verwijderen? \r\n Let op: verwijderde items blijven in het systeem en kunnen weer actief gezet worden door een administrator. \r\n Gelieve de administrator te contacteren om een vak definitief te verwijderen.", function(val){
        if(val){
            $.ajax({
                url: "/api/deleteworksheet/" + id,
                type: "DELETE",
                success: function() {
                    viewModel.tabledata.remove(tblOject);
                }
            });
        }
    });
}

function showNewWorksheetModal() {
    resetGeneralModal();
    setGeneralModalTitle(i18n.__("AddNewWorksheet"));
    setGeneralModalBody('<form id="newworksheetform"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('NameTableTitle') + '" " name="name"> \

 \
            </form>' );

    addGeneralModalButton(i18n.__("AddBtn"), function(){
       addNewWorksheet($('#newworksheetform').serialize(), viewModel.currentCourseId, function(result){
            hideModal();
        });
    });

    showGeneralModal();
}

function showEditWorksheetModal(id, name)
{
    resetGeneralModal();
    setGeneralModalTitle(i18n.__("EditWorksheet"));
    setGeneralModalBody('<form id="updateworksheetform"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('NameTableTitle') + '" " name="name" value="' + name + '"> \

 \
        </form>');
    $.getJSON()

    addGeneralModalButton(i18n.__("SaveBtn"), function(){
        updateWorksheet(id, $('#updateworksheetform').serialize(), function(result){
            hideModal();
        });
    });

    addGeneralModalButton(i18n.__("CancelBtn"), function(){
        hideModal();
    })

    showGeneralModal();
}

function loadTablePage(pagenr)
{
    $.getJSON('/api/worksheets/page/' + pagenr + '/' + viewModel.currentCourseId, function(data){

        /* Clear current table page */
        viewModel.clearTable();

        // Load table data
        $.each(data.data, function(i, item) {
            viewModel.addTableData(item.id, item.Name);
        });

        /* Let previous en next buttons work */
        if(data.prev == "none"){
            $('#pager-prev-btn').addClass('disabled');
        } else {
            $('#pager-prev-btn').removeClass('disabled');
            $('#pager-prev-btn a').click(function(){
                loadTablePage(data.prev);
            });
        }

        if(data.next == "none"){
            $('#pager-next-btn').addClass('disabled');
        } else {
            $('#pager-next-btn').removeClass('disabled');
            $('#pager-next-btn a').click(function(){
                loadTablePage(data.next);
            });
        }

        // Number of pager buttons
        var numItems = $('.pager-nr-btn').length;

        /* Calculate for the pager buttons */
        var lowPage = Math.floor(pagenr/numItems) + 1;

        $('.pager-nr-btn').each(function() {
            /* calculate current page number */
            var thispagenr = lowPage++;

            /* Add the page number */
            $(this).html('' + thispagenr + '');

            /* Add active class to current page */
            if(thispagenr == pagenr) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }

            /* Disable inactive classes and bind handlers to active classes */
            if(thispagenr > data.pagecount) {
                $(this).addClass('disabled');
            } else {
                /* Add click listener for button */
                $(this).click(function() {
                    loadTablePage(thispagenr);
                });
            }
        });
    });
}

function initPage() {
    $('#addWorksheetBtn').click(function() {
        showNewWorksheetModal();
    });

    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        viewModel.updateCourseRapport();
    });
}
<|endoftext|>


<commit_before>"use strict";

var couchbase = require('./lib/couchbase.js'),
  fs = require('fs'),
  util = require('util');
var assert = require('assert');

var config;
var configFilename = 'config.json';

if (fs.existsSync(configFilename)) {
  config = JSON.parse(fs.readFileSync(configFilename));
} else {
  config = {
    mock : process.env.CNMOCK ? process.env.CNMOCK : false,
    host : process.env.CNHOST ? process.env.CNHOST : "localhost:8091",
    bucket : process.env.CNBUCKET ? process.env.CNBUCKET : "default",
    operationTimeout : 20000,
    connectionTimeout : 20000
  };
}

if (config.mock) {
  couchbase = couchbase.Mock;
}
delete config.mock;

function Harness(callback) {
  this.client = this.newClient();
  this.errors = couchbase.errors;
  this.format = couchbase.format;
  this.keySerial = 0;
}

Harness.prototype.newClient = function(callback) {
  return new couchbase.Connection(config, callback);
};

Harness.prototype.genKey = function(prefix) {
  if (!prefix) {
    prefix = "generic";
  }

  var ret = "TEST-" +
    (process.env.CNTESTPREFIX ? process.env.CNTESTPREFIX : process.pid) +
    '-' + prefix + this.keySerial;
  this.keySerial++;
  return ret;
};

Harness.prototype.genMultiKeys = function(count, prefix) {
  var ret = {};
  for (var i = 0; i < count; i++) {
    var key = this.genKey(prefix);
    ret[key] = { value: "value_for_" + key };
  }
  return ret;
};

Harness.prototype.okCallback = function(target) {
  // Get the stack
  var stack = new Error().stack;

  return function(err, result) {
    if (err) {
      assert(!err, "Got unrecognized error: " + util.inspect(err));
    }
    assert(typeof result === "object", "Meta is missing");
    target(result);
  };
};

Harness.prototype.setGet = function(key, value, callback) {
  var o = this;
  o.client.set(key, value, o.okCallback(function(result) {
    o.client.get(key, o.okCallback(function(result) {
      callback(result.value);
    }));
  }));
};

module.exports = new Harness();
<commit_msg>Updated harness so you can command-line override file configs.<commit_after>"use strict";

var couchbase = require('./lib/couchbase.js'),
  fs = require('fs'),
  util = require('util');
var assert = require('assert');

var config;
var configFilename = 'config.json';

if (fs.existsSync(configFilename)) {
  config = JSON.parse(fs.readFileSync(configFilename));
} else {
  config = {
    mock : false,
    host : 'localhost:8091',
    queryhosts : 'localhost:8093',
    bucket : 'default',
    operationTimeout : 20000,
    connectionTimeout : 20000
  };
}

if (process.env.CNMOCK !== undefined) {
  config.mock = process.env.CNMOCK ? true : false;
}
if (process.env.CNHOST !== undefined) {
  config.host = process.env.CNHOST;
}
if (process.env.CNQHOSTS !== undefined) {
  config.queryhosts = process.env.CNQHOSTS;
}
if (process.env.CNBUCKET !== undefined) {
  config.bucket = process.env.CNBUCKET;
}

if (config.mock) {
  couchbase = couchbase.Mock;
}
var isMock = config.mock;
delete config.mock;

function Harness(callback) {
  this.client = this.newClient();
  this.errors = couchbase.errors;
  this.format = couchbase.format;
  this.keySerial = 0;
}

Harness.prototype.newClient = function(callback) {
  return new couchbase.Connection(config, callback);
};

Harness.prototype.genKey = function(prefix) {
  if (!prefix) {
    prefix = "generic";
  }

  var ret = "TEST-" +
    (process.env.CNTESTPREFIX ? process.env.CNTESTPREFIX : process.pid) +
    '-' + prefix + this.keySerial;
  this.keySerial++;
  return ret;
};

Harness.prototype.genMultiKeys = function(count, prefix) {
  var ret = {};
  for (var i = 0; i < count; i++) {
    var key = this.genKey(prefix);
    ret[key] = { value: "value_for_" + key };
  }
  return ret;
};

Harness.prototype.okCallback = function(target) {
  // Get the stack
  var stack = new Error().stack;

  return function(err, result) {
    if (err) {
      assert(!err, "Got unrecognized error: " + util.inspect(err));
    }
    assert(typeof result === "object", "Meta is missing");
    target(result);
  };
};

Harness.prototype.setGet = function(key, value, callback) {
  var o = this;
  o.client.set(key, value, o.okCallback(function(result) {
    o.client.get(key, o.okCallback(function(result) {
      callback(result.value);
    }));
  }));
};

// Skips the test if in no-mock mode.
Harness.prototype.nmIt = function(name, func) {
  if (!isMock) {
    it(name, func);
  } else {
    it.skip(name, func);
  }
};

module.exports = new Harness();
<|endoftext|>


<commit_before>import styles from '../styles.module.css'
import Image from 'next/image'
import Link from 'next/link'
import ViewSource from '../components/view-source'

const Code = (p) =>

const Index = () => (

    <ViewSource pathname="pages/index.js" />

Image Component with Next.js

        This page demonstrates the usage of the{' '}

          next/image
        {' '}
        component with live examples.

        This component is designed to{' '}

          automatically optimizate
        {' '}
        images on-demand as the browser requests them.

Layout

        The layout property tells the image to respond differently
        depending on the device size or the container size.

        Select a layout below and try resizing the window or rotating your
        device to see how the image reacts.

          <Link href="/layout-intrinsic">
            layout="intrinsic"
          </Link>

          <Link href="/layout-responsive">
            layout="responsive"
          </Link>

          <Link href="/layout-fixed">
            layout="fixed"
          </Link>

          <Link href="/layout-fill">
            layout="fill"
          </Link>

          <Link href="/background">
            background demo
          </Link>

Internal Image

        The following is an example of a reference to an interal image from the{' '}
        public directory.

        This image is intentionally large so you have to scroll down to the next
        image.

      <Image alt="Vercel logo" src="/vercel.png" width={1000} height={1000} />

External Image

        The following is an example of a reference to an external image at{' '}
        assets.vercel.com.

        External domains must be configured in next.config.js using
        the domains property.

      <Image
        alt="Next.js logo"
        src="https://assets.vercel.com/image/upload/v1538361091/repositories/next-js/next-js-bg.png"
        width={1200}
        height={400}
      />

Learn More

        You can optionally configure a cloud provider, device sizes, and more!

        Checkout the{' '}

          Image Optimization documentation
        {' '}
        to learn more.

)

export default Index
<commit_msg>[examples] Fix image-component typo (#23437)<commit_after>import styles from '../styles.module.css'
import Image from 'next/image'
import Link from 'next/link'
import ViewSource from '../components/view-source'

const Code = (p) =>

const Index = () => (

    <ViewSource pathname="pages/index.js" />

Image Component with Next.js

        This page demonstrates the usage of the{' '}

          next/image
        {' '}
        component with live examples.

        This component is designed to{' '}

          automatically optimize
        {' '}
        images on-demand as the browser requests them.

Layout

        The layout property tells the image to respond differently
        depending on the device size or the container size.

        Select a layout below and try resizing the window or rotating your
        device to see how the image reacts.

          <Link href="/layout-intrinsic">
            layout="intrinsic"
          </Link>

          <Link href="/layout-responsive">
            layout="responsive"
          </Link>

          <Link href="/layout-fixed">
            layout="fixed"
          </Link>

          <Link href="/layout-fill">
            layout="fill"
          </Link>

          <Link href="/background">
            background demo
          </Link>

Internal Image

        The following is an example of a reference to an interal image from the{' '}
        public directory.

        This image is intentionally large so you have to scroll down to the next
        image.

      <Image alt="Vercel logo" src="/vercel.png" width={1000} height={1000} />

External Image

        The following is an example of a reference to an external image at{' '}
        assets.vercel.com.

        External domains must be configured in next.config.js using
        the domains property.

      <Image
        alt="Next.js logo"
        src="https://assets.vercel.com/image/upload/v1538361091/repositories/next-js/next-js-bg.png"
        width={1200}
        height={400}
      />

Learn More

        You can optionally configure a cloud provider, device sizes, and more!

        Checkout the{' '}

          Image Optimization documentation
        {' '}
        to learn more.

)

export default Index
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp'),
	addsrc = require('gulp-add-src'),
	concat = require('gulp-concat'),
	cssnano = require('gulp-cssnano'),
	del = require('del'),
	filter = require('gulp-filter'),
	htmlmin = require('gulp-htmlmin'),
	imagemin = require('gulp-imagemin'),
	install = require('gulp-install'),
	mainBowerFiles = require('gulp-main-bower-files'),
	pngquant = require('imagemin-pngquant'),
	sourcemaps = require('gulp-sourcemaps'),
	uglify = require('gulp-uglify'),
	watch = require('gulp-watch');

gulp.task('default', ['build']);

gulp.task('build', ['clean', 'minHtml', 'minCss', 'minJs', 'minImages']);

gulp.task('install', function() {
	gulp.src(['./bower.json', './package.json'])
		.pipe(install());
});

gulp.task('clean', function(cb) {
	del.sync(['public/dist', 'public/src/css/vendor', 'public/src/js/vendor'], cb);
});

gulp.task('watch', ['build', 'registerWatchTasks']);

gulp.task('registerWatchTasks', function() {
	watch('./Gulpfile.js', function() {
		gulp.start('build');
	});

	watch('public/src/js/**/*.html', function() {
		gulp.start('minHtml');
	});

	watch('bower_components/**/*.css', function() {
		gulp.start('minVendorCss');
	});

	watch('public/src/css/**/*.css', function() {
		gulp.start('minAppCss');
	});

	watch('bower_components/**/*.js', function() {
		gulp.start('minVendorJs');
	});

	watch('public/src/js/**/*.js', function() {
		gulp.start('minAppJs');
	});

	watch('public/images/**/*.*', function() {
		gulp.start('minImages');
	});
});

gulp.task('minHtml', function() {
	return gulp.src('public/src/**/*.html')
		.pipe(htmlmin({collapseWhitespace: true}))
		.pipe(gulp.dest('public/dist'));
});

gulp.task('minCss', ['minVendorCss', 'minAppCss']);

gulp.task('minVendorCss', function() {
	var cssFilter = filter('**/*.css');

	return gulp.src('./bower.json')
		.pipe(mainBowerFiles())
		.pipe(cssFilter)
		.pipe(addsrc.append('bower_components/html5-boilerplate/dist/css/**/*.css'))
		.pipe(sourcemaps.init())
		.pipe(concat('vendor.css'))
		.pipe(cssnano())
		.pipe(sourcemaps.write('.'))
		.pipe(gulp.dest('public/dist/css'));
});

gulp.task('minAppCss', function() {
	return gulp.src('public/src/css/**/*.css')
		.pipe(sourcemaps.init())
		.pipe(cssnano())
		.pipe(concat('app.css'))
		.pipe(sourcemaps.write('.'))
		.pipe(gulp.dest('public/dist/css'));
});

gulp.task('minJs', ['minVendorJs', 'minAppJs']);

gulp.task('minVendorJs', function() {
	var jsFilter = filter('**/*.js');

	return gulp.src('./bower.json')
		.pipe(mainBowerFiles())
		.pipe(jsFilter)
		.pipe(sourcemaps.init())
		.pipe(concat('vendor.js'))
		.pipe(uglify())
		.pipe(sourcemaps.write('.'))
		.pipe(gulp.dest('public/dist/js'));
});

gulp.task('minAppJs', function() {
	return gulp.src('public/src/js/**/*.js')
		.pipe(sourcemaps.init())
		.pipe(concat('app.js'))
		//.pipe(uglify())
		.pipe(sourcemaps.write('.'))
		.pipe(gulp.dest('public/dist/js'));
});

gulp.task('minImages', function() {
	return gulp.src('public/src/images/*')
		.pipe(imagemin({
			// JPG
			progressive: true,
			// PNG
			optimizationLevel: 4,
			use: [pngquant()],
			// SVG
			multipass: true,
			svgoPlugins: [{ removeViewBox: false }]
		}))
		.pipe(gulp.dest('public/dist/images'));
});
<commit_msg>Forced the order of main.css and normalize.css<commit_after>'use strict';

var gulp = require('gulp'),
	addsrc = require('gulp-add-src'),
	concat = require('gulp-concat'),
	cssnano = require('gulp-cssnano'),
	del = require('del'),
	filter = require('gulp-filter'),
	htmlmin = require('gulp-htmlmin'),
	imagemin = require('gulp-imagemin'),
	install = require('gulp-install'),
	mainBowerFiles = require('gulp-main-bower-files'),
	pngquant = require('imagemin-pngquant'),
	sourcemaps = require('gulp-sourcemaps'),
	uglify = require('gulp-uglify'),
	watch = require('gulp-watch');

gulp.task('default', ['build']);

gulp.task('build', ['clean', 'minHtml', 'minCss', 'minJs', 'minImages']);

gulp.task('install', function() {
	gulp.src(['./bower.json', './package.json'])
		.pipe(install());
});

gulp.task('clean', function(cb) {
	del.sync(['public/dist', 'public/src/css/vendor', 'public/src/js/vendor'], cb);
});

gulp.task('watch', ['build', 'registerWatchTasks']);

gulp.task('registerWatchTasks', function() {
	watch('./Gulpfile.js', function() {
		gulp.start('build');
	});

	watch('public/src/js/**/*.html', function() {
		gulp.start('minHtml');
	});

	watch('bower_components/**/*.css', function() {
		gulp.start('minVendorCss');
	});

	watch('public/src/css/**/*.css', function() {
		gulp.start('minAppCss');
	});

	watch('bower_components/**/*.js', function() {
		gulp.start('minVendorJs');
	});

	watch('public/src/js/**/*.js', function() {
		gulp.start('minAppJs');
	});

	watch('public/images/**/*.*', function() {
		gulp.start('minImages');
	});
});

gulp.task('minHtml', function() {
	return gulp.src('public/src/**/*.html')
		.pipe(htmlmin({collapseWhitespace: true}))
		.pipe(gulp.dest('public/dist'));
});

gulp.task('minCss', ['minVendorCss', 'minAppCss']);

gulp.task('minVendorCss', function() {
	var cssFilter = filter('**/*.css');

	return gulp.src('./bower.json')
		.pipe(mainBowerFiles())
		.pipe(cssFilter)
		.pipe(addsrc.prepend('bower_components/html5-boilerplate/dist/css/main.css'))
		.pipe(addsrc.prepend('bower_components/html5-boilerplate/dist/css/normalize.css'))
		.pipe(sourcemaps.init())
		.pipe(concat('vendor.css'))
		.pipe(cssnano())
		.pipe(sourcemaps.write('.'))
		.pipe(gulp.dest('public/dist/css'));
});

gulp.task('minAppCss', function() {
	return gulp.src('public/src/css/**/*.css')
		.pipe(sourcemaps.init())
		.pipe(cssnano())
		.pipe(concat('app.css'))
		.pipe(sourcemaps.write('.'))
		.pipe(gulp.dest('public/dist/css'));
});

gulp.task('minJs', ['minVendorJs', 'minAppJs']);

gulp.task('minVendorJs', function() {
	var jsFilter = filter('**/*.js');

	return gulp.src('./bower.json')
		.pipe(mainBowerFiles())
		.pipe(jsFilter)
		.pipe(sourcemaps.init())
		.pipe(concat('vendor.js'))
		.pipe(uglify())
		.pipe(sourcemaps.write('.'))
		.pipe(gulp.dest('public/dist/js'));
});

gulp.task('minAppJs', function() {
	return gulp.src('public/src/js/**/*.js')
		.pipe(sourcemaps.init())
		.pipe(concat('app.js'))
		//.pipe(uglify())
		.pipe(sourcemaps.write('.'))
		.pipe(gulp.dest('public/dist/js'));
});

gulp.task('minImages', function() {
	return gulp.src('public/src/images/*')
		.pipe(imagemin({
			// JPG
			progressive: true,
			// PNG
			optimizationLevel: 4,
			use: [pngquant()],
			// SVG
			multipass: true,
			svgoPlugins: [{ removeViewBox: false }]
		}))
		.pipe(gulp.dest('public/dist/images'));
});
<|endoftext|>


<commit_before>// back to the main site link on navbar
$('#forumTitle').before('Back to the main site');
$('#forumTitle').attr('style', 'padding-top:10px;padding-bottom:20px;');

// themes
$('#ftr-content .menu').append('

');
$('#theme').append('Theme: <select id="theme-select" style="border-radius:5px;outline:none;"><option>Regular</option><option>Dark</option></select>');

// when theme selection is changed
$('#theme-select').on('change', function() {
	var newt = $(this).val();
	localStorage['os-theme'] = newt;
	window.location.reload();
});

// is theme defined / valid?
var themes = ['Regular', 'Dark'];
if(typeof localStorage['os-theme'] === 'undefined' || themes.indexOf(localStorage['os-theme']) === -1) {
	console.log('wrong theme');
	localStorage['os-theme'] = 'Regular';
}

// set selection to the saved theme
$('#theme-select').val(localStorage['os-theme']);

// set theme based on the theme selection
var theme = $('#theme-select').val();
$('head').append('');
$('head').append('<link href="/forums/themes/' + 'all' + '.css" rel="stylesheet" type="text/css">');
$('head').append('<link href="/forums/themes/' + theme.toLowerCase() + '.css" rel="stylesheet" type="text/css">');

// channel fixes
$('a[class|=channel').each(function() {
	var goto = $(this).attr('href');
	$(this).removeAttr('href');
	$(this).on('click', function() {
		location.href = goto;
	});
});
<commit_msg>Update custom.js<commit_after>// back to the main site link on navbar
$('#forumTitle').before('Back to the main site');
$('#forumTitle').attr('style', 'padding-top:10px;padding-bottom:20px;');

// themes
$('#ftr-content .menu').append('

');
$('#theme').append('Theme: <select id="theme-select" style="border-radius:5px;outline:none;"><option>Regular</option><option>Dark</option></select>');

// when theme selection is changed
$('#theme-select').on('change', function() {
	var newt = $(this).val();
	localStorage['os-theme'] = newt;
	window.location.reload();
});

// is theme defined / valid?
var themes = ['Regular', 'Dark'];
if(typeof localStorage['os-theme'] === 'undefined' || themes.indexOf(localStorage['os-theme']) === -1) {
	console.log('wrong theme');
	localStorage['os-theme'] = 'Regular';
}

// set selection to the saved theme
$('#theme-select').val(localStorage['os-theme']);

// set theme based on the theme selection
var theme = $('#theme-select').val();
$('head').append('');
$('head').append('<link href="/forums/themes/' + 'all' + '.css" rel="stylesheet" type="text/css">');
$('head').append('<link href="/forums/themes/' + theme.toLowerCase() + '.css" rel="stylesheet" type="text/css">');

// channel fixes
$('a[class|=channel').each(function() {
	var goto = $(this).attr('href');
	$(this).removeAttr('href');
	$(this).off('click');
	$(this).on('click', function() {
		location.href = goto;
	});
});
<|endoftext|>


<commit_before>var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var deploy      = require('gulp-gh-pages');
var runSequence = require('run-sequence');
var $ = require('gulp-load-plugins')({
      pattern: ['gulp-*', 'autoprefixer', 'concat', 'del', 'main-bower-files']
    });

///////////BABEL//////////////////
gulp.task('babel:dev', function () {
  return gulp
    .src('src/js/*.js')
    .pipe($.sourcemaps.init())
    .pipe($.babel())
    .pipe($.concat('all.js'))
    .pipe($.sourcemaps.write('.'))
    .pipe(gulp.dest('public/js'));
});

gulp.task('babel:prod', function () {
  return gulp
    .src('src/**/*.js')
    .pipe($.babel())
    .pipe($.concat('all.js'))
    .pipe(gulp.dest('public/js'))
});

//////////////BOWER///////////////
gulp.task('bower', function() {
  return gulp
    .src($.mainBowerFiles('**/*.js'))
    .pipe($.concat('build.js'))
    .pipe(gulp.dest('public/lib'))
})

/////////////CLEAN//////////////////
gulp.task('clean', function () {
   $.del('public')
})

///////////////COPY////////////////// trying to copy CNAME
// gulp.task('copy', function () {
//   gulp.src(['/src/CNAME'])
//   .pipe($.copy('./public/'))
// });

/////////////DEPLOY/////////////////
gulp.task('deploy', function () {
  return gulp.src("./public/**/*")
    .pipe(deploy())
});

///////////////JADE////////////////
gulp.task('jade:dev', function () {
  return gulp
    .src(['src/**/*.jade', '!src/**/_*.jade'])
    .pipe($.jade({
      pretty: true
    }))
    .pipe(gulp.dest('public'));
});

gulp.task('jade:prod', function () {
  return gulp
    .src(['src/**/*.jade', '!src/**/_*.jade'])
    .pipe($.jade())
    .pipe(gulp.dest('public'));
});

///////////////SASS///////////////////
gulp.task('sass:dev', function () {
  return gulp
    .src('src/_styles/main.scss')
    .pipe($.sourcemaps.init())
    .pipe($.sass().on('error', $.sass.logError))
    .pipe($.sourcemaps.write())
    .pipe($.autoprefixer('last 2 version'))
    .pipe(gulp.dest('public/css'))
    .pipe(browserSync.stream())
});

gulp.task('sass:prod', function () {
  return gulp
    .src('src/_styles/main.scss')
    .pipe($.sass({
        outputStyle: 'compressed'
      })
      .on('error', $.sass.logError)
    )
    .pipe($.autoprefixer('last 2 version'))
    .pipe(gulp.dest('public/css'))
    .pipe(browserSync.stream())
});

///////////////UGLIFY OR COMPRESS////////////////
gulp.task('compress', function() { //not working.
  return gulp.src('public/lib/*.js')
    .pipe($.uglify())
    .pipe(gulp.dest('public/lib'));
});

//trying the runsequence for dev
gulp.task('build:dev', ['clean'], function(callback) {
  runSequence([
        'jade:dev',
        'sass:dev',
        'babel:dev',
        'bower'
      ],
      [
        'serve'
      ],
        callback);
});

gulp.task('build', ['clean', 'jade:dev', 'sass:dev', 'babel:dev', 'bower'])

gulp.task('build:prod', ['clean'], function(callback) {
  runSequence([
        'jade:prod',
        'sass:prod',
        'babel:prod',
        'bower'
      ],
      [
        'compress'
      ],
      [
        'serve'
      ],
        callback);
});

//SERVER AND WATCH
gulp.task('serve', function () {
  browserSync.init({
      server: {
        baseDir: "public/"
      }
    });
  gulp.watch(['src/**/*.jade'], ['jade:dev'])
  gulp.watch(['src/**/*.scss'], ['sass:dev'])
  gulp.watch(['src/**/*.js'], ['babel:dev'])
  gulp.watch(['public/*.html', 'public/*.css', 'public/js/*.js']).on('change', browserSync.reload);
});

gulp.task('default', function() {});
<commit_msg>minor change to Gulpfile<commit_after>var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var deploy      = require('gulp-gh-pages');
var runSequence = require('run-sequence');
var $ = require('gulp-load-plugins')({
      pattern: ['gulp-*', 'autoprefixer', 'concat', 'del', 'main-bower-files']
    });

///////////BABEL//////////////////
gulp.task('babel:dev', function () {
  return gulp
    .src('src/js/*.js')
    .pipe($.sourcemaps.init())
    .pipe($.babel())
    .pipe($.concat('all.js'))
    .pipe($.sourcemaps.write('.'))
    .pipe(gulp.dest('public/js'));
});

gulp.task('babel:prod', function () {
  return gulp
    .src('src/**/*.js')
    .pipe($.babel())
    .pipe($.concat('all.js'))
    .pipe(gulp.dest('public/js'))
});

//////////////BOWER///////////////
gulp.task('bower', function() {
  return gulp
    .src($.mainBowerFiles('**/*.js'))
    .pipe($.concat('build.js'))
    .pipe(gulp.dest('public/lib'))
})

/////////////CLEAN//////////////////
gulp.task('clean', function () {
   $.del('public')
})

///////////////COPY////////////////// trying to copy CNAME. May need to add up top
// gulp.task('copy', function () {
//   gulp.src(['/src/CNAME'])
//   .pipe(gulp.dest('./public/'))
// });

/////////////DEPLOY/////////////////
gulp.task('deploy', function () {
  return gulp.src("./public/**/*")
    .pipe(deploy())
});

///////////////JADE////////////////
gulp.task('jade:dev', function () {
  return gulp
    .src(['src/**/*.jade', '!src/**/_*.jade'])
    .pipe($.jade({
      pretty: true
    }))
    .pipe(gulp.dest('public'));
});

gulp.task('jade:prod', function () {
  return gulp
    .src(['src/**/*.jade', '!src/**/_*.jade'])
    .pipe($.jade())
    .pipe(gulp.dest('public'));
});

///////////////SASS///////////////////
gulp.task('sass:dev', function () {
  return gulp
    .src('src/_styles/main.scss')
    .pipe($.sourcemaps.init())
    .pipe($.sass().on('error', $.sass.logError))
    .pipe($.sourcemaps.write())
    .pipe($.autoprefixer('last 2 version'))
    .pipe(gulp.dest('public/css'))
    .pipe(browserSync.stream())
});

gulp.task('sass:prod', function () {
  return gulp
    .src('src/_styles/main.scss')
    .pipe($.sass({
        outputStyle: 'compressed'
      })
      .on('error', $.sass.logError)
    )
    .pipe($.autoprefixer('last 2 version'))
    .pipe(gulp.dest('public/css'))
    .pipe(browserSync.stream())
});

///////////////UGLIFY OR COMPRESS////////////////
gulp.task('compress', function() { //not working.
  return gulp.src('public/lib/*.js')
    .pipe($.uglify())
    .pipe(gulp.dest('public/lib'));
});

//trying the runsequence for dev
gulp.task('build:dev', ['clean'], function(callback) {
  runSequence([
        'jade:dev',
        'sass:dev',
        'babel:dev',
        'bower'
      ],
      [
        'serve'
      ],
        callback);
});

gulp.task('build', ['clean', 'jade:dev', 'sass:dev', 'babel:dev', 'bower'])

gulp.task('build:prod', ['clean'], function(callback) {
  runSequence([
        'jade:prod',
        'sass:prod',
        'babel:prod',
        'bower'
      ],
      [
        'compress'
      ],
      [
        'serve'
      ],
        callback);
});

//SERVER AND WATCH
gulp.task('serve', function () {
  browserSync.init({
      server: {
        baseDir: "public/"
      }
    });
  gulp.watch(['src/**/*.jade'], ['jade:dev'])
  gulp.watch(['src/**/*.scss'], ['sass:dev'])
  gulp.watch(['src/**/*.js'], ['babel:dev'])
  gulp.watch(['public/*.html', 'public/*.css', 'public/js/*.js']).on('change', browserSync.reload);
});

gulp.task('default', function() {});
<|endoftext|>


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

(function(tinymce) {
	tinymce.html.DomParser = function(settings, schema) {
		var self = this, nodeFilters = {}, attributeFilters = [];

		settings = settings || {};

		self.addNodeFilter = function(name, callback) {
			tinymce.each(tinymce.explode(name), function(name) {
				var list = nodeFilters[name];

				if (!list)
					nodeFilters[name] = list = [];

				list.push(callback);
			});
		};

		self.addAttributeFilter = function(name, callback) {
			tinymce.each(tinymce.explode(name), function(name) {
				var i;

				for (i = 0; i < attributeFilters.length; i++) {
					if (attributeFilters[i].name === name) {
						attributeFilters[i].callbacks.push(callback);
						return;
					}
				}

				attributeFilters.push({name: name, callbacks: [callback]});
			});
		};

		self.parse = function(html) {
			var parser, rootNode, node, Node = tinymce.html.Node, matchedNodes = {}, matchedAttributes = {},
				i, l, fi, fl, list, name, blockElements, startWhiteSpaceRegExp,
				endWhiteSpaceRegExp, allWhiteSpaceRegExp, whiteSpaceElements;

			blockElements = tinymce.extend({
				script: 1,
				style: 1
			}, schema.getBlockElements());

			whiteSpaceElements = schema.getWhiteSpaceElements();
			startWhiteSpaceRegExp = /^[ \t\r\n]+/;
			endWhiteSpaceRegExp = /[ \t\r\n]+$/;
			allWhiteSpaceRegExp = /[ \t\r\n]+/g;

			function createNode(name, type) {
				var node = new Node(name, type), list;

				if (name in nodeFilters) {
					list = matchedNodes[name];

					if (list)
						list.push(node);
					else
						matchedNodes[name] = [node];
				}

				return node;
			}

			parser = new tinymce.html.SaxParser(tinymce.extend({
				cdata: function(text) {
					node.append(createNode('#cdata', 4)).value = text;
				},

				text: function(text, raw) {
					var textNode;

					// Trim all redundant whitespace on non white space elements
					if (!whiteSpaceElements[node.name]) {
						text = text.replace(allWhiteSpaceRegExp, ' ');

						if (node.lastChild && blockElements[node.lastChild.name])
							text = text.replace(startWhiteSpaceRegExp, '');
					}

					// Do we need to create the node
					if (text.length !== 0) {
						textNode = createNode('#text', 3);
						textNode.raw = !!raw;
						node.append(textNode).value = text;
					}
				},

				comment: function(text) {
					node.append(createNode('#comment', 8)).value = text;
				},

				pi: function(text) {
					node.append(createNode('#pi', 7)).value = text;
				},

				doctype: function(text) {
					node.append(createNode('#doctype', 10)).value = text;
				},

				start: function(name, attrs, empty) {
					var newNode, attrFiltersLen, elementRule, textNode;

					elementRule = schema.getElementRule(name);
					if (elementRule) {
						newNode = createNode(elementRule.outputName || name, 1);
						newNode.attributes = attrs;
						newNode.empty = empty;

						node.append(newNode);

						attrFiltersLen = attributeFilters.length;
						while (attrFiltersLen--) {
							name = attributeFilters[attrFiltersLen].name;

							if (name in attrs.map) {
								list = matchedAttributes[name];

								if (list)
									list.push(newNode);
								else
									matchedAttributes[name] = [newNode];
							}
						}

						if (!empty)
							node = newNode;
						else {
							if (blockElements[name]) {
								// Trim start white space
								textNode = newNode.prev;
								if (textNode && textNode.type === 3)
									textNode.value = textNode.value.replace(endWhiteSpaceRegExp, '');
							}
						}
					}
				},

				end: function(name) {
					var textNode, elementRule;

					elementRule = schema.getElementRule(name);
					if (elementRule) {
						if (blockElements[name]) {
							if (!whiteSpaceElements[node.name]) {
								// Trim start white space
								textNode = node.firstChild;
								if (textNode && textNode.type === 3)
									textNode.value = textNode.value.replace(startWhiteSpaceRegExp, '');

								// Trim end white space
								textNode = node.lastChild;
								if (textNode && textNode.type === 3)
									textNode.value = textNode.value.replace(endWhiteSpaceRegExp, '');
							}

							// Trim start white space
							textNode = node.prev;
							if (textNode && textNode.type === 3)
								textNode.value = textNode.value.replace(startWhiteSpaceRegExp, '');
						}

						// Handle empty nodes
						if (elementRule.removeEmpty || elementRule.paddEmpty) {
							if (node.isEmpty(schema.getEmptyElements())) {
								if (elementRule.paddEmpty)
									node.clear().append(new tinymce.html.Node('#text', '3')).value = '\u00a0';
								else
									return node.remove();
							}
						}

						node = node.parent;
					}
				}
			}, settings), schema);

			rootNode = node = new Node('#frag', 11);

			parser.parse(html);

			// Run node filters
			for (name in matchedNodes) {
				list = nodeFilters[name];

				for (i = 0, l = list.length; i < l; i++) {
					list[i](matchedNodes[name], name);
				}
			}

			// Run attribute filters
			for (i = 0, l = attributeFilters.length; i < l; i++) {
				list = attributeFilters[i];

				if (list.name in matchedAttributes) {
					for (fi = 0, fl = list.callbacks.length; fi < fl; fi++) {
						list.callbacks[fi](matchedAttributes[list.name], list.name);
					}
				}
			}

			return rootNode;
		};
	}
})(tinymce);
<commit_msg>Fixed white space removal issue with the DomParser and empty tags.<commit_after>/**
 * DomParser.js
 *
 * Copyright 2010, Moxiecode Systems AB
 * Released under LGPL License.
 *
 * License: http://tinymce.moxiecode.com/license
 * Contributing: http://tinymce.moxiecode.com/contributing
 */

(function(tinymce) {
	tinymce.html.DomParser = function(settings, schema) {
		var self = this, nodeFilters = {}, attributeFilters = [];

		settings = settings || {};

		self.addNodeFilter = function(name, callback) {
			tinymce.each(tinymce.explode(name), function(name) {
				var list = nodeFilters[name];

				if (!list)
					nodeFilters[name] = list = [];

				list.push(callback);
			});
		};

		self.addAttributeFilter = function(name, callback) {
			tinymce.each(tinymce.explode(name), function(name) {
				var i;

				for (i = 0; i < attributeFilters.length; i++) {
					if (attributeFilters[i].name === name) {
						attributeFilters[i].callbacks.push(callback);
						return;
					}
				}

				attributeFilters.push({name: name, callbacks: [callback]});
			});
		};

		self.parse = function(html) {
			var parser, rootNode, node, Node = tinymce.html.Node, matchedNodes = {}, matchedAttributes = {},
				i, l, fi, fl, list, name, blockElements, startWhiteSpaceRegExp,
				endWhiteSpaceRegExp, allWhiteSpaceRegExp, whiteSpaceElements;

			blockElements = tinymce.extend({
				script: 1,
				style: 1
			}, schema.getBlockElements());

			whiteSpaceElements = schema.getWhiteSpaceElements();
			startWhiteSpaceRegExp = /^[ \t\r\n]+/;
			endWhiteSpaceRegExp = /[ \t\r\n]+$/;
			allWhiteSpaceRegExp = /[ \t\r\n]+/g;

			function createNode(name, type) {
				var node = new Node(name, type), list;

				if (name in nodeFilters) {
					list = matchedNodes[name];

					if (list)
						list.push(node);
					else
						matchedNodes[name] = [node];
				}

				return node;
			}

			parser = new tinymce.html.SaxParser(tinymce.extend({
				cdata: function(text) {
					node.append(createNode('#cdata', 4)).value = text;
				},

				text: function(text, raw) {
					var textNode;

					// Trim all redundant whitespace on non white space elements
					if (!whiteSpaceElements[node.name]) {
						text = text.replace(allWhiteSpaceRegExp, ' ');

						if (node.lastChild && blockElements[node.lastChild.name])
							text = text.replace(startWhiteSpaceRegExp, '');
					}

					// Do we need to create the node
					if (text.length !== 0) {
						textNode = createNode('#text', 3);
						textNode.raw = !!raw;
						node.append(textNode).value = text;
					}
				},

				comment: function(text) {
					node.append(createNode('#comment', 8)).value = text;
				},

				pi: function(text) {
					node.append(createNode('#pi', 7)).value = text;
				},

				doctype: function(text) {
					node.append(createNode('#doctype', 10)).value = text;
				},

				start: function(name, attrs, empty) {
					var newNode, attrFiltersLen, elementRule, textNode, attrName;

					elementRule = schema.getElementRule(name);
					if (elementRule) {
						newNode = createNode(elementRule.outputName || name, 1);
						newNode.attributes = attrs;
						newNode.empty = empty;

						node.append(newNode);

						attrFiltersLen = attributeFilters.length;
						while (attrFiltersLen--) {
							attrName = attributeFilters[attrFiltersLen].name;

							if (attrName in attrs.map) {
								list = matchedAttributes[attrName];

								if (list)
									list.push(newNode);
								else
									matchedAttributes[attrName] = [newNode];
							}
						}

						if (empty) {
							if (blockElements[name]) {
								// Trim start white space
								textNode = newNode.prev;
								if (textNode && textNode.type === 3)
									textNode.value = textNode.value.replace(endWhiteSpaceRegExp, '');
							}
						} else
							node = newNode;
					}
				},

				end: function(name) {
					var textNode, elementRule;

					elementRule = schema.getElementRule(name);
					if (elementRule) {
						if (blockElements[name]) {
							if (!whiteSpaceElements[node.name]) {
								// Trim start white space
								textNode = node.firstChild;
								if (textNode && textNode.type === 3)
									textNode.value = textNode.value.replace(startWhiteSpaceRegExp, '');

								// Trim end white space
								textNode = node.lastChild;
								if (textNode && textNode.type === 3)
									textNode.value = textNode.value.replace(endWhiteSpaceRegExp, '');
							}

							// Trim start white space
							textNode = node.prev;
							if (textNode && textNode.type === 3)
								textNode.value = textNode.value.replace(startWhiteSpaceRegExp, '');
						}

						// Handle empty nodes
						if (elementRule.removeEmpty || elementRule.paddEmpty) {
							if (node.isEmpty(schema.getEmptyElements())) {
								if (elementRule.paddEmpty)
									node.clear().append(new tinymce.html.Node('#text', '3')).value = '\u00a0';
								else
									return node.remove();
							}
						}

						node = node.parent;
					}
				}
			}, settings), schema);

			rootNode = node = new Node('#frag', 11);

			parser.parse(html);

			// Run node filters
			for (name in matchedNodes) {
				list = nodeFilters[name];

				for (i = 0, l = list.length; i < l; i++) {
					list[i](matchedNodes[name], name);
				}
			}

			// Run attribute filters
			for (i = 0, l = attributeFilters.length; i < l; i++) {
				list = attributeFilters[i];

				if (list.name in matchedAttributes) {
					for (fi = 0, fl = list.callbacks.length; fi < fl; fi++) {
						list.callbacks[fi](matchedAttributes[list.name], list.name);
					}
				}
			}

			return rootNode;
		};
	}
})(tinymce);
<|endoftext|>


<commit_before>/**
 * 	SEA3D - Google Draco
 * 	@author Sunag / http://www.sunag.com.br/
 */

'use strict';

//
//	Lossy Compression
//

SEA3D.GeometryDraco = function ( name, data, sea3d ) {

	this.name = name;
	this.data = data;
	this.sea3d = sea3d;

	var attrib = data.readUShort(),
		i;

	this.isBig = ( attrib & 1 ) !== 0;

	data.readVInt = this.isBig ? data.readUInt : data.readUShort;

	this.groups = [];

	if ( attrib & 32 ) {

		this.uv = [];
		this.uv.length = data.readUByte();

	}

	if ( attrib & 1024 ) {

		var numGroups = data.readUByte(),
			groupOffset = 0;

		for ( i = 0; i < numGroups; i ++ )		{

			var groupLength = data.readVInt() * 3;

			this.groups.push( {
				start: groupOffset,
				count: groupLength,
			} );

			groupOffset += groupLength;

		}

	}

	var module = SEA3D.GeometryDraco.getModule(),
		dracoData = new Int8Array( data.concat( data.position, data.bytesAvailable ).buffer );

	var decoder = new module.Decoder();

	var buffer = new module.DecoderBuffer();
	buffer.Init( dracoData, dracoData.length );

	var geometryType = decoder.GetEncodedGeometryType( buffer );

	var mesh = new module.Mesh();

	var decodingStatus = decoder.DecodeBufferToMesh( buffer, mesh );

	if ( ! decodingStatus.ok() ) {

		console.error( "SEA3D Draco Decoding failed:", decodingStatus.error_msg() );

	}

	var index = 0;

	this.vertex = this.readFloat32Array( module, decoder, mesh, index ++, module.POSITION );

	if ( attrib & 4 ) this.normal = this.readFloat32Array( module, decoder, mesh, index ++, module.NORMAL );

	if ( attrib & 32 ) {

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

			this.uv[ i ] = this.readFloat32Array( module, decoder, mesh, index ++, module.TEX_COORD );

		}

	}

	if ( attrib & 64 ) {

		this.jointPerVertex = decoder.GetAttribute( mesh, index ).num_components();

		this.joint = this.readUint16Array( module, decoder, mesh, index ++ );
		this.weight = this.readFloat32Array( module, decoder, mesh, index ++ );

	}

	this.indexes = this.readIndices( module, decoder, mesh );

	module.destroy( mesh );
	module.destroy( buffer );
	module.destroy( decoder );

};

SEA3D.GeometryDraco.getModule = function () {

	if ( ! this.module ) {

		this.module = DracoDecoderModule();

	}

	return this.module;

};

SEA3D.GeometryDraco.prototype.type = "sdrc";

SEA3D.GeometryDraco.prototype.readIndices = function ( module, decoder, mesh ) {

	var numFaces = mesh.num_faces(),
		numIndices = numFaces * 3,
		indices = new ( numIndices >= 0xFFFE ? Uint32Array : Uint16Array )( numIndices );

	var ia = new module.DracoInt32Array();

	for ( var i = 0; i < numFaces; ++ i ) {

		  decoder.GetFaceFromMesh( mesh, i, ia );

		  var index = i * 3;

		  indices[ index ] = ia.GetValue( 0 );
		  indices[ index + 1 ] = ia.GetValue( 1 );
		  indices[ index + 2 ] = ia.GetValue( 2 );

	}

	module.destroy( ia );

	return indices;

};

SEA3D.GeometryDraco.prototype.readTriangleStripIndices = function ( module, decoder, mesh ) {

	var dracoArray = new module.DracoInt32Array();
	decoder.GetTriangleStripsFromMesh( mesh, dracoArray );

	var size = mesh.num_faces() * 3,
		output = new ( size >= 0xFFFE ? Uint32Array : Uint16Array )( size );

	for ( var i = 0; i < size; ++ i ) {

		output[ i ] = dracoArray.GetValue( i );

	}

	module.destroy( dracoArray );

	return output;

};

SEA3D.GeometryDraco.prototype.readFloat32Array = function ( module, decoder, mesh, attrib, type ) {

	var attribute = decoder.GetAttribute( mesh, attrib ),
		numPoints = mesh.num_points();

	var dracoArray = new module.DracoFloat32Array();
	decoder.GetAttributeFloatForAllPoints( mesh, attribute, dracoArray );

	var size = numPoints * attribute.num_components(),
		output = new Float32Array( size );

	for ( var i = 0; i < size; ++ i ) {

		output[ i ] = dracoArray.GetValue( i );

	}

	module.destroy( dracoArray );

	return output;

};

SEA3D.GeometryDraco.prototype.readUint16Array = function ( module, decoder, mesh, attrib, type ) {

	var attribute = decoder.GetAttribute( mesh, attrib ),
		numPoints = mesh.num_points();

	var dracoArray = new module.DracoUInt16Array();
	decoder.GetAttributeUInt16ForAllPoints( mesh, attribute, dracoArray );

	var size = numPoints * attribute.num_components(),
		output = new Uint16Array( size );

	for ( var i = 0; i < size; ++ i ) {

		output[ i ] = dracoArray.GetValue( i );

	}

	module.destroy( dracoArray );

	return output;

};

//
//	Geometry Update
//

SEA3D.GeometryUpdateDraco = function ( name, data, sea3d ) {

	this.name = name;
	this.data = data;
	this.sea3d = sea3d;

	this.index = data.readUInt();
	this.bytes = data.concat( data.position, data.length - data.position );

};

SEA3D.GeometryUpdateDraco.prototype.type = "sDRC";

//
//	Updaters
//

THREE.SEA3D.prototype.readGeometryUpdateDraco = function ( sea ) {

	var obj = this.file.objects[ sea.index ],
		geo = obj.tag;

	var seaUpdate = new SEA3D.GeometryDraco( "", sea.bytes, sea.sea3d );
	seaUpdate.tag = geo;

	this.readGeometryBuffer( seaUpdate );

};

//
//	Extension
//

THREE.SEA3D.EXTENSIONS_LOADER.push( {

	setTypeRead: function () {

		this.file.addClass( SEA3D.GeometryDraco, true );
		this.file.addClass( SEA3D.GeometryUpdateDraco, true );

		this.file.typeRead[ SEA3D.GeometryDraco.prototype.type ] = this.readGeometryBuffer;
		this.file.typeRead[ SEA3D.GeometryUpdateDraco.prototype.type ] = this.readGeometryUpdateDraco;

	}

} );
<commit_msg>unnecessary updater<commit_after>/**
 * 	SEA3D - Google Draco
 * 	@author Sunag / http://www.sunag.com.br/
 */

'use strict';

//
//	Lossy Compression
//

SEA3D.GeometryDraco = function ( name, data, sea3d ) {

	this.name = name;
	this.data = data;
	this.sea3d = sea3d;

	var attrib = data.readUShort(),
		i;

	this.isBig = ( attrib & 1 ) !== 0;

	data.readVInt = this.isBig ? data.readUInt : data.readUShort;

	this.groups = [];

	if ( attrib & 32 ) {

		this.uv = [];
		this.uv.length = data.readUByte();

	}

	if ( attrib & 1024 ) {

		var numGroups = data.readUByte(),
			groupOffset = 0;

		for ( i = 0; i < numGroups; i ++ )		{

			var groupLength = data.readVInt() * 3;

			this.groups.push( {
				start: groupOffset,
				count: groupLength,
			} );

			groupOffset += groupLength;

		}

	}

	var module = SEA3D.GeometryDraco.getModule(),
		dracoData = new Int8Array( data.concat( data.position, data.bytesAvailable ).buffer );

	var decoder = new module.Decoder();

	var buffer = new module.DecoderBuffer();
	buffer.Init( dracoData, dracoData.length );

	var geometryType = decoder.GetEncodedGeometryType( buffer );

	var mesh = new module.Mesh();

	var decodingStatus = decoder.DecodeBufferToMesh( buffer, mesh );

	if ( ! decodingStatus.ok() ) {

		console.error( "SEA3D Draco Decoding failed:", decodingStatus.error_msg() );

	}

	var index = 0;

	this.vertex = this.readFloat32Array( module, decoder, mesh, index ++, module.POSITION );

	if ( attrib & 4 ) this.normal = this.readFloat32Array( module, decoder, mesh, index ++, module.NORMAL );

	if ( attrib & 32 ) {

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

			this.uv[ i ] = this.readFloat32Array( module, decoder, mesh, index ++, module.TEX_COORD );

		}

	}

	if ( attrib & 64 ) {

		this.jointPerVertex = decoder.GetAttribute( mesh, index ).num_components();

		this.joint = this.readUint16Array( module, decoder, mesh, index ++ );
		this.weight = this.readFloat32Array( module, decoder, mesh, index ++ );

	}

	this.indexes = this.readIndices( module, decoder, mesh );

	module.destroy( mesh );
	module.destroy( buffer );
	module.destroy( decoder );

};

SEA3D.GeometryDraco.getModule = function () {

	if ( ! this.module ) {

		this.module = DracoDecoderModule();

	}

	return this.module;

};

SEA3D.GeometryDraco.prototype.type = "sdrc";

SEA3D.GeometryDraco.prototype.readIndices = function ( module, decoder, mesh ) {

	var numFaces = mesh.num_faces(),
		numIndices = numFaces * 3,
		indices = new ( numIndices >= 0xFFFE ? Uint32Array : Uint16Array )( numIndices );

	var ia = new module.DracoInt32Array();

	for ( var i = 0; i < numFaces; ++ i ) {

		  decoder.GetFaceFromMesh( mesh, i, ia );

		  var index = i * 3;

		  indices[ index ] = ia.GetValue( 0 );
		  indices[ index + 1 ] = ia.GetValue( 1 );
		  indices[ index + 2 ] = ia.GetValue( 2 );

	}

	module.destroy( ia );

	return indices;

};

SEA3D.GeometryDraco.prototype.readTriangleStripIndices = function ( module, decoder, mesh ) {

	var dracoArray = new module.DracoInt32Array();
	decoder.GetTriangleStripsFromMesh( mesh, dracoArray );

	var size = mesh.num_faces() * 3,
		output = new ( size >= 0xFFFE ? Uint32Array : Uint16Array )( size );

	for ( var i = 0; i < size; ++ i ) {

		output[ i ] = dracoArray.GetValue( i );

	}

	module.destroy( dracoArray );

	return output;

};

SEA3D.GeometryDraco.prototype.readFloat32Array = function ( module, decoder, mesh, attrib, type ) {

	var attribute = decoder.GetAttribute( mesh, attrib ),
		numPoints = mesh.num_points();

	var dracoArray = new module.DracoFloat32Array();
	decoder.GetAttributeFloatForAllPoints( mesh, attribute, dracoArray );

	var size = numPoints * attribute.num_components(),
		output = new Float32Array( size );

	for ( var i = 0; i < size; ++ i ) {

		output[ i ] = dracoArray.GetValue( i );

	}

	module.destroy( dracoArray );

	return output;

};

SEA3D.GeometryDraco.prototype.readUint16Array = function ( module, decoder, mesh, attrib, type ) {

	var attribute = decoder.GetAttribute( mesh, attrib ),
		numPoints = mesh.num_points();

	var dracoArray = new module.DracoUInt16Array();
	decoder.GetAttributeUInt16ForAllPoints( mesh, attribute, dracoArray );

	var size = numPoints * attribute.num_components(),
		output = new Uint16Array( size );

	for ( var i = 0; i < size; ++ i ) {

		output[ i ] = dracoArray.GetValue( i );

	}

	module.destroy( dracoArray );

	return output;

};

//
//	Extension
//

THREE.SEA3D.EXTENSIONS_LOADER.push( {

	setTypeRead: function () {

		this.file.addClass( SEA3D.GeometryDraco, true );
		this.file.typeRead[ SEA3D.GeometryDraco.prototype.type ] = this.readGeometryBuffer;

	}

} );
<|endoftext|>


<commit_before>var gulp = require('gulp');
var react = require('gulp-react');

gulp.task('default', function () {
    return gulp.src('src/components/ComponentHelper/**/*.jsx')
        .pipe(react({harmony:true}))
        .pipe(gulp.dest('lib'));
});<commit_msg>Modified gulpfile<commit_after>var gulp = require('gulp');
var react = require('gulp-react');

gulp.task('default', function () {
    return gulp.src(['src/components/ComponentHelper/**/*.jsx','src/mixins/*.js'])
        .pipe(react({harmony:true}))
        .pipe(gulp.dest('lib'));
});<|endoftext|>