<commit_before>"use strict";

function gsuiGridSamples() {
	var root = this._clone();

	this.rootElement = root;
	this._elPanel = root.querySelector( ".gsui-panel" );
	this._elGrid = root.querySelector( ".gsui-grid" );
	this._elPanelExt = this._elPanel.querySelector( ".gsui-extend" );
	this._elPanelCnt = this._elPanel.querySelector( ".gsui-content" );
	this._elGridCnt = this._elGrid.querySelector( ".gsui-content" );
	this._elSelection = this._elGrid.querySelector( ".gsui-select" );
	this.uiTimeLine = new gsuiTimeLine();
	this.uiBeatLines = new gsuiBeatLines();
	root.prepend( this.uiTimeLine.rootElement );
	this._elGrid.prepend( this.uiBeatLines.rootElement );

	this._elPanelExt.onmousedown = this._evmdPanelEx.bind( this );
	this._elGrid.onmousedown = this._evmdGrid.bind( this );
	this._elGrid.onwheel = this._evowGrid.bind( this );
	this._elPanel.onwheel = this._evowPanel.bind( this );
	this.uiTimeLine.onchangeCurrentTime = this._evocCurrentTime.bind( this );
	this.uiTimeLine.oninputLoop = this._evoiLoop.bind( this );
	this._panelMaxWidth = Infinity;
	this._contentY =
	this._panelMinWidth =
	this._timeOffset = 0;
	this._pxPerBeat = 80;
	this.panelWidth( 100 );
}

gsuiGridSamples.prototype = {
	empty() {
		if ( this.uiTrackList ) {
			this.uiTrackList.empty();
		}
	},
	change( obj ) {
		if ( obj.tracks ) {
			this.uiTrackList.change( obj.tracks );
			this.uiTrackList.newRowElements.forEach(
				this._elGridCnt.appendChild.bind( this._elGridCnt ) );
		}
	},
	resized() {
		var panelStyle = getComputedStyle( this._elPanel );

		this.width = this.rootElement.clientWidth;
		this._panelMinWidth = parseFloat( panelStyle.minWidth );
		this._panelMaxWidth = parseFloat( panelStyle.maxWidth ) || this.width;
		this._resizeGrid();
		this._updateGrid();
	},
	setFontSize( emPx ) {
		this._fontSize = ~~Math.min( Math.max( 16, emPx ), 256 );
		this.rootElement.style.fontSize = this._fontSize + "px";
	},
	offset( offset, beatPx ) {
		this._timeOffset = offset;
		this._pxPerBeat = beatPx;
		this._updateGrid();
	},
	timeSignature( a, b ) {
		this.uiTimeLine.timeSignature( a, b );
		this.uiBeatLines.timeSignature( a, b );
	},
	currentTime( beat ) {
		this.uiTimeLine.currentTime( beat );
		this.uiBeatLines.currentTime( beat );
	},
	loop( a, b ) {
		this.uiTimeLine.loop( a, b );
		this.uiBeatLines.loop( a, b );
	},
	panelWidth( width ) {
		width = Math.max( this._panelMinWidth, Math.min( width, this._panelMaxWidth ) );
		if ( this._timeOffset > 0 ) {
			this._timeOffset += ( width - this._panelWidth ) / this._pxPerBeat;
		}
		this._panelWidth = width;
		this._updatePanelSize();
	},
	contentY( yEm ) {
		var h = ( this.uiTrackList || this.uiKeys ).rootElement.clientHeight;

		h = Math.max( 0, h - this._elGrid.clientHeight ) / this._fontSize;
		this._contentY = yEm = Math.min( Math.max( 0, yEm ), h );
		this._elGridCnt.style.marginTop =
		this._elPanelCnt.style.marginTop = -yEm + "em";
	},
	loadKeys( from, nbOctaves ) {
		this._loadPanelCmp( "uiKeys", "uiTrackList" );
		this.uiKeys.octaves( from, nbOctaves );
		this.uiKeys.newRowElements.forEach(
			this._elGridCnt.appendChild.bind( this._elGridCnt ) );
	},
	loadTrackList() {
		this._loadPanelCmp( "uiTrackList", "uiKeys" );
		this.uiTrackList.onchange = obj => this.onchange( {
			redo: { tracks: obj.redo },
			undo: { tracks: obj.undo }
		} );
	},

	// private:
	_clone() {
		var div = document.createElement( "div" );

		gsuiGridSamples.template = gsuiGridSamples.template || this._init();
		div.appendChild( document.importNode( gsuiGridSamples.template.content, true ) );
		return div.removeChild( div.querySelector( "*" ) );
	},
	_init() {
		document.body.addEventListener( "mousemove", function( e ) {
			gsuiGridSamples._focused && gsuiGridSamples._focused._evmmRoot( e );
		} );
		document.body.addEventListener( "mouseup", function( e ) {
			gsuiGridSamples._focused && gsuiGridSamples._focused._evmuRoot( e );
		} );
		return document.getElementById( "gsuiGridSamples" );
	},
	_loadPanelCmp( cmpStr, oldCmpStr ) {
		var cmp = this[ cmpStr ],
			oldCmp = this[ oldCmpStr ];

		if ( oldCmp ) {
			oldCmp.remove();
			this.setFontSize( this._fontSize * ( cmpStr === "uiKeys" ? .5 : 2 ) );
			delete this[ oldCmpStr ];
		} else {
			this.setFontSize( cmpStr === "uiKeys" ? 20 : 40 );
		}
		if ( !cmp ) {
			this[ cmpStr ] = cmp = cmpStr === "uiKeys" ? new gsuiKeys() : new gsuiTrackList();
			this._elPanelCnt.prepend( cmp.rootElement );
		}
	},
	_resizeGrid() {
		this.uiTimeLine.resized();
		this.uiBeatLines.resized();
	},
	_contentScroll( e ) {
		this.contentY( this._contentY + ( 20 * ( e.deltaY > 0 ? 1 : -1 ) ) / this._fontSize );
	},
	_getMouseBeat( e ) {
		this._elGridCntBCR = this._elGridCnt.getBoundingClientRect();
		return this.uiTimeLine._round( ( e.pageX - this._elGridCntBCR.left ) / this._pxPerBeat );
	},
	_drawSelection( e ) {
		var sty = this._elSelection.style,
			left = this._mdBeat,
			width = this._getMouseBeat( e ) - left,
			top = Math.min( this._mdTrackBCR.top, this._mmTrackBCR.top ),
			bottom = Math.max( this._mdTrackBCR.bottom, this._mmTrackBCR.bottom );

		if ( width < 0 ) {
			width = -width;
			left -= width;
		}
		sty.left = left * this._pxPerBeat + "px";
		sty.width = width * this._pxPerBeat + "px";
		sty.top = top - this._elGridCntBCR.top + "px";
		sty.height = bottom - top + "px";
	},
	_updateGrid() {
		this.uiTimeLine.offset( this._timeOffset, this._pxPerBeat );
		this.uiBeatLines.offset( this._timeOffset, this._pxPerBeat );
		this._timeOffset = this.uiTimeLine._offset;
		this._elGridCnt.style.left = -this._timeOffset * this._pxPerBeat + "px";
		this._timeOffset = this.uiTimeLine._offset;
		this._pxPerBeat = this.uiTimeLine._pxPerBeat;
	},
	_updatePanelSize() {
		this._elPanel.style.width =
		this._elGrid.style.left = this._panelWidth + "px";
		this.uiTimeLine.rootElement.style.left = this._panelWidth - 1 + "px";
		this._resizeGrid();
		this._updateGrid();
	},
	_findTrack( e ) {
		return this._elGridCnt.querySelectorAll( ".gsui-row" )[
			~~( ( e.pageY - this._elGridCntBCR.top ) / this._fontSize ) ]
	},

	// events:
	_evocCurrentTime( beat ) {
		this.uiBeatLines.currentTime( beat );
		this.onchangeCurrentTime && this.onchangeCurrentTime( beat );
	},
	_evoiLoop( toggle, a, b ) {
		this.uiBeatLines.loop( toggle && a, b );
		this.oninputLoop && this.oninputLoop( toggle, a, b );
	},
	_evmdGrid( e ) {
		this._mdPageX = e.pageX;
		this._mdPageY = e.pageY;
		this._mdBeat = this._getMouseBeat( e );
		gsuiGridSamples._focused = this;
		if ( e.shiftKey ) {
			this._selectionStarting = true;
		} else if ( e.altKey ) {
			this._gridDragging = true;
			this._mouseOffset = this._timeOffset;
			this._mouseContentY = this._contentY;
		}
	},
	_evmdPanelEx( e ) {
		this._rootLeft = this.rootElement.getBoundingClientRect().left;
		this._panelResizing = this._elPanelExt.clientWidth - e.layerX;
		this._elPanelExt.classList.add( "gsui-hover" );
		gsuiGridSamples._focused = this;
	},
	_evowGrid( e ) {
		if ( !e.shiftKey && !e.ctrlKey ) {
			this._contentScroll( e );
		} else {
			var layerX, offInc, beatPx = this._pxPerBeat;

			if ( e.ctrlKey ) {
				layerX = e.pageX - this._elGrid.getBoundingClientRect().left;
				beatPx = Math.min( Math.max( 8, beatPx * ( e.deltaY > 0 ? .9 : 1.1 ) ), 512 );
				offInc = ( layerX / this._pxPerBeat * ( beatPx - this._pxPerBeat ) ) / beatPx;
			} else {
				offInc = ( e.deltaY > 0 ? 20 : -20 ) / beatPx;
			}
			this.offset( Math.max( 0, this._timeOffset + offInc ), beatPx );
		}
		return false;
	},
	_evowPanel( e ) {
		if ( e.ctrlKey ) {
			var layerY = e.pageY - this._elPanel.getBoundingClientRect().top,
				oldFs = this._fontSize,
				fs = oldFs * ( e.deltaY > 0 ? .9 : 1.1 );

			this.setFontSize( fs );
			fs = this._fontSize;
			this.contentY( this._contentY + ( layerY / oldFs * ( fs - oldFs ) ) / fs );
		} else if ( !e.shiftKey ) {
			this._contentScroll( e );
		}
		return false;
	},
	_evmmRoot( e ) {
		var pxRel = e.pageX - this._mdPageX,
			pyRel = e.pageY - this._mdPageY;

		if ( this._gridDragging ) {
			this.offset( this._mouseOffset - pxRel / this._pxPerBeat, this._pxPerBeat );
			this.contentY( this._mouseContentY - pyRel / this._fontSize );
		} else if ( this._panelResizing != null ) {
			this.panelWidth( e.pageX - this._rootLeft + this._panelResizing );
		} else if ( this._selectionStarted ) {
			this._mmTrackBCR = this._findTrack( e ).getBoundingClientRect();
			this._drawSelection( e );
		} else if ( this._selectionStarting ) {
			if ( Math.max( Math.abs( pxRel ), Math.abs( pyRel ) ) > 6 ) {
				this._mdTrackBCR =
				this._mmTrackBCR = this._findTrack( e ).getBoundingClientRect();
				this._drawSelection( e );
				this._elSelection.classList.remove( "hidden" );
				this._selectionStarted = true;
				delete this._selectionStarting;
			}
		}
	},
	_evmuRoot( e ) {
		this._elPanelExt.classList.remove( "gsui-hover" );
		this._elSelection.classList.add( "hidden" );
		delete this._gridDragging;
		delete this._selectionStarted;
		delete this._selectionStarting;
		delete this._panelResizing;
		delete gsuiGridSamples._focused;
	}
};
<commit_msg>gsuiGridSamples: .offset(), change the row's fontSize<commit_after>"use strict";

