<commit_before>/*global PDFJS:false*/
/*eslint-env browser*/
/*eslint-env es6*/

var CSS_UNITS = 96.0 / 72.0; //this is apparently a thing.
var xform = 'transform';
['','webkit', 'Moz', 'O', 'ms'].every(function (prefix) {
    var e = prefix + (prefix ? 'T':'t') +  'ransform';
    if (typeof document.body.style[e] !== 'undefined') {
        xform = e;
        return false;
    }
    return true;
});

/*
!function (w) {

    function getOutputScale(ctx) {
        var devicePixelRatio = window.devicePixelRatio || 1;
        var backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
                                ctx.mozBackingStorePixelRatio ||
                                ctx.msBackingStorePixelRatio ||
                                ctx.oBackingStorePixelRatio ||
                                ctx.backingStorePixelRatio || 1;
        var pixelRatio = devicePixelRatio / backingStoreRatio;
        return {
            sx: pixelRatio,
            sy: pixelRatio,
            scaled: pixelRatio !== 1
        };
    }

    PDFJS.getDocument('1609.01714.pdf').then(function (pdf) {
        var pageDivs = [];
        function createPage(n) {
            if (n > pdf.numPages) {
                return;
            }
            var div = document.createElement('div');
            pageDivs.push(div);
            pdf.getPage(n).then(function (page) {
                var scale = 0.6;
                var viewport = page.getViewport(scale * CSS_UNITS);

                var canvas = document.createElement('canvas');
                var context = canvas.getContext('2d');

                var outputScale = getOutputScale(canvas);
                canvas.height = viewport.height * outputScale.sy;
                canvas.width = viewport.width * outputScale.sx;

                div.appendChild(canvas);
                page.render({
                    canvasContext: context,
                    viewport: viewport
                });
            });
            createPage(n + 1);
        }
        createPage(1);
        pageDivs.forEach(function (div) {
            document.body.appendChild(div);
        });
    });
} (window);
*/

function getOutputScale(ctx) {
    var canvas;
    if (ctx === undefined) {
        if (canvas === undefined) {
            canvas = document.createElement('canvas');
        }
        ctx = canvas.getContext('2d');
    }
    var devicePixelRatio = window.devicePixelRatio || 1;
    var backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
                            ctx.mozBackingStorePixelRatio ||
                            ctx.msBackingStorePixelRatio ||
                            ctx.oBackingStorePixelRatio ||
                            ctx.backingStorePixelRatio || 1;
    var pixelRatio = devicePixelRatio / backingStoreRatio;
    return {
        sx: pixelRatio,
        sy: pixelRatio,
        scaled: pixelRatio !== 1
    };
}

window.pdfViewer = function pdfViewer(container, documentUri) {
    // todo:
    /// Creates a pdf viewer in the given container
    /// <param name="container" type="HTMLElement">The container to create the pdf viewer in.</param>
    'use strict';

    if (container === null) {
        throw 'can not create viewer in null container';
    }
    if (container === undefined) {
        throw 'can not create viewer in undefined container';
    }
    if (!(container instanceof HTMLElement)) {
        throw 'can not create viewer in container that is not HTMLElement';
    }
    /** @type HTMLElement */
    var _container = container;

    /** @type String */
    var _uri = documentUri;
    /** @type HTMLElement */
    var _inner;
    /** @type PDFPromise<PDFDocumentProxy> */
    var _loadingTask;
    /** @type PDFDocumentProxy */
    var _pdfDocument;

    var _pages = [];
    /** @type {number} */
    var _pageCount;
    /** @type {number} */
    var _scale = defaultScale();
    /** @type {number} */
    var _page_gap = 10; //pixel space between pages

    var _resizeEventTriggered = false;

    initialiseContainers();
    setPdf(_uri);

    var _viewer = {
        position: function (value) {
            if (value === undefined) {
                return _container.scrollLeft;
            }
            _container.scrollLeft = value;
        },
    };
    return _viewer;

    function renderViewer() {
        _pages.forEach(function (p) {
            redrawPage(p);
        });
    }

    /**
     * @param {String} uri
     */
    function setPdf(uri) {
        _loadingTask = PDFJS.getDocument(uri);
        _loadingTask.then(pdfReady);
    }
    /**
     * @param {PDFDocumentProxy} pdf
     */
    function pdfReady(pdf) {
        _pdfDocument = pdf;
        _pageCount = pdf.numPages;
        addPageContainers();
        _pdfDocument.getDownloadInfo().then(pdfLoaded);
    }
    /**
     * @param {PDFDocumentProxy} pdf
     */
    function pdfLoaded() {
        //create pageViewObjects
        for (var n = 1; n <= _pageCount; ++n) {
            var pageView = {
                id: n,
                scale: _scale,
                rendered: false,
                loaded: false,
            };
            //todo: ? bind events
            _pages.push(pageView);
        }
        var pagePromises = [];
        _pages.forEach(function (pageView) {
            var pagePromise = _pdfDocument.getPage(pageView.id);
            pagePromises.push(pagePromise);
            var index = pageView.id - 1;
            /** @param {} page */
            pagePromise.then(function (page) {
                _pages[index].baseWidth = page.getViewport(1.0 * CSS_UNITS).width;
                _pages[index].defaultScale = defaultScale(_pages[index]);
                _pages[index].page = page;
                _pages[index].loaded = true;
            });
        });
        Promise.all(pagePromises).then(function () {
            _scale = _pages[0].defaultScale;
            renderViewer();
            registerEvents();
        });
    }

    function initialiseContainers() {
        _container.classList.add('pdfviewer-container');
        _inner = document.createElement('div');
        _inner.classList.add('pdfviewer-inner');
        _container.appendChild(_inner);
        //todo: add mini previews?
    }

    function addPageContainers() {
        for (var i = 0; i < _pageCount; ++i){
            var pageContainer = document.createElement('div');
            pageContainer.classList.add('pdfviewer-pagecontainer');
            pageContainer.classList.add('pdfviewer-loading');
            pageContainer.style.visibility = 'hidden';
            _inner.appendChild(pageContainer);
        }
    }

    function redrawPage(pageView) {
        var index = pageView.id - 1;
        var pageContainer = _inner.children[index];
        if (pageContainer === undefined) {
            throw 'can not redraw, not properly initialised';
        }
        var inView = pageInView(index);
        var rendered = pageView.rendered;
        var loaded = pageView.loaded;
        //draw page if it is in view and not currently rendered or has changed scale since last render.
        if (loaded && inView && (!rendered || _scale != pageView.scale)) {
            drawPage(pageView);
        }
        //clear a page which is not in view, but is currently rendered;
        if (!inView && rendered) {
            clearPage(pageView);
        }
    }

    function drawPage(pageView) {
        var index = pageView.id - 1;
        var pageContainer = _inner.children[index];

        var canvas = document.createElement('canvas');
        var outputScale = getOutputScale(canvas);
        var viewport = pageView.page.getViewport(_scale * CSS_UNITS * outputScale.sx);

        canvas.height = viewport.height;
        canvas.width = viewport.width;

        var context = canvas.getContext('2d');
        pageView.rendered = true;
        pageView.page.render({
            canvasContext: context,
            viewport: viewport
        }).then(function () {
            pageContainer.classList.remove('pdfview-loading');
            if (pageContainer.firstChild) {
                var hasChild = true;
            }
            pageContainer.appendChild(canvas);
            if (hasChild) {
                pageContainer.removeChild(pageContainer.firstChild);
            }
            pageContainer.style.visibility = 'visible';
        });
    }

    function clearPage(pageView) {
        var index = pageView.id - 1;
        var pageContainer = _inner.children[index];
        while (pageContainer.firstChild) {
            pageContainer.removeChild(pageContainer.firstChild);
        }
        pageContainer.classList.add('pdfview-loading');
        pageView.rendered = false;
    }

    function pageInView(index) {
        var pageWidth = _pages[0].baseWidth * _scale * getOutputScale().sx;
        var viewerWidth = _container.clientWidth;
        var minIndex = Math.floor(_container.scrollLeft / (pageWidth + _page_gap)) - 1; //-1 to allow an extra page to be prerendered
        var maxIndex = Math.floor((_container.scrollLeft + viewerWidth) / (pageWidth + _page_gap)) + 1; //same for the + 1

        return index >= minIndex && index <= maxIndex;
    }

    function defaultScale(page) {
        ///Determine a reasonable default scale based on device
        if (page === undefined) {
            return 1;
        }
        return window.innerWidth / (page.baseWidth * getOutputScale().sx);
    }

    function registerEvents() {
        window.addEventListener('resize', onResize);
        _container.addEventListener('scroll', onScroll);
    }

    function onResize() {
        if (!_resizeEventTriggered) {
            window.requestAnimationFrame( function () {
                renderViewer();
                _resizeEventTriggered = false;
            });
        }
        _resizeEventTriggered = true;
    }

    function onScroll() {
        if (!_resizeEventTriggered) {
            window.requestAnimationFrame( function () {
                renderViewer();
                _resizeEventTriggered = false;
            });
        }
        _resizeEventTriggered = true;
    }
};<commit_msg>fix containers taking no space<commit_after>/*global PDFJS:false*/
/*eslint-env browser*/
/*eslint-env es6*/

var CSS_UNITS = 96.0 / 72.0; //this is apparently a thing.
var xform = 'transform';
['','webkit', 'Moz', 'O', 'ms'].every(function (prefix) {
    var e = prefix + (prefix ? 'T':'t') +  'ransform';
    if (typeof document.body.style[e] !== 'undefined') {
        xform = e;
        return false;
    }
    return true;
});

/*
!function (w) {

    function getOutputScale(ctx) {
        var devicePixelRatio = window.devicePixelRatio || 1;
        var backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
                                ctx.mozBackingStorePixelRatio ||
                                ctx.msBackingStorePixelRatio ||
                                ctx.oBackingStorePixelRatio ||
                                ctx.backingStorePixelRatio || 1;
        var pixelRatio = devicePixelRatio / backingStoreRatio;
        return {
            sx: pixelRatio,
            sy: pixelRatio,
            scaled: pixelRatio !== 1
        };
    }

    PDFJS.getDocument('1609.01714.pdf').then(function (pdf) {
        var pageDivs = [];
        function createPage(n) {
            if (n > pdf.numPages) {
                return;
            }
            var div = document.createElement('div');
            pageDivs.push(div);
            pdf.getPage(n).then(function (page) {
                var scale = 0.6;
                var viewport = page.getViewport(scale * CSS_UNITS);

                var canvas = document.createElement('canvas');
                var context = canvas.getContext('2d');

                var outputScale = getOutputScale(canvas);
                canvas.height = viewport.height * outputScale.sy;
                canvas.width = viewport.width * outputScale.sx;

                div.appendChild(canvas);
                page.render({
                    canvasContext: context,
                    viewport: viewport
                });
            });
            createPage(n + 1);
        }
        createPage(1);
        pageDivs.forEach(function (div) {
            document.body.appendChild(div);
        });
    });
} (window);
*/

