<commit_before>var config = require('config');
var d3 = require('d3');
var debug = require('debug')(config.name() + ':transitive-view');
var each = require('each');
var Transitive = require('transitive');
var view = require('view');

/**
 * Expose `View`
 */

var View = module.exports = view(require('./template.html'), function(view,
  model) {
  view.on('rendered', function() {
    var journey = model.journey();
    if (journey) view.display(journey);
  });

  model.on('change journey', function(journey) {
    if (journey) view.display(journey);
  });
});

/**
 * Display
 */

View.prototype.display = function(journey) {
  debug('--> displaying journey');

  if (journey.journeys && journey.journeys.length > 0) {
    this.el.innerHTML = require('./legend.html');

    try {
      var transitive = window.transitive = new Transitive({
        el: this.el,
        legendEl: this.find('.legend'),
        data: journey,
        gridCellSize: 200,
        mapboxId: config.mapbox_map_id(),
        useDynamicRendering: true,
        styles: require('./style')
      });
      transitive.render();
    } catch(e) {
      debug('<-- failed to display journey');
      return;
    }
  }

  var el = this.el;
  this.find('.zoom.in').onclick = function() {
    el.dispatchEvent(new window.WheelEvent('wheel', {
      view: window,
      bubbles: true,
      cancelable: true,
      clientX: el.clientWidth / 2,
      clientY: el.clientHeight * 0.7,
      deltaY: -300
    }));
  };

  this.find('.zoom.out').onclick = function() {
    el.dispatchEvent(new window.WheelEvent('wheel', {
      view: window,
      bubbles: true,
      cancelable: true,
      clientX: el.clientWidth / 2,
      clientY: el.clientHeight * 0.7,
      deltaY: 300
    }));
  };

  debug('<-- done displaying patterns');
};
<commit_msg>Log transitive error<commit_after>var config = require('config');
var d3 = require('d3');
var debug = require('debug')(config.name() + ':transitive-view');
var each = require('each');
var Transitive = require('transitive');
var view = require('view');

/**
 * Expose `View`
 */

var View = module.exports = view(require('./template.html'), function(view,
  model) {
  view.on('rendered', function() {
    var journey = model.journey();
    if (journey) view.display(journey);
  });

  model.on('change journey', function(journey) {
    if (journey) view.display(journey);
  });
});

/**
 * Display
 */

View.prototype.display = function(journey) {
  debug('--> displaying journey');

  if (journey.journeys && journey.journeys.length > 0) {
    this.el.innerHTML = require('./legend.html');

    try {
      var transitive = window.transitive = new Transitive({
        el: this.el,
        legendEl: this.find('.legend'),
        data: journey,
        gridCellSize: 200,
        mapboxId: config.mapbox_map_id(),
        useDynamicRendering: true,
        styles: require('./style')
      });
      transitive.render();
    } catch(e) {
      debug('<-- failed to display journey: %s', e.message);
      return;
    }
  }

  var el = this.el;
  this.find('.zoom.in').onclick = function() {
    el.dispatchEvent(new window.WheelEvent('wheel', {
      view: window,
      bubbles: true,
      cancelable: true,
      clientX: el.clientWidth / 2,
      clientY: el.clientHeight * 0.7,
      deltaY: -300
    }));
  };

  this.find('.zoom.out').onclick = function() {
    el.dispatchEvent(new window.WheelEvent('wheel', {
      view: window,
      bubbles: true,
      cancelable: true,
      clientX: el.clientWidth / 2,
      clientY: el.clientHeight * 0.7,
      deltaY: 300
    }));
  };

  debug('<-- done displaying patterns');
};
<|endoftext|>


<commit_before>Template.regionSelectionWrap.created = function() {
	 this.subscribe("Regions");
	 var instance = this;
	 instance.searchingRegions = new ReactiveVar(false);
};

Template.regionSelectionWrap.helpers({
	searchingRegions: function() {
		return Template.instance().searchingRegions.get();
	}
});

Template.regionDisplay.helpers({
	region: function() {
		var region = Regions.findOne(Session.get('region'));
		return region;
	}
});

Template.regionDisplay.events({
	'click .js-region-display': function(event, instance) {
		instance.parentInstance().searchingRegions.set(true);
	}
});

Template.regionSelection.onCreated(function() {
	this.regionSearch = new ReactiveVar('');
});

Template.regionSelection.rendered = function() {
	Template.instance().$('.js-region-search').select();
};

var updateRegionSearch = function(event, instance) {
	var search = instance.$('.js-region-search').val();
	search = String(search).trim();
	instance.regionSearch.set(search);
};

Template.regionSelection.helpers({
	regions: function() {
		var search = Template.instance().regionSearch.get();
		var query = {};
		if (search !== '') query = { name: new RegExp(search, 'i') };

		return Regions.find(query);
	},

	regionNameMarked: function() {
		var search = Template.instance().regionSearch.get();
		var name = this.name;
		if (search === '') return name;
		var match = name.match(new RegExp(search, 'i'));

		// To add markup we have to escape all the parts separately
		var marked;
		if (match) {
			var term = match[0];
			var parts = name.split(term);
			marked = _.map(parts, Blaze._escape).join(''+Blaze._escape(term)+'');
		} else {
			marked = Blaze._escape(name);
		}
		return Spacebars.SafeString(marked);
	},

	region: function() {
		var region = Regions.findOne(Session.get('region'));
		return region;
	},

	allCourses: function() {
		return _.reduce(Regions.find().fetch(), function(acc, region) {
			return acc + region.courseCount;
		}, 0);
	},

	allUpcomingEvents: function() {
		return _.reduce(Regions.find().fetch(), function(acc, region) {
			return acc + region.futureEventCount;
		}, 0);
	},

	courses: function() {
		return coursesFind({ region: this._id }).count();
	},

	currentRegion: function() {
		var region = this._id || "all";
		return region == Session.get('region');
	}
});

Template.regionSelection.events({
	'click .js-region-link': function(event, instance) {
		event.preventDefault();
		var region_id = this._id ? this._id : 'all';
		var changed = Session.get('region') !== region_id;

		localStorage.setItem("region", region_id); // to survive page reload
		Session.set('region', region_id);

		// When the region changes, we want the content of the page to update
		// Many pages do not change when the region changed, so we go to
		// the homepage for those
		if (changed) {
			var routeName = Router.current().route.getName();
			var routesToKeep = ['home', 'find', 'locations', 'calendar'];
			if (routesToKeep.indexOf(routeName) < 0) Router.go('/');
		}
		instance.parentInstance().searchingRegions.set(false);
	},

	'mouseover .js-region-link:not(.all-regions-link)': function() {
		if (Session.get('region') == "all") {
			courseFilterPreview(true, '.'+this._id);
		}
	},

	'mouseout .js-region-link:not(.all-regions-link)': function() {
		if (Session.get('region') == "all") {
			courseFilterPreview(false, '.'+this._id);
		}
	},

	'keyup .js-region-search': _.debounce(updateRegionSearch, 100),

	'focus .js-region-search': function(event, instance) {
		var viewportWidth = Session.get('viewportWidth');
		var screenMd = viewportWidth >= 768 && viewportWidth <= 992;
		if (screenMd) {
			$('.navbar-collapse > .nav:first-child > li:not(.navbar-link-active)').fadeTo("slow", 0);
			$('.navbar-collapse > .nav:first-child > li:not(.navbar-link-active)').hide();
		}
		instance.$('.dropdown-toggle').dropdown('toggle');
	},
});

Template.regionSelection.onRendered(function() {
	var parentInstance = this.parentInstance();
	parentInstance.$('.dropdown').on('hide.bs.dropdown', function(e) {
		var viewportWidth = Session.get('viewportWidth');
		var screenMd = viewportWidth >= 768 && viewportWidth <= 992;
		if (screenMd) {
			$('.navbar-collapse > .nav:first-child > li:not(.navbar-link-active)').show();
			$('.navbar-collapse > .nav:first-child > li:not(.navbar-link-active)').fadeTo("slow", 1);
		}
		parentInstance.searchingRegions.set(false);
	});
});
<commit_msg>remove obsolete helper<commit_after>Template.regionSelectionWrap.created = function() {
	 this.subscribe("Regions");
	 var instance = this;
	 instance.searchingRegions = new ReactiveVar(false);
};

Template.regionSelectionWrap.helpers({
	searchingRegions: function() {
		return Template.instance().searchingRegions.get();
	}
});

Template.regionDisplay.helpers({
	region: function() {
		var region = Regions.findOne(Session.get('region'));
		return region;
	}
});

Template.regionDisplay.events({
	'click .js-region-display': function(event, instance) {
		instance.parentInstance().searchingRegions.set(true);
	}
});

Template.regionSelection.onCreated(function() {
	this.regionSearch = new ReactiveVar('');
});

Template.regionSelection.rendered = function() {
	Template.instance().$('.js-region-search').select();
};

var updateRegionSearch = function(event, instance) {
	var search = instance.$('.js-region-search').val();
	search = String(search).trim();
	instance.regionSearch.set(search);
};

Template.regionSelection.helpers({
	regions: function() {
		var search = Template.instance().regionSearch.get();
		var query = {};
		if (search !== '') query = { name: new RegExp(search, 'i') };

		return Regions.find(query);
	},

	regionNameMarked: function() {
		var search = Template.instance().regionSearch.get();
		var name = this.name;
		if (search === '') return name;
		var match = name.match(new RegExp(search, 'i'));

		// To add markup we have to escape all the parts separately
		var marked;
		if (match) {
			var term = match[0];
			var parts = name.split(term);
			marked = _.map(parts, Blaze._escape).join(''+Blaze._escape(term)+'');
		} else {
			marked = Blaze._escape(name);
		}
		return Spacebars.SafeString(marked);
	},

	region: function() {
		var region = Regions.findOne(Session.get('region'));
		return region;
	},

	allCourses: function() {
		return _.reduce(Regions.find().fetch(), function(acc, region) {
			return acc + region.courseCount;
		}, 0);
	},

	allUpcomingEvents: function() {
		return _.reduce(Regions.find().fetch(), function(acc, region) {
			return acc + region.futureEventCount;
		}, 0);
	},

	currentRegion: function() {
		var region = this._id || "all";
		return region == Session.get('region');
	}
});