function gsuiGridSamples() {
	var root = this._clone();

	this.rootElement = root;
	this._elPanel = root.querySelector( ".gsui-panel" );
	this._elGrid = root.querySelector( ".gsui-grid" );
	this._elPanelExt = this._elPanel.querySelector( ".gsui-extend" );
	this._elPanelCnt = this._elPanel.querySelector( ".gsui-content" );
	this._elGridCnt = this._elGrid.querySelector( ".gsui-content" );
	this._elSelection = this._elGrid.querySelector( ".gsui-select" );
	this.uiTimeLine = new gsuiTimeLine();
	this.uiBeatLines = new gsuiBeatLines();
	root.prepend( this.uiTimeLine.rootElement );
	this._elGrid.prepend( this.uiBeatLines.rootElement );

	this._elPanelExt.onmousedown = this._evmdPanelEx.bind( this );
	this._elGrid.onmousedown = this._evmdGrid.bind( this );
	this._elGrid.onwheel = this._evowGrid.bind( this );
	this._elPanel.onwheel = this._evowPanel.bind( this );
	this.uiTimeLine.onchangeCurrentTime = this._evocCurrentTime.bind( this );
	this.uiTimeLine.oninputLoop = this._evoiLoop.bind( this );
	this._panelMaxWidth = Infinity;
	this._contentY =
	this._panelMinWidth =
	this._timeOffset = 0;
	this._pxPerBeat = 80;
	this.panelWidth( 100 );
}

gsuiGridSamples.prototype = {
	empty() {
		if ( this.uiTrackList ) {
			this.uiTrackList.empty();
		}
	},
	change( obj ) {
		if ( obj.tracks ) {
			this.uiTrackList.change( obj.tracks );
			this.uiTrackList.newRowElements.forEach(
				this._elGridCnt.appendChild.bind( this._elGridCnt ) );
		}
	},
	resized() {
		var panelStyle = getComputedStyle( this._elPanel );

		this.width = this.rootElement.clientWidth;
		this._panelMinWidth = parseFloat( panelStyle.minWidth );
		this._panelMaxWidth = parseFloat( panelStyle.maxWidth ) || this.width;
		this._resizeGrid();
		this._updateGrid();
	},
	setFontSize( emPx ) {
		this._fontSize = ~~Math.min( Math.max( 16, emPx ), 256 );
		this.rootElement.style.fontSize = this._fontSize + "px";
	},
	offset( offset, beatPx ) {
		this._timeOffset = offset;
		this._pxPerBeat = beatPx || this._pxPerBeat;
		this._updateGrid( !!beatPx );
	},
	timeSignature( a, b ) {
		this.uiTimeLine.timeSignature( a, b );
		this.uiBeatLines.timeSignature( a, b );
	},
	currentTime( beat ) {
		this.uiTimeLine.currentTime( beat );
		this.uiBeatLines.currentTime( beat );
	},
	loop( a, b ) {
		this.uiTimeLine.loop( a, b );
		this.uiBeatLines.loop( a, b );
	},
	panelWidth( width ) {
		width = Math.max( this._panelMinWidth, Math.min( width, this._panelMaxWidth ) );
		if ( this._timeOffset > 0 ) {
			this._timeOffset += ( width - this._panelWidth ) / this._pxPerBeat;
		}
		this._panelWidth = width;
		this._updatePanelSize();
	},
	contentY( yEm ) {
		var h = ( this.uiTrackList || this.uiKeys ).rootElement.clientHeight;

		h = Math.max( 0, h - this._elGrid.clientHeight ) / this._fontSize;
		this._contentY = yEm = Math.min( Math.max( 0, yEm ), h );
		this._elGridCnt.style.marginTop =
		this._elPanelCnt.style.marginTop = -yEm + "em";
	},
	loadKeys( from, nbOctaves ) {
		this._loadPanelCmp( "uiKeys", "uiTrackList" );
		this.uiKeys.octaves( from, nbOctaves );
		this.uiKeys.newRowElements.forEach(
			this._elGridCnt.appendChild.bind( this._elGridCnt ) );
	},
	loadTrackList() {
		this._loadPanelCmp( "uiTrackList", "uiKeys" );
		this.uiTrackList.onchange = obj => this.onchange( {
			redo: { tracks: obj.redo },
			undo: { tracks: obj.undo }
		} );
	},

	// private:
	_clone() {
		var div = document.createElement( "div" );

		gsuiGridSamples.template = gsuiGridSamples.template || this._init();
		div.appendChild( document.importNode( gsuiGridSamples.template.content, true ) );
		return div.removeChild( div.querySelector( "*" ) );
	},
	_init() {
		document.body.addEventListener( "mousemove", function( e ) {
			gsuiGridSamples._focused && gsuiGridSamples._focused._evmmRoot( e );
		} );
		document.body.addEventListener( "mouseup", function( e ) {
			gsuiGridSamples._focused && gsuiGridSamples._focused._evmuRoot( e );
		} );
		return document.getElementById( "gsuiGridSamples" );
	},
	_loadPanelCmp( cmpStr, oldCmpStr ) {
		var cmp = this[ cmpStr ],
			oldCmp = this[ oldCmpStr ];

		if ( oldCmp ) {
			oldCmp.remove();
			this.setFontSize( this._fontSize * ( cmpStr === "uiKeys" ? .5 : 2 ) );
			delete this[ oldCmpStr ];
		} else {
			this.setFontSize( cmpStr === "uiKeys" ? 20 : 40 );
		}
		if ( !cmp ) {
			this[ cmpStr ] = cmp = cmpStr === "uiKeys" ? new gsuiKeys() : new gsuiTrackList();
			this._elPanelCnt.prepend( cmp.rootElement );
		}
	},
	_resizeGrid() {
		this.uiTimeLine.resized();
		this.uiBeatLines.resized();
	},
	_contentScroll( e ) {
		this.contentY( this._contentY + ( 20 * ( e.deltaY > 0 ? 1 : -1 ) ) / this._fontSize );
	},
	_getMouseBeat( e ) {
		this._elGridCntBCR = this._elGridCnt.getBoundingClientRect();
		return this.uiTimeLine._round( ( e.pageX - this._elGridCntBCR.left ) / this._pxPerBeat );
	},
	_drawSelection( e ) {
		var sty = this._elSelection.style,
			left = this._mdBeat,
			width = this._getMouseBeat( e ) - left,
			top = Math.min( this._mdTrackBCR.top, this._mmTrackBCR.top ),
			bottom = Math.max( this._mdTrackBCR.bottom, this._mmTrackBCR.bottom );

		if ( width < 0 ) {
			width = -width;
			left -= width;
		}
		sty.left = left * this._pxPerBeat + "px";
		sty.width = width * this._pxPerBeat + "px";
		sty.top = top - this._elGridCntBCR.top + "px";
		sty.height = bottom - top + "px";
	},
	_updateGrid( beatPxChanged ) {
		var beatPx = this._pxPerBeat;

		this.uiTimeLine.offset( this._timeOffset, beatPx );
		this.uiBeatLines.offset( this._timeOffset, beatPx );
		this._timeOffset = this.uiTimeLine._offset;
		this._pxPerBeat = beatPx = this.uiTimeLine._pxPerBeat;
		this._elGridCnt.style.left = -this._timeOffset * beatPx + "px";
		if ( beatPxChanged ) {
			this._elGridCnt.querySelectorAll( ".gsui-row" ).forEach( function( row ) {
				row.firstChild.style.fontSize = beatPx + "px";
			} );
		}
	},
	_updatePanelSize() {
		this._elPanel.style.width =
		this._elGrid.style.left = this._panelWidth + "px";
		this.uiTimeLine.rootElement.style.left = this._panelWidth - 1 + "px";
		this._resizeGrid();
		this._updateGrid();
	},
	_findTrack( e ) {
		return this._elGridCnt.querySelectorAll( ".gsui-row" )[
			~~( ( e.pageY - this._elGridCntBCR.top ) / this._fontSize ) ]
	},

	// events:
	_evocCurrentTime( beat ) {
		this.uiBeatLines.currentTime( beat );
		this.onchangeCurrentTime && this.onchangeCurrentTime( beat );
	},
	_evoiLoop( toggle, a, b ) {
		this.uiBeatLines.loop( toggle && a, b );
		this.oninputLoop && this.oninputLoop( toggle, a, b );
	},
	_evmdGrid( e ) {
		this._mdPageX = e.pageX;
		this._mdPageY = e.pageY;
		this._mdBeat = this._getMouseBeat( e );
		gsuiGridSamples._focused = this;
		if ( e.shiftKey ) {
			this._selectionStarting = true;
		} else if ( e.altKey ) {
			this._gridDragging = true;
			this._mouseOffset = this._timeOffset;
			this._mouseContentY = this._contentY;
		}
	},
	_evmdPanelEx( e ) {
		this._rootLeft = this.rootElement.getBoundingClientRect().left;
		this._panelResizing = this._elPanelExt.clientWidth - e.layerX;
		this._elPanelExt.classList.add( "gsui-hover" );
		gsuiGridSamples._focused = this;
	},
	_evowGrid( e ) {
		if ( !e.shiftKey && !e.ctrlKey ) {
			this._contentScroll( e );
		} else {
			var layerX, offInc, beatPx = this._pxPerBeat;

			if ( e.ctrlKey ) {
				layerX = e.pageX - this._elGrid.getBoundingClientRect().left;
				beatPx = Math.min( Math.max( 8, beatPx * ( e.deltaY > 0 ? .9 : 1.1 ) ), 512 );
				offInc = ( layerX / this._pxPerBeat * ( beatPx - this._pxPerBeat ) ) / beatPx;
			} else {
				offInc = ( e.deltaY > 0 ? 20 : -20 ) / beatPx;
			}
			this.offset( Math.max( 0, this._timeOffset + offInc ),
				e.ctrlKey ? beatPx : undefined );
		}
		return false;
	},
	_evowPanel( e ) {
		if ( e.ctrlKey ) {
			var layerY = e.pageY - this._elPanel.getBoundingClientRect().top,
				oldFs = this._fontSize,
				fs = oldFs * ( e.deltaY > 0 ? .9 : 1.1 );

			this.setFontSize( fs );
			fs = this._fontSize;
			this.contentY( this._contentY + ( layerY / oldFs * ( fs - oldFs ) ) / fs );
		} else if ( !e.shiftKey ) {
			this._contentScroll( e );
		}
		return false;
	},
	_evmmRoot( e ) {
		var pxRel = e.pageX - this._mdPageX,
			pyRel = e.pageY - this._mdPageY;

		if ( this._gridDragging ) {
			this.offset( this._mouseOffset - pxRel / this._pxPerBeat, this._pxPerBeat );
			this.contentY( this._mouseContentY - pyRel / this._fontSize );
		} else if ( this._panelResizing != null ) {
			this.panelWidth( e.pageX - this._rootLeft + this._panelResizing );
		} else if ( this._selectionStarted ) {
			this._mmTrackBCR = this._findTrack( e ).getBoundingClientRect();
			this._drawSelection( e );
		} else if ( this._selectionStarting ) {
			if ( Math.max( Math.abs( pxRel ), Math.abs( pyRel ) ) > 6 ) {
				this._mdTrackBCR =
				this._mmTrackBCR = this._findTrack( e ).getBoundingClientRect();
				this._drawSelection( e );
				this._elSelection.classList.remove( "hidden" );
				this._selectionStarted = true;
				delete this._selectionStarting;
			}
		}
	},
	_evmuRoot( e ) {
		this._elPanelExt.classList.remove( "gsui-hover" );
		this._elSelection.classList.add( "hidden" );
		delete this._gridDragging;
		delete this._selectionStarted;
		delete this._selectionStarting;
		delete this._panelResizing;
		delete gsuiGridSamples._focused;
	}
};
<|endoftext|>