function getOutputScale(ctx) {
    var canvas;
    if (ctx === undefined) {
        if (canvas === undefined) {
            canvas = document.createElement('canvas');
        }
        ctx = canvas.getContext('2d');
    }
    var devicePixelRatio = window.devicePixelRatio || 1;
    var backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
                            ctx.mozBackingStorePixelRatio ||
                            ctx.msBackingStorePixelRatio ||
                            ctx.oBackingStorePixelRatio ||
                            ctx.backingStorePixelRatio || 1;
    var pixelRatio = devicePixelRatio / backingStoreRatio;
    return {
        sx: pixelRatio,
        sy: pixelRatio,
        scaled: pixelRatio !== 1
    };
}

window.pdfViewer = function pdfViewer(container, documentUri) {
    // todo:
    /// Creates a pdf viewer in the given container
    /// <param name="container" type="HTMLElement">The container to create the pdf viewer in.</param>
    'use strict';

    if (container === null) {
        throw 'can not create viewer in null container';
    }
    if (container === undefined) {
        throw 'can not create viewer in undefined container';
    }
    if (!(container instanceof HTMLElement)) {
        throw 'can not create viewer in container that is not HTMLElement';
    }
    /** @type HTMLElement */
    var _container = container;

    /** @type String */
    var _uri = documentUri;
    /** @type HTMLElement */
    var _inner;
    /** @type PDFPromise<PDFDocumentProxy> */
    var _loadingTask;
    /** @type PDFDocumentProxy */
    var _pdfDocument;

    var _pages = [];
    /** @type {number} */
    var _pageCount;
    /** @type {number} */
    var _scale = defaultScale();
    /** @type {number} */
    var _page_gap = 10; //pixel space between pages

    var _resizeEventTriggered = false;

    initialiseContainers();
    setPdf(_uri);

    var _viewer = {
        position: function (value) {
            if (value === undefined) {
                return _container.scrollLeft;
            }
            _container.scrollLeft = value;
        },
    };
    return _viewer;

    function renderViewer() {
        _pages.forEach(function (p) {
            redrawPage(p);
        });
        //set all widths of containers to max width of a container;
        var width = 0;
        _container.children.forEach(function (c) {
            if (c.clientWidth > width) {
                width = c.width;
            }
        });
        _container.children.forEach(function (c) {
            c.style.minWidth = width + 'px';
        });
    }

    /**
     * @param {String} uri
     */
    function setPdf(uri) {
        _loadingTask = PDFJS.getDocument(uri);
        _loadingTask.then(pdfReady);
    }
    /**
     * @param {PDFDocumentProxy} pdf
     */
    function pdfReady(pdf) {
        _pdfDocument = pdf;
        _pageCount = pdf.numPages;
        addPageContainers();
        _pdfDocument.getDownloadInfo().then(pdfLoaded);
    }
    /**
     * @param {PDFDocumentProxy} pdf
     */
    function pdfLoaded() {
        //create pageViewObjects
        for (var n = 1; n <= _pageCount; ++n) {
            var pageView = {
                id: n,
                scale: _scale,
                rendered: false,
                loaded: false,
            };
            //todo: ? bind events
            _pages.push(pageView);
        }
        var pagePromises = [];
        _pages.forEach(function (pageView) {
            var pagePromise = _pdfDocument.getPage(pageView.id);
            pagePromises.push(pagePromise);
            var index = pageView.id - 1;
            /** @param {} page */
            pagePromise.then(function (page) {
                _pages[index].baseWidth = page.getViewport(1.0 * CSS_UNITS).width;
                _pages[index].defaultScale = defaultScale(_pages[index]);
                _pages[index].page = page;
                _pages[index].loaded = true;
            });
        });
        Promise.all(pagePromises).then(function () {
            _scale = _pages[0].defaultScale;
            renderViewer();
            registerEvents();
        });
    }

    function initialiseContainers() {
        _container.classList.add('pdfviewer-container');
        _inner = document.createElement('div');
        _inner.classList.add('pdfviewer-inner');
        _container.appendChild(_inner);
        //todo: add mini previews?
    }

    function addPageContainers() {
        for (var i = 0; i < _pageCount; ++i){
            var pageContainer = document.createElement('div');
            pageContainer.classList.add('pdfviewer-pagecontainer');
            pageContainer.classList.add('pdfviewer-loading');
            pageContainer.style.visibility = 'hidden';
            _inner.appendChild(pageContainer);
        }
    }

    function redrawPage(pageView) {
        var index = pageView.id - 1;
        var pageContainer = _inner.children[index];
        if (pageContainer === undefined) {
            throw 'can not redraw, not properly initialised';
        }
        var inView = pageInView(index);
        var rendered = pageView.rendered;
        var loaded = pageView.loaded;
        //draw page if it is in view and not currently rendered or has changed scale since last render.
        if (loaded && inView && (!rendered || _scale != pageView.scale)) {
            drawPage(pageView);
        }
        //clear a page which is not in view, but is currently rendered;
        if (!inView && rendered) {
            clearPage(pageView);
        }
    }

    function drawPage(pageView) {
        var index = pageView.id - 1;
        var pageContainer = _inner.children[index];

        var canvas = document.createElement('canvas');
        var outputScale = getOutputScale(canvas);
        var viewport = pageView.page.getViewport(_scale * CSS_UNITS * outputScale.sx);

        canvas.height = viewport.height;
        canvas.width = viewport.width;

        var context = canvas.getContext('2d');
        pageView.rendered = true;
        pageView.page.render({
            canvasContext: context,
            viewport: viewport
        }).then(function () {
            pageContainer.classList.remove('pdfview-loading');
            if (pageContainer.firstChild) {
                var hasChild = true;
            }
            pageContainer.appendChild(canvas);
            if (hasChild) {
                pageContainer.removeChild(pageContainer.firstChild);
            }
            pageContainer.style.visibility = 'visible';
        });
    }

    function clearPage(pageView) {
        var index = pageView.id - 1;
        var pageContainer = _inner.children[index];
        while (pageContainer.firstChild) {
            pageContainer.removeChild(pageContainer.firstChild);
        }
        pageContainer.classList.add('pdfview-loading');
        pageView.rendered = false;
    }

    function pageInView(index) {
        var pageWidth = _pages[0].baseWidth * _scale * getOutputScale().sx;
        var viewerWidth = _container.clientWidth;
        var minIndex = Math.floor(_container.scrollLeft / (pageWidth + _page_gap)) - 1; //-1 to allow an extra page to be prerendered
        var maxIndex = Math.floor((_container.scrollLeft + viewerWidth) / (pageWidth + _page_gap)) + 1; //same for the + 1

        return index >= minIndex && index <= maxIndex;
    }

    function defaultScale(page) {
        ///Determine a reasonable default scale based on device
        if (page === undefined) {
            return 1;
        }
        return window.innerWidth / (page.baseWidth * getOutputScale().sx);
    }

    function registerEvents() {
        window.addEventListener('resize', onResize);
        _container.addEventListener('scroll', onScroll);
    }

    function onResize() {
        if (!_resizeEventTriggered) {
            window.requestAnimationFrame( function () {
                renderViewer();
                _resizeEventTriggered = false;
            });
        }
        _resizeEventTriggered = true;
    }

    function onScroll() {
        if (!_resizeEventTriggered) {
            window.requestAnimationFrame( function () {
                renderViewer();
                _resizeEventTriggered = false;
            });
        }
        _resizeEventTriggered = true;
    }
};<|endoftext|>


<commit_before>//the page used to configure the application
Ti.include('../includes/enums.js');
Ti.include('../includes/utils.js');
Ti.include('../includes/lib/json.i18n.js');
Ti.include('../includes/ui.js');

var win = Ti.UI.currentWindow;

var profileField = addParentRow(I('more.settings.profile.title'), I('more.settings.profile.header'), I('more.settings.profile.prefix', ''), 'profile');
var codeField = addTextFieldRow(I('more.settings.code.title'), I('more.settings.code.header'));
var hdField = addParentRow(I('more.settings.hd.title'), null, I('more.settings.hd.prefix', ''), 'hd');
var modelField = addParentRow(I('more.settings.model'), null, I('more.settings.model'), 'model');

//values to store the properties
var profile, code, hd, model;

//returns a row containing a title and a value. opens a window when clicked
function addParentRow(title, header, rowName, configID) {
	var row = Ti.UI.createTableViewRow({
		title:title,
		hasChild:true,
		header:header
	});

	//the label containing the value you want to display
	var lbl = Ti.UI.createLabel({
		right:10,
		textAlign:'right',
		width:150,
		highlightedColor:'white',
		color:'#336699'
	});

	row.add(lbl);

	row.addEventListener('click', function(e) {
		var win = Ti.UI.createWindow({
			url:'options_select.js',
			title:title,
			rowName:rowName,
			configID:configID,
			backgroundColor:'stripped',
			barColor:'#464646'
		});
		Ti.UI.currentTab.open(win, {
			animated:true
		});
	});
	return row;
}

//returns a row containing a text field
function addTextFieldRow(text, header) {
	var row = Ti.UI.createTableViewRow({
		title:text,
		header:header,
		selectionStyle:Ti.UI.iPhone.TableViewCellSelectionStyle.NONE,
	});

	var textfield = Ti.UI.createTextField({
		color:'#336699',
		height:35,
		top:4,
		right:20,
		width:80,
		borderStyle:Ti.UI.INPUT_BORDERSTYLE_NONE,
		keyboardType:Ti.UI.KEYBOARD_NUMBERS_PUNCTUATION,
		appearance:Titanium.UI.KEYBOARD_APPEARANCE_ALERT,
		hintText:'12345678'
	});

	textfield.addEventListener('change', function(e) {
		//the value must be between 0 and 8 characters only
		e.source.value = e.source.value.slice(0, 8);
	});

	row.add(textfield);
	return row;
}

var data = [profileField, codeField, hdField, modelField];

var tableView = Ti.UI.createTableView({
	data:data,
	style:Ti.UI.iPhone.TableViewStyle.GROUPED
});

tableView.footerView = getDestructionView(I('more.settings.reset.title'));
tableView.footerView.children[0].addEventListener('click', function(e) {
	//if the user wants to reset the properties of the app
	//asking if he's really sure
	var alert = Ti.UI.createOptionDialog({
		title:I('more.settings.reset.message', Ti.App.name),
		options:[I('more.settings.reset.yes'), I('more.settings.reset.cancel')],
		destructive:0,
		cancel:1
	});

	alert.show();
	alert.addEventListener('click', function(e) {
		//if we clicked the confirmation button
		if(e.index == 0) {
			var props = Ti.App.Properties.listProperties();
			//delete all properties using a loop
			for(var i = 0; i < props.length; i++) {
				var value = Titanium.App.Properties.getString(props[i]);
				Titanium.App.Properties.removeProperty(props[i]);
			}
			//get the updated values
			getFields();
		}
	});
});