Template.regionSelection.events({
	'click .js-region-link': function(event, instance) {
		event.preventDefault();
		var region_id = this._id ? this._id : 'all';
		var changed = Session.get('region') !== region_id;

		localStorage.setItem("region", region_id); // to survive page reload
		Session.set('region', region_id);

		// When the region changes, we want the content of the page to update
		// Many pages do not change when the region changed, so we go to
		// the homepage for those
		if (changed) {
			var routeName = Router.current().route.getName();
			var routesToKeep = ['home', 'find', 'locations', 'calendar'];
			if (routesToKeep.indexOf(routeName) < 0) Router.go('/');
		}
		instance.parentInstance().searchingRegions.set(false);
	},

	'mouseover .js-region-link:not(.all-regions-link)': function() {
		if (Session.get('region') == "all") {
			courseFilterPreview(true, '.'+this._id);
		}
	},

	'mouseout .js-region-link:not(.all-regions-link)': function() {
		if (Session.get('region') == "all") {
			courseFilterPreview(false, '.'+this._id);
		}
	},

	'keyup .js-region-search': _.debounce(updateRegionSearch, 100),

	'focus .js-region-search': function(event, instance) {
		var viewportWidth = Session.get('viewportWidth');
		var screenMd = viewportWidth >= 768 && viewportWidth <= 992;
		if (screenMd) {
			$('.navbar-collapse > .nav:first-child > li:not(.navbar-link-active)').fadeTo("slow", 0);
			$('.navbar-collapse > .nav:first-child > li:not(.navbar-link-active)').hide();
		}
		instance.$('.dropdown-toggle').dropdown('toggle');
	},
});

Template.regionSelection.onRendered(function() {
	var parentInstance = this.parentInstance();
	parentInstance.$('.dropdown').on('hide.bs.dropdown', function(e) {
		var viewportWidth = Session.get('viewportWidth');
		var screenMd = viewportWidth >= 768 && viewportWidth <= 992;
		if (screenMd) {
			$('.navbar-collapse > .nav:first-child > li:not(.navbar-link-active)').show();
			$('.navbar-collapse > .nav:first-child > li:not(.navbar-link-active)').fadeTo("slow", 1);
		}
		parentInstance.searchingRegions.set(false);
	});
});
<|endoftext|>


<commit_before>define( ['dojo/_base/declare',
         'JBrowse/Store/SeqFeature'
        ],
        function( declare, SeqFeatureStore ) {

// return declare( "testScratchPadClass", SeqFeatureStore,
return declare( SeqFeatureStore,
{
    constructor: function( args ) {
        this.features = {};
	this.sorted_feats = [];
        this._calculateStats();
    },

    insert: function( feature ) {
        this.features[ feature.id() ] = feature;
//	this._sort();
        this._calculateStats();
    },

    replace: function( feature ) {
	this.features[ feature.id() ] = feature;
//	this._sort();
        this._calculateStats();
    },

/*    _sort: function()  {
	sorted_feats.sort(function(a, b) {
	    var astart = a.get('start');
	    var bstart = b.get('start');
            if (astart != bstart)  {
		return astart - bstart;
	    }
            else {
		return b.get('end') - a.get('end');
	    }
	} );
    },
*/

/*
    delete: function( feature ) {
	this.deleteFeatureById[ feature.id() ];
    },
*/

    deleteFeatureById: function( id ) {
	delete  this.features[ id ];
        this._calculateStats();
    },

    /* if feature with given id is present in store, return it.  Otherwise return null */
    getFeatureById: function( id )  {
	return this.features[ id ];
    },

    _calculateStats: function() {
        var minStart = Infinity;
        var maxEnd = -Infinity;
        var featureCount = 0;
        for( var id in this.features ) {
            var f = this.features[id];
            var s = f.get('start');
            var e = f.get('end');
            if( s < minStart )
                minStart = s;

            if( e > maxEnd )
                maxEnd = e;

            featureCount++;
        }

        this.globalStats = {
            featureDensity: featureCount/(maxEnd-minStart+1),
            featureCount: featureCount,
            minStart: minStart,
            maxEnd: maxEnd,
            span: (maxEnd-minStart+1)
        };
    },

    getFeatures: function( query, featCallback, endCallback, errorCallback ) {
        var start = query.start;
        var end = query.end;
        for( var id in this.features ) {
            var f = this.features[id];
            if(! ( f.get('end') < start  || f.get('start') > end ) ) {
                featCallback( f );
            }
        }
        if (endCallback)  { endCallback() }
    }
});
});<commit_msg>Fixed bug that sometimes incorrectly triggered "Too much data" message in Annotation track rather than rendering the annotations.  <commit_after>define( ['dojo/_base/declare',
         'JBrowse/Store/SeqFeature'
        ],
        function( declare, SeqFeatureStore ) {

// return declare( "testScratchPadClass", SeqFeatureStore,
return declare( SeqFeatureStore,
{
    constructor: function( args ) {
        this.refSeq = args.refSeq;
        this.features = {};
	this.sorted_feats = [];
        this._calculateStats();
    },

    insert: function( feature ) {
        this.features[ feature.id() ] = feature;
//	this._sort();
        this._calculateStats();
    },

    replace: function( feature ) {
	this.features[ feature.id() ] = feature;
//	this._sort();
        this._calculateStats();
    },

/*    _sort: function()  {
	sorted_feats.sort(function(a, b) {
	    var astart = a.get('start');
	    var bstart = b.get('start');
            if (astart != bstart)  {
		return astart - bstart;
	    }
            else {
		return b.get('end') - a.get('end');
	    }
	} );
    },
*/

/*
    delete: function( feature ) {
	this.deleteFeatureById[ feature.id() ];
    },
*/

    deleteFeatureById: function( id ) {
	delete  this.features[ id ];
        this._calculateStats();
    },

    /* if feature with given id is present in store, return it.  Otherwise return null */
    getFeatureById: function( id )  {
	return this.features[ id ];
    },

    _calculateStats: function() {
        var minStart = Infinity;
        var maxEnd = -Infinity;
        var featureCount = 0;
        for( var id in this.features ) {
            var f = this.features[id];
            var s = f.get('start');
            var e = f.get('end');
            if( s < minStart )
                minStart = s;

            if( e > maxEnd )
                maxEnd = e;

            featureCount++;
        }

        this.globalStats = {
            featureDensity: featureCount/(this.refSeq.end - this.refSeq.start +1),
            featureCount: featureCount,
            minStart: minStart, /* 5'-most feature start */
            maxEnd: maxEnd,     /* 3'-most feature end */
            span: (maxEnd-minStart+1)  /* min span containing all features */
        };
    },

    getFeatures: function( query, featCallback, endCallback, errorCallback ) {
        var start = query.start;
        var end = query.end;
        for( var id in this.features ) {
            var f = this.features[id];
            if(! ( f.get('end') < start  || f.get('start') > end ) ) {
                featCallback( f );
            }
        }
        if (endCallback)  { endCallback() }
    }
});
});<|endoftext|>


<commit_before>// Unit test for a.state (plugin)
module('plugin/state.js');

// Test raising a 404 error does raise the chainer error function
asyncTest('a.state.error', function() {
    expect(2);

    var test = {
        id : 'test-error',
        hash : 'test-error',
        data : 'resource/data/notexist.json'
    };

    a.state.add(test);

    a.message.bind('a.state.error', function(data) {
        strictEqual(data.resource.indexOf('resource/data/notexist.json'), 0,
                                            'Test data resource error');
        strictEqual(data.status, 404, 'Test data response');
    });

    chain('test-error', start, 100);

    hashtag('test-error');
});

// Test raising 404 on html
asyncTest('a.state.error2', function() {
    expect(2);

    var test = {
        id : 'test-error2',
        hash : 'test-error2',

        include : {
            html : 'resource/data/notexist.html'
        }
    };

    a.state.add(test);

    a.message.bind('a.state.error', function(data) {
        strictEqual(data.resource.indexOf('resource/data/notexist.html'), 0,
                                            'Test html resource error');
        strictEqual(data.status, 404, 'Test data response');
    });

    chain('test-error2', start, 100);

    hashtag('test-error2');
});

// Test getting hashtag loaded on error appearing
asyncTest('a.state.error-hash', function() {
    expect(4);

    var tree = {
        id : 'errorhashroot',

        error: {
            _404: function(state, resource, status) {
                strictEqual(true, true, 'Test 404 is found');
                strictEqual(state, 'test-error-hash',
                                                'Test 404 is raised by state');
                strictEqual(resource.substring(0, 13), 'someunknowurl',
                                                    'Test resourced handled');
                strictEqual(status, 404, 'Test 404 error code');
            },
            _40x: function() {
                strictEqual(true, false, 'Test 40x should not be raised here');
            }
        },

        children : {
            id : 'test-error-hash',
            hash : 'test-error-hash',
            data : 'someunknowurl',
            error: {
                generic: function() {
                    strictEqual(true, false, 'Test generic is not used');
                }
            }
        }
    };

    a.state.add(tree);

    chain('test-error-hash', start, 100);

    hashtag('test-error-hash');
});

// Test getting hashtag loaded on error appearing
asyncTest('a.state.error-hash2', function() {
    expect(1);

    var tree = {
        id : 'errorhashroot2',

        children : {
            id : 'test-error-hash2',
            hash : 'test-error-hash2',
            data : 'someunknowurl2',

            error: {
                generic: function() {
                    strictEqual(true, true, 'Test generic is raised');
                }
            }
        }
    };

    a.state.add(tree);

    chain('test-error-hash2', start, 100);

    hashtag('test-error-hash2');
});

// Test getting hashtag loaded on error appearing
asyncTest('a.state.error-hash3', function() {
    expect(1);

    var tree = {
        id : 'errorhashroot3',

        children : {
            id : 'test-error-hash3',
            hash : 'test-error-hash3',
            data : 'someunknowurl3',

            error: {
                generic: 'hash-error-404'
            }
        }
    };

    a.state.add(tree);

    a.hash.bind('change', function(data) {
        // Prevent a wrong catch bug, and does not make test unreliable
        // (as it will raise 0 event if nothing is found, stopping system)
        if(data.value === 'hash-error-404') {
            strictEqual(data.value, 'hash-error-404', 'Test value is linked');
        }
    });

    chain('test-error-hash3', start, 100);

    hashtag('test-error-hash3');
});<commit_msg>Unit test for 'empty error' handler.<commit_after>// Unit test for a.state (plugin)
module('plugin/state.js');