<commit_before>'use strict';

function webreport($timeout, $routeParams, common, datacontext, threatmodellocator) {
    // Using 'Controller As' syntax, so we assign this to the vm variable (for viewmodel).
    /*jshint validthis: true */
    var vm = this;
    var controllerId = 'webreport';
    var getLogFn = common.logger.getLogFn;
    var log = getLogFn(controllerId);
    var logError = getLogFn(controllerId, 'error');
    vm.title = 'Threat Model Report';
    vm.threatModel = {};
    vm.error = null;
    vm.loaded = false;
    vm.onLoaded = onLoaded;
    vm.onError = onError;
    vm.printPDF = printPDF;

    activate();

    function activate() {
        common.activateController([getThreatModel()], controllerId)
            .then(function () { log('Activated Web Report Controller'); });
    }

    function getThreatModel(forceReload) {

        var location = threatModelLocation();

        return datacontext.load(location, forceReload).then(onLoad, onError);

        function onLoad(data) {
            vm.threatModel = data;
            return vm.threatModel;
        }
    }

    function onLoaded() {
        vm.loaded = true;
        return 'called onLoaded';
    }

    function onError(err) {
        vm.error = err;
        logError(err.data.message);
    }

    function threatModelLocation() {
        return threatmodellocator.getModelLocation($routeParams);
    }

    function printPDF(done) {

        //use timeout to ensure the buttons etc. are not visible on the printed page
        //seems ugly, but works
        $timeout(function() {
            console.log('printing pdf');
            window.print();
            done();
        });
    }
}

module.exports = webreport;<commit_msg>delinting<commit_after>'use strict';

function webreport($timeout, $routeParams, common, datacontext, threatmodellocator) {
    // Using 'Controller As' syntax, so we assign this to the vm variable (for viewmodel).
    /*jshint validthis: true */
    var vm = this;
    var controllerId = 'webreport';
    var getLogFn = common.logger.getLogFn;
    var log = getLogFn(controllerId);
    var logError = getLogFn(controllerId, 'error');
    vm.title = 'Threat Model Report';
    vm.threatModel = {};
    vm.error = null;
    vm.loaded = false;
    vm.onLoaded = onLoaded;
    vm.onError = onError;
    vm.printPDF = printPDF;

    activate();

    function activate() {
        common.activateController([getThreatModel()], controllerId)
            .then(function () { log('Activated Web Report Controller'); });
    }

    function getThreatModel(forceReload) {

        var location = threatModelLocation();

        return datacontext.load(location, forceReload).then(onLoad, onError);

        function onLoad(data) {
            vm.threatModel = data;
            return vm.threatModel;
        }
    }

    function onLoaded() {
        vm.loaded = true;
        return 'called onLoaded';
    }

    function onError(err) {
        vm.error = err;
        logError(err.data.message);
    }

    function threatModelLocation() {
        return threatmodellocator.getModelLocation($routeParams);
    }

    function printPDF(done) {

        //use timeout to ensure the buttons etc. are not visible on the printed page
        //seems ugly, but works
        $timeout(function() {
            window.print();
            done();
        });
    }
}

module.exports = webreport;<|endoftext|>


<commit_before>// Copyright 2002-2014, University of Colorado Boulder

/**
 * A rectangular push button that draws gradients and such in order to create
 * a somewhat 2D effect.
 *
 * @author John Blanco
 */