//a quick shorcut in case the user needs help
var b_help = Ti.UI.createButton({
	title:I('more.help.title')
})

b_help.addEventListener('click', function(e) {
	var win = Ti.UI.createWindow({
		url:'help.js',
		title:I('more.help.title'),
		backgroundColor:getDefaultBackground(),
		barColor:'#464646'
	});
	Ti.UI.currentTab.open(win, {
		animated:true
	});
});

win.addEventListener('focus', function(e) {
	//getting the updated properties on focus
	profile = Ti.App.Properties.getInt('profileToModify', Profile.PROFILE_1);
	code = Ti.App.Properties.getString('profile' + profile + '.code', '');
	hd = Ti.App.Properties.getInt('profile' + profile + '.hd', HD.HD_1);
	model = Ti.App.Properties.getInt('profile' + profile + '.model', Model.FREEBOX_HD);

	//setting the fields with their respective values
	getFields();
});

win.addEventListener('blur', function(e) {
	//writing in the properties that the settings have been filled
	if(data[1].children[0].value != '')
		Ti.App.Properties.setBool('hasBeenSet', true);
	//saving the code value
	Ti.App.Properties.setString('profile' + profile + '.code', data[1].children[0].value);
});

win.setRightNavButton(b_help);
win.add(tableView);

//used to set all the data in their respective fields
function getFields() {
	data[0].children[0].text = I('more.settings.profile.prefix', profile.toString());
	data[1].children[0].value = code;
	data[2].children[0].text = I('more.settings.hd.prefix', hd.toString());
	data[3].children[0].text = getModelString(model);
}

Ti.App.Properties.setInt('profileToModify', Profile.PROFILE_1);<commit_msg>Fixes for 1.8.1 SDK + code improvement<commit_after>//the page used to configure the application
Ti.include('../includes/enums.js');
Ti.include('../includes/utils.js');
Ti.include('../includes/lib/json.i18n.js');
Ti.include('../includes/ui.js');

var win = Ti.UI.currentWindow;

var profileField = addParentRow(I('more.settings.profile.title'), I('more.settings.profile.header'), I('more.settings.profile.prefix', ''), 'profile');
var codeField = addTextFieldRow(I('more.settings.code.title'));
var hdField = addParentRow(I('more.settings.hd.title'), null, I('more.settings.hd.prefix', ''), 'hd');
var modelField = addParentRow(I('more.settings.model'), null, I('more.settings.model'), 'model');

var settingsSection = Ti.UI.createTableViewSection({
	headerTitle:I('more.settings.code.header')
});

settingsSection.add(codeField);
settingsSection.add(hdField);
settingsSection.add(modelField);

//values to store the properties
var profile, code, hd, model;

//returns a row containing a title and a value. opens a window when clicked
function addParentRow(title, header, rowName, configID) {
	var row = Ti.UI.createTableViewRow({
		title:title,
		hasChild:true,
		header:header
	});

	//the label containing the value you want to display
	var lbl = Ti.UI.createLabel({
		right:10,
		textAlign:'right',
		width:150,
		highlightedColor:'white',
		color:'#336699'
	});

	row.add(lbl);

	row.addEventListener('click', function(e) {
		var win = Ti.UI.createWindow({
			url:'options_select.js',
			title:title,
			rowName:rowName,
			configID:configID,
			backgroundColor:'stripped',
			barColor:'#464646'
		});
		Ti.UI.currentTab.open(win, {
			animated:true
		});
	});
	return row;
}

//returns a row containing a text field
function addTextFieldRow(text) {
	var row = Ti.UI.createTableViewRow({
		title:text,
		selectionStyle:Ti.UI.iPhone.TableViewCellSelectionStyle.NONE,
	});

	var textfield = Ti.UI.createTextField({
		color:'#336699',
		height:35,
		top:4,
		right:20,
		width:80,
		borderStyle:Ti.UI.INPUT_BORDERSTYLE_NONE,
		keyboardType:Ti.UI.KEYBOARD_NUMBERS_PUNCTUATION,
		appearance:Titanium.UI.KEYBOARD_APPEARANCE_ALERT,
		hintText:'12345678'
	});

	textfield.addEventListener('change', function(e) {
		//the value must be between 0 and 8 characters only
		e.source.value = e.source.value.slice(0, 8);
	});

	row.add(textfield);
	return row;
}

var tableView = Ti.UI.createTableView({
	data:[profileField, settingsSection],
	style:Ti.UI.iPhone.TableViewStyle.GROUPED,
	footerView:getDestructionView(I('more.settings.reset.title'))
});

tableView.footerView.children[0].addEventListener('click', function(e) {
	//if the user wants to reset the properties of the app asking if he's really sure
	var alert = Ti.UI.createOptionDialog({
		title:I('more.settings.reset.message', Ti.App.name),
		options:[I('more.settings.reset.yes'), I('more.settings.reset.cancel')],
		destructive:0,
		cancel:1
	});

	alert.show();
	alert.addEventListener('click', function(e) {
		//if we clicked the confirmation button
		if(e.index == 0) {
			var props = Ti.App.Properties.listProperties();
			//delete all properties using a loop
			for(var i = 0; i < props.length; i++) {
				var value = Titanium.App.Properties.getString(props[i]);
				Titanium.App.Properties.removeProperty(props[i]);
			}
			//get the updated values
			setFields();
		}
	});
});

//a quick shorcut in case the user needs help
var b_help = Ti.UI.createButton({
	title:I('more.help.title')
})

b_help.addEventListener('click', function(e) {
	var win = Ti.UI.createWindow({
		url:'help.js',
		title:I('more.help.title'),
		backgroundColor:getDefaultBackground(),
		barColor:'#464646'
	});
	Ti.UI.currentTab.open(win, {
		animated:true
	});
});

win.addEventListener('focus', function(e) {
	//getting the updated properties on focus
	profile = Ti.App.Properties.getInt('profileToModify', Profile.PROFILE_1);
	code = Ti.App.Properties.getString('profile' + profile + '.code', '');
	hd = Ti.App.Properties.getInt('profile' + profile + '.hd', HD.HD_1);
	model = Ti.App.Properties.getInt('profile' + profile + '.model', Model.FREEBOX_HD);

	//setting the fields with their respective values
	setFields();
});

win.addEventListener('blur', function(e) {
	//writing in the properties that the settings have been filled
	if(codeField.children[0].getValue() != '')
		Ti.App.Properties.setBool('hasBeenSet', true);
	//saving the code value
	Ti.App.Properties.setString('profile' + profile + '.code', codeField.children[0].getValue());
});

win.setRightNavButton(b_help);
win.add(tableView);

//used to set all the data in their respective fields
function setFields() {
	profileField.children[0].setText(I('more.settings.profile.prefix', profile.toString()));
	codeField.children[0].setValue(code);
	hdField.children[0].setText(I('more.settings.hd.prefix', hd.toString()));
	modelField.children[0].setText(getModelString(model));
}

Ti.App.Properties.setInt('profileToModify', Profile.PROFILE_1);<|endoftext|>


<commit_before>(function(module) {

  var parksView = {};
  var completeData;

  parksView.populateStateFilter = function(array) {
    var statesArray = [];
    array.forEach(function(obj) {
      var str = obj.states.split(',');
      statesArray.push(str);
    });
    var concatArray = statesArray.reduce(function(acc, curr) {
      return acc.concat(curr);
    },[]);
    concatArray = concatArray.sort();
    var myout = concatArray.reduce(function(prev, next) {
      prev[next] = (prev[next] || 0) + 1;
      return prev;
    }, {});

    for (keys in myout) {
      this.keys = myout.keys;
      var optionTag = '<option value="' + keys + '">' + keys + ' ' + myout[keys] + '</option>';
      $('#state-filter').append(optionTag);
    }
  };

  parksView.populateParksFilter = function(array) {
    array.forEach(function(obj) {
      var name = obj.name;
      var code = obj.code;
      var optionTag = '<option value="' + code + '">' + name + '</option>';
      $('#park-filter').append(optionTag);
    });
  };

  parksView.handleParksFilter = function() {
      $('#park-filter').on('change', function() {
        if ($(this).val()) {
          var codeValue = $(this).val();
          $.ajax({
            url: '/nps/parks?fields=addresses%2Ccontacts%2CentranceFees%2CentrancePasses%2Cimages%2CoperatingHours&parkCode=' + codeValue,
            success: function(data) {
              completeData = data;
              $('#gov-data').append(parksObj.toHtml(completeData));
            }
          });
        }
    });
  };

  parksView.showPark = function() {
    $('#gov-data').append(parksObj.toHtml(completeData));
  };

  parksView.renderIndexPage = function() {
    parksObj.fetchParkNames();
    parksView.handleParksFilter();
  };

  module.parksView = parksView;
})(window);
<commit_msg>page is called with a route of /park/name+of+park.  park name inexplicble multiplies for now<commit_after>(function(module) {

  var parksView = {};
  var completeData;

  parksView.populateStateFilter = function(array) {
    var statesArray = [];
    array.forEach(function(obj) {
      var str = obj.states.split(',');
      statesArray.push(str);
    });
    var concatArray = statesArray.reduce(function(acc, curr) {
      return acc.concat(curr);
    },[]);
    concatArray = concatArray.sort();
    var myout = concatArray.reduce(function(prev, next) {
      prev[next] = (prev[next] || 0) + 1;
      return prev;
    }, {});

    for (keys in myout) {
      this.keys = myout.keys;
      var optionTag = '<option value="' + keys + '">' + keys + ' ' + myout[keys] + '</option>';
      $('#state-filter').append(optionTag);
    }
  };

  parksView.populateParksFilter = function(array) {
    array.forEach(function(obj) {
      var name = obj.name;
      var code = obj.code;
      var optionTag = '<option value="' + code + '">' + name + '</option>';
      $('#park-filter').append(optionTag);
    });
  };

  parksView.handleParksFilter = function() {
      $('#park-filter').on('change', function() {
        if ($(this).val()) {
          var codeValue = $(this).val();
          $.ajax({
            url: '/nps/parks?fields=addresses%2Ccontacts%2CentranceFees%2CentrancePasses%2Cimages%2CoperatingHours&parkCode=' + codeValue,
            success: function(data) {
              completeData = data;
              $('#gov-data').append(parksObj.toHtml(completeData));
            }
          });
          var parkName = "";
          var parkName = $('option[value=' + $(this).val() +']').text().toLowerCase().replace(/\W+/g, '+');
          page('/park/' + parkName);
        }
    });
  };

  parksView.showPark = function() {
    $('#gov-data').append(parksObj.toHtml(completeData));
  };

  parksView.renderIndexPage = function() {
    parksObj.fetchParkNames();
    parksView.handleParksFilter();
  };

  module.parksView = parksView;
})(window);
<|endoftext|>