// Test raising a 404 error does raise the chainer error function
asyncTest('a.state.error', function() {
    expect(2);

    var test = {
        id : 'test-error',
        hash : 'test-error',
        data : 'resource/data/notexist.json'
    };

    a.state.add(test);

    a.message.bind('a.state.error', function(data) {
        strictEqual(data.resource.indexOf('resource/data/notexist.json'), 0,
                                            'Test data resource error');
        strictEqual(data.status, 404, 'Test data response');
    });

    chain('test-error', function() {
        hashtag('');
        start();
    }, 100);

    hashtag('test-error');
});

// Test raising 404 on html
asyncTest('a.state.error2', function() {
    expect(2);

    var test = {
        id : 'test-error2',
        hash : 'test-error2',

        include : {
            html : 'resource/data/notexist.html'
        }
    };

    a.state.add(test);

    a.message.bind('a.state.error', function(data) {
        strictEqual(data.resource.indexOf('resource/data/notexist.html'), 0,
                                            'Test html resource error');
        strictEqual(data.status, 404, 'Test data response');
    });

    chain('test-error2', function() {
        hashtag('');
        start();
    }, 100);

    hashtag('test-error2');
});

// Test getting hashtag loaded on error appearing
asyncTest('a.state.error-hash', function() {
    expect(4);

    var tree = {
        id : 'errorhashroot',

        error: {
            _404: function(state, resource, status) {
                strictEqual(true, true, 'Test 404 is found');
                strictEqual(state, 'test-error-hash',
                                                'Test 404 is raised by state');
                strictEqual(resource.substring(0, 13), 'someunknowurl',
                                                    'Test resourced handled');
                strictEqual(status, 404, 'Test 404 error code');
            },
            _40x: function() {
                strictEqual(true, false, 'Test 40x should not be raised here');
            }
        },

        children : {
            id : 'test-error-hash',
            hash : 'test-error-hash',
            data : 'someunknowurl',
            error: {
                generic: function() {
                    strictEqual(true, false, 'Test generic is not used');
                }
            }
        }
    };

    a.state.add(tree);

    chain('test-error-hash', function() {
        hashtag('');
        start();
    }, 100);

    hashtag('test-error-hash');
});

// Test getting hashtag loaded on error appearing
asyncTest('a.state.error-hash2', function() {
    expect(1);

    var tree = {
        id : 'errorhashroot2',

        children : {
            id : 'test-error-hash2',
            hash : 'test-error-hash2',
            data : 'someunknowurl2',

            error: {
                generic: function() {
                    strictEqual(true, true, 'Test generic is raised');
                }
            }
        }
    };

    a.state.add(tree);

    chain('test-error-hash2', function() {
        hashtag('');
        start();
    }, 100);

    hashtag('test-error-hash2');
});

// Test getting hashtag loaded on error appearing
asyncTest('a.state.error-hash3', function() {
    expect(1);

    var tree = {
        id : 'errorhashroot3',

        children : {
            id : 'test-error-hash3',
            hash : 'test-error-hash3',
            data : 'someunknowurl3',

            error: {
                generic: 'hash-error-404'
            }
        }
    };

    a.state.add(tree);

    a.hash.bind('change', function(data) {
        // Prevent a wrong catch bug, and does not make test unreliable
        // (as it will raise 0 event if nothing is found, stopping system)
        if(data.value === 'hash-error-404') {
            strictEqual(data.value, 'hash-error-404', 'Test value is linked');
        }
    });

    chain('test-error-hash3', function() {
        hashtag('');
        start();
    }, 100);

    hashtag('test-error-hash3');
});

// Test an error with empty error content to catch it
asyncTest('a.state.error-empty', function() {
    expect(1);

    a.console.clear();

    var state = {
        id: 'error-empty-hash',
        hash: 'a.state.error-empty',
        data: 'someunknowurl4'
    };

    a.state.add(state);

    chain('a.state.error-empty', function() {
        // We expect a message on console.error saying 'an error has not been
        // handled'
        var trace = a.console.trace('error');
        strictEqual(trace[0], 'a.state.raiseError: an error occurs, but no ' +
                                'error function/hash inside the state ' +
                                'where existing to handle it. ' +
                                'Please check your error handler (status: ' +
                                '404, state id: error-empty-hash)');
        hashtag('');
        start();
    }, 100);
    hashtag('a.state.error-empty');
});<|endoftext|>


<commit_before>/*
---

script: Behavior.js

description: Defines global selectors that mix the mixins in

license: Public domain (http://unlicense.org).

authors: Yaroslaff Fedin

requires:
  - LSD

provides:
  - LSD.Behavior

...
*/

LSD.Behavior = function() {
  this.attached = [];
  this.expectations = {};
}

/**
  The best way to customize widget behavior, is to define a widget role. The role may be further extended or reused by widgets with the
  matching tag name. But a widget can only have one role at time. There is a way to provide additional customizations to widget through
  use of mixins, a reusable class definition that may be applied on top of the widget role. Both role and mixins are applied when the
  widget matches specific condition. Widgets can find their role easily, because often the role name matches with the widget tag name, so
  their condition would be a specific tag name. But mixins may also be triggered with any selector, for example, watching for a specific
  pseudo class. LSD.Behavior is used to make mixin observe a selector, so every mixin comes with a pre-defined behavior. Behavior may be
  also used to apply plain widget options, instead of mixins.
 **/

LSD.Behavior.prototype = {
  /**
    Provides additional behavor for LSD Widgets.

    There are several ways to define a new behavior (commands). For a complete list of commands, refer Widget guide.

    As pseudo:

      LSD.Behavior.define(':submittable', 'submittable')

    As pseudo containing certain attributes:

      LSD.Behavior.define(':form[acttion], [src], [href]', 'request')

    As an object containing certain attributes

      LSD.Behavior.define('[scrollable]', 'scrollable')

    Submitable, Request and Scrollable in the given examples are retrieved from LSD.Mixin object (they are LSD.Mixin.Submitable, LSD.Mixin.Request,
    LSD. Mixin.Scrollable).

    You can also specify a concerete class:

      LSD.Behavior.define('[scrollable]', LSD.Mixin.Scrollable)

   **/
  define: function(selector, behavior) {
    selector.split(/\s*,\s*/).each(function(bit) {
      var group = this.expectations[bit];
      if (!group) group = this.expectations[bit] = [];
      group.push(behavior);
      this.attached.each(function(object) {
        this.expect(object, bit, behavior)
      }, this);
    }, this);
  },

  expect: function(object, selector, behavior) {
    var proto = object.prototype, type = typeOf(behavior);
    var watcher = function(widget, state) {
      if (type == 'object') widget[state ? 'setOptions' : 'unsetOptions'](behavior);
      else widget[state ? 'mixin' : 'unmix'](behavior, true);
    }
    if (proto.expect) {
      var parsed = Object.clone(LSD.Slick.parse(selector).expressions[0][0]);
      delete parsed.combinator;
      proto.expect(parsed, watcher);
    }
  },

  attach: function(object) {
    this.attached.push(object);
    for (var expectation in this.expectations)
      for (var exps = this.expectations[expectation], i = 0, exp; exp = exps[i++];)
        this.expect(object, expectation, exp);
  }
};

LSD.Behavior = new LSD.Behavior;<commit_msg>Handle function behaviors<commit_after>/*
---

script: Behavior.js

description: Defines global selectors that mix the mixins in

license: Public domain (http://unlicense.org).

authors: Yaroslaff Fedin

requires:
  - LSD

provides:
  - LSD.Behavior

...
*/

LSD.Behavior = function() {
  this.attached = [];
  this.expectations = {};
}

/**
  The best way to customize widget behavior, is to define a widget role. The role may be further extended or reused by widgets with the
  matching tag name. But a widget can only have one role at time. There is a way to provide additional customizations to widget through
  use of mixins, a reusable class definition that may be applied on top of the widget role. Both role and mixins are applied when the
  widget matches specific condition. Widgets can find their role easily, because often the role name matches with the widget tag name, so
  their condition would be a specific tag name. But mixins may also be triggered with any selector, for example, watching for a specific
  pseudo class. LSD.Behavior is used to make mixin observe a selector, so every mixin comes with a pre-defined behavior. Behavior may be
  also used to apply plain widget options, instead of mixins.
 **/

LSD.Behavior.prototype = {
  /**
    Provides additional behavor for LSD Widgets.

    There are several ways to define a new behavior (commands). For a complete list of commands, refer Widget guide.

    As pseudo:

      LSD.Behavior.define(':submittable', 'submittable')

    As pseudo containing certain attributes:

      LSD.Behavior.define(':form[acttion], [src], [href]', 'request')

    As an object containing certain attributes

      LSD.Behavior.define('[scrollable]', 'scrollable')

    Submitable, Request and Scrollable in the given examples are retrieved from LSD.Mixin object (they are LSD.Mixin.Submitable, LSD.Mixin.Request,
    LSD. Mixin.Scrollable).

    You can also specify a concerete class:

      LSD.Behavior.define('[scrollable]', LSD.Mixin.Scrollable)

   **/
  define: function(selector, behavior) {
    selector.split(/\s*,\s*/).each(function(bit) {
      var group = this.expectations[bit];
      if (!group) group = this.expectations[bit] = [];
      group.push(behavior);
      this.attached.each(function(object) {
        this.expect(object, bit, behavior)
      }, this);
    }, this);
  },

  expect: function(object, selector, behavior) {
    var proto = object.prototype, type = typeOf(behavior);
    var watcher = function(widget, state) {
      if (type == 'object') widget[state ? 'setOptions' : 'unsetOptions'](behavior);
      else if (type == 'function') behavior(widget, state)
      else widget[state ? 'mixin' : 'unmix'](behavior, true);
    }
    if (proto.expect) {
      var parsed = Object.clone(LSD.Slick.parse(selector).expressions[0][0]);
      delete parsed.combinator;
      proto.expect(parsed, watcher);
    }
  },

  attach: function(object) {
    this.attached.push(object);
    for (var expectation in this.expectations)
      for (var exps = this.expectations[expectation], i = 0, exp; exp = exps[i++];)
        this.expect(object, expectation, exp);
  }
};

LSD.Behavior = new LSD.Behavior;<|endoftext|>


<commit_before>/**
 * @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
 * For licensing, see LICENSE.html or http://ckeditor.com/license
 */