define( function( require ) {
  'use strict';

  // Includes
  var AbstractButton = require( 'SUN/experimental/buttons/AbstractButton' );
  var Color = require( 'SCENERY/util/Color' );
  var inherit = require( 'PHET_CORE/inherit' );
  var LinearGradient = require( 'SCENERY/util/LinearGradient' );
  var Rectangle = require( 'SCENERY/nodes/Rectangle' );
  var Shape = require( 'KITE/Shape' );
  var Vector2 = require( 'DOT/Vector2' );

  // Constants
  var HIGHLIGHT_GRADIENT_LENGTH = 7; // In screen coords, which are roughly pixels.
  var SHADE_GRADIENT_LENGTH = 3; // In screen coords, which are roughly pixels.

  /**
   * @param {Node} content - Node to put on surface of button, could be text, icon, or whatever
   * @param {Object} options
   * @constructor
   */
  function RectangularPushButton( content, options ) {

    var thisButton = this;
    AbstractButton.call( thisButton, { listener: options.listener, fireOnDown: options.fireOnDown } );

    options = _.extend( {
      // Default values.
      cursor: 'pointer',
      cornerRounding: 4,
      baseColor: new Color( 153, 206, 255 ),
      disabledBaseColor: new Color( 220, 220, 220 ),
      xPadding: 5,
      yPadding: 5,
      listener: null,
      fireOnDown: false,
      touchExpansionX: 5,
      touchExpansionY: 5
    }, options );

    var buttonWidth = content.width + options.xPadding * 2;
    var buttonHeight = content.height + options.yPadding * 2;
    var upCenter = new Vector2( buttonWidth / 2, buttonHeight / 2 );
    var downCenter = upCenter.plus( new Vector2( 0.5, 0.5 ) ); // Displacement empirically determined.
    var verticalHighlightStop = HIGHLIGHT_GRADIENT_LENGTH / buttonHeight;
    var verticalShadowStop = 1 - SHADE_GRADIENT_LENGTH / buttonHeight;
    var horizontalHighlightStop = HIGHLIGHT_GRADIENT_LENGTH / buttonWidth;
    var horizontalShadowStop = 1 - SHADE_GRADIENT_LENGTH / buttonWidth;
    var baseColor = options.baseColor;
    var disabledBaseColor = options.disabledBaseColor;
    var transparentBaseColor = new Color( baseColor.getRed(), baseColor.getGreen(), baseColor.getBlue(), 0 );
    var transparentDisabledBaseColor = new Color( disabledBaseColor.getRed(), disabledBaseColor.getGreen(), disabledBaseColor.getBlue(), 0 );

    // Create the gradient fills used for various button states
    var upFillVertical = new LinearGradient( 0, 0, 0, buttonHeight )
      .addColorStop( 0, baseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( verticalHighlightStop, baseColor )
      .addColorStop( verticalShadowStop, baseColor )
      .addColorStop( 1, baseColor.colorUtilsDarker( 0.5 ) );

    var upFillHorizontal = new LinearGradient( 0, 0, buttonWidth, 0 )
      .addColorStop( 0, baseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( horizontalHighlightStop, transparentBaseColor )
      .addColorStop( horizontalShadowStop, transparentBaseColor )
      .addColorStop( 1, baseColor.colorUtilsDarker( 0.5 ) );

    var overFillVertical = new LinearGradient( 0, 0, 0, buttonHeight )
      .addColorStop( 0, baseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( verticalHighlightStop, baseColor.colorUtilsBrighter( 0.5 ) )
      .addColorStop( verticalShadowStop, baseColor.colorUtilsBrighter( 0.5 ) )
      .addColorStop( 1, baseColor.colorUtilsDarker( 0.5 ) );

    var overFillHorizontal = new LinearGradient( 0, 0, buttonWidth, 0 )
      .addColorStop( 0, baseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( horizontalHighlightStop, transparentBaseColor )
      .addColorStop( horizontalShadowStop, transparentBaseColor )
      .addColorStop( 1, baseColor.colorUtilsDarker( 0.5 ) );

    var downFill = new LinearGradient( 0, 0, 0, buttonHeight )
      .addColorStop( 0, baseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( verticalHighlightStop * 0.67, baseColor.colorUtilsDarker( 0.3 ) )
      .addColorStop( verticalShadowStop, baseColor.colorUtilsBrighter( 0.2 ) )
      .addColorStop( 1, baseColor.colorUtilsDarker( 0.5 ) );

    var disabledFillVertical = new LinearGradient( 0, 0, 0, buttonHeight )
      .addColorStop( 0, disabledBaseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( verticalHighlightStop, disabledBaseColor.colorUtilsBrighter( 0.5 ) )
      .addColorStop( verticalShadowStop, disabledBaseColor.colorUtilsBrighter( 0.5 ) )
      .addColorStop( 1, disabledBaseColor.colorUtilsDarker( 0.5 ) );

    var disabledFillHorizontal = new LinearGradient( 0, 0, buttonWidth, 0 )
      .addColorStop( 0, disabledBaseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( horizontalHighlightStop, transparentDisabledBaseColor )
      .addColorStop( horizontalShadowStop, transparentDisabledBaseColor )
      .addColorStop( 1, disabledBaseColor.colorUtilsDarker( 0.5 ) );

    // Create the basic button shape.
    var background = new Rectangle( 0, 0, buttonWidth, buttonHeight, options.cornerRounding, options.cornerRounding,
      {
        fill: options.baseColor
      } );
    this.addChild( background );

    // Create the overlay that is used to add horizontal shading.
    var overlayForHorizGradient = new Rectangle( 0, 0, buttonWidth, buttonHeight, options.cornerRounding, options.cornerRounding,
      {
        fill: options.baseColor
      } );
    this.addChild( overlayForHorizGradient );

    content.center = upCenter;
    thisButton.addChild( content );

    // Hook up the function that will modify button appearance as the state changes.
    this.buttonModel.interactionState.link( function( interactionState ) {

      switch( interactionState ) {

        case 'idle':
          content.center = upCenter;
          content.opacity = 1;
          background.fill = upFillVertical;
          overlayForHorizGradient.fill = upFillHorizontal;
          thisButton.pickable = true;
          break;

        case 'over':
          content.center = upCenter;
          content.opacity = 1;
          background.fill = overFillVertical;
          overlayForHorizGradient.fill = overFillHorizontal;
          thisButton.pickable = true;
          break;

        case 'pressed':
          content.center = downCenter;
          content.opacity = 1;
          background.fill = downFill;
          overlayForHorizGradient.fill = overFillHorizontal;
          thisButton.pickable = true;
          break;

        case 'disabled':
          content.center = upCenter;
          content.opacity = 0.3;
          background.fill = disabledFillVertical;
          overlayForHorizGradient.fill = disabledFillHorizontal;
          thisButton.pickable = false;
          break;
      }
    } );

    // Add explicit mouse and touch areas so that the child nodes can all be non-pickable.
    this.mouseArea = Shape.rectangle( 0, 0, buttonWidth, buttonHeight );
    this.touchArea = Shape.rectangle( -options.touchExpansionX, -options.touchExpansionY, buttonWidth + options.touchExpansionX * 2, buttonHeight + options.touchExpansionY * 2 );

    // Mutate with the options after the layout is complete so that
    // width-dependent fields like centerX will work.
    thisButton.mutate( options );
  }

  return inherit( AbstractButton, RectangularPushButton );
} );<commit_msg>Fill in options defaults before calling super constructor, see #49<commit_after>// Copyright 2002-2014, University of Colorado Boulder

/**
 * A rectangular push button that draws gradients and such in order to create
 * a somewhat 2D effect.
 *
 * @author John Blanco
 */
define( function( require ) {
  'use strict';

  // Includes
  var AbstractButton = require( 'SUN/experimental/buttons/AbstractButton' );
  var Color = require( 'SCENERY/util/Color' );
  var inherit = require( 'PHET_CORE/inherit' );
  var LinearGradient = require( 'SCENERY/util/LinearGradient' );
  var Rectangle = require( 'SCENERY/nodes/Rectangle' );
  var Shape = require( 'KITE/Shape' );
  var Vector2 = require( 'DOT/Vector2' );

  // Constants
  var HIGHLIGHT_GRADIENT_LENGTH = 7; // In screen coords, which are roughly pixels.
  var SHADE_GRADIENT_LENGTH = 3; // In screen coords, which are roughly pixels.

  /**
   * @param {Node} content - Node to put on surface of button, could be text, icon, or whatever
   * @param {Object} options
   * @constructor
   */
  function RectangularPushButton( content, options ) {

    var thisButton = this;

    options = _.extend( {
      // Default values.
      cursor: 'pointer',
      cornerRounding: 4,
      baseColor: new Color( 153, 206, 255 ),
      disabledBaseColor: new Color( 220, 220, 220 ),
      xPadding: 5,
      yPadding: 5,
      listener: null,
      fireOnDown: false,
      touchExpansionX: 5,
      touchExpansionY: 5
    }, options );

    AbstractButton.call( thisButton, { listener: options.listener, fireOnDown: options.fireOnDown } );

    var buttonWidth = content.width + options.xPadding * 2;
    var buttonHeight = content.height + options.yPadding * 2;
    var upCenter = new Vector2( buttonWidth / 2, buttonHeight / 2 );
    var downCenter = upCenter.plus( new Vector2( 0.5, 0.5 ) ); // Displacement empirically determined.
    var verticalHighlightStop = HIGHLIGHT_GRADIENT_LENGTH / buttonHeight;
    var verticalShadowStop = 1 - SHADE_GRADIENT_LENGTH / buttonHeight;
    var horizontalHighlightStop = HIGHLIGHT_GRADIENT_LENGTH / buttonWidth;
    var horizontalShadowStop = 1 - SHADE_GRADIENT_LENGTH / buttonWidth;
    var baseColor = options.baseColor;
    var disabledBaseColor = options.disabledBaseColor;
    var transparentBaseColor = new Color( baseColor.getRed(), baseColor.getGreen(), baseColor.getBlue(), 0 );
    var transparentDisabledBaseColor = new Color( disabledBaseColor.getRed(), disabledBaseColor.getGreen(), disabledBaseColor.getBlue(), 0 );

    // Create the gradient fills used for various button states
    var upFillVertical = new LinearGradient( 0, 0, 0, buttonHeight )
      .addColorStop( 0, baseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( verticalHighlightStop, baseColor )
      .addColorStop( verticalShadowStop, baseColor )
      .addColorStop( 1, baseColor.colorUtilsDarker( 0.5 ) );

    var upFillHorizontal = new LinearGradient( 0, 0, buttonWidth, 0 )
      .addColorStop( 0, baseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( horizontalHighlightStop, transparentBaseColor )
      .addColorStop( horizontalShadowStop, transparentBaseColor )
      .addColorStop( 1, baseColor.colorUtilsDarker( 0.5 ) );

    var overFillVertical = new LinearGradient( 0, 0, 0, buttonHeight )
      .addColorStop( 0, baseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( verticalHighlightStop, baseColor.colorUtilsBrighter( 0.5 ) )
      .addColorStop( verticalShadowStop, baseColor.colorUtilsBrighter( 0.5 ) )
      .addColorStop( 1, baseColor.colorUtilsDarker( 0.5 ) );

    var overFillHorizontal = new LinearGradient( 0, 0, buttonWidth, 0 )
      .addColorStop( 0, baseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( horizontalHighlightStop, transparentBaseColor )
      .addColorStop( horizontalShadowStop, transparentBaseColor )
      .addColorStop( 1, baseColor.colorUtilsDarker( 0.5 ) );

    var downFill = new LinearGradient( 0, 0, 0, buttonHeight )
      .addColorStop( 0, baseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( verticalHighlightStop * 0.67, baseColor.colorUtilsDarker( 0.3 ) )
      .addColorStop( verticalShadowStop, baseColor.colorUtilsBrighter( 0.2 ) )
      .addColorStop( 1, baseColor.colorUtilsDarker( 0.5 ) );

    var disabledFillVertical = new LinearGradient( 0, 0, 0, buttonHeight )
      .addColorStop( 0, disabledBaseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( verticalHighlightStop, disabledBaseColor.colorUtilsBrighter( 0.5 ) )
      .addColorStop( verticalShadowStop, disabledBaseColor.colorUtilsBrighter( 0.5 ) )
      .addColorStop( 1, disabledBaseColor.colorUtilsDarker( 0.5 ) );

    var disabledFillHorizontal = new LinearGradient( 0, 0, buttonWidth, 0 )
      .addColorStop( 0, disabledBaseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( horizontalHighlightStop, transparentDisabledBaseColor )
      .addColorStop( horizontalShadowStop, transparentDisabledBaseColor )
      .addColorStop( 1, disabledBaseColor.colorUtilsDarker( 0.5 ) );

    // Create the basic button shape.
    var background = new Rectangle( 0, 0, buttonWidth, buttonHeight, options.cornerRounding, options.cornerRounding,
      {
        fill: options.baseColor
      } );
    this.addChild( background );

    // Create the overlay that is used to add horizontal shading.
    var overlayForHorizGradient = new Rectangle( 0, 0, buttonWidth, buttonHeight, options.cornerRounding, options.cornerRounding,
      {
        fill: options.baseColor
      } );
    this.addChild( overlayForHorizGradient );

    content.center = upCenter;
    thisButton.addChild( content );

    // Hook up the function that will modify button appearance as the state changes.
    this.buttonModel.interactionState.link( function( interactionState ) {

      switch( interactionState ) {

        case 'idle':
          content.center = upCenter;
          content.opacity = 1;
          background.fill = upFillVertical;
          overlayForHorizGradient.fill = upFillHorizontal;
          thisButton.pickable = true;
          break;

        case 'over':
          content.center = upCenter;
          content.opacity = 1;
          background.fill = overFillVertical;
          overlayForHorizGradient.fill = overFillHorizontal;
          thisButton.pickable = true;
          break;

        case 'pressed':
          content.center = downCenter;
          content.opacity = 1;
          background.fill = downFill;
          overlayForHorizGradient.fill = overFillHorizontal;
          thisButton.pickable = true;
          break;

        case 'disabled':
          content.center = upCenter;
          content.opacity = 0.3;
          background.fill = disabledFillVertical;
          overlayForHorizGradient.fill = disabledFillHorizontal;
          thisButton.pickable = false;
          break;
      }
    } );

    // Add explicit mouse and touch areas so that the child nodes can all be non-pickable.
    this.mouseArea = Shape.rectangle( 0, 0, buttonWidth, buttonHeight );
    this.touchArea = Shape.rectangle( -options.touchExpansionX, -options.touchExpansionY, buttonWidth + options.touchExpansionX * 2, buttonHeight + options.touchExpansionY * 2 );

    // Mutate with the options after the layout is complete so that
    // width-dependent fields like centerX will work.
    thisButton.mutate( options );
  }

  return inherit( AbstractButton, RectangularPushButton );
} );<|endoftext|>


<commit_before>/* vim:set ts=2 sw=2 sts=2 expandtab */
/*jshint asi: true undef: true es5: true node: true browser: true devel: true
         forin: true latedef: false globalstrict: true */

'use strict';

var Name = require('name')
var Method = require('method')

var core = require('./core'),
    convert = core.convert, accumulate = core.accumulate

var queued = Name()
var input = Name()
var forward = Name()
var state = Name()

function drain(buffer, next, result) {
  var values = buffer[queued]
  while (values.length) result = next(values.shift(), result)
  buffer[queued] = null
  return result
}

function isDrained(buffer) {
  return buffer[queued] === null
}

function buffer(source) {
  /**
  Buffer a reducible, saving items from reducible in-memory until a consumer
  reduces the buffer.

  Reducibles are not required to expose a data container for the sequence they
  represent, meaning items in the reducible may not be represented in-memory
  at all. This is great for representing potentially infinite data structures
  like "mouse clicks over time", or "data streamed from server". However,
  sometimes it's important to reduce all items in the reducible, even if the
  item was emitted at a point in the past. This is where buffer comes in handy.
  It stores a backlog of previously emitted items in-memory until you're
  ready to consume.
  **/
  var self = convert(source, buffer.accumulate)
  self[state] = null
  self[input] = source
  self[queued] = []
  self[forward] = function(value) {
    self[queued].push(value)
  }
  accumulate(source, function(value) {
    self[state] = self[forward](value, self[state])
  })
  return self
}
buffer.accumulate = function(buffer, next, initial) {
  if (isDrained(buffer)) return accumulate(buffer[input], next, initial)
  buffer[state] = drain(buffer, next, initial)
  buffer[forward] = next
  return buffer
}

module.exports = buffer
<commit_msg>Explain how buffer.accumulate works<commit_after>/* vim:set ts=2 sw=2 sts=2 expandtab */
/*jshint asi: true undef: true es5: true node: true browser: true devel: true
         forin: true latedef: false globalstrict: true */

'use strict';

var Name = require('name')
var Method = require('method')

var core = require('./core'),
    convert = core.convert, accumulate = core.accumulate

var queued = Name()
var input = Name()
var forward = Name()
var state = Name()

function drain(buffer, next, result) {
  var values = buffer[queued]
  while (values.length) result = next(values.shift(), result)
  buffer[queued] = null
  return result
}

function isDrained(buffer) {
  return buffer[queued] === null
}

function buffer(source) {
  /**
  Buffer a reducible, saving items from reducible in-memory until a consumer
  reduces the buffer.

  Reducibles are not required to expose a data container for the sequence they
  represent, meaning items in the reducible may not be represented in-memory
  at all. This is great for representing potentially infinite data structures
  like "mouse clicks over time", or "data streamed from server". However,
  sometimes it's important to reduce all items in the reducible, even if the
  item was emitted at a point in the past. This is where buffer comes in handy.
  It stores a backlog of previously emitted items in-memory until you're
  ready to consume.
  **/
  var self = convert(source, buffer.accumulate)
  self[state] = null
  self[input] = source
  self[queued] = []
  self[forward] = function(value) {
    self[queued].push(value)
  }
  accumulate(source, function(value) {
    self[state] = self[forward](value, self[state])
  })
  return self
}
buffer.accumulate = function(buffer, next, initial) {
  // If buffer has already been drained accumulate from the original source.
  if (isDrained(buffer)) return accumulate(buffer[input], next, initial)
  // Otherwise, drain the buffer, passing items to the accumulating function.
  buffer[state] = drain(buffer, next, initial)
  // Overshadow forward function, insuring that
  // future values are not buffered, and are instead passed directly to the
  // accumulation function.
  buffer[forward] = next
  return buffer
}

module.exports = buffer
<|endoftext|>


<commit_before><commit_msg>quickAlgo: Fix i18n message name<commit_after><|endoftext|>


<commit_before>// Manage the small views in the sidebar, which show only a subset of the data
view.manageSideViews=function(animate){

// Compute the size of the histogram, as it impacts the number of authors that can be shown
var histogramWidth = Math.max(window.innerWidth/10,180),
    histogramHeight=150;

//////////////////      authors list       ///////////////////////////////

//------------------DATA JOIN-------------------//
var authors = d3.select("#authors-list").selectAll(".author")
.data(global.frequentAuthors)

//--------------------ENTER---------------------//
var enteringAuthors = authors.enter()
.append("li")
.attr("class","author")
.style("display",function(a,i) { return (i*20+164) < window.innerHeight-histogramHeight-20? "":"none";  })
// this is super ugly...

//------------------ENTER+UPDATE-------------------//
authors
.text(function(d) { return d.author + " (" + d.frequency + ")"; })

//--------------------EXIT---------------------//
authors.exit().remove();

//////////////////		histogram 		///////////////////////////////

var values=global.publicationYears();

var margin = {top: 10, right: 15, bottom: 30, left: 5},
    innerWidth = histogramWidth - margin.left - margin.right,
    innerHeight = histogramHeight - margin.top - margin.bottom;

// fixed boundaries to allow comparisons across different sets of papers
var x = d3.scale.linear()
    .domain([global.oldestPublicationYear, global.latestPublicationYear])
    .range([0, innerWidth])

// Generate a histogram using uniformly-spaced bins.
var data = d3.layout.histogram()
    //.bins(x.ticks(parameters.nBinsYears))
    .bins(x.ticks(global.latestPublicationYear-global.oldestPublicationYear))
    (values);

var y = d3.scale.linear()
    .domain([0, d3.max(data, function(d) { return d.y; })])
    .range([innerHeight, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .ticks(parameters.nBinsYears)
    .tickFormat(d3.format("d"))
    .orient("bottom");

//--------------- draw static elements ----------//
d3.select("svg#publication-years").attr("width", innerWidth + margin.left + margin.right)
    .attr("height", innerHeight + margin.top + margin.bottom)

var histogram = d3.select("svg#publication-years #histogram")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

histogram.select("#x-axis")
    .attr("transform", "translate(0," + innerHeight + ")")
    .call(xAxis);

//------------------DATA JOIN-------------------//
var bars = histogram.selectAll(".bar")
    .data(data)

//--------------------ENTER---------------------//
var enteringBars = bars.enter()
    .append("g")
    .attr("class", "bar")
    .attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });

enteringBars.append("rect")
    .attr("x", 1)
    .attr("width", x(data[1].x)-x(data[0].x))
    .attr("y", function(d) { return innerHeight - y(d.y); })
    .attr("height", 0)

    .append("svg:title")
    .text(function(d) { return d.y+" papers in "+d.x; })

/*
* Since the bars are very narrow, we don't show a number inside them
enteringBars.append("text")
    .attr("dy", ".75em")
    .attr("text-anchor", "middle")
    .attr("x", (x(data[1].x)-x(data[0].x)) / 2)
    .attr("y",innerHeight)
    .text(function(d) { return d.y>0? d.y : ""; });
*/

//------------------ENTER+UPDATE----------------//
var t0=bars.transition().duration(parameters.fringePapersPositionTransitionDuration[animate])
        .ease(parameters.fringePapersTransitionEasing)

t0.attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });

t0.select("rect")
    .attr("y", 0)
    .attr("height", function(d) { return innerHeight - y(d.y); })
    .attr("width", x(data[1].x)-x(data[0].x))

/*t0.select("text")
    .attr("y", 6)
    .attr("x", (x(data[1].x)-x(data[0].x)) / 2)
    .text(function(d) { return d.y>0? d.y : ""; })*/

//--------------------EXIT---------------------//
// although this should probably never happen (always same number of bins)
bars.exit().remove();
}<commit_msg>fixing histogram tooltips<commit_after>// Manage the small views in the sidebar, which show only a subset of the data
view.manageSideViews=function(animate){

// Compute the size of the histogram, as it impacts the number of authors that can be shown
var histogramWidth = Math.max(window.innerWidth/10,180),
    histogramHeight=150;

//////////////////      authors list       ///////////////////////////////

//------------------DATA JOIN-------------------//
var authors = d3.select("#authors-list").selectAll(".author")
.data(global.frequentAuthors)

//--------------------ENTER---------------------//
var enteringAuthors = authors.enter()
.append("li")
.attr("class","author")
.style("display",function(a,i) { return (i*20+164) < window.innerHeight-histogramHeight-20? "":"none";  })
// this is super ugly...

//------------------ENTER+UPDATE-------------------//
authors
.text(function(d) { return d.author + " (" + d.frequency + ")"; })

//--------------------EXIT---------------------//
authors.exit().remove();

//////////////////		histogram 		///////////////////////////////

var values=global.publicationYears();

var margin = {top: 10, right: 15, bottom: 30, left: 5},
    innerWidth = histogramWidth - margin.left - margin.right,
    innerHeight = histogramHeight - margin.top - margin.bottom;

// fixed boundaries to allow comparisons across different sets of papers
var x = d3.scale.linear()
    .domain([global.oldestPublicationYear, global.latestPublicationYear])
    .range([0, innerWidth])

// Generate a histogram using uniformly-spaced bins.
var data = d3.layout.histogram()
    //.bins(x.ticks(parameters.nBinsYears))
    .bins(x.ticks(global.latestPublicationYear-global.oldestPublicationYear))
    (values);

var y = d3.scale.linear()
    .domain([0, Math.max(3,d3.max(data, function(d) { return d.y; })) ])
    .range([innerHeight, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .ticks(parameters.nBinsYears)
    .tickFormat(d3.format("d"))
    .orient("bottom");

//--------------- draw static elements ----------//
d3.select("svg#publication-years").attr("width", innerWidth + margin.left + margin.right)
    .attr("height", innerHeight + margin.top + margin.bottom)

var histogram = d3.select("svg#publication-years #histogram")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

histogram.select("#x-axis")
    .attr("transform", "translate(0," + innerHeight + ")")
    .call(xAxis);

//------------------DATA JOIN-------------------//
var bars = histogram.selectAll(".bar")
    .data(data)

//--------------------ENTER---------------------//
var enteringBars = bars.enter()
    .append("g")
    .attr("class", "bar")
    .attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });

enteringBars.append("rect")
    .attr("x", 1)
    .attr("width", x(data[1].x)-x(data[0].x))
    .attr("y", function(d) { return innerHeight - y(d.y); })
    .attr("height", 0)

    .append("svg:title")
    .attr("class","tooltip")

/*
* Since the bars are very narrow, we don't show a number inside them
enteringBars.append("text")
    .attr("dy", ".75em")
    .attr("text-anchor", "middle")
    .attr("x", (x(data[1].x)-x(data[0].x)) / 2)
    .attr("y",innerHeight)
    .text(function(d) { return d.y>0? d.y : ""; });
*/

//------------------ENTER+UPDATE----------------//
var t0=bars.transition().duration(parameters.fringePapersPositionTransitionDuration[animate])
        .ease(parameters.fringePapersTransitionEasing)

t0.attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });

t0.select("rect")
    .attr("y", 0)
    .attr("height", function(d) { return innerHeight - y(d.y); })
    .attr("width", x(data[1].x)-x(data[0].x))

    .select(".tooltip")
    .text(function(d) { return d.y+" paper"+(d.y>1? "s":"")+" in "+d.x; })

/*t0.select("text")
    .attr("y", 6)
    .attr("x", (x(data[1].x)-x(data[0].x)) / 2)
    .text(function(d) { return d.y>0? d.y : ""; })*/

//--------------------EXIT---------------------//
// although this should probably never happen (always same number of bins)
bars.exit().remove();
}<|endoftext|>


<commit_before>// See Purple/license.txt for Google BSD license
// Copyright 2011 Google, Inc. johnjbarton@johnjbarton.com

define(['../lib/domplate/lib/domplate', '../resources/BaseRep', '../resources/Resources'], function (domplate, BaseRep, Resources) {

  //  http://code.google.com/chrome/devtools/docs/protocol/0.1/console.html#type-ConsoleMessage

  with(domplate.tags) {
    var StackFrameRep =  domplate.domplate(
      BaseRep,
      {
        stackFrameTag:
              TR({'class':'callStackFrame', },
                TD('$object|getFunctionName'),
                TD({'title':'$object|getURL', 'class': '$object|getPartLinkClass'},
                   BaseRep.PARTLINK('$object|getResourceName')
                )
              )
      });

    ConsoleEntryRep = domplate.domplate(
      StackFrameRep,
      {
      tag: DIV({'class': 'console-$object.message.level'},
        DIV({'class': 'linkedText $object|hasMore', 'onclick': '$toggleMore'},
          SPAN('$object.message.text'),
          SPAN({'title':'$object|getURL', 'class': 'messageLink $object.message|getPartLinkClass'},
                   BaseRep.PARTLINK('$object|getResourceName')
          )
        ),
        TABLE({'class':'callStack'},
          TBODY(
            FOR('frame', '$object.message|getFrames',
              TAG(StackFrameRep.stackFrameTag, {object: '$frame'})
            )
          )
        )
      ),
      getURL: function(object) {
        return object.message.url;
      },
      toggleMore: function(event) {
        var target = event.currentTarget;  // the element with the handler
        target.classList.toggle('hadMore');
        target.classList.toggle('hasMore');
      },
      hasMore: function(object) {
        return this.getFrames(object).length ? 'hasMore' : '';
      },
      getFrames: function(consoleMessage) {
        return consoleMessage.stackTrace || [];
      },

      getFunctionName: function(frame) {
        return frame.functionName;
      },
      getPartLinkClass: function(object) {
        var url = object.url;
        var resource = Resources.get(url);
        return (resource && resource.hasSource) ? 'partLink' : '';
      },
      getResourceName: function(object) {
        var url = this.getURL(object);
        var splits = url.split('/');
        return splits.slice(-1);
      }

    });

    ConsoleEntryRep.messagesClearedEntryRep = domplate.domplate({
        tag: DIV({'class':'consoleCleared'}, "Console Cleared")
      });

    ConsoleEntryRep.InternalExceptionTag = domplate.domplate(
      ConsoleEntryRep,
      {
      tag: DIV({'class': 'console-error internalError hasMore', 'onclick': '$toggleMore'}, '$object.message',
        TABLE({'class':'callStack'},
          TBODY (
            FOR('frame', '$object|getFrames',
              TAG(StackFrameRep.stackFrameTag, {object: '$frame'})
            )
          )
        )
      ),
      getFrames: function(message) {
        var stack = message.stack;
        // The internal errors has a funky string stack
        var frames = [];
        if (!stack) {
          return frames;
        }
        var frameStrings = stack.split('\n');
        // zeroth entry is exception message
        for (var i = 1; i < frameStrings.length; i++) {
          var frame = {};
          //eg:     at Object.<anonymous> (eval at <anonymous> (http://localhost:8080/file/f/lib/domplate/lib/domplate.js:482:34))
          var frameString = frameStrings[i];
          var splits = frameString.split(/\s/);
          frame.functionName = splits.slice(5,-1).join(' ');
          var fileArea = splits.slice(-1)[0];
          var m = /\(([^\)]*)\)/.exec(fileArea);
          var colonSplits = m[1].split(':');
          frame.url = colonSplits.slice(0, -2).join('');
          frame.lineNumber = colonSplits.slice(-2, -1)[0];
          frame.columnNumber = colonSplits.slice(-1)[0];
          frames.push(frame);
        }
        return frames;
      },

    });
  }

  return ConsoleEntryRep;
});
<commit_msg>add support for line positions<commit_after>// See Purple/license.txt for Google BSD license
// Copyright 2011 Google, Inc. johnjbarton@johnjbarton.com

define(['../lib/domplate/lib/domplate', '../resources/BaseRep', '../resources/Resources'], function (domplate, BaseRep, Resources) {

  //  http://code.google.com/chrome/devtools/docs/protocol/0.1/console.html#type-ConsoleMessage

  with(domplate.tags) {
    var StackFrameRep =  domplate.domplate(
      BaseRep,
      {
        stackFrameTag:
              TR({'class':'callStackFrame', },
                TD('$object|getFunctionName'),
                TD({'title':'$object|getURL', 'class': '$object|getPartLinkClass'},
                   BaseRep.PARTLINK('$object|getResourceName')
                )
              )
      });

    ConsoleEntryRep = domplate.domplate(
      StackFrameRep,
      {
      tag: DIV({'class': 'console-$object.message.level'},
        DIV({'class': 'linkedText $object|hasMore', 'onclick': '$toggleMore'},
          SPAN('$object.message.text'),
          SPAN({'title':'$object|getURL', 'class': 'messageLink $object.message|getPartLinkClass'},
                   BaseRep.PARTLINK('$object|getResourceName')
          )
        ),
        TABLE({'class':'callStack'},
          TBODY(
            FOR('frame', '$object.message|getFrames',
              TAG(StackFrameRep.stackFrameTag, {object: '$frame'})
            )
          )
        )
      ),
      getURL: function(object) {
        return object.message.url;
      },
      toggleMore: function(event) {
        var target = event.currentTarget;  // the element with the handler
        target.classList.toggle('hadMore');
        target.classList.toggle('hasMore');
      },
      hasMore: function(object) {
        return this.getFrames(object).length ? 'hasMore' : '';
      },
      getFrames: function(consoleMessage) {
        return consoleMessage.stackTrace || [];
      },

      getFunctionName: function(frame) {
        return frame.functionName;
      },
      getPartLinkClass: function(object) {
        var url = object.url;
        var resource = Resources.get(url);
        return (resource && resource.hasSource) ? 'partLink' : '';
      },
      getResourceName: function(object) {
        var url = this.getURL(object);
        var splits = url.split('/');
        return splits.slice(-1);
      },
      getLineNumber: function(object) {
        return object.message.line;
      },

    });

    ConsoleEntryRep.messagesClearedEntryRep = domplate.domplate({
        tag: DIV({'class':'consoleCleared'}, "Console Cleared")
      });

    ConsoleEntryRep.InternalExceptionTag = domplate.domplate(
      ConsoleEntryRep,
      {
      tag: DIV({'class': 'console-error internalError hasMore', 'onclick': '$toggleMore'}, '$object.message',
        TABLE({'class':'callStack'},
          TBODY (
            FOR('frame', '$object|getFrames',
              TAG(StackFrameRep.stackFrameTag, {object: '$frame'})
            )
          )
        )
      ),
      getFrames: function(message) {
        var stack = message.stack;
        // The internal errors has a funky string stack
        var frames = [];
        if (!stack) {
          return frames;
        }
        var frameStrings = stack.split('\n');
        // zeroth entry is exception message
        for (var i = 1; i < frameStrings.length; i++) {
          var frame = {};
          //eg:     at Object.<anonymous> (eval at <anonymous> (http://localhost:8080/file/f/lib/domplate/lib/domplate.js:482:34))
          var frameString = frameStrings[i];
          var splits = frameString.split(/\s/);
          frame.functionName = splits.slice(5,-1).join(' ');
          var fileArea = splits.slice(-1)[0];
          var m = /\(([^\)]*)\)/.exec(fileArea);
          var colonSplits = m[1].split(':');
          frame.url = colonSplits.slice(0, -2).join('');
          frame.lineNumber = colonSplits.slice(-2, -1)[0];
          frame.columnNumber = colonSplits.slice(-1)[0];
          frames.push(frame);
        }
        return frames;
      },

    });
  }

  return ConsoleEntryRep;
});
<|endoftext|>


<commit_before>'use strict';

/**!
 * [square]
 * @copyright (c) 2012 observe.it (observe.it) <opensource@observe.it>
 * MIT Licensed
 */

/**
 * Native modules.
 */
var EventEmitter = require('events').EventEmitter;

/**
 * Third party modules.
 */
var canihaz = require('canihaz')('square')
  , async = require('async')
  , _ = require('lodash');

/**
 * Plugin interface for square.
 *
 * @constructor
 * @param {Square} square
 * @param {Object} collection
 * @api public
 */
function Plugin(square, collection) {
  if (!(this instanceof Plugin)) return new Plugin(square, collection);
  if (!square) throw new Error('Missing square instance');
  if (!collection) throw new Error('Missing collection');

  this.square = square;           // Reference to the current square instance.
  this.logger = square.logger;    // The logger.
  this.async = async;             // Handle async operation.
  this._ = _;                     // Utilities.

  this.configure();
}

Plugin.prototype.__proto__ = EventEmitter.prototype;

_.extend(Plugin.prototype, {
    /**
     * The name of the plugin.
     *
     * @type {String}
     * @api public
     */
    name: 'plugin'

    /**
     * A small description of the plugin
     *
     * @type {String}
     * @api public
     */
  , description: 'Base template for every plugin'

    /**
     * What type of transformations does this plugin do?
     *
     * @type {String}
     * @api public
     */
  , type: Plugin.modifier

    /**
     * Array of extensions that we accept. Leave empty to accept every
     * extension.
     *
     * @type {Array}
     * @api public
     */
  , accepts: []

    /**
     * Which distributions do we parse modify.
     *
     * @type {Array}
     * @api public
     */
  , distributions: []

    /**
     * The modules that should be lazy installed using `canihaz`
     *
     * @type {Array}
     * @api public
     */
  , requires: []

    /**
     * Configure the plugin, prepare all the things.
     *
     * @api private
     */
  , configure: function configure() {
      var pkg = this.square.package
        , configuration = pkg.configuration
        , self = this;

      // Should we allow this plugin to run? It should accept the correct
      // distribution and it should accept the given extension.
      if (!this.distribution() || !this.accepted()) {
        return this.emit('disregard');
      }

      // Check if there are any configuration options in the package.
      if (pkg.plugins && this.name in pkg.plugins) {
        _.extend(this, pkg.plugins[this.name] || {});
      }

      // Check if the bundle it self also had specific configurations for this
      // plugin.
      if (this.name in this) {
        _.extend(this, this[this.name] || {});
      }

      // Ensure that our requires is an array, before we continue
      if (!Array.isArray(this.requires)) this.requires = [this.requires];

      if (this.requires && this.requires.length) {
        canihaz.all.apply(canihaz.all, this.requires.concat(function canihaz(err) {
          if (err) return self.emit('error', err);

          // Add all the libraries to the context, the `canihaz#all` returns an
          // error first, and then all libraries it installed or required in the
          // order as given to it, which is in our case the `this.requires` order.
          Array.prototype.slice.call(arguments, 1).forEach(function (lib, index) {
            self[self.requires[index]] = lib;
          });

          // We are now fully initialized.
          if (self.initialize) process.nextTick(self.initialize.bind(self));
        }));
      } else {
        process.nextTick(self.initialize.bind(self));
      }
    }

    /**
     * Check if this distribution is accepted.
     *
     * @returns {Boolean}
     * @api private
     */
  , distribution: function distribution() {
      if (!Array.isArray(this.distributions)) return this.distributions === this.dist;
      if (!this.distributions.length) return true;

      return !!~this.distributions.indexOf(this.dist);
    }

    /**
     * Check if we accept these extensions.
     *
     * @returns {Boolean}
     * @api private
     */
  , accepted: function accepted() {
      if (!Array.isArray(this.accepts)) return this.accepts === this.extension;
      if (!this.accepts.length) return true;

      return !!~this.accepts.indexOf(this.extension);
    }
});

/**
 * Differentiate between the different types of plugins. The `update` plugin
 * only needs to run once for the whole lifetime of the script. While the minify
 * script should run against each file and a test plugin should only run after
 * everything is compiled.
 *
 * To accommodate all these different states when the plugin should run we have
 * to use plugin types.
 *
 * - Plugin.modifier: This modifies the content, and should run every single time.
 * - Plugin.after: This plugin is ran after is compiled correctly.
 * - Plugin.once: This plugin should only run once.
 *
 * @type {String} in plugin::{type} format
 * @api public
 */
Plugin.modifier = 'plugin::modifier';
Plugin.after    = 'plugin::after';
Plugin.once     = 'plugin::once';

/**
 * Make the plugin extendible so every thing inherits from this `class`.
 *
 * @type {Function}
 * @api public
 */
Plugin.extend = require('extendable');

/**
 * Expose the module.
 */
module.exports = Plugin;
<commit_msg>[api][minor] Add the correct namespace to the logging methods. [api][minor] Merge collection with `this` if it's key does not exist<commit_after>'use strict';

/**!
 * [square]
 * @copyright (c) 2012 observe.it (observe.it) <opensource@observe.it>
 * MIT Licensed
 */

/**
 * Native modules.
 */
var EventEmitter = require('events').EventEmitter;

/**
 * Third party modules.
 */
var canihaz = require('canihaz')('square')
  , async = require('async')
  , _ = require('lodash');

/**
 * Plugin interface for square.
 *
 * @constructor
 * @param {Square} square
 * @param {Object} collection
 * @api public
 */
function Plugin(square, collection) {
  if (!(this instanceof Plugin)) return new Plugin(square, collection);
  if (!square) throw new Error('Missing square instance');
  if (!collection) throw new Error('Missing collection');

  var self = this;

  this.square = square;           // Reference to the current square instance.
  this.async = async;             // Handle async operation.
  this._ = _;                     // Utilities.
  this.logger = {};               // Our logging utility

  // Provide a default namespace to the logging method, we are going to prefix
  // it with the plugin's name which will help with the debug ability of this
  // module.
  Object.keys(square.logger.levels).forEach(function generate(level) {
    self.logger[level] = square[level].bind(square, self.name);
  });

  // Merge the given collection with the plugin, but don't override the default
  // values.
  Object.keys(collection).forEach(function each(key) {
    if (key in self) {
      return self.logger.warning(
          'The '
        + self.name
        + ' plugin uses a property that would be overriden by the collection.'
      );
    }

    // Add the property
    self[key] = collection[key];
  });

  this.configure();
}

Plugin.prototype.__proto__ = EventEmitter.prototype;

_.extend(Plugin.prototype, {
    /**
     * The name of the plugin.
     *
     * @type {String}
     * @api public
     */
    name: 'plugin'

    /**
     * A small description of the plugin
     *
     * @type {String}
     * @api public
     */
  , description: 'Base template for every plugin'

    /**
     * What type of transformations does this plugin do?
     *
     * @type {String}
     * @api public
     */
  , type: Plugin.modifier

    /**
     * Array of extensions that we accept. Leave empty to accept every
     * extension.
     *
     * @type {Array}
     * @api public
     */
  , accepts: []

    /**
     * Which distributions do we parse modify.
     *
     * @type {Array}
     * @api public
     */
  , distributions: []

    /**
     * The modules that should be lazy installed using `canihaz`
     *
     * @type {Array}
     * @api public
     */
  , requires: []

    /**
     * Configure the plugin, prepare all the things.
     *
     * @api private
     */
  , configure: function configure() {
      var pkg = this.square.package
        , configuration = pkg.configuration
        , self = this;

      // Should we allow this plugin to run? It should accept the correct
      // distribution and it should accept the given extension.
      if (!this.distribution() || !this.accepted()) {
        return this.emit('disregard');
      }

      // Check if there are any configuration options in the package.
      if (pkg.plugins && this.name in pkg.plugins) {
        _.extend(this, pkg.plugins[this.name] || {});
      }

      // Check if the bundle it self also had specific configurations for this
      // plugin.
      if (this.name in this) {
        _.extend(this, this[this.name] || {});
      }

      // Ensure that our requires is an array, before we continue
      if (!Array.isArray(this.requires)) this.requires = [this.requires];

      if (this.requires && this.requires.length) {
        canihaz.all.apply(canihaz.all, this.requires.concat(function canihaz(err) {
          if (err) return self.emit('error', err);

          // Add all the libraries to the context, the `canihaz#all` returns an
          // error first, and then all libraries it installed or required in the
          // order as given to it, which is in our case the `this.requires` order.
          Array.prototype.slice.call(arguments, 1).forEach(function (lib, index) {
            self[self.requires[index]] = lib;
          });

          // We are now fully initialized.
          if (self.initialize) process.nextTick(self.initialize.bind(self));
        }));
      } else {
        process.nextTick(self.initialize.bind(self));
      }
    }

    /**
     * Check if this distribution is accepted.
     *
     * @returns {Boolean}
     * @api private
     */
  , distribution: function distribution() {
      if (!Array.isArray(this.distributions)) return this.distributions === this.dist;
      if (!this.distributions.length) return true;

      return !!~this.distributions.indexOf(this.dist);
    }

    /**
     * Check if we accept these extensions.
     *
     * @returns {Boolean}
     * @api private
     */
  , accepted: function accepted() {
      if (!Array.isArray(this.accepts)) return this.accepts === this.extension;
      if (!this.accepts.length) return true;

      return !!~this.accepts.indexOf(this.extension);
    }
});

/**
 * Differentiate between the different types of plugins. The `update` plugin
 * only needs to run once for the whole lifetime of the script. While the minify
 * script should run against each file and a test plugin should only run after
 * everything is compiled.
 *
 * To accommodate all these different states when the plugin should run we have
 * to use plugin types.
 *
 * - Plugin.modifier: This modifies the content, and should run every single time.
 * - Plugin.after: This plugin is ran after is compiled correctly.
 * - Plugin.once: This plugin should only run once.
 *
 * @type {String} in plugin::{type} format
 * @api public
 */
Plugin.modifier = 'plugin::modifier';
Plugin.after    = 'plugin::after';
Plugin.once     = 'plugin::once';

/**
 * Make the plugin extendible so every thing inherits from this `class`.
 *
 * @type {Function}
 * @api public
 */
Plugin.extend = require('extendable');

/**
 * Expose the module.
 */
module.exports = Plugin;
<|endoftext|>


<commit_before>/**
 * Created by zenghong on 2017/4/26.
 */

var baseUrl = 'http://' + window.location.host;
var tenders = [];

$(function () {
  $('.list-item-wrapper').click(function () {
    window.location = '/wechat2_detial';
  });

  var unVerifiedBtn = $('.un-verify');
  var verifiedBtn = $('.verified');
  var list = $('.view-list');

  unVerifiedBtn.click(function () {
    if (!unVerifiedBtn.hasClass('select')) {
      var tenders = [];
      getTenders('unpayment');
      unVerifiedBtn.addClass('select');
      verifiedBtn.removeClass('select');
    }
  });
  verifiedBtn.click(function () {
    var tenders = [];
    if (!verifiedBtn.hasClass('select')) {
      getTenders('payment');
      verifiedBtn.addClass('select');
      unVerifiedBtn.removeClass('select');
    }
  });

  unVerifiedBtn.click();

  function getTenders(type) {
    $.ajax({
      url: baseUrl + '/tender/user/getPaymentTenderList',
      method: 'post',
      data: {
        type: type
      },
      success: function (data) {
        console.log(data);
        if (!data.err) {
          appendTenderItem(data);
        }
      },
      error: function () {

      }
    });
  }

  function appendTenderItem(items) {
    items.forEach(function (item) {
      var title = '';
      if (item.mobile_goods && item.mobile_goods.length > 0) {
        item.mobile_goods.forEach(function (good) {
          title += good.name + ' ' + good.count + good.unit + ', '
        });
      }

      var jq = $(
        '
' +
        '
' +
        '
' +
        item.order_number +
        '
' +
        '
' +
        '
' + title + '
' +
        '
' +
        '
' +
        '起 ： ' + item.pickup_address +
        '
' +
        '
' +
        '到 ： ' + item.delivery_address +
        '
' +
        '
' +
        '
' +
        '
' +
        '
'
      );

      list.append(jq);
    });

  }
});<commit_msg>Add tender click event<commit_after>/**
 * Created by zenghong on 2017/4/26.
 */

var baseUrl = 'http://' + window.location.host;
var tenders = [];

$(function () {
  $('.list-item-wrapper').click(function () {
    window.location = '/wechat2_detial';
  });

  var unVerifiedBtn = $('.un-verify');
  var verifiedBtn = $('.verified');
  var list = $('.view-list');

  unVerifiedBtn.click(function () {
    if (!unVerifiedBtn.hasClass('select')) {
      var tenders = [];
      getTenders('unpayment');
      unVerifiedBtn.addClass('select');
      verifiedBtn.removeClass('select');
    }
  });
  verifiedBtn.click(function () {
    var tenders = [];
    if (!verifiedBtn.hasClass('select')) {
      getTenders('payment');
      verifiedBtn.addClass('select');
      unVerifiedBtn.removeClass('select');
    }
  });

  unVerifiedBtn.click();

  function getTenders(type) {
    $.ajax({
      url: baseUrl + '/tender/user/getPaymentTenderList',
      method: 'post',
      data: {
        type: type
      },
      success: function (data) {
        console.log(data);
        if (!data.err) {
          appendTenderItem(data);
        }
      },
      error: function () {

      }
    });
  }

  function appendTenderItem(items) {
    items.forEach(function (item) {
      var title = '';
      if (item.mobile_goods && item.mobile_goods.length > 0) {
        item.mobile_goods.forEach(function (good) {
          title += good.name + ' ' + good.count + good.unit + ', '
        });
      }

      var jq = $(
        '
' +
        '
' +
        '
' +
        item.order_number +
        '
' +
        '
' +
        '
' + title + '
' +
        '
' +
        '
' +
        '起 ： ' + item.pickup_address +
        '
' +
        '
' +
        '到 ： ' + item.delivery_address +
        '
' +
        '
' +
        '
' +
        '
' +
        '
'
      );

      jq.click(function () {
        window.location = '/wechat2_detial?tender_id' + $(this).id;
      });

      list.append(jq);
    });

  }
});<|endoftext|>


<commit_before>var userid;
//arrays gebruikt voor autocompletes en selecteren waarde hiervan.
var studentLists = [];
var studentListsid = [];
var teachers = []
var teachersid = []

function pageViewModel(gvm) {
    gvm.projecttitle = ko.observable("");
    gvm.userId = -1;
    gvm.coupledCount = 0;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    gvm.addmoduleBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Addmodule");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + $("#projectHeader").data('value'), function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.coupledLists = ko.observableArray([]);
    gvm.availableLists = ko.observableArray([]);

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

        $("#uncouplebtn-" + id).click(function(){
            showYesNoModal("Bent u zeker dat u dit item wil ontkoppelen?", function(val){
                if(val){
                    $.ajax({
                        url: '/api/project/' + $("#projectHeader").data('value') +'/studentlist/uncouple/' + id,
                        type: "DELETE",
                        success: function() {
                            gvm.coupledCount--;
                            viewModel.coupledLists.remove(tblOject);
                        }
                    });

                }
            });
        });
    }

    gvm.addAvailableLists = function(id, name) {
        var tblOject = {tid: id, tname: name};
        gvm.availableLists.push(tblOject);

        $("#couplebtn-" + id).click(function(){
            if(gvm.coupledCount == 0) {
                $.ajax({
                    url: '/api/project/' + $("#projectHeader").data('value') + '/studentlist/' + id,
                    type: "POST",
                    success: function() {
                        gvm.coupledCount++;
                        viewModel.coupledLists.push(tblOject);
                    }
                });
            } else {
                alert("list already coupled");
            }
        });
    }

    gvm.getCoupledLists = function() {
        $.getJSON('/api/project/' + $("#projectHeader").data('value') + '/coupledlists', function(data) {
            $.each(data, function(i, item) {
                gvm.coupledCount++;
                gvm.addCoupledList(item.id, item.name);
            });
        });
}

    gvm.getAvailableLists = function() {
        $.getJSON('/api/studentlists/' + gvm.userId, function(data) {
            $.each(data, function(i, item) {
                gvm.addAvailableLists(item.id, item.name);
            });
        });
    }

    // The table data observable array
    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(studid, userid, studlist, name) {
        // Push data
        var tblOject = {tid: studid + "-" + userid, tstudlist: studlist, tteacher: name};
        gvm.tabledata.push(tblOject);

        // Attach delete handler to delete button
        $('#removebtn-' + studid + "-" + userid).bind('click', function(event, data){
            // Delete the table item
            deleteTableItem(studid + "-" + userid, tblOject);
            event.stopPropagation();
        });
            }

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

 }

 function getAllTeachers() {
     teachers = [];
     teachersid = [];
     $.getJSON('/api/getteacherrapport', function(data) {
        $.each(data, function(i, item) {
            teachers.push(item.firstname + " " + item.lastname);
            teachersid.push(item.id);
        });
    });
    return teachers;
 }

function getAllStudentLists() {
    studentLists = [];
    studentListsid = [];
    $.getJSON('/api/studentlistsrapporten/' + userid, function (data) {
        $.each(data, function (i, item) {
            studentLists.push(item.name);
            studentListsid.push(item.id);
        });
    });
    return studentLists;
}

function getTeacherid() {

    // functie voor het opsplitsen van naam indien gewenst.
    // console.log(getTeacherID($('#teachersComplete').val().substr(0,$('#teachersComplete').val().indexOf(' ')), $('#teachersComplete').val().substr($('#teachersComplete').val().indexOf(' ')+1)));

    var i = 0;
    var teacher = 0;
    teachers.forEach(function(entry) {
        if (new String(entry).valueOf() == new String($('#teachersComplete').val()).valueOf()) {
            teacher = teachersid[i];
        }
        i+= 1;
    });
    return teacher
}

function getGroupid() {
    var i = 0;
    var studlijst;
    studentLists.forEach(function(entry) {
        if (new String(entry).valueOf() == new String($('#studentListComplete').val()).valueOf()) {
            studlijst = (studentListsid[i]);
        }
        i+= 1;
    });
    return studlijst;
}

 function addGroup(courseid, teacherid, studlijstid) {
     //TODO if teacher or studlijst = 0 dan bestaat deze niet!
     //TODO momenteel nog mogelijk om meer als 1 maal zelfde velden in te voeren.

         $.ajax({
            url: "/api/coursecouple/" + courseid + "/" + studlijstid + "/" + teacherid,
             type: "POST",
             data: {'course': courseid, 'teacher': teacherid, 'studentlist': teacherid},
             success: function(data) {
                 //callback(true);
             },
             error: function(data) {
                 console.log('Failed to add new student');
                 //callback(false);
             }
         });
 }

/*
 * Load page of the table
 */
function loadTablePage(pagenr,course)
{
    $.getJSON('/api/getStudentGroupTeacherByCourseID/page/' + pagenr + '/' + course, function(data){

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

        // Load table data
        $.each(data.data, function(i, item) {
            console.log("studid: " + item.studid + " en userid: " + item.userid);
           viewModel.addTableData(item.studid, item.userid , item.name , item.firstname + " " + item.lastname);
        });

        console.log(data.prev);
        /* 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);
            });
        }

        console.log(data.next);
        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);
                });
            }
        });
    });
}

/*
 * Delete item from table given the id.
 */
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){
            //courseid = $('#projectHeader').attr("data-value");
            //studielijstid = "studid " + id.substr(0,id.indexOf('-'));
            //teacherid = "userid " + id.substr(id.indexOf('-')+1);

             $.ajax({
             url: "/api/setInactiveCourseStudlistCouple/" + $('#projectHeader').attr("data-value") + '/' + id.substr(0,id.indexOf('-')) + '/' + id.substr(id.indexOf('-')+1),
             type: "DELETE",
             success: function() {
             viewModel.tabledata.remove(tblOject);
             }
             });

            }
    });
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getCoupledLists();

    //Add Course members

    $('#addGroupForm').hide();

    $('#addCoursemembers').click(function() {
        $("#addGroupForm").show();
        $('#teachersComplete').autocomplete({ source: getAllTeachers() });
        $('#studentListComplete').autocomplete({ source: getAllStudentLists() });
    });

    $('#addGroupBtn').click(function() {
         addGroup($('#projectHeader').attr("data-value"), getTeacherid(), getGroupid());

        $('#studentListComplete').val("");
        $('#teachersComplete').val("");

        loadTablePage(1,$('#projectHeader').attr("data-value"));

        $('addGroupForm').hide();
    });

    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        userid = data.id;
        viewModel.getAvailableLists(data.id);
    });
    loadTablePage(1,$('#projectHeader').attr("data-value"));
}
<commit_msg>pagers doen werken.<commit_after>var userid;
//arrays gebruikt voor autocompletes en selecteren waarde hiervan.
var studentLists = [];
var studentListsid = [];
var teachers = []
var teachersid = []

function pageViewModel(gvm) {
    gvm.projecttitle = ko.observable("");
    gvm.userId = -1;
    gvm.coupledCount = 0;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    gvm.addmoduleBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Addmodule");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + $("#projectHeader").data('value'), function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.coupledLists = ko.observableArray([]);
    gvm.availableLists = ko.observableArray([]);

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

        $("#uncouplebtn-" + id).click(function(){
            showYesNoModal("Bent u zeker dat u dit item wil ontkoppelen?", function(val){
                if(val){
                    $.ajax({
                        url: '/api/project/' + $("#projectHeader").data('value') +'/studentlist/uncouple/' + id,
                        type: "DELETE",
                        success: function() {
                            gvm.coupledCount--;
                            viewModel.coupledLists.remove(tblOject);
                        }
                    });

                }
            });
        });
    }

    gvm.addAvailableLists = function(id, name) {
        var tblOject = {tid: id, tname: name};
        gvm.availableLists.push(tblOject);

        $("#couplebtn-" + id).click(function(){
            if(gvm.coupledCount == 0) {
                $.ajax({
                    url: '/api/project/' + $("#projectHeader").data('value') + '/studentlist/' + id,
                    type: "POST",
                    success: function() {
                        gvm.coupledCount++;
                        viewModel.coupledLists.push(tblOject);
                    }
                });
            } else {
                alert("list already coupled");
            }
        });
    }

    gvm.getCoupledLists = function() {
        $.getJSON('/api/project/' + $("#projectHeader").data('value') + '/coupledlists', function(data) {
            $.each(data, function(i, item) {
                gvm.coupledCount++;
                gvm.addCoupledList(item.id, item.name);
            });
        });
}

    gvm.getAvailableLists = function() {
        $.getJSON('/api/studentlists/' + gvm.userId, function(data) {
            $.each(data, function(i, item) {
                gvm.addAvailableLists(item.id, item.name);
            });
        });
    }

    // The table data observable array
    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(studid, userid, studlist, name) {
        // Push data
        var tblOject = {tid: studid + "-" + userid, tstudlist: studlist, tteacher: name};
        gvm.tabledata.push(tblOject);

        // Attach delete handler to delete button
        $('#removebtn-' + studid + "-" + userid).bind('click', function(event, data){
            // Delete the table item
            deleteTableItem(studid + "-" + userid, tblOject);
            event.stopPropagation();
        });
            }

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

 }

 function getAllTeachers() {
     teachers = [];
     teachersid = [];
     $.getJSON('/api/getteacherrapport', function(data) {
        $.each(data, function(i, item) {
            teachers.push(item.firstname + " " + item.lastname);
            teachersid.push(item.id);
        });
    });
    return teachers;
 }

function getAllStudentLists() {
    studentLists = [];
    studentListsid = [];
    $.getJSON('/api/studentlistsrapporten/' + userid, function (data) {
        $.each(data, function (i, item) {
            studentLists.push(item.name);
            studentListsid.push(item.id);
        });
    });
    return studentLists;
}

function getTeacherid() {

    // functie voor het opsplitsen van naam indien gewenst.
    // console.log(getTeacherID($('#teachersComplete').val().substr(0,$('#teachersComplete').val().indexOf(' ')), $('#teachersComplete').val().substr($('#teachersComplete').val().indexOf(' ')+1)));

    var i = 0;
    var teacher = 0;
    teachers.forEach(function(entry) {
        if (new String(entry).valueOf() == new String($('#teachersComplete').val()).valueOf()) {
            teacher = teachersid[i];
        }
        i+= 1;
    });
    return teacher
}

function getGroupid() {
    var i = 0;
    var studlijst;
    studentLists.forEach(function(entry) {
        if (new String(entry).valueOf() == new String($('#studentListComplete').val()).valueOf()) {
            studlijst = (studentListsid[i]);
        }
        i+= 1;
    });
    return studlijst;
}

 function addGroup(courseid, teacherid, studlijstid) {
     //TODO if teacher or studlijst = 0 dan bestaat deze niet!
     //TODO momenteel nog mogelijk om meer als 1 maal zelfde velden in te voeren.

         $.ajax({
            url: "/api/coursecouple/" + courseid + "/" + studlijstid + "/" + teacherid,
             type: "POST",
             data: {'course': courseid, 'teacher': teacherid, 'studentlist': teacherid},
             success: function(data) {
                 //callback(true);
             },
             error: function(data) {
                 console.log('Failed to add new student');
                 //callback(false);
             }
         });
 }

/*
 * Load page of the table
 */
function loadTablePage(pagenr,course)
{
    $.getJSON('/api/getStudentGroupTeacherByCourseID/page/' + pagenr + '/' + course, function(data){

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

        // Load table data
        $.each(data.data, function(i, item) {
            console.log("studid: " + item.studid + " en userid: " + item.userid);
           viewModel.addTableData(item.studid, item.userid , item.name , item.firstname + " " + item.lastname);
        });

        /* 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);
                });
            }
        });
    });
}

/*
 * Delete item from table given the id.
 */
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){
            //courseid = $('#projectHeader').attr("data-value");
            //studielijstid = "studid " + id.substr(0,id.indexOf('-'));
            //teacherid = "userid " + id.substr(id.indexOf('-')+1);

             $.ajax({
             url: "/api/setInactiveCourseStudlistCouple/" + $('#projectHeader').attr("data-value") + '/' + id.substr(0,id.indexOf('-')) + '/' + id.substr(id.indexOf('-')+1),
             type: "DELETE",
             success: function() {
             viewModel.tabledata.remove(tblOject);
             }
             });

            }
    });
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getCoupledLists();

    //Add Course members

    $('#addGroupForm').hide();

    $('#addCoursemembers').click(function() {
        $("#addGroupForm").show();
        $('#teachersComplete').autocomplete({ source: getAllTeachers() });
        $('#studentListComplete').autocomplete({ source: getAllStudentLists() });
    });

    $('#addGroupBtn').click(function() {
         addGroup($('#projectHeader').attr("data-value"), getTeacherid(), getGroupid());

        $('#studentListComplete').val("");
        $('#teachersComplete').val("");

        loadTablePage(1,$('#projectHeader').attr("data-value"));

        $('addGroupForm').hide();
    });

    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        userid = data.id;
        viewModel.getAvailableLists(data.id);
    });
    loadTablePage(1,$('#projectHeader').attr("data-value"));
}
<|endoftext|>