<commit_before>/**
* Copyright 2012-2017, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');
var layoutAttributes = require('./layout_attributes');

/**
 * options: inherits font, outerTicks, noHover from axes.handleAxisDefaults
 */
module.exports = function handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options) {
    var showAttrDflt = getShowAttrDflt(containerIn);

    var tickPrefix = coerce('tickprefix');
    if(tickPrefix) coerce('showtickprefix', showAttrDflt);

    var tickSuffix = coerce('ticksuffix');
    if(tickSuffix) coerce('showticksuffix', showAttrDflt);

    var showTickLabels = coerce('showticklabels');
    if(showTickLabels) {
        var font = options.font || {};
        // as with titlefont.color, inherit axis.color only if one was
        // explicitly provided
        var dfltFontColor = (containerOut.color === containerIn.color) ?
            containerOut.color : font.color;
        Lib.coerceFont(coerce, 'tickfont', {
            family: font.family,
            size: font.size,
            color: dfltFontColor
        });
        coerce('tickangle');

        if(axType !== 'category') {
            var tickFormat = coerce('tickformat');
            tickformatstopsDefaults(containerIn, containerOut);
            if(!tickFormat && axType !== 'date') {
                coerce('showexponent', showAttrDflt);
                coerce('exponentformat');
                coerce('separatethousands');
            }
        }
    }

    if(axType !== 'category' && !options.noHover) coerce('hoverformat');
};

/*
 * Attributes 'showexponent', 'showtickprefix' and 'showticksuffix'
 * share values.
 *
 * If only 1 attribute is set,
 * the remaining attributes inherit that value.
 *
 * If 2 attributes are set to the same value,
 * the remaining attribute inherits that value.
 *
 * If 2 attributes are set to different values,
 * the remaining is set to its dflt value.
 *
 */
function getShowAttrDflt(containerIn) {
    var showAttrsAll = ['showexponent',
            'showtickprefix',
            'showticksuffix'],
        showAttrs = showAttrsAll.filter(function(a) {
            return containerIn[a] !== undefined;
        }),
        sameVal = function(a) {
            return containerIn[a] === containerIn[showAttrs[0]];
        };

    if(showAttrs.every(sameVal) || showAttrs.length === 1) {
        return containerIn[showAttrs[0]];
    }
}

function tickformatstopsDefaults(tickformatIn, tickformatOut) {
    var valuesIn = tickformatIn.tickformatstops;
    var valuesOut = tickformatOut.tickformatstops = [];

    if(!Array.isArray(valuesIn)) return;

    var valueIn, valueOut;

    function coerce(attr, dflt) {
        return Lib.coerce(valueIn, valueOut, layoutAttributes.tickformatstops, attr, dflt);
    }

    for(var i = 0; i < valuesIn.length; i++) {
        valueIn = valuesIn[i];
        valueOut = {};

        coerce('dtickrange');
        coerce('value');

        valuesOut.push(valueOut);
    }
}
<commit_msg>allow ticksuffix dflt to be passed via option<commit_after>/**
* Copyright 2012-2017, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');
var layoutAttributes = require('./layout_attributes');

/**
 * options: inherits font, outerTicks, noHover from axes.handleAxisDefaults
 */
module.exports = function handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options) {
    var showAttrDflt = getShowAttrDflt(containerIn);

    var tickPrefix = coerce('tickprefix');
    if(tickPrefix) coerce('showtickprefix', showAttrDflt);

    var tickSuffix = coerce('ticksuffix', options.tickSuffixDflt);
    if(tickSuffix) coerce('showticksuffix', showAttrDflt);

    var showTickLabels = coerce('showticklabels');
    if(showTickLabels) {
        var font = options.font || {};
        // as with titlefont.color, inherit axis.color only if one was
        // explicitly provided
        var dfltFontColor = (containerOut.color === containerIn.color) ?
            containerOut.color : font.color;
        Lib.coerceFont(coerce, 'tickfont', {
            family: font.family,
            size: font.size,
            color: dfltFontColor
        });
        coerce('tickangle');

        if(axType !== 'category') {
            var tickFormat = coerce('tickformat');
            tickformatstopsDefaults(containerIn, containerOut);
            if(!tickFormat && axType !== 'date') {
                coerce('showexponent', showAttrDflt);
                coerce('exponentformat');
                coerce('separatethousands');
            }
        }
    }

    if(axType !== 'category' && !options.noHover) coerce('hoverformat');
};

/*
 * Attributes 'showexponent', 'showtickprefix' and 'showticksuffix'
 * share values.
 *
 * If only 1 attribute is set,
 * the remaining attributes inherit that value.
 *
 * If 2 attributes are set to the same value,
 * the remaining attribute inherits that value.
 *
 * If 2 attributes are set to different values,
 * the remaining is set to its dflt value.
 *
 */
function getShowAttrDflt(containerIn) {
    var showAttrsAll = ['showexponent',
            'showtickprefix',
            'showticksuffix'],
        showAttrs = showAttrsAll.filter(function(a) {
            return containerIn[a] !== undefined;
        }),
        sameVal = function(a) {
            return containerIn[a] === containerIn[showAttrs[0]];
        };

    if(showAttrs.every(sameVal) || showAttrs.length === 1) {
        return containerIn[showAttrs[0]];
    }
}

function tickformatstopsDefaults(tickformatIn, tickformatOut) {
    var valuesIn = tickformatIn.tickformatstops;
    var valuesOut = tickformatOut.tickformatstops = [];

    if(!Array.isArray(valuesIn)) return;

    var valueIn, valueOut;

    function coerce(attr, dflt) {
        return Lib.coerce(valueIn, valueOut, layoutAttributes.tickformatstops, attr, dflt);
    }

    for(var i = 0; i < valuesIn.length; i++) {
        valueIn = valuesIn[i];
        valueOut = {};

        coerce('dtickrange');
        coerce('value');

        valuesOut.push(valueOut);
    }
}
<|endoftext|>


<commit_before>/*
Copyright 2011 Justin Obara

Licensed under the MIT License. You may not use this file except
in compliance with this License.
*/

// Declare Dependencies
/*global setTimeout, clearTimout, tt, jQuery*/

var tt = tt || {};

(function ($) {

    var fetchText = function (that, pathToFile) {
        $.ajax({
            url: pathToFile,
            dataType: "text",
            success: that.events.afterTextFetched.fire
        });
    };

    var renderText = function (that, text) {
        that.sampleText = text;
        var sampleTextDisplay = that.locate("sampleText");
        sampleTextDisplay.text(that.sampleText);
    };

    var startTimer = function (that) {
        return setTimeout(that.events.afterTimeFinished.fire, 60000);
    };

    var calculateWPMStats = function (that) {
        var sampleText = that.toArray(that.sampleText);
        var typedText = that.toArray(that.locate("input").val());
        var errors = that.compare(sampleText, typedText);
        var adjustedWPM = that.calculateWPM(typedText.length, errors.length, 1);

        return {
            WPM: typedText.length,
            errors: errors.length,
            adjustedWPM: adjustedWPM
        };
    };

    var displayWPM = function (that, WPM) {
        that.locate("WPMScore").text(WPM);
    };

    var bindStartEvent = function (that) {
        that.locate("input").bind("keyup.tt-start", function (event) {
            that.events.afterStarted.fire(event.which);
        });
    };

    var bindCancelEvent = function (that) {
        that.locate("input").bind("blur.tt-cancel", function (event) {
            that.cancel();
        });
    };

    var bindEvents = function (that) {
        bindStartEvent(that);
    };

    var addListeners = function (that) {
        that.events.afterTextFetched.addListener(function (text) {
            renderText(that, text);
        });

        that.events.afterStarted.addListener(function () {
            that.locate("input").unbind("keyup.tt-start");
            bindCancelEvent(that);
            that.timerID = startTimer(that);
        });

        that.events.afterTimeFinished.addListener(function () {
            that.locate("input").attr("disabled", true);
            var WPMStats = calculateWPMStats(that);
            displayWPM(that, WPMStats.adjustedWPM);
            that.notify(WPMStats);
            that.cancel();
        });
    };

    var resetTest = function (that) {
        var textInput = that.locate("input");
        textInput.val("");
        textInput.removeAttr("disabled");
        textInput.unbind("blur.tt-cancel");
        bindStartEvent(that);
    };

    var setup = function (that) {
        bindEvents(that);
        addListeners(that);
        fetchText(that, that.options.texts[0].url);
    };

    fluid.registerNamespace("tt.typingTest");

    tt.typingTest.stringToArray = function (str) {
        return str.split(/\s/);
    };

    tt.typingTest.compareStringArrays = function (baseArray, comparisonArray) {
        var differences = [];

        for (var i = 0; i < comparisonArray.length; i++) {
            var baseString = baseArray[i];
            var comparisonString = comparisonArray[i];

            if (baseString !== comparisonString) {
                differences.push({
                    position: i,
                    expected: baseString,
                    actual: comparisonString
                });
            }
        }

        return differences;
    };

    tt.typingTest.wordsPerMinute = function (numWords, numErrors, numMinutes) {
        return Math.max((numWords - numErrors) / numMinutes, 0);
    };

    tt.typingTest.defaultNotification = function (WPMStats) {
        alert("Your WPM is " + WPMStats.adjustedWPM + "\n\n" + "WPM: " + WPMStats.WPM + "\nErrors: " + WPMStats.errors + "\nAdjusted WPM: " + WPMStats.adjustedWPM);
    };

    tt.typingTest.preInit = function (that) {
        that.cancel = function () {
            clearTimeout(that.timerID);
            resetTest(that);
        };
    };

    tt.typingTest.finalInit = function (that) {
        setup(that);
    };

    fluid.defaults("tt.typingTest", {
        gradeNames: ["fluid.viewComponent", "autoInit"],
        preInitFunction: "tt.typingTest.preInit",
        finalInitFunction: "tt.typingTest.finalInit",

        invokers: {
            notify: "tt.typingTest.defaultNotification",
            toArray: "tt.typingTest.stringToArray",
            compare: "tt.typingTest.compareStringArrays",
            calculateWPM: "tt.typingTest.wordsPerMinute"
        },

        selectors: {
            sampleText: ".tt-typingTest-sampleText",
            input: ".tt-typingTest-input",
            WPMScore: ".tt-typingTest-WMPScore"
        },

        events: {
            afterTextFetched: null,
            afterStarted: null,
            afterTimeFinished: null
        },

        texts: [
            {
                name: "Macbeth",
                url: "../text/Macbeth.txt"
            },
            {
                name: "A Tale of Two Cities",
                url: "../text/A_Tale_of_Two_Cities.txt"
            },
            {
                name: "The Wonderful Wizard of Oz",
                url: "../text/The_Wonderful_Wizard_of_Oz.txt"
            }
        ]
    });
})(jQuery);
<commit_msg>GH-14 : Made resetTest a public instance method.<commit_after>/*
Copyright 2011 Justin Obara

Licensed under the MIT License. You may not use this file except
in compliance with this License.
*/