(function() {
    CKEDITOR.plugins.addExternal('readmore','extras/readmore/', 'plugin.js');
    CKEDITOR.plugins.addExternal('images','extras/images/', 'plugin.js');
    CKEDITOR.plugins.addExternal('autosave','extras/autosave/', 'plugin.js');
    CKEDITOR.plugins.addExternal('files','extras/files/', 'plugin.js');
    //CKEDITOR.plugins.addExternal('links','extras/links/', 'plugin.js');
})();

CKEDITOR.editorConfig = function( config ) {

	// Define changes to default configuration here. For example:
	// config.language = 'fr';
	// config.uiColor = '#AADC6E';

    config.extraPlugins = 'codemirror,readmore,autosave,images,onchange,files';
    // wee need to remove the default image and link plugins for the custom plugin's to work properly

    config.protectedSource.push( /<\?[\s\S]*?\?>/g );
    config.autosave_delay = '10';
    config.codemirror = {
        theme: 'default',
        lineNumbers: true,
        lineWrapping: true,
        matchBrackets: true,
        autoCloseTags: true,
        autoCloseBrackets: true,
        enableSearchTools: true, // Whether or not to enable search tools, CTRL+F (Find), CTRL+SHIFT+F (Replace), CTRL+SHIFT+R (Replace All), CTRL+G (Find Next), CTRL+SHIFT+G (Find Previous)
        enableCodeFolding: true,
        enableCodeFormatting: true,
        autoFormatOnStart: true,
        autoFormatOnUncomment: true,
        highlightActiveLine: true,
        highlightMatches: true,
        showFormatButton: true,
        showCommentButton: true,
        showUncommentButton: true
    };

    config.allowedContent = true;
    config.toolbar_full =
        [
            { name: 'document', items : [ 'Source','-','Save','NewPage','DocProps','Preview','Print','-','Templates' ] },
            { name: 'clipboard', items : [ 'Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo' ] },
            { name: 'editing', items : [ 'Find','Replace','-','SelectAll','-','SpellChecker', 'Scayt' ] },
            { name: 'forms', items : [ 'Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton',
                'HiddenField' ] },
            '/',
            { name: 'basicstyles', items : [ 'Bold','Italic','Underline','Strike','Subscript','Superscript','-','RemoveFormat' ] },
            { name: 'paragraph', items : [ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote','CreateDiv',
                '-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','BidiLtr','BidiRtl' ] },
            { name: 'links', items : [ 'Link','Unlink','Anchor' ] },
            { name: 'insert', items : [ 'images','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak','Iframe' ] },
            '/',
            { name: 'styles', items : [ 'Styles','Format','Font','FontSize' ] },
            { name: 'colors', items : [ 'TextColor','BGColor' ] },
            { name: 'tools', items : [ 'Maximize', 'ShowBlocks','-','readmore' ] }
        ];

    config.toolbar_basic =
        [
            ['Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink','-','HorizontalRule','readmore','images']
        ];

    config.toolbar_standard =
        [
            { name: 'styles', items: [ 'Styles' ] },
            { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'Bold', 'Italic' ] },
            { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align' ], items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent' ] },
            { name: 'links', items: [ 'readmore' ] },
            { name: 'insert', items: [ 'images', 'files','Link','Unlink' ,'Table' ] },
            { name: 'clipboard', groups: [ 'clipboard', 'undo' ], items: [ 'PasteText', '-', 'Undo', 'Redo' ] },
            { name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ], items: [ 'Scayt' ] },
            { name: 'document', groups: [ 'mode', 'document', 'doctools' ], items: [ 'Source' ] }
        ];
    config.toolbar_title =
        [
            ['Undo','Redo']
        ];
};
<commit_msg>Removed "Link Dialog" plugin completely re #386<commit_after>/**
 * @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
 * For licensing, see LICENSE.html or http://ckeditor.com/license
 */
(function() {
    CKEDITOR.plugins.addExternal('readmore','extras/readmore/', 'plugin.js');
    CKEDITOR.plugins.addExternal('images','extras/images/', 'plugin.js');
    CKEDITOR.plugins.addExternal('autosave','extras/autosave/', 'plugin.js');
    CKEDITOR.plugins.addExternal('files','extras/files/', 'plugin.js');
})();

CKEDITOR.editorConfig = function( config ) {

	// Define changes to default configuration here. For example:
	// config.language = 'fr';
	// config.uiColor = '#AADC6E';

    config.extraPlugins = 'codemirror,readmore,autosave,images,onchange,files';
    // wee need to remove the default image and link plugins for the custom plugin's to work properly

    config.protectedSource.push( /<\?[\s\S]*?\?>/g );
    config.autosave_delay = '10';
    config.codemirror = {
        theme: 'default',
        lineNumbers: true,
        lineWrapping: true,
        matchBrackets: true,
        autoCloseTags: true,
        autoCloseBrackets: true,
        enableSearchTools: true, // Whether or not to enable search tools, CTRL+F (Find), CTRL+SHIFT+F (Replace), CTRL+SHIFT+R (Replace All), CTRL+G (Find Next), CTRL+SHIFT+G (Find Previous)
        enableCodeFolding: true,
        enableCodeFormatting: true,
        autoFormatOnStart: true,
        autoFormatOnUncomment: true,
        highlightActiveLine: true,
        highlightMatches: true,
        showFormatButton: true,
        showCommentButton: true,
        showUncommentButton: true
    };

    config.allowedContent = true;
    config.toolbar_full =
        [
            { name: 'document', items : [ 'Source','-','Save','NewPage','DocProps','Preview','Print','-','Templates' ] },
            { name: 'clipboard', items : [ 'Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo' ] },
            { name: 'editing', items : [ 'Find','Replace','-','SelectAll','-','SpellChecker', 'Scayt' ] },
            { name: 'forms', items : [ 'Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton',
                'HiddenField' ] },
            '/',
            { name: 'basicstyles', items : [ 'Bold','Italic','Underline','Strike','Subscript','Superscript','-','RemoveFormat' ] },
            { name: 'paragraph', items : [ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote','CreateDiv',
                '-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','BidiLtr','BidiRtl' ] },
            { name: 'links', items : [ 'Link','Unlink','Anchor' ] },
            { name: 'insert', items : [ 'images','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak','Iframe' ] },
            '/',
            { name: 'styles', items : [ 'Styles','Format','Font','FontSize' ] },
            { name: 'colors', items : [ 'TextColor','BGColor' ] },
            { name: 'tools', items : [ 'Maximize', 'ShowBlocks','-','readmore' ] }
        ];

    config.toolbar_basic =
        [
            ['Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink','-','HorizontalRule','readmore','images']
        ];

    config.toolbar_standard =
        [
            { name: 'styles', items: [ 'Styles' ] },
            { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'Bold', 'Italic' ] },
            { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align' ], items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent' ] },
            { name: 'links', items: [ 'readmore' ] },
            { name: 'insert', items: [ 'images', 'files','Link','Unlink' ,'Table' ] },
            { name: 'clipboard', groups: [ 'clipboard', 'undo' ], items: [ 'PasteText', '-', 'Undo', 'Redo' ] },
            { name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ], items: [ 'Scayt' ] },
            { name: 'document', groups: [ 'mode', 'document', 'doctools' ], items: [ 'Source' ] }
        ];
    config.toolbar_title =
        [
            ['Undo','Redo']
        ];
};
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 Memorial Sloan-Kettering Cancer Center.
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation; either version 2.1 of the License, or
 * any later version.
 *
 * This library 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.  The software and
 * documentation provided hereunder is on an "as is" basis, and
 * Memorial Sloan-Kettering Cancer Center
 * has no obligations to provide maintenance, support,
 * updates, enhancements or modifications.  In no event shall
 * Memorial Sloan-Kettering Cancer Center
 * be liable to any party for direct, indirect, special,
 * incidental or consequential damages, including lost profits, arising
 * out of the use of this software and its documentation, even if
 * Memorial Sloan-Kettering Cancer Center
 * has been advised of the possibility of such damage.  See
 * the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, write to the Free Software Foundation,
 * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
 */

var plotsTab = (function() {

    var append_view_switch_opt = function() {
        $("#" + ids.sidebar.util.view_switch).empty();

        var stat = plotsData.stat();
        var tmp = setInterval(function () {timer();}, 1000);
        function timer() {
            if (metaData.getRetrieveStatus() !== -1 && stat.retrieved) {
                clearInterval(tmp);
                append();
            }
        }
        function append() {
            if (genetic_vs_genetic()) {
                if(isSameGene()) {
                    if (stat.hasCnaAnno) {
                        $("#" + ids.sidebar.util.view_switch).append(
                            "
View
" +
                            "<input type='radio' value='mutation_details' name='mutation_details_vs_gistic_view' checked>Mutation Details" +
                            "<input type='radio' value='gistic' name='mutation_details_vs_gistic_view' >GISTIC"
                        );
                    }
                }
            }
        }
    };

    return {
        init: function() {

            //init logic
            $("#" + ids.main_view.div).empty();
            appendLoadingImg(ids.main_view.div);

            metaData.fetch();
            sidebar.init();
            plotsData.fetch("x");
            plotsData.fetch("y");
            plotsbox.init();
            append_view_switch_opt();

            //apply event listening logic
            $( "#" + ids.sidebar.x.div ).bind({
                change: function() {
                    $("#" + ids.main_view.div).empty();
                    appendLoadingImg(ids.main_view.div);
                    plotsData.fetch("x");
                    append_view_switch_opt();
                    plotsbox.init();
                }
            });
            $( "#" + ids.sidebar.y.div ).bind({
                change: function() {
                    $("#" + ids.main_view.div).empty();
                    appendLoadingImg(ids.main_view.div);
                    plotsData.fetch("y");
                    append_view_switch_opt();
                    plotsbox.init();
                }
            });
            $("#" + ids.sidebar.util.view_switch).bind({
                change: function() {
                    $("#" + ids.main_view.div).empty();
                    appendLoadingImg(ids.main_view.div);
                    plotsData.fetch("x");
                    plotsData.fetch("y");
                    plotsbox.init();
                }
            });

        }

    };
}());
<commit_msg>Rename GISTIC to copy-number and mutation details to mutation type<commit_after>/*
 * Copyright (c) 2012 Memorial Sloan-Kettering Cancer Center.
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation; either version 2.1 of the License, or
 * any later version.
 *
 * This library 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.  The software and
 * documentation provided hereunder is on an "as is" basis, and
 * Memorial Sloan-Kettering Cancer Center
 * has no obligations to provide maintenance, support,
 * updates, enhancements or modifications.  In no event shall
 * Memorial Sloan-Kettering Cancer Center
 * be liable to any party for direct, indirect, special,
 * incidental or consequential damages, including lost profits, arising
 * out of the use of this software and its documentation, even if
 * Memorial Sloan-Kettering Cancer Center
 * has been advised of the possibility of such damage.  See
 * the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, write to the Free Software Foundation,
 * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
 */