<commit_before>embedMe.addModule(function(){
	"use strict";
	return {
		name: "Twitch",
		domains: ["www.twitch.tv"],
		getPatterns: function() {
			return [
				/twitch\.tv\/(\w+)\/v\/(\d+)/i
			];
		},
		getEmbedFunction: function() {
			return function (user, id) {
				var container = document.createElement("div");
				container.innerHTML = '<object bgcolor="#000000" data="//www.twitch.tv/swflibs/TwitchPlayer.swf" height="378" id="clip_embed_player_flash" type="application/x-shockwave-flash" width="620"><param name="movie" value="//www.twitch.tv/swflibs/TwitchPlayer.swf" /><param name="allowScriptAccess" value="always" /><param name="allowNetworking" value="all" /><param name="allowFullScreen" value="true" /><param name="flashvars" value="channel=' + user + '&auto_play=false&autoplay=false&autostart=false&start_volume=25&videoId=v' + id + '" /></object>
Watch live video from ' + user + ' on Twitch';
				return container;
			};
		}
	};
});
<commit_msg>Twitch does not support ssh<commit_after>embedMe.addModule(function(){
	"use strict";
	return {
		name: "Twitch",
		domains: ["www.twitch.tv"],
		getPatterns: function() {
			return [
				/twitch\.tv\/(\w+)\/v\/(\d+)/i
			];
		},
		getEmbedFunction: function() {
			return function (user, id) {
				var container = document.createElement("div");
				container.innerHTML = '<object bgcolor="#000000" data="http://www.twitch.tv/swflibs/TwitchPlayer.swf" height="378" id="clip_embed_player_flash" type="application/x-shockwave-flash" width="620"><param name="movie" value="http://www.twitch.tv/swflibs/TwitchPlayer.swf" /><param name="allowScriptAccess" value="always" /><param name="allowNetworking" value="all" /><param name="allowFullScreen" value="true" /><param name="flashvars" value="channel=' + user + '&auto_play=false&autoplay=false&autostart=false&start_volume=25&videoId=v' + id + '" /></object>
Watch live video from ' + user + ' on Twitch';
				return container;
			};
		}
	};
});
<|endoftext|>