// Declare Dependencies
/*global setTimeout, clearTimout, tt, jQuery*/

var tt = tt || {};

(function ($) {

    var fetchText = function (that, pathToFile) {
        $.ajax({
            url: pathToFile,
            dataType: "text",
            success: that.events.afterTextFetched.fire
        });
    };

    var renderText = function (that, text) {
        that.sampleText = text;
        var sampleTextDisplay = that.locate("sampleText");
        sampleTextDisplay.text(that.sampleText);
    };

    var startTimer = function (that) {
        return setTimeout(that.events.afterTimeFinished.fire, 60000);
    };

    var calculateWPMStats = function (that) {
        var sampleText = that.toArray(that.sampleText);
        var typedText = that.toArray(that.locate("input").val());
        var errors = that.compare(sampleText, typedText);
        var adjustedWPM = that.calculateWPM(typedText.length, errors.length, 1);

        return {
            WPM: typedText.length,
            errors: errors.length,
            adjustedWPM: adjustedWPM
        };
    };

    var displayWPM = function (that, WPM) {
        that.locate("WPMScore").text(WPM);
    };

    var bindStartEvent = function (that) {
        that.locate("input").bind("keyup.tt-start", function (event) {
            that.events.afterStarted.fire(event.which);
        });
    };

    var bindCancelEvent = function (that) {
        that.locate("input").bind("blur.tt-cancel", function (event) {
            that.cancel();
        });
    };

    var bindEvents = function (that) {
        bindStartEvent(that);
    };

    var addListeners = function (that) {
        that.events.afterTextFetched.addListener(function (text) {
            renderText(that, text);
        });

        that.events.afterStarted.addListener(function () {
            that.locate("input").unbind("keyup.tt-start");
            bindCancelEvent(that);
            that.timerID = startTimer(that);
        });

        that.events.afterTimeFinished.addListener(function () {
            that.locate("input").attr("disabled", true);
            var WPMStats = calculateWPMStats(that);
            displayWPM(that, WPMStats.adjustedWPM);
            that.notify(WPMStats);
            that.cancel();
        });
    };

    var setup = function (that) {
        bindEvents(that);
        addListeners(that);
        fetchText(that, that.options.texts[0].url);
    };

    fluid.registerNamespace("tt.typingTest");

    tt.typingTest.stringToArray = function (str) {
        return str.split(/\s/);
    };

    tt.typingTest.compareStringArrays = function (baseArray, comparisonArray) {
        var differences = [];

        for (var i = 0; i < comparisonArray.length; i++) {
            var baseString = baseArray[i];
            var comparisonString = comparisonArray[i];

            if (baseString !== comparisonString) {
                differences.push({
                    position: i,
                    expected: baseString,
                    actual: comparisonString
                });
            }
        }

        return differences;
    };

    tt.typingTest.wordsPerMinute = function (numWords, numErrors, numMinutes) {
        return Math.max((numWords - numErrors) / numMinutes, 0);
    };

    tt.typingTest.defaultNotification = function (WPMStats) {
        alert("Your WPM is " + WPMStats.adjustedWPM + "\n\n" + "WPM: " + WPMStats.WPM + "\nErrors: " + WPMStats.errors + "\nAdjusted WPM: " + WPMStats.adjustedWPM);
    };

    tt.typingTest.preInit = function (that) {
        that.resetTest = function () {
            var textInput = that.locate("input");
            textInput.val("");
            textInput.removeAttr("disabled");
            textInput.unbind("blur.tt-cancel");
            bindStartEvent(that);
        };

        that.cancel = function () {
            clearTimeout(that.timerID);
            that.resetTest();
        };
    };

    tt.typingTest.finalInit = function (that) {
        setup(that);
    };

    fluid.defaults("tt.typingTest", {
        gradeNames: ["fluid.viewComponent", "autoInit"],
        preInitFunction: "tt.typingTest.preInit",
        finalInitFunction: "tt.typingTest.finalInit",

        invokers: {
            notify: "tt.typingTest.defaultNotification",
            toArray: "tt.typingTest.stringToArray",
            compare: "tt.typingTest.compareStringArrays",
            calculateWPM: "tt.typingTest.wordsPerMinute"
        },

        selectors: {
            sampleText: ".tt-typingTest-sampleText",
            input: ".tt-typingTest-input",
            WPMScore: ".tt-typingTest-WMPScore"
        },

        events: {
            afterTextFetched: null,
            afterStarted: null,
            afterTimeFinished: null
        },

        texts: [
            {
                name: "Macbeth",
                url: "../text/Macbeth.txt"
            },
            {
                name: "A Tale of Two Cities",
                url: "../text/A_Tale_of_Two_Cities.txt"
            },
            {
                name: "The Wonderful Wizard of Oz",
                url: "../text/The_Wonderful_Wizard_of_Oz.txt"
            }
        ]
    });
})(jQuery);
<|endoftext|>


<commit_before>'use strict';
var router = require('express').Router();

var slackService = require('./lib/slackService');
var bitbucketParser = require('./lib/incomingHooks/bitbucketParser');
var extensionNumberCommand = require('./lib/slashCommands/ExtensionNumber');

router.get('/slashCommands/ramal', function (req, res) {
    console.log(req.query);
    var command = req.query && req.query.command || undefined;
    var text = req.query.text || undefined;

    if (command && command === '/ramal') {
        var findExtension = text ?
            extensionNumberCommand.find.bind(extensionNumberCommand, text) :
            extensionNumberCommand.find.bind(extensionNumberCommand);

        findExtension(function(out) {
            res.send(out);
        });
    } else {
        res.send('Set your hooks to point here.');
    }
});

router.post('*', function (req, res) {
    var channel = req.path.substring(1);
    var message = bitbucketParser.generateMessage(req.body);

    if (message !== undefined) {
        slackService.sendMessage(message, channel);
    }

    res.status(200).end();
});

module.exports = router;
<commit_msg>Changing bitbucket endpoint<commit_after>'use strict';
var router = require('express').Router();

var slackService = require('./lib/slackService');
var bitbucketParser = require('./lib/incomingHooks/bitbucketParser');
var extensionNumberCommand = require('./lib/slashCommands/ExtensionNumber');

router.get('/slashCommands/ramal', function (req, res) {
    console.log(req.query);
    var command = req.query && req.query.command || undefined;
    var text = req.query.text || undefined;

    if (command && command === '/ramal') {
        var findExtension = text ?
            extensionNumberCommand.find.bind(extensionNumberCommand, text) :
            extensionNumberCommand.find.bind(extensionNumberCommand);

        findExtension(function(out) {
            res.send(out);
        });
    } else {
        res.send('Set your hooks to point here.');
    }
});

router.post('incomingHooks/bitbucket', function (req, res) {
    var channel = req.path.substring(1);
    var message = bitbucketParser.generateMessage(req.body);

    if (message !== undefined) {
        slackService.sendMessage(message, channel);
    }

    res.status(200).end();
});

module.exports = router;
<|endoftext|>


<commit_before>import { Switch, ScrollView, TouchableOpacity } from 'react-native';
import styled from 'styled-components/native';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import React from 'react';
import R from 'ramda';

import { DASHBOARD_MODE } from '../reducers/switches';
import * as actions from '../actions/switches';
import * as colors from '../constants/colors';
import { selector } from '../utils/redux';

const ListItem = styled.View`
  flex-direction: row;
  padding: 16px;
  background-color: ${colors.groups.bg};
  border-bottom-width: 1px;
  border-bottom-color: ${colors.groups.divider};
  justify-content: space-between;
`;

const OptionText = styled.Text`
  color: ${colors.text};
  font-size: 20px;
`;

export class AppSettings extends React.Component {
  static navigationOptions = {
    title: 'Settings',
  };

  static propTypes = {
    persistSwitches: PropTypes.func.isRequired,
    toggleSwitch: PropTypes.func.isRequired,
    switches: PropTypes.object.isRequired,
    navigation: PropTypes.shape({
      navigate: PropTypes.func.isRequired,
    }).isRequired,
  };

  openLayoutManager = () => this.props.navigation.navigate('LayoutManager');

  setDashboardMode = enabled => {
    const { switches } = this.props;

    this.props.toggleSwitch({ name: DASHBOARD_MODE, on: enabled });
    this.props.persistSwitches({
      ...switches,
      [DASHBOARD_MODE]: !switches[DASHBOARD_MODE],
    });
  };

  render() {
    const { switches } = this.props;

    return (
      <ScrollView>
        <TouchableOpacity onPress={this.openLayoutManager}>
          <ListItem>
            <OptionText>Set group layout</OptionText>
          </ListItem>
        </TouchableOpacity>

        <ListItem>
          <OptionText>Dashboard mode</OptionText>
          <Switch
            onValueChange={this.setDashboardMode}
            value={switches[DASHBOARD_MODE]}
          />
        </ListItem>
      </ScrollView>
    );
  }
}

export const mapStateToProps = selector({
  switches: R.prop('switches'),
});

const mapDispatchToProps = {
  persistSwitches: actions.persistSwitches,
  toggleSwitch: actions.toggleSwitch,
};

export default connect(mapStateToProps, mapDispatchToProps)(AppSettings);
<commit_msg>Use better words<commit_after>import { Switch, ScrollView, TouchableOpacity } from 'react-native';
import styled from 'styled-components/native';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import React from 'react';
import R from 'ramda';

import { DASHBOARD_MODE } from '../reducers/switches';
import * as actions from '../actions/switches';
import * as colors from '../constants/colors';
import { selector } from '../utils/redux';

const ListItem = styled.View`
  flex-direction: row;
  padding: 16px;
  background-color: ${colors.groups.bg};
  border-bottom-width: 1px;
  border-bottom-color: ${colors.groups.divider};
  justify-content: space-between;
`;

const OptionText = styled.Text`
  color: ${colors.text};
  font-size: 20px;
`;

export class AppSettings extends React.Component {
  static navigationOptions = {
    title: 'Settings',
  };

  static propTypes = {
    persistSwitches: PropTypes.func.isRequired,
    toggleSwitch: PropTypes.func.isRequired,
    switches: PropTypes.object.isRequired,
    navigation: PropTypes.shape({
      navigate: PropTypes.func.isRequired,
    }).isRequired,
  };

  openLayoutManager = () => this.props.navigation.navigate('LayoutManager');