var plotsTab = (function() {

    var append_view_switch_opt = function() {
        $("#" + ids.sidebar.util.view_switch).empty();

        var stat = plotsData.stat();
        var tmp = setInterval(function () {timer();}, 1000);
        function timer() {
            if (metaData.getRetrieveStatus() !== -1 && stat.retrieved) {
                clearInterval(tmp);
                append();
            }
        }
        function append() {
            if (genetic_vs_genetic()) {
                if(isSameGene()) {
                    if (stat.hasCnaAnno) {
                        $("#" + ids.sidebar.util.view_switch).append(
                            "
View
" +
                            "<input type='radio' value='mutation_details' name='mutation_details_vs_gistic_view' checked>Mutation Type" +
                            "<input type='radio' value='gistic' name='mutation_details_vs_gistic_view' >Copy-number"
                        );
                    }
                }
            }
        }
    };

    return {
        init: function() {

            //init logic
            $("#" + ids.main_view.div).empty();
            appendLoadingImg(ids.main_view.div);

            metaData.fetch();
            sidebar.init();
            plotsData.fetch("x");
            plotsData.fetch("y");
            plotsbox.init();
            append_view_switch_opt();

            //apply event listening logic
            $( "#" + ids.sidebar.x.div ).bind({
                change: function() {
                    $("#" + ids.main_view.div).empty();
                    appendLoadingImg(ids.main_view.div);
                    plotsData.fetch("x");
                    append_view_switch_opt();
                    plotsbox.init();
                }
            });
            $( "#" + ids.sidebar.y.div ).bind({
                change: function() {
                    $("#" + ids.main_view.div).empty();
                    appendLoadingImg(ids.main_view.div);
                    plotsData.fetch("y");
                    append_view_switch_opt();
                    plotsbox.init();
                }
            });
            $("#" + ids.sidebar.util.view_switch).bind({
                change: function() {
                    $("#" + ids.main_view.div).empty();
                    appendLoadingImg(ids.main_view.div);
                    plotsData.fetch("x");
                    plotsData.fetch("y");
                    plotsbox.init();
                }
            });

        }

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


<commit_before>angular.module('Aggie')
.controller('SettingsModalController', [
  '$scope',
  '$modal',
  function($scope, $modal) {
    $scope.edit = function(item, settings, set) {
      var modalInstance = $modal.open({
        controller: 'SettingsModalInstanceController',
        templateUrl: 'templates/' + set + '-settings-modal.html',
        resolve: {
          item: function() {
            return item;
          },
          settingsValues: function() {
            return settings;
          }
        }
      });
    };
  }])
.controller('SettingsModalInstanceController', [
  '$scope',
  '$modalInstance',
  'Settings',
  'FlashService',
  'settingsValues',
  'item',
  '$resource',
  '$filter',
  'tz',
  function($scope, $modalInstance, Settings, flash, settings, item, $resource, $filter, tz) {
    $scope.settings = settings;
    $scope.item = item;
    $scope._showErrors = false;
    $scope.loading = false;
    $scope.minimalLatLng = true;

    $scope.save = function(form, itemName, settings) {
      Settings.set(itemName, settings, success(itemName, 'saved'), failure);
      $modalInstance.close();
    };

    $scope.delete = function(itemName, settings) {

      for (var setting in settings) {
        settings[setting] = '';
      }

      Settings.set(itemName, settings, success(itemName, 'deleted'), failure);
      $modalInstance.close();
    };

    $scope.close = function() {
      $modalInstance.dismiss('cancel');
    };

    $scope.download = function(before, after) {
    var url = "/api/v1/viz";
    var afterDate = "";

    if(after === undefined){
      afterDate = "2000-01-01T00:00:00.000Z"
    }
    else{
      afterDate = before + ":00.277Z";
    }
    if(before === undefined){
      var today = new Date();
      var bString = today.getFullYear() + "-" + String(today.getMonth() + 1).padStart(2, '0') +"-"+ String(today.getDate()).padStart(2, '0') + "T00:00:00.000Z";
      url = url.concat("/?before=" + bString + "&after=" + afterDate);
    }
    else{
      url = url.concat("/?before=" + before + "&after=" + afterDate  + ":00.277Z");
    }

    console.log(url);
    //gets reports from viz code
    $resource(url).get().$promise.then(function(res){ //success function
      var toWrite = "author \t authoredAt \t content \t fetchedAt \t flagged \t read \t tags \t url \t media";
      for(i=0; i < res.reports.length; i++) {
        //for each of the given rows, remove line breaks/tabs to correcly format output
        //output is a tsv, since commas frequently show up in plain
        var newString = "\n" + res.reports[i].author.replace(/(?:\r\n|\r|\n)/g, ' ') + "\t" +
                                res.reports[i].authoredAt.replace(/(?:\r\n|\r|\n)/g,' ') + "\t"+
                                res.reports[i].content.replace(/(?:\r\n|\r|\n)/g,' ') + "\t"+
                                res.reports[i].fetchedAt.replace(/(?:\r\n|\r|\n)/g,' ') + "\t"+
                                res.reports[i].flagged +"\t"+
                                res.reports[i].read +"\t"+
                                res.reports[i].tags[0].replace(/(?:\r\n|\r|\n)/g,' ') + "\t"+
                                res.reports[i].url.replace('\t','') +"\t"+
                                res.reports[i]._media[0].replace(/(?:\r\n|\r|\n)/g,' ');
        toWrite = toWrite.concat(newString);
      }
      var hiddenElement = document.createElement('a');
      hiddenElement.href = 'data:text/tsv;charset=utf-8,' + encodeURIComponent(toWrite);
      hiddenElement.target = '_blank';
      hiddenElement.download = 'reports.tsv';
      hiddenElement.click();
      $modalInstance.close();
    }, function(error){ //error function
      console.log(error);
      $modalInstance.close();
    })
    };

    function success(itemName, verb) {
      flash.setNoticeNow('settings.settingsModal.success',
                         { itemName: $filter('capitalize')(itemName),
                           verb: verb });
    }

    function failure(data) {
      flash.setAlertNow('settings.settingsModal.error');
      console.log('failure: ', data);
    }

    $scope.test = function(mediaName, settings) {
      $scope.success = false;
      $scope.failure = false;
      $scope.loading = true;
      Settings.test('media', mediaName, settings, successTest, failureTest);
    };

    function successTest(response) {
      $scope.loading = false;

      if (response.success) {
        $scope.success = true;
      } else {
        $scope.failure = true;
        $scope.message = response.message;
      }
    }

    function failureTest(data) {
      $scope.loading = false;

      $scope.failure = true;
      $scope.message = data.message;
    }

    $scope.$watch('details.geometry.location', function(newVal, oldVal) {
      if (oldVal === newVal) return;
      $scope.settings['latitude'] = $scope.details.geometry.location.lat();
      $scope.settings['longitude'] = $scope.details.geometry.location.lng();
    });
  }
]);<commit_msg>Fixed Date Range<commit_after>angular.module('Aggie')
.controller('SettingsModalController', [
  '$scope',
  '$modal',
  function($scope, $modal) {
    $scope.edit = function(item, settings, set) {
      var modalInstance = $modal.open({
        controller: 'SettingsModalInstanceController',
        templateUrl: 'templates/' + set + '-settings-modal.html',
        resolve: {
          item: function() {
            return item;
          },
          settingsValues: function() {
            return settings;
          }
        }
      });
    };
  }])
.controller('SettingsModalInstanceController', [
  '$scope',
  '$modalInstance',
  'Settings',
  'FlashService',
  'settingsValues',
  'item',
  '$resource',
  '$filter',
  'tz',
  function($scope, $modalInstance, Settings, flash, settings, item, $resource, $filter, tz) {
    $scope.settings = settings;
    $scope.item = item;
    $scope._showErrors = false;
    $scope.loading = false;
    $scope.minimalLatLng = true;

    $scope.save = function(form, itemName, settings) {
      Settings.set(itemName, settings, success(itemName, 'saved'), failure);
      $modalInstance.close();
    };

    $scope.delete = function(itemName, settings) {

      for (var setting in settings) {
        settings[setting] = '';
      }

      Settings.set(itemName, settings, success(itemName, 'deleted'), failure);
      $modalInstance.close();
    };

    $scope.close = function() {
      $modalInstance.dismiss('cancel');
    };

    $scope.download = function(before, after) {
    var url = "/api/v1/viz";
    var afterDate = "";

    if(after === undefined){
      afterDate = "2000-01-01T00:00:00.000Z"
    }
    else{
      afterDate = after + ":00.277Z";
    }
    if(before === undefined){
      var today = new Date();
      var bString = today.getFullYear() + "-" + String(today.getMonth() + 1).padStart(2, '0') +"-"+ String(today.getDate()).padStart(2, '0') + "T00:00:00.000Z";
      url = url.concat("/?before=" + bString + "&after=" + afterDate);
    }
    else{
      url = url.concat("/?before=" + before + ":00.277Z" + "&after=" + afterDate);
    }

    console.log(url);
    //gets reports from viz code
    $resource(url).get().$promise.then(function(res){ //success function
      var toWrite = "author \t authoredAt \t content \t fetchedAt \t flagged \t read \t tags \t url \t media";
      for(i=0; i < res.reports.length; i++) {
        //for each of the given rows, remove line breaks/tabs to correcly format output
        //output is a tsv, since commas frequently show up in plain
        var newString = "\n" + res.reports[i].author.replace(/(?:\r\n|\r|\n)/g, ' ') + "\t" +
                                res.reports[i].authoredAt.replace(/(?:\r\n|\r|\n)/g,' ') + "\t"+
                                res.reports[i].content.replace(/(?:\r\n|\r|\n)/g,' ') + "\t"+
                                res.reports[i].fetchedAt.replace(/(?:\r\n|\r|\n)/g,' ') + "\t"+
                                res.reports[i].flagged +"\t"+
                                res.reports[i].read +"\t"+
                                res.reports[i].tags[0].replace(/(?:\r\n|\r|\n)/g,' ') + "\t"+
                                res.reports[i].url.replace('\t','') +"\t"+
                                res.reports[i]._media[0].replace(/(?:\r\n|\r|\n)/g,' ');
        toWrite = toWrite.concat(newString);
      }
      var hiddenElement = document.createElement('a');
      hiddenElement.href = 'data:text/tsv;charset=utf-8,' + encodeURIComponent(toWrite);
      hiddenElement.target = '_blank';
      hiddenElement.download = 'reports.tsv';
      hiddenElement.click();
      $modalInstance.close();
    }, function(error){ //error function
      console.log(error);
      $modalInstance.close();
    })
    };

    function success(itemName, verb) {
      flash.setNoticeNow('settings.settingsModal.success',
                         { itemName: $filter('capitalize')(itemName),
                           verb: verb });
    }

    function failure(data) {
      flash.setAlertNow('settings.settingsModal.error');
      console.log('failure: ', data);
    }

    $scope.test = function(mediaName, settings) {
      $scope.success = false;
      $scope.failure = false;
      $scope.loading = true;
      Settings.test('media', mediaName, settings, successTest, failureTest);
    };

    function successTest(response) {
      $scope.loading = false;

      if (response.success) {
        $scope.success = true;
      } else {
        $scope.failure = true;
        $scope.message = response.message;
      }
    }

    function failureTest(data) {
      $scope.loading = false;

      $scope.failure = true;
      $scope.message = data.message;
    }

    $scope.$watch('details.geometry.location', function(newVal, oldVal) {
      if (oldVal === newVal) return;
      $scope.settings['latitude'] = $scope.details.geometry.location.lat();
      $scope.settings['longitude'] = $scope.details.geometry.location.lng();
    });
  }
]);<|endoftext|>


<commit_before>function injectedScript() {

	'use strict';

	var ViveData = {
		name: 'Emulated HTC Vive DVT',
		resolution: { width: 1512, height: 1680 },
		features: { canPresent: true, hasExternalDisplay: true, hasOrientation: true, hasPosition: true },
		leftEye: { offset: -0.032, up: 41.653, down: 48.008, left: 43.977, right: 35.575 },
		rightEye: { offset: 0.032, up: 41.653, down: 48.008, left: 35.575, right: 43.977 }
	}

	var RiftData = {
		name: 'Emulated Oculus Rift CV1',
		resolution: { width: 1332, height: 1586 },
		features: { canPresent: true, hasExternalDisplay: true, hasOrientation: true, hasPosition: true },
		leftEye: { offset: -0.032, up: 55.814, down: 55.728, left: 54.429, right: 51.288 },
		rightEye: { offset: 0.032, up: 55.687, down: 55.658, left: 51.110, right: 54.397 }
	}

	var CardboardData = {
		name: 'Emulated Google, Inc. Cardboard v1',
		resolution: { width: 960, height: 1080 },
		features: { canPresent: true, hasExternalDisplay: false, hasOrientation: true, hasPosition: false },
		leftEye: { offset: -0.030, up: 40, down: 40, left: 40, right: 40 },
		rightEye: { offset: 0.030, up: 40, down: 40, left: 40, right: 40 }
	}

	var startDate = Date.now();
	var startPerfNow = performance.now();
	var currentLayers = [];

	// WebVR 1.0

	function VRDisplayCapabilities () {

		this.canPresent = true;
		this.hasExternalDisplay = true;
		this.hasOrientation = true;
		this.hasPosition = true;
		this.maxLayers = 1

	}

	function VRStageParameters() {

		this.sittingToStandingTransform = new Float32Array( [
			1, 0, 0, 0,
			0, 1, 0, 0,
			0, 0, 1, 0,
			0, 0, 0, 1
		] );

		this.sizeX = 5;
		this.sizeZ = 3;

	}

	function VRPose() {

		this.timestamp = startDate + ( performance.now() - startPerfNow );
		this.position = new Float32Array( [ 0, 0, 0 ] );
		this.linearVelocity = new Float32Array( [ 0, 0, 0 ] );
		this.linearAcceleration = null;
		this.orientation = new Float32Array( [ 0, 0, 0, 1 ] );
		this.angularVelocity = new Float32Array( [ 0, 0, 0 ] );
		this.angularAcceleration = null;

	}

	function VRFieldOfView() {

		this.upDegrees = 0;
		this.downDegrees = 0;
		this.leftDegrees = 0;
		this.rightDegrees = 0;

	}

	function VREyeParameters() {

		this.offset = new Float32Array( [ 0, 0, 0 ] );
		this.fieldOfView = new VRFieldOfView();
		this.renderWidth = 0;
		this.renderHeight = 0;

	}

	function createVRDisplayEvent( type, display, reason ) {

		var event = new CustomEvent( type );
		event.display = display;
		event.reason = reason;

		return event;

	}

	function VRDisplay( model ) {

		this.depthFar = 1000;
		this.depthNear = .1;
		this.displayId = 1;
		this.displayName = model.name;
		this.isConnected = true;
		this.isPresenting = false;

		this.stageParameters = new VRStageParameters();

		this.capabilities = new VRDisplayCapabilities();
		this.capabilities.canPresent = model.features.canPresent;
		this.capabilities.hasExternalDisplay = model.features.hasExternalDisplay;
		this.capabilities.hasOrientation = model.features.hasOrientation;
		this.capabilities.hasPosition = model.features.hasPosition;

		this.pose = new VRPose();

		this.leftEyeParameters = new VREyeParameters();
		this.leftEyeParameters.fieldOfView.upDegrees = model.leftEye.up;
		this.leftEyeParameters.fieldOfView.downDegrees = model.leftEye.down;
		this.leftEyeParameters.fieldOfView.leftDegrees = model.leftEye.left;
		this.leftEyeParameters.fieldOfView.rightDegrees = model.leftEye.right;
		this.leftEyeParameters.renderWidth = model.resolution.width;
		this.leftEyeParameters.renderHeight = model.resolution.height;
		this.leftEyeParameters.offset[ 0 ] = model.leftEye.offset;

		this.rightEyeParameters = new VREyeParameters();
		this.rightEyeParameters.fieldOfView.upDegrees = model.rightEye.up;
		this.rightEyeParameters.fieldOfView.downDegrees = model.rightEye.down;
		this.rightEyeParameters.fieldOfView.leftDegrees = model.rightEye.left;
		this.rightEyeParameters.fieldOfView.rightDegrees = model.rightEye.right;
		this.rightEyeParameters.renderWidth = model.resolution.width;
		this.rightEyeParameters.renderHeight = model.resolution.height;
		this.rightEyeParameters.offset[ 0 ] = model.rightEye.offset;

		window.addEventListener( 'webvr-pose', function( e ) {

			this.pose.linearVelocity[ 0 ] = e.detail.position.x - this.pose.position[ 0 ];
			this.pose.linearVelocity[ 1 ] = e.detail.position.y - this.pose.position[ 1 ];
			this.pose.linearVelocity[ 2 ] = e.detail.position.z - this.pose.position[ 2 ];

			this.pose.position[ 0 ] = e.detail.position.x;
			this.pose.position[ 1 ] = e.detail.position.y;
			this.pose.position[ 2 ] = e.detail.position.z;

			this.pose.orientation[ 0 ] = e.detail.rotation.x;
			this.pose.orientation[ 1 ] = e.detail.rotation.y;
			this.pose.orientation[ 2 ] = e.detail.rotation.z;
			this.pose.orientation[ 3 ] = e.detail.rotation.w;

		}.bind( this ) );

		window.addEventListener( 'webvr-hmd-activate', function( e ) {

			if( e.detail.state ){
				var event = createVRDisplayEvent( 'vrdisplayactivate', this, 'HMD activated' );
				window.dispatchEvent(event);
			} else {
				var event = createVRDisplayEvent( 'vrdisplaydeactivate', this, 'HMD deactivated' );
				window.dispatchEvent(event);
			}

		}.bind( this ) );

	}

	VRDisplay.prototype.requestAnimationFrame = function( c ) {

		return requestAnimationFrame( c );

	}

	VRDisplay.prototype.cancelAnimationFrame = function(handle) {

		cancelAnimationFrame(handle);

	}

	VRDisplay.prototype.getEyeParameters = function( id ) {

		if( id === 'left' ) return this.leftEyeParameters;
		return this.rightEyeParameters;

	}

	VRDisplay.prototype.getPose = function() {

		this.pose.timestamp = startDate + ( performance.now() - startPerfNow );

		return this.pose;

	}

	VRDisplay.prototype.requestPresent = function(layers) {

		return new Promise( function( resolve, reject ) {

			this.isPresenting = true;

			currentLayers = layers;

			var event = createVRDisplayEvent( 'vrdisplaypresentchange', this, 'Presenting requested' );
			window.dispatchEvent(event);

			resolve();

		}.bind( this ) );

	}

	VRDisplay.prototype.exitPresent = function() {

		return new Promise( function( resolve, reject ) {

			this.isPresenting = false;

			currentLayers = [];

			var event = createVRDisplayEvent( 'vrdisplaypresentchange', this, 'Presenting exited' );
			window.dispatchEvent(event);

			resolve();

		}.bind( this ) );

	}

	VRDisplay.prototype.submitFrame = function( pose ) {
	}

	VRDisplay.prototype.resetPose = function() {

		var event = new Event( 'webvr-resetpose' );
		window.dispatchEvent( event );

	}

	VRDisplay.prototype.getLayers = function() {

		return currentLayers;

	}

	window.VRDisplay = VRDisplay;

	( function() {

		var vrD = new VRDisplay( ViveData )

		navigator.getVRDisplays = function() {

			return new Promise( function( resolve, reject ) {

				resolve( [ vrD ] );

			} );

		}

	} )();

	// LEGACY

	function HMDVRDevice( model ) {

		this.deviceName = model.name;

		this.leftEyeParameters = new VREyeParameters();
		this.leftEyeParameters.fieldOfView.upDegrees = model.leftEye.up;
		this.leftEyeParameters.fieldOfView.downDegrees = model.leftEye.down;
		this.leftEyeParameters.fieldOfView.leftDegrees = model.leftEye.left;
		this.leftEyeParameters.fieldOfView.rightDegrees = model.leftEye.right;
		this.leftEyeParameters.renderWidth = model.resolution.width;
		this.leftEyeParameters.renderHeight = model.resolution.height;
		this.leftEyeParameters.offset[ 0 ] = model.leftEye.offset;

		this.rightEyeParameters = new VREyeParameters();
		this.rightEyeParameters.fieldOfView.upDegrees = model.rightEye.up;
		this.rightEyeParameters.fieldOfView.downDegrees = model.rightEye.down;
		this.rightEyeParameters.fieldOfView.leftDegrees = model.rightEye.left;
		this.rightEyeParameters.fieldOfView.rightDegrees = model.rightEye.right;
		this.rightEyeParameters.renderWidth = model.resolution.width;
		this.rightEyeParameters.renderHeight = model.resolution.height;
		this.rightEyeParameters.offset[ 0 ] = model.rightEye.offset;

		this.leftRecommendedFOV = new VREyeParameters();
		this.leftRecommendedFOV.fieldOfView.upDegrees = model.leftEye.up;
		this.leftRecommendedFOV.fieldOfView.downDegrees = model.leftEye.down;
		this.leftRecommendedFOV.fieldOfView.leftDegrees = model.leftEye.left;
		this.leftRecommendedFOV.fieldOfView.rightDegrees = model.leftEye.right;
		this.leftRecommendedFOV.renderWidth = model.resolution.width;
		this.leftRecommendedFOV.renderHeight = model.resolution.height;
		this.leftRecommendedFOV.offset[ 0 ] = model.leftEye.offset;

		this.rightRecommendedFOV = new VREyeParameters();
		this.rightRecommendedFOV.fieldOfView.upDegrees = model.rightEye.up;
		this.rightRecommendedFOV.fieldOfView.downDegrees = model.rightEye.down;
		this.rightRecommendedFOV.fieldOfView.leftDegrees = model.rightEye.left;
		this.rightRecommendedFOV.fieldOfView.rightDegrees = model.rightEye.right;
		this.rightRecommendedFOV.renderWidth = model.resolution.width;
		this.rightRecommendedFOV.renderHeight = model.resolution.height;
		this.rightRecommendedFOV.offset[ 0 ] = model.rightEye.offset;

	}

	HMDVRDevice.prototype.getEyeTranslation = function( eye ) {

		return 3;

	}

	HMDVRDevice.prototype.getRecommendedEyeFieldOfView = function( eye ) {

		if( eye === 'left' ) return this.leftRecommendedFOV;
		return this.rightRecommendedFOV;

	}

	function VRFieldOfView() {

		this.upDegrees = 0;
		this.downDegrees = 0;
		this.leftDegrees = 0;
		this.rightDegrees = 0;

	}

	function VREyeParameters() {

		this.eyeTranslation = 0;
		this.recommendedFieldOfView = new VRFieldOfView();
		this.offset = new Float32Array( [ 0, 0, 0 ] );
		this.fieldOfView = new VRFieldOfView();
		this.renderWidth = 0;
		this.renderHeight = 0;

	}

	HMDVRDevice.prototype.getEyeParameters = function( eye ) {

		if( eye === 'left' ) return this.leftEyeParameters;
		return this.rightEyeParameters;

	}

	function PositionSensorVRDevice( model ) {

		this.deviceName = model.name;

		this.state = new VRPositionState( model );

		window.addEventListener( 'webvr-pose', function( e ) {

			this.state.linearVelocity.x = e.detail.position.x - this.state.position.x;
			this.state.linearVelocity.y = e.detail.position.y - this.state.position.y;
			this.state.linearVelocity.z = e.detail.position.z - this.state.position.z;

			this.state.position.x = e.detail.position.x;
			this.state.position.y = e.detail.position.y;
			this.state.position.z = e.detail.position.z;

			this.state.orientation.x = e.detail.rotation.x;
			this.state.orientation.y = e.detail.rotation.y;
			this.state.orientation.z = e.detail.rotation.z;
			this.state.orientation.w = e.detail.rotation.w;

		}.bind( this ) );

	}

	function VRPositionState( model ) {

		this.angularAcceleration = new DOMPoint();
		this.angularVelocity = new DOMPoint();
		this.linearAcceleration = new DOMPoint();
		this.linearVelocity = new DOMPoint();
		this.orientation = new DOMPoint();
		this.position = new DOMPoint();
		this.timestamp = null;

		this.hasPosition = model.features.hasPosition;
		this.hasOrientation = model.features.hasOrientation;

	}

	function DOMPoint() {
		this.x = 0;
		this.y = 0;
		this.z = 0;
		this.w = 0;
	}

	PositionSensorVRDevice.prototype.getState = function() {

		this.state.timestamp = startDate + ( performance.now() - startPerfNow );

		return this.state;

	}

	window.HMDVRDevice = HMDVRDevice;
	window.PositionSensorVRDevice = PositionSensorVRDevice;

	window.VRDisplay = VRDisplay;

	( function() {

		var vrD = new HMDVRDevice( ViveData );
		var vrP = new PositionSensorVRDevice( ViveData );

		navigator.getVRDevices = function() {

			return new Promise( function( resolve, reject ) {

				resolve( [ vrD, vrP ] );

			} );

		}

	} )();

	var event = new Event( 'webvr-ready' );
	window.dispatchEvent( event );

}
<commit_msg>currentLayers now pseudo-private on VRDisplay<commit_after>function injectedScript() {

	'use strict';

	var ViveData = {
		name: 'Emulated HTC Vive DVT',
		resolution: { width: 1512, height: 1680 },
		features: { canPresent: true, hasExternalDisplay: true, hasOrientation: true, hasPosition: true },
		leftEye: { offset: -0.032, up: 41.653, down: 48.008, left: 43.977, right: 35.575 },
		rightEye: { offset: 0.032, up: 41.653, down: 48.008, left: 35.575, right: 43.977 }
	}

	var RiftData = {
		name: 'Emulated Oculus Rift CV1',
		resolution: { width: 1332, height: 1586 },
		features: { canPresent: true, hasExternalDisplay: true, hasOrientation: true, hasPosition: true },
		leftEye: { offset: -0.032, up: 55.814, down: 55.728, left: 54.429, right: 51.288 },
		rightEye: { offset: 0.032, up: 55.687, down: 55.658, left: 51.110, right: 54.397 }
	}

	var CardboardData = {
		name: 'Emulated Google, Inc. Cardboard v1',
		resolution: { width: 960, height: 1080 },
		features: { canPresent: true, hasExternalDisplay: false, hasOrientation: true, hasPosition: false },
		leftEye: { offset: -0.030, up: 40, down: 40, left: 40, right: 40 },
		rightEye: { offset: 0.030, up: 40, down: 40, left: 40, right: 40 }
	}

	var startDate = Date.now();
	var startPerfNow = performance.now();

	// WebVR 1.0

	function VRDisplayCapabilities () {

		this.canPresent = true;
		this.hasExternalDisplay = true;
		this.hasOrientation = true;
		this.hasPosition = true;
		this.maxLayers = 1

	}

	function VRStageParameters() {

		this.sittingToStandingTransform = new Float32Array( [
			1, 0, 0, 0,
			0, 1, 0, 0,
			0, 0, 1, 0,
			0, 0, 0, 1
		] );

		this.sizeX = 5;
		this.sizeZ = 3;

	}

	function VRPose() {

		this.timestamp = startDate + ( performance.now() - startPerfNow );
		this.position = new Float32Array( [ 0, 0, 0 ] );
		this.linearVelocity = new Float32Array( [ 0, 0, 0 ] );
		this.linearAcceleration = null;
		this.orientation = new Float32Array( [ 0, 0, 0, 1 ] );
		this.angularVelocity = new Float32Array( [ 0, 0, 0 ] );
		this.angularAcceleration = null;

	}

	function VRFieldOfView() {

		this.upDegrees = 0;
		this.downDegrees = 0;
		this.leftDegrees = 0;
		this.rightDegrees = 0;

	}

	function VREyeParameters() {

		this.offset = new Float32Array( [ 0, 0, 0 ] );
		this.fieldOfView = new VRFieldOfView();
		this.renderWidth = 0;
		this.renderHeight = 0;

	}

	function createVRDisplayEvent( type, display, reason ) {

		var event = new CustomEvent( type );
		event.display = display;
		event.reason = reason;

		return event;

	}

	function VRDisplay( model ) {

		this.depthFar = 1000;
		this.depthNear = .1;
		this.displayId = 1;
		this.displayName = model.name;
		this.isConnected = true;
		this.isPresenting = false;
		this.__currentLayers = [];

		this.stageParameters = new VRStageParameters();

		this.capabilities = new VRDisplayCapabilities();
		this.capabilities.canPresent = model.features.canPresent;
		this.capabilities.hasExternalDisplay = model.features.hasExternalDisplay;
		this.capabilities.hasOrientation = model.features.hasOrientation;
		this.capabilities.hasPosition = model.features.hasPosition;

		this.pose = new VRPose();

		this.leftEyeParameters = new VREyeParameters();
		this.leftEyeParameters.fieldOfView.upDegrees = model.leftEye.up;
		this.leftEyeParameters.fieldOfView.downDegrees = model.leftEye.down;
		this.leftEyeParameters.fieldOfView.leftDegrees = model.leftEye.left;
		this.leftEyeParameters.fieldOfView.rightDegrees = model.leftEye.right;
		this.leftEyeParameters.renderWidth = model.resolution.width;
		this.leftEyeParameters.renderHeight = model.resolution.height;
		this.leftEyeParameters.offset[ 0 ] = model.leftEye.offset;

		this.rightEyeParameters = new VREyeParameters();
		this.rightEyeParameters.fieldOfView.upDegrees = model.rightEye.up;
		this.rightEyeParameters.fieldOfView.downDegrees = model.rightEye.down;
		this.rightEyeParameters.fieldOfView.leftDegrees = model.rightEye.left;
		this.rightEyeParameters.fieldOfView.rightDegrees = model.rightEye.right;
		this.rightEyeParameters.renderWidth = model.resolution.width;
		this.rightEyeParameters.renderHeight = model.resolution.height;
		this.rightEyeParameters.offset[ 0 ] = model.rightEye.offset;

		window.addEventListener( 'webvr-pose', function( e ) {

			this.pose.linearVelocity[ 0 ] = e.detail.position.x - this.pose.position[ 0 ];
			this.pose.linearVelocity[ 1 ] = e.detail.position.y - this.pose.position[ 1 ];
			this.pose.linearVelocity[ 2 ] = e.detail.position.z - this.pose.position[ 2 ];

			this.pose.position[ 0 ] = e.detail.position.x;
			this.pose.position[ 1 ] = e.detail.position.y;
			this.pose.position[ 2 ] = e.detail.position.z;

			this.pose.orientation[ 0 ] = e.detail.rotation.x;
			this.pose.orientation[ 1 ] = e.detail.rotation.y;
			this.pose.orientation[ 2 ] = e.detail.rotation.z;
			this.pose.orientation[ 3 ] = e.detail.rotation.w;

		}.bind( this ) );

		window.addEventListener( 'webvr-hmd-activate', function( e ) {

			if( e.detail.state ){
				var event = createVRDisplayEvent( 'vrdisplayactivate', this, 'HMD activated' );
				window.dispatchEvent(event);
			} else {
				var event = createVRDisplayEvent( 'vrdisplaydeactivate', this, 'HMD deactivated' );
				window.dispatchEvent(event);
			}

		}.bind( this ) );

	}

	VRDisplay.prototype.requestAnimationFrame = function( c ) {

		return requestAnimationFrame( c );

	}

	VRDisplay.prototype.cancelAnimationFrame = function(handle) {

		cancelAnimationFrame(handle);

	}

	VRDisplay.prototype.getEyeParameters = function( id ) {

		if( id === 'left' ) return this.leftEyeParameters;
		return this.rightEyeParameters;

	}

	VRDisplay.prototype.getPose = function() {

		this.pose.timestamp = startDate + ( performance.now() - startPerfNow );

		return this.pose;

	}

	VRDisplay.prototype.requestPresent = function(layers) {

		return new Promise( function( resolve, reject ) {

			this.isPresenting = true;

			this.__currentLayers = layers;

			var event = createVRDisplayEvent( 'vrdisplaypresentchange', this, 'Presenting requested' );
			window.dispatchEvent(event);

			resolve();

		}.bind( this ) );

	}

	VRDisplay.prototype.exitPresent = function() {

		return new Promise( function( resolve, reject ) {

			this.isPresenting = false;

			this.__currentLayers = [];

			var event = createVRDisplayEvent( 'vrdisplaypresentchange', this, 'Presenting exited' );
			window.dispatchEvent(event);

			resolve();

		}.bind( this ) );

	}

	VRDisplay.prototype.submitFrame = function( pose ) {
	}

	VRDisplay.prototype.resetPose = function() {

		var event = new Event( 'webvr-resetpose' );
		window.dispatchEvent( event );

	}

	VRDisplay.prototype.getLayers = function() {

		return currentLayers;

	}

	window.VRDisplay = VRDisplay;

	( function() {

		var vrD = new VRDisplay( ViveData )

		navigator.getVRDisplays = function() {

			return new Promise( function( resolve, reject ) {

				resolve( [ vrD ] );

			} );

		}

	} )();

	// LEGACY

	function HMDVRDevice( model ) {

		this.deviceName = model.name;

		this.leftEyeParameters = new VREyeParameters();
		this.leftEyeParameters.fieldOfView.upDegrees = model.leftEye.up;
		this.leftEyeParameters.fieldOfView.downDegrees = model.leftEye.down;
		this.leftEyeParameters.fieldOfView.leftDegrees = model.leftEye.left;
		this.leftEyeParameters.fieldOfView.rightDegrees = model.leftEye.right;
		this.leftEyeParameters.renderWidth = model.resolution.width;
		this.leftEyeParameters.renderHeight = model.resolution.height;
		this.leftEyeParameters.offset[ 0 ] = model.leftEye.offset;

		this.rightEyeParameters = new VREyeParameters();
		this.rightEyeParameters.fieldOfView.upDegrees = model.rightEye.up;
		this.rightEyeParameters.fieldOfView.downDegrees = model.rightEye.down;
		this.rightEyeParameters.fieldOfView.leftDegrees = model.rightEye.left;
		this.rightEyeParameters.fieldOfView.rightDegrees = model.rightEye.right;
		this.rightEyeParameters.renderWidth = model.resolution.width;
		this.rightEyeParameters.renderHeight = model.resolution.height;
		this.rightEyeParameters.offset[ 0 ] = model.rightEye.offset;

		this.leftRecommendedFOV = new VREyeParameters();
		this.leftRecommendedFOV.fieldOfView.upDegrees = model.leftEye.up;
		this.leftRecommendedFOV.fieldOfView.downDegrees = model.leftEye.down;
		this.leftRecommendedFOV.fieldOfView.leftDegrees = model.leftEye.left;
		this.leftRecommendedFOV.fieldOfView.rightDegrees = model.leftEye.right;
		this.leftRecommendedFOV.renderWidth = model.resolution.width;
		this.leftRecommendedFOV.renderHeight = model.resolution.height;
		this.leftRecommendedFOV.offset[ 0 ] = model.leftEye.offset;

		this.rightRecommendedFOV = new VREyeParameters();
		this.rightRecommendedFOV.fieldOfView.upDegrees = model.rightEye.up;
		this.rightRecommendedFOV.fieldOfView.downDegrees = model.rightEye.down;
		this.rightRecommendedFOV.fieldOfView.leftDegrees = model.rightEye.left;
		this.rightRecommendedFOV.fieldOfView.rightDegrees = model.rightEye.right;
		this.rightRecommendedFOV.renderWidth = model.resolution.width;
		this.rightRecommendedFOV.renderHeight = model.resolution.height;
		this.rightRecommendedFOV.offset[ 0 ] = model.rightEye.offset;

	}

	HMDVRDevice.prototype.getEyeTranslation = function( eye ) {

		return 3;

	}

	HMDVRDevice.prototype.getRecommendedEyeFieldOfView = function( eye ) {

		if( eye === 'left' ) return this.leftRecommendedFOV;
		return this.rightRecommendedFOV;

	}

	function VRFieldOfView() {

		this.upDegrees = 0;
		this.downDegrees = 0;
		this.leftDegrees = 0;
		this.rightDegrees = 0;

	}

	function VREyeParameters() {

		this.eyeTranslation = 0;
		this.recommendedFieldOfView = new VRFieldOfView();
		this.offset = new Float32Array( [ 0, 0, 0 ] );
		this.fieldOfView = new VRFieldOfView();
		this.renderWidth = 0;
		this.renderHeight = 0;

	}

	HMDVRDevice.prototype.getEyeParameters = function( eye ) {

		if( eye === 'left' ) return this.leftEyeParameters;
		return this.rightEyeParameters;

	}

	function PositionSensorVRDevice( model ) {

		this.deviceName = model.name;

		this.state = new VRPositionState( model );

		window.addEventListener( 'webvr-pose', function( e ) {

			this.state.linearVelocity.x = e.detail.position.x - this.state.position.x;
			this.state.linearVelocity.y = e.detail.position.y - this.state.position.y;
			this.state.linearVelocity.z = e.detail.position.z - this.state.position.z;

			this.state.position.x = e.detail.position.x;
			this.state.position.y = e.detail.position.y;
			this.state.position.z = e.detail.position.z;

			this.state.orientation.x = e.detail.rotation.x;
			this.state.orientation.y = e.detail.rotation.y;
			this.state.orientation.z = e.detail.rotation.z;
			this.state.orientation.w = e.detail.rotation.w;

		}.bind( this ) );

	}

	function VRPositionState( model ) {

		this.angularAcceleration = new DOMPoint();
		this.angularVelocity = new DOMPoint();
		this.linearAcceleration = new DOMPoint();
		this.linearVelocity = new DOMPoint();
		this.orientation = new DOMPoint();
		this.position = new DOMPoint();
		this.timestamp = null;

		this.hasPosition = model.features.hasPosition;
		this.hasOrientation = model.features.hasOrientation;

	}

	function DOMPoint() {
		this.x = 0;
		this.y = 0;
		this.z = 0;
		this.w = 0;
	}

	PositionSensorVRDevice.prototype.getState = function() {

		this.state.timestamp = startDate + ( performance.now() - startPerfNow );

		return this.state;

	}

	window.HMDVRDevice = HMDVRDevice;
	window.PositionSensorVRDevice = PositionSensorVRDevice;

	window.VRDisplay = VRDisplay;

	( function() {

		var vrD = new HMDVRDevice( ViveData );
		var vrP = new PositionSensorVRDevice( ViveData );

		navigator.getVRDevices = function() {

			return new Promise( function( resolve, reject ) {

				resolve( [ vrD, vrP ] );

			} );

		}

	} )();

	var event = new Event( 'webvr-ready' );
	window.dispatchEvent( event );

}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import './navbar.css';
import { Navbar } from 'react-bootstrap';

class TopNav extends Component {
  render() {
    return (

My Awesome Logo | Stuff | More Stuff

        <Navbar>This shi** navbar</Navbar>

    );
  }
}

export default TopNav;<commit_msg>experimenting with sh** navbars<commit_after>import React, { Component } from 'react';
import './navbar.css';
import { Navbar, Nav, NavDropdown, NavItem, MenuItem } from 'react-bootstrap';

class TopNav extends Component {
  render() {
    return (

My Awesome Logo | Stuff | More Stuff

        <Navbar inverse collapseOnSelect>
          <Navbar.Header>
            <Navbar.Brand>
              React-Bootstrap
            </Navbar.Brand>
            <Navbar.Toggle />
          </Navbar.Header>
          <Navbar.Collapse>

              <NavItem eventKey={1} href="#">
                Link
              </NavItem>
              <NavItem eventKey={2} href="#">
                Link
              </NavItem>
              <NavDropdown eventKey={3} title="Dropdown" id="basic-nav-dropdown">
                <MenuItem eventKey={3.1}>Action</MenuItem>
                <MenuItem eventKey={3.2}>Another action</MenuItem>
                <MenuItem eventKey={3.3}>Something else here</MenuItem>
                <MenuItem divider />
                <MenuItem eventKey={3.3}>Separated link</MenuItem>
              </NavDropdown>

              <NavItem eventKey={1} href="#">
                Link Right
              </NavItem>
              <NavItem eventKey={2} href="#">
                Link Right
              </NavItem>

          </Navbar.Collapse>
        </Navbar>

    );
  }
}

export default TopNav;<|endoftext|>