  setDashboardMode = enabled => {
    const { switches } = this.props;

    this.props.toggleSwitch({ name: DASHBOARD_MODE, on: enabled });
    this.props.persistSwitches({
      ...switches,
      [DASHBOARD_MODE]: !switches[DASHBOARD_MODE],
    });
  };

  render() {
    const { switches } = this.props;

    return (
      <ScrollView>
        <TouchableOpacity onPress={this.openLayoutManager}>
          <ListItem>
            <OptionText>Change layout</OptionText>
          </ListItem>
        </TouchableOpacity>

        <ListItem>
          <OptionText>Dashboard mode</OptionText>
          <Switch
            onValueChange={this.setDashboardMode}
            value={switches[DASHBOARD_MODE]}
          />
        </ListItem>
      </ScrollView>
    );
  }
}

export const mapStateToProps = selector({
  switches: R.prop('switches'),
});

const mapDispatchToProps = {
  persistSwitches: actions.persistSwitches,
  toggleSwitch: actions.toggleSwitch,
};

export default connect(mapStateToProps, mapDispatchToProps)(AppSettings);
<|endoftext|>


<commit_before>'use strict';

describe('Service: history', function () {

  // load the service's module
  beforeEach(function () {
    module('wdiApp', function ($provide) {
      $provide.service('$route', function () {
        this.current = {};
      });
    });
  });

  // instantiate service
  var history;
  beforeEach(inject(function (_history_) {
    history = _history_;
  }));

  it('should just exist', function () {
    expect(history).toBeTruthy();
  });

});
<commit_msg>Add tests for history service.<commit_after>'use strict';

describe('Service: history', function () {

	var history,
		$routeMock;

	// load the service's module
	beforeEach(function () {
		module('wdiApp', function ($provide) {
			$provide.service('$route', function () {
				this.current = {};
				this.updateParams = jasmine.createSpy('updateParams');
				$routeMock = this;
			});
		});
	});

	// instantiate service
	beforeEach(inject(function (_history_) {
		history = _history_;
	}));

	it('should start with US/CA and no indicators', function () {
		expect(history).toBeDefined();
		expect(history.get('countries')).toEqual(['USA', 'CAN']);
		expect(history.get('indicators')).toEqual([]);
	});

	it('should support get/set methods', function () {
		history.set('countries', ['JPN']);
		expect(history.get('countries')).toEqual(['JPN']);

		history.set('indicators', ['a62t39']);
		expect(history.get('indicators')).toEqual(['a62t39']);

		history.set('indicators', []);
		expect(history.get('indicators')).toEqual([]);
	});

	it('should throw for unknown keys', function () {
		expect(function () { history.get('foo'); }).toThrow();
		expect(function () { history.set('bar', 'baz'); }).toThrow();
	});

	it('should publish on change', function () {
		expect($routeMock.updateParams).not.toHaveBeenCalled();
		history.set('countries', ['Ithaca']);
		expect($routeMock.updateParams).toHaveBeenCalledWith({
			countries: ['Ithaca'],
			indicators: []
		});
	});

});
<|endoftext|>


<commit_before>const { fetchBlogPosts } = require('./common/lib')
const routes = async () => {
  const { posts } = await fetchBlogPosts()

  // transform the list of posts into a map of pages with the pathname `/blog/:slug`
  const blogPosts = posts.reduce(
    (pages, post) =>
      Object.assign({}, pages, {
        [`/blog/${post.urlSlug}`]: {
          page: '/blog/single',
          query: { slug: post.urlSlug }
        }
      }),
    {}
  )

  // combine the map of post pages with our static pages
  return Object.assign({}, blogPosts, {
    '/': { page: '/' },
    '/404': { page: '/_error' },
    '/about': { page: '/about' },
    '/blog': { page: '/blog' },
    '/faq': { page: '/faq' },
    '/careers': { page: '/careers' },
    '/funding': { page: '/funding' },
    '/install': { page: '/install' },
    '/papers': { page: '/papers' },
    '/press': { page: '/press' },
    '/videos': { page: '/videos' },
    '/roadmap': { page: '/roadmap' },
    '/what-is-blockstack': { page: '/what-is-blockstack' },
    '/legal/disclaimers': { page: '/legal/disclaimers' },
    '/legal/privacy-policy': { page: '/legal/privacy-policy' },
    '/legal/terms-of-use': { page: '/legal/terms-of-use' }
  })
}

module.exports = routes
<commit_msg>remove blog from static export<commit_after>const { fetchBlogPosts } = require('./common/lib')
const routes = async () => {
  // combine the map of post pages with our static pages
  return {
    '/': { page: '/' },
    '/404': { page: '/_error' },
    '/about': { page: '/about' },
    '/blog': { page: '/blog' },
    '/faq': { page: '/faq' },
    '/careers': { page: '/careers' },
    '/funding': { page: '/funding' },
    '/install': { page: '/install' },
    '/papers': { page: '/papers' },
    '/press': { page: '/press' },
    '/videos': { page: '/videos' },
    '/roadmap': { page: '/roadmap' },
    '/what-is-blockstack': { page: '/what-is-blockstack' },
    '/legal/disclaimers': { page: '/legal/disclaimers' },
    '/legal/privacy-policy': { page: '/legal/privacy-policy' },
    '/legal/terms-of-use': { page: '/legal/terms-of-use' }
  }
}

module.exports = routes
<|endoftext|>


<commit_before>/*
 * test.lb.base.template.js - Unit Tests of lb.base.template module
 *
 * Author:    Eric Bréchemier <legalbox@eric.brechemier.name>
 * Copyright: Legal Box (c) 2010, All Rights Reserved
 * License:   BSD License - http://creativecommons.org/licenses/BSD/
 * Version:   2010-12-24
 *
 * Based on Test Runner from bezen.org JavaScript library
 * CC-BY: Eric Bréchemier - http://bezen.org/javascript/
 */

/*requires lb.base.template.js */
/*jslint white:false, onevar:false, plusplus:false */
/*global lb, bezen, window */
(function() {
  // Builder of
  // Closure object for Test of lb.base.template

  // Define aliases
      /*requires bezen.assert.js */
  var assert = bezen.assert,
      /*requires bezen.object.js */
      object = bezen.object,
      /*requires bezen.testrunner.js */
      testrunner = bezen.testrunner,
      /*requires bezen.dom.js*/
      element = bezen.dom.element;

  function testNamespace(){

    assert.isTrue( object.exists(window,'lb','base','template'),
                                  "lb.base.template namespace was not found");
  }

  function testApplyFilters(){
    var ut = lb.base.template.applyFilters;

    try {
      ut();
    }catch(noFilters){
      assert.fail("No error expected without filter argument: "+noFilters);
    }

    try {
      ut([]);
    }catch(emptyFilters){
      assert.fail("No error expected with empty filters array: "+emptyFilters);
    }

    var captured = [];
    function catchFilter(){
      captured.push.apply(captured,arguments);
    }

    var arg1 = {}, arg2 = 'XYZ', arg3 = /abc/g;
    var filters = [catchFilter];
    ut(arg1,arg2,arg3,filters);
    assert.arrayEquals(captured, [arg1,arg2,arg3,filters],
                                     "3 arguments expected to be captured");

    captured = [];
    filters = [catchFilter];
    ut(arg1,arg2,arg3, arg1,arg2,arg3, arg1,arg2,arg3, filters);
    assert.arrayEquals(captured, [arg1,arg2,arg3,
                                  arg1,arg2,arg3,
                                  arg1,arg2,arg3,
                                  filters],
                                     "9 arguments expected to be captured");

    function constant(value){
      // Function: constant(value): function
      // Get a function always returning the given value.

      return function(){
        return value;
      };
    }

    var returnFalse = constant(false),
        returnTrue = constant(true),
        returnUndefined = constant(),
        returnNull = constant(null),
        returnZero = constant(0),
        returnEmptyString = constant('');

    captured = [];
    // filters are applied from right to left:
    //                    <-----------
    filters = [catchFilter, returnTrue];
    assert.equals( ut(filters), true,  "true value expected to be returned");
    assert.arrayEquals(captured,[],
            "processing expected to stop when previous filter returns true");

    filters = [catchFilter, returnFalse];
    assert.equals( ut(filters), false, "false value expected to be returned");
    assert.arrayEquals(captured, [],
           "processing expected to stop when previous filter returns false");

    filters = [catchFilter, returnEmptyString];
    assert.equals( ut(filters), '',   "empty string expected to be returned");
    assert.arrayEquals(captured, [],
               "processing expected to stop when previous filter returns ''");

    filters = [catchFilter, returnZero];
    assert.equals( ut(filters), 0,              "0 expected to be returned");
    assert.arrayEquals(captured, [],
                "processing expected to stop when previous filter returns 0");

    filters = [catchFilter, returnNull];
    assert.equals( ut(filters), null,         "null expected to be returned");
    assert.arrayEquals(captured, [],
             "processing expected to stop when previous filter returns null");

    captured = [];
    filters = [catchFilter, returnUndefined];
    ut(filters);
    assert.equals(captured.length, 1,
     "processing expected to continue when previous filter returns undefined");

    captured = [];
    filters = [
                 catchFilter,
                 constant('value'),
                 catchFilter,
                 returnUndefined,
                 catchFilter,
                 catchFilter
              ];
    assert.equals( ut(filters), 'value',     "value expected to be returned");
    assert.equals(captured.length, 3,
              "filters expected to be triggered until one returns any value "+
                                                  "different from undefined");

    // Test functions defined in documentation of the method
    var applyFilters = ut;
    var ELEMENT_NODE = 1;
    function topDownParsing(node,context,filters){
      if (!node || node.nodeType!==ELEMENT_NODE){
        return;
      }
      var i, length, attribute, child;
      for (i=0, length=node.attributes.length; i<length; i++){
        attribute = node.attributes[i];
        applyFilters(attribute,context,filters);
      }
      for (i=0, length=node.childNodes.length; i<length; i++){
        child = node.childNodes[i];
        applyFilters(child,context,filters);
      }
    }

    var PARAM_REGEXP = /#([a-zA-Z0-9\-]+)#/g;
    function replaceParams(node,context){
      if ( !node || !node.nodeValue || !node.nodeValue.replace ||
           !context || !context.data){
        return;
      }

      node.nodeValue = node.nodeValue.replace(
        PARAM_REGEXP,
        function(match,param){
          return context.data[param];
        }
      );
    }

    var node = element('span',{},'Welcome #name#');
bezen.log.info( node.innerHTML, true);

    ut(
      node,
      {data:
        {name:'John Doe'}
      },
      [ topDownParsing, replaceParams]
    );
bezen.log.info( node.innerHTML, true);

    var TEXT_NODE = 3;
    assert.arrayEquals(
      [
        node.nodeType,
        node.nodeName,
        node.childNodes.length,
        node.childNodes[0].nodeType,
        node.childNodes[0].nodeValue
      ],
      [
        ELEMENT_NODE,
        'SPAN',
        1,
        TEXT_NODE,
        'Welcome John Doe'
      ],      "input node expected to be updated with param value replaced");

    function replaceParamsInString(string, data){
      return string.replace(PARAM_REGEXP, function(match,param){
        return data[param];
      });
    }

    var greeting = ut(
      'Welcome #name#',
      {name: 'John Doe'},
      [replaceParamsInString]
    );
    assert.equals( greeting, 'Welcome John Doe',
                         "value expected to be replaced in string greeting");

    assert.equals( ut('#empty#',{empty:''},[replaceParamsInString]), '',
                   "empty string expected to be returned after replacement");
  }

  var tests = {
    testNamespace: testNamespace,
    testApplyFilters: testApplyFilters
  };

  testrunner.define(tests, "lb.base.template");
  return tests;

}());
<commit_msg>Removed debug logs from unit tests of lb.base.template<commit_after>/*
 * test.lb.base.template.js - Unit Tests of lb.base.template module
 *
 * Author:    Eric Bréchemier <legalbox@eric.brechemier.name>
 * Copyright: Legal Box (c) 2010, All Rights Reserved
 * License:   BSD License - http://creativecommons.org/licenses/BSD/
 * Version:   2010-12-24
 *
 * Based on Test Runner from bezen.org JavaScript library
 * CC-BY: Eric Bréchemier - http://bezen.org/javascript/
 */

/*requires lb.base.template.js */
/*jslint white:false, onevar:false, plusplus:false */
/*global lb, bezen, window */
(function() {
  // Builder of
  // Closure object for Test of lb.base.template

  // Define aliases
      /*requires bezen.assert.js */
  var assert = bezen.assert,
      /*requires bezen.object.js */
      object = bezen.object,
      /*requires bezen.testrunner.js */
      testrunner = bezen.testrunner,
      /*requires bezen.dom.js*/
      element = bezen.dom.element;

  function testNamespace(){

    assert.isTrue( object.exists(window,'lb','base','template'),
                                  "lb.base.template namespace was not found");
  }

  function testApplyFilters(){
    var ut = lb.base.template.applyFilters;

    try {
      ut();
    }catch(noFilters){
      assert.fail("No error expected without filter argument: "+noFilters);
    }

    try {
      ut([]);
    }catch(emptyFilters){
      assert.fail("No error expected with empty filters array: "+emptyFilters);
    }

    var captured = [];
    function catchFilter(){
      captured.push.apply(captured,arguments);
    }

    var arg1 = {}, arg2 = 'XYZ', arg3 = /abc/g;
    var filters = [catchFilter];
    ut(arg1,arg2,arg3,filters);
    assert.arrayEquals(captured, [arg1,arg2,arg3,filters],
                                     "3 arguments expected to be captured");

    captured = [];
    filters = [catchFilter];
    ut(arg1,arg2,arg3, arg1,arg2,arg3, arg1,arg2,arg3, filters);
    assert.arrayEquals(captured, [arg1,arg2,arg3,
                                  arg1,arg2,arg3,
                                  arg1,arg2,arg3,
                                  filters],
                                     "9 arguments expected to be captured");

    function constant(value){
      // Function: constant(value): function
      // Get a function always returning the given value.

      return function(){
        return value;
      };
    }

    var returnFalse = constant(false),
        returnTrue = constant(true),
        returnUndefined = constant(),
        returnNull = constant(null),
        returnZero = constant(0),
        returnEmptyString = constant('');

    captured = [];
    // filters are applied from right to left:
    //                    <-----------
    filters = [catchFilter, returnTrue];
    assert.equals( ut(filters), true,  "true value expected to be returned");
    assert.arrayEquals(captured,[],
            "processing expected to stop when previous filter returns true");

    filters = [catchFilter, returnFalse];
    assert.equals( ut(filters), false, "false value expected to be returned");
    assert.arrayEquals(captured, [],
           "processing expected to stop when previous filter returns false");

    filters = [catchFilter, returnEmptyString];
    assert.equals( ut(filters), '',   "empty string expected to be returned");
    assert.arrayEquals(captured, [],
               "processing expected to stop when previous filter returns ''");

    filters = [catchFilter, returnZero];
    assert.equals( ut(filters), 0,              "0 expected to be returned");
    assert.arrayEquals(captured, [],
                "processing expected to stop when previous filter returns 0");

    filters = [catchFilter, returnNull];
    assert.equals( ut(filters), null,         "null expected to be returned");
    assert.arrayEquals(captured, [],
             "processing expected to stop when previous filter returns null");

    captured = [];
    filters = [catchFilter, returnUndefined];
    ut(filters);
    assert.equals(captured.length, 1,
     "processing expected to continue when previous filter returns undefined");

    captured = [];
    filters = [
                 catchFilter,
                 constant('value'),
                 catchFilter,
                 returnUndefined,
                 catchFilter,
                 catchFilter
              ];
    assert.equals( ut(filters), 'value',     "value expected to be returned");
    assert.equals(captured.length, 3,
              "filters expected to be triggered until one returns any value "+
                                                  "different from undefined");

    // Test functions defined in documentation of the method
    var applyFilters = ut;
    var ELEMENT_NODE = 1;
    function topDownParsing(node,context,filters){
      if (!node || node.nodeType!==ELEMENT_NODE){
        return;
      }
      var i, length, attribute, child;
      for (i=0, length=node.attributes.length; i<length; i++){
        attribute = node.attributes[i];
        applyFilters(attribute,context,filters);
      }
      for (i=0, length=node.childNodes.length; i<length; i++){
        child = node.childNodes[i];
        applyFilters(child,context,filters);
      }
    }

    var PARAM_REGEXP = /#([a-zA-Z0-9\-]+)#/g;
    function replaceParams(node,context){
      if ( !node || !node.nodeValue || !node.nodeValue.replace ||
           !context || !context.data){
        return;
      }

      node.nodeValue = node.nodeValue.replace(
        PARAM_REGEXP,
        function(match,param){
          return context.data[param];
        }
      );
    }

    var node = element('span',{},'Welcome #name#');

    ut(
      node,
      {data:
        {name:'John Doe'}
      },
      [ topDownParsing, replaceParams]
    );

    var TEXT_NODE = 3;
    assert.arrayEquals(
      [
        node.nodeType,
        node.nodeName,
        node.childNodes.length,
        node.childNodes[0].nodeType,
        node.childNodes[0].nodeValue
      ],
      [
        ELEMENT_NODE,
        'SPAN',
        1,
        TEXT_NODE,
        'Welcome John Doe'
      ],      "input node expected to be updated with param value replaced");

    function replaceParamsInString(string, data){
      return string.replace(PARAM_REGEXP, function(match,param){
        return data[param];
      });
    }

    var greeting = ut(
      'Welcome #name#',
      {name: 'John Doe'},
      [replaceParamsInString]
    );
    assert.equals( greeting, 'Welcome John Doe',
                         "value expected to be replaced in string greeting");

    assert.equals( ut('#empty#',{empty:''},[replaceParamsInString]), '',
                   "empty string expected to be returned after replacement");
  }

  var tests = {
    testNamespace: testNamespace,
    testApplyFilters: testApplyFilters
  };

  testrunner.define(tests, "lb.base.template");
  return tests;

}());
<|endoftext|>


<commit_before>/*eslint no-unused-vars: 1*/

import React, { Component } from 'react'
import classNames from 'classnames'
import More from '../components/More'
import { Link } from 'react-router'
import { INTERACTIVE_ARTICLE_STYLE } from '../constants/index'
import { date2yyyymmdd } from '../lib/date-transformer'
import { getArticleImageSrc, getImageSrcSet } from '../utils/index'

// lodash
import get from 'lodash/get'
import map from 'lodash/map'

if (process.env.BROWSER) {
  require('./ArticleList.css')
}

export default class ListArticleItem extends Component {
  constructor(props, context) {
    super(props, context)
  }

  render() {
    const { articles, hasMore, loadMore, loadMoreError } = this.props
    const bgStyle = {}
    let photoClass

    if (this.props.bgStyle === 'dark') {
      photoClass = 'tag-photography'
    }
    if (articles && articles.length > 0) {
      return (

              { map(articles, (a) => {
                let image = getArticleImageSrc(a)
                let imageSrcSet = getImageSrcSet(a)
                const d_str = date2yyyymmdd(a.publishedDate , '.')
                let url = '/a/' + a.slug
                let excerpt =  get(a, 'ogDescription', '')
                if (image) {
                  return (

                      <Link to={url} target={a.style === INTERACTIVE_ARTICLE_STYLE ? '_self' : undefined}>

{a.title}

{excerpt}

                          <time dateTime={date2yyyymmdd(a.publishedDate, '-')} className="tag-itempublished">{d_str}</time>

                      </Link>

                  )
                }
              })}

          {
            hasMore ? (

                <More loadMore={loadMore}>
                  {loadMoreError ? '更多文章（請重試）' : '更多文章'}
                </More>

            )
            : null
          }

      )
    } else {
      return (

)
    }
  }
}
<commit_msg>[Bug] Fix images not showing.<commit_after>/*eslint no-unused-vars: 1*/

import React, { Component } from 'react'
import classNames from 'classnames'
import More from '../components/More'
import { Link } from 'react-router'
import { INTERACTIVE_ARTICLE_STYLE } from '../constants/index'
import { date2yyyymmdd } from '../lib/date-transformer'
import { getArticleImageSrc, getArticleImageSrcSet } from '../utils/index'

// lodash
import get from 'lodash/get'
import map from 'lodash/map'

if (process.env.BROWSER) {
  require('./ArticleList.css')
}

export default class ListArticleItem extends Component {
  constructor(props, context) {
    super(props, context)
  }

  render() {
    const { articles, hasMore, loadMore, loadMoreError } = this.props
    const bgStyle = {}
    let photoClass

    if (this.props.bgStyle === 'dark') {
      photoClass = 'tag-photography'
    }
    if (articles && articles.length > 0) {
      return (

              { map(articles, (a) => {
                let image = getArticleImageSrc(a)
                let imageSrcSet = getArticleImageSrcSet(a)
                const d_str = date2yyyymmdd(a.publishedDate , '.')
                let url = '/a/' + a.slug
                let excerpt =  get(a, 'ogDescription', '')
                if (image) {
                  return (

                      <Link to={url} target={a.style === INTERACTIVE_ARTICLE_STYLE ? '_self' : undefined}>

{a.title}

{excerpt}

                          <time dateTime={date2yyyymmdd(a.publishedDate, '-')} className="tag-itempublished">{d_str}</time>

                      </Link>

                  )
                }
              })}

          {
            hasMore ? (

                <More loadMore={loadMore}>
                  {loadMoreError ? '更多文章（請重試）' : '更多文章'}
                </More>

            )
            : null
          }

      )
    } else {
      return (

)
    }
  }
}
<|endoftext|>


<commit_before>///////////////////////////////////////
//get requests
///////////////////////////////////////

app.get('/HV', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/HV.jade');
});

app.get('/GRIFFIN', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('detectors/GRIFFIN.jade');
});

app.get('/DAQ', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/DAQ.jade');
});

app.get('/PPG', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/PPG.jade');
});

app.get('/Clocks', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/Clock.jade');
});

app.get('/Filter', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/Filter.jade');
});

///////////////////////////////////////
//post routes
///////////////////////////////////////

app.post('/postHV', function(req, res){

	spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Variables/Demand["+req.body.chIndex+"] " + req.body.demandVoltage]);
	spawn('odbedit', ['-c', "set '/Equipment/HV-"+req.body.crateIndex+"/Settings/Ramp Up Speed["+req.body.chIndex+"]' " + req.body.voltageUp]);
	spawn('odbedit', ['-c', "set '/Equipment/HV-"+req.body.crateIndex+"/Settings/Ramp Down Speed["+req.body.chIndex+"]' " + req.body.voltageDown]);

	if(req.body.powerSwitch == 'off')
		spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Settings/ChState["+req.body.chIndex+"] 0"]);
	else
		spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Settings/ChState["+req.body.chIndex+"] 1"]);

	return res.redirect('/HV?crate=0&channel='+req.body.chName);
});

app.post('/registerCycle', function(req, res){
	var cycle = (req.body.cycleString) ? JSON.parse(req.body.cycleString) : null,
		i,
		steps = [],
		durations = [];

	//just load an existing cycle
	if(req.body.loadTarget != 'null'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.loadTarget]);
		return res.redirect('/PPG');
	}

	//delete an existing cycle
	if(req.body.deleteTarget != 'null'){
		spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.deleteTarget]);
		return res.redirect('/PPG');
	}

	//register a new cycle
	for(i=0; i<cycle.length; i++){
		steps[i] = parseInt(cycle[i].PPGcode, 10);
		durations[i] = parseInt(cycle[i].duration, 10);
	}

	spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.cycleName]);

	spawn('odbedit', ['-c', "mkdir /PPG/Cycles/" + req.body.cycleName]);

	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/PPGcodes[" + steps.length + "]"]);
	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/durations[" + steps.length + "]"]);
	for(i=0; i<cycle.length; i++){
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/PPGcodes["+ i +"]  " + Math.round(steps[i]) ]);
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/durations["+ i +"]  " + Math.round(durations[i]) ]);
	}

	if(req.body.applyCycle == 'on'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.cycleName]);
	}

	return res.redirect('/PPG');
});

app.post('/registerFilter', function(req, res){
	var filter = (req.body.filterString) ? JSON.parse(req.body.filterString) : null,
		odbManipulationFile = '',
		i, j,
		steps = [],
		durations = [];

/*
	//just load an existing cycle
	if(req.body.loadTarget != 'null'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.loadTarget]);
		return res.redirect('/PPG');
	}

	//delete an existing cycle
	if(req.body.deleteTarget != 'null'){
		spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.deleteTarget]);
		return res.redirect('/PPG');
	}
*/
	//register a new filter - build file and run with execFile for most robust execution (spawn seems to create a race condition, consider removing).
	odbManipulationFile += 'odbedit -c "rm /Filter/Filters/' + req.body.filterName + '"\n';
	odbManipulationFile += 'odbedit -c "mkdir /Filter/Filters/' + req.body.filterName + '"\n';
	for(i=0; i<filter.length; i++){
		odbManipulationFile += 'odbedit -c "create string /Filter/Filters/' + req.body.filterName + '/orCondition'+i+'[' + filter[i].length + ']"\n';
		for(j=0; j<filter[i].length; j++){
			odbManipulationFile += 'odbedit -c "set /Filter/Filters/' + req.body.filterName + '/orCondition'+i + '['+j+'] ' + filter[i][j] + '"\n';
		}
	}

	fs.writeFile('odbManipulation.sh', odbManipulationFile, function(){
		fs.chmod('./odbManipulation.sh', '777', function(){
			execFile('./odbManipulation.sh', function(error, stdout, stderr){
				console.log('Writing ' + req.body.filterName + ' filter to ODB, process [error, stdout, stderr]:');
				console.log([error, stdout, stderr]);
			});
		});
	});

	if(req.body.applyFilter == 'on'){
		spawn('odbedit', ['-c', "set /Filter/Current " + req.body.cycleName]);
	}

	return res.redirect('/Filter');

});

app.post('/updateClock', function(req, res){
	var ClockEnB = 0,
		powerOn,
		stepdown = parseInt(req.body.freqStepdown,10);

	//channel on / off
	for(i=0; i<6; i++){
		powerOn = req.body['eSATAtoggle' + i] == 1
		ClockEnB = ClockEnB | ((powerOn) ? (0xF << 4*i) : 0);
	}
	spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[0] " + ClockEnB]);

	//freq. stepdown
	if(stepdown && req.body.isMaster=='1'){
		for(i=0; i<8; i++){
			spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[" + (11+4*i) + "] " + stepdown]);
			spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[" + (12+4*i) + "] " + stepdown]);
		}
	}

	return res.redirect('/Clocks');
});

app.post('/toggleClock', function(req, res){
	spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[1] " + req.body['radio'+req.body.clockIndex] ]);

	return res.redirect('/Clocks');
})

<commit_msg>setting current filter in ODB<commit_after>///////////////////////////////////////
//get requests
///////////////////////////////////////

app.get('/HV', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/HV.jade');
});

app.get('/GRIFFIN', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('detectors/GRIFFIN.jade');
});

app.get('/DAQ', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/DAQ.jade');
});

app.get('/PPG', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/PPG.jade');
});

app.get('/Clocks', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/Clock.jade');
});

app.get('/Filter', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/Filter.jade');
});

///////////////////////////////////////
//post routes
///////////////////////////////////////

app.post('/postHV', function(req, res){

	spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Variables/Demand["+req.body.chIndex+"] " + req.body.demandVoltage]);
	spawn('odbedit', ['-c', "set '/Equipment/HV-"+req.body.crateIndex+"/Settings/Ramp Up Speed["+req.body.chIndex+"]' " + req.body.voltageUp]);
	spawn('odbedit', ['-c', "set '/Equipment/HV-"+req.body.crateIndex+"/Settings/Ramp Down Speed["+req.body.chIndex+"]' " + req.body.voltageDown]);

	if(req.body.powerSwitch == 'off')
		spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Settings/ChState["+req.body.chIndex+"] 0"]);
	else
		spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Settings/ChState["+req.body.chIndex+"] 1"]);

	return res.redirect('/HV?crate=0&channel='+req.body.chName);
});

app.post('/registerCycle', function(req, res){
	var cycle = (req.body.cycleString) ? JSON.parse(req.body.cycleString) : null,
		i,
		steps = [],
		durations = [];

	//just load an existing cycle
	if(req.body.loadTarget != 'null'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.loadTarget]);
		return res.redirect('/PPG');
	}

	//delete an existing cycle
	if(req.body.deleteTarget != 'null'){
		spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.deleteTarget]);
		return res.redirect('/PPG');
	}

	//register a new cycle
	for(i=0; i<cycle.length; i++){
		steps[i] = parseInt(cycle[i].PPGcode, 10);
		durations[i] = parseInt(cycle[i].duration, 10);
	}

	spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.cycleName]);

	spawn('odbedit', ['-c', "mkdir /PPG/Cycles/" + req.body.cycleName]);

	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/PPGcodes[" + steps.length + "]"]);
	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/durations[" + steps.length + "]"]);
	for(i=0; i<cycle.length; i++){
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/PPGcodes["+ i +"]  " + Math.round(steps[i]) ]);
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/durations["+ i +"]  " + Math.round(durations[i]) ]);
	}

	if(req.body.applyCycle == 'on'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.cycleName]);
	}

	return res.redirect('/PPG');
});

app.post('/registerFilter', function(req, res){
	var filter = (req.body.filterString) ? JSON.parse(req.body.filterString) : null,
		odbManipulationFile = '',
		i, j,
		steps = [],
		durations = [];
console.log(filterString)
/*
	//just load an existing cycle
	if(req.body.loadTarget != 'null'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.loadTarget]);
		return res.redirect('/PPG');
	}

	//delete an existing cycle
	if(req.body.deleteTarget != 'null'){
		spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.deleteTarget]);
		return res.redirect('/PPG');
	}
*/
	//register a new filter - build file and run with execFile for most robust execution (spawn seems to create a race condition, consider removing).
	odbManipulationFile += 'odbedit -c "rm /Filter/Filters/' + req.body.filterName + '"\n';
	odbManipulationFile += 'odbedit -c "mkdir /Filter/Filters/' + req.body.filterName + '"\n';
	for(i=0; i<filter.length; i++){
		odbManipulationFile += 'odbedit -c "create string /Filter/Filters/' + req.body.filterName + '/orCondition'+i+'[' + filter[i].length + ']"\n';
		for(j=0; j<filter[i].length; j++){
			odbManipulationFile += 'odbedit -c "set /Filter/Filters/' + req.body.filterName + '/orCondition'+i + '['+j+'] ' + filter[i][j] + '"\n';
		}
	}

	fs.writeFile('odbManipulation.sh', odbManipulationFile, function(){
		fs.chmod('./odbManipulation.sh', '777', function(){
			execFile('./odbManipulation.sh', function(error, stdout, stderr){
				console.log('Writing ' + req.body.filterName + ' filter to ODB, process [error, stdout, stderr]:');
				console.log([error, stdout, stderr]);
			});
		});
	});

	if(req.body.applyFilter == 'on'){
		spawn('odbedit', ['-c', "set /Filter/Current " + req.body.cycleName]);
	}

	return res.redirect('/Filter');

});

app.post('/updateClock', function(req, res){
	var ClockEnB = 0,
		powerOn,
		stepdown = parseInt(req.body.freqStepdown,10);

	//channel on / off
	for(i=0; i<6; i++){
		powerOn = req.body['eSATAtoggle' + i] == 1
		ClockEnB = ClockEnB | ((powerOn) ? (0xF << 4*i) : 0);
	}
	spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[0] " + ClockEnB]);

	//freq. stepdown
	if(stepdown && req.body.isMaster=='1'){
		for(i=0; i<8; i++){
			spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[" + (11+4*i) + "] " + stepdown]);
			spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[" + (12+4*i) + "] " + stepdown]);
		}
	}

	return res.redirect('/Clocks');
});

app.post('/toggleClock', function(req, res){
	spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[1] " + req.body['radio'+req.body.clockIndex] ]);

	return res.redirect('/Clocks');
})

<|endoftext|>