<commit_before>app = new Vue({
    router: router,
    data: {
        links: [],
        title: '',
        hosts: {
            vue: null,
            api: null,
            uc: null,
            forum: null,
            blog: null
        },
        showUrlCover: router.history.current.fullPath != '/' && router.history.current.fullPath != '/home',
        fullScreen: false,
        layout: {
            loginBoxOpened: false
        },
        user: {
            isSignedIn: false,
            profile: {
                id: null,
                username: null,
                avatarUrl: null,
                role: null,
                tried: [],
                passed: [],
                chat: null
            }
        },
        preferences: {
            language: 'C++'
        },
        signalr: {
            onlinejudge: {
                connection: null,
                listeners: []
            }
        },
        lookup: {
            user: {},
            problem: {}
        },
        control: {
            apiLock: false,
            currentNotification: null,
            notifications: [],
            notificationLock: false,
            userInfoView: null,
            chatIframeUrl: null,
            chatInterval: null
        }
    },
    created: function () {
        var self = this;

        /* Initialize host addresses */
        this.hosts.blog = 'http://{USERNAME}.blog.joyoi.cn';
        this.hosts.forum = 'http://forum.joyoi.cn';
        this.hosts.api = 'http://localhost:5000';
        this.hosts.uc = 'http://uc.joyoi.cn';
        qv.__host = this.hosts.api;

        this.signalr.onlinejudge.connection = new signalR.HubConnection(this.hosts.api + '/signalr/onlinejudge');
        this.signalr.onlinejudge.connection.on('ItemUpdated', (type, id) => {
            var listners = this.signalr.onlinejudge.listeners.filter(x => x.type === type && (x.id === id || !x.id)).map(x => {
                x.view.removeCache();
                return x.view.fetch(x.view._fetchFunc);
            });
        });
        this.signalr.onlinejudge.connection.start()

        if (document.cookie.indexOf("AspNetCore") >= 0) {
            self.user.isSignedIn = true;
            self.control.userInfoView = qv.createView('/api/user/session/info');
            self.control.userInfoView.fetch((x) => {
                self.user.profile.username = x.data.username;
                self.user.profile.role = x.data.role;
                self.user.profile.id = x.data.id;
                self.user.tried = x.data.tried;
                self.user.passed = x.data.passed;
                self.user.chat = x.data.chat;
                self.preferences.language = x.data.preferredLanguage || 'C++';
                self.control.chatIframeUrl = x.data.chat;
            });
        }
        else {
            this.user.isSignedIn = false;
        }

        qv.createView('/api/user/message', null, 30000)
            .fetch(x => {
                if (x.data) {
                    self.control.chatInterval = setInterval(function () {
                        if ($('#back-to-top').hasClass('msg-alert'))
                            $('#back-to-top').removeClass('msg-alert');
                        else
                            $('#back-to-top').addClass('msg-alert');
                    }, 1000);
                } else {
                    if (self.control.chatInterval) {
                        clearInterval(self.control.chatInterval);
                        $('#back-to-top').removeClass('msg-alert');
                    }
                }
            });
    },
    watch: {
        title: function (val) {
            $('title').text(val + ' - JoyOI Online Judge');
        },
        fullScreen: function (val) {
            if (val) {
                $('body').addClass('full-screen');
            } else {
                $('body').removeClass('full-screen');
            }
        },
        'host.api': function (val) {
            if (qv)
                qv.__host = val;
        },
        deep: true
    },
    methods: {
        toggleLoginBox: function () {
            if (this.layout.loginBoxOpened) {
                this.layout.loginBoxOpened = false;
            } else {
                this.layout.loginBoxOpened = true;
            }
        },
        loginFocusIn: function (selector) {
            $(selector).parent('label').addClass('login-focus-label');
        },
        loginFocusOut: function (selector) {
            $(selector).parent('label').removeClass('login-focus-label');
        },
        login: function () {
            var self = this;
            app.notification('pending', '正在登录...');
            qv.put('/api/user/session', { username: $('#username').val(), password: $('#password').val() })
                .then(function (result) {
                    document.cookie = result.data.cookie;
                    self.user.isSignedIn = true;
                    return qv.get('/api/user/session/info');
                })
                .then(x => {
                    self.user.profile.username = x.data.username;
                    self.user.profile.role = x.data.role;
                    self.user.profile.id = x.data.id;
                    self.user.tried = x.data.tried;
                    self.user.passed = x.data.passed;
                    self.user.chat = x.data.chat;
                    self.preferences.language = x.data.preferredLanguage;
                    self.control.chatIframeUrl = x.data.chat;
                    self.notification("succeeded", "登录成功");
                    self.toggleLoginBox();
                })
                .catch(err => {
                    self.notification("error", "登录失败", err.responseJSON.msg);
                });
        },
        logout: function () {
            document.cookie += '; Expires=' + new Date(0).toUTCString();
            this.user.isSignedIn = false;
            app.notification('succeeded', '注销成功', '您已经注销了Joy OI的登录状态');
        },
        marked: function (str) {
            return filterXSS(marked(str || ""))
        },
        xss: function (str) {
            return filterXSS(str);
        },
        notification: function (level, title, detail) {
            this.control.notifications.push({ level: level, title: title, detail: detail });
            if (this.control.currentNotification && this.control.currentNotification.level === 'pending') {
                this.control.notificationLock = false;
            }
            this._showNotification();
        },
        redirect: function (name, path, params) {
            if (name && !path)
                path = name;
            LazyRouting.RedirectTo(name, path, params);
        },
        toLocalTime: function (timeStr) {
            return moment(new Date(timeStr + 'Z')).format('YYYY-MM-DD HH:mm:ss');
        },
        toggleChatBox: function () {
            if ($('.chat-iframe').hasClass('active')) {
                $('.chat-iframe').removeClass('active');
                $('#back-to-top').css('margin-right', 0);
            } else {
                $('.chat-iframe').addClass('active');
                $('#back-to-top').css('margin-right', 350);
            }
        },
        _showNotification: function () {
            var self = this;
            if (!this.control.notificationLock && this.control.notifications.length) {
                this.control.notificationLock = true;
                var notification = this.control.notifications[0];
                this.control.notifications = this.control.notifications.slice(1);
                this.control.currentNotification = notification;
                setTimeout(function () {
                    self.control.currentNotification = null;
                    setTimeout(function () {
                        self.control.notificationLock = false;
                        if (self.control.notifications.length) {
                            self._showNotification();
                        }
                    }, 250);
                }, 4000);
            }
        }
    }
});

router.beforeEach((to, from, next) => {
    $('.xdsoft_datetimepicker').remove();
    app.fullScreen = false;
    next();
});

router.afterEach(() => {
    app.showUrlCover = router.history.current.fullPath != '/' && router.history.current.fullPath != '/home';
});
<commit_msg>Fixes session bug<commit_after>app = new Vue({
    router: router,
    data: {
        links: [],
        title: '',
        hosts: {
            vue: null,
            api: null,
            uc: null,
            forum: null,
            blog: null
        },
        showUrlCover: router.history.current.fullPath != '/' && router.history.current.fullPath != '/home',
        fullScreen: false,
        layout: {
            loginBoxOpened: false
        },
        user: {
            isSignedIn: false,
            profile: {
                id: null,
                username: null,
                avatarUrl: null,
                role: null,
                tried: [],
                passed: [],
                chat: null
            }
        },
        preferences: {
            language: 'C++'
        },
        signalr: {
            onlinejudge: {
                connection: null,
                listeners: []
            }
        },
        lookup: {
            user: {},
            problem: {}
        },
        control: {
            apiLock: false,
            currentNotification: null,
            notifications: [],
            notificationLock: false,
            userInfoView: null,
            chatIframeUrl: null,
            chatInterval: null
        }
    },
    created: function () {
        var self = this;

        /* Initialize host addresses */
        this.hosts.blog = 'http://{USERNAME}.blog.joyoi.cn';
        this.hosts.forum = 'http://forum.joyoi.cn';
        this.hosts.api = 'http://localhost:5000';
        this.hosts.uc = 'http://uc.joyoi.cn';
        qv.__host = this.hosts.api;

        this.signalr.onlinejudge.connection = new signalR.HubConnection(this.hosts.api + '/signalr/onlinejudge');
        this.signalr.onlinejudge.connection.on('ItemUpdated', (type, id) => {
            var listners = this.signalr.onlinejudge.listeners.filter(x => x.type === type && (x.id === id || !x.id)).map(x => {
                x.view.removeCache();
                return x.view.fetch(x.view._fetchFunc);
            });
        });
        this.signalr.onlinejudge.connection.start()

        if (document.cookie.indexOf("AspNetCore") >= 0) {
            self.user.isSignedIn = true;
            self.control.userInfoView = qv.createView('/api/user/session/info');
            self.control.userInfoView.fetch((x) => {
                if (x.data.isSignedIn) {
                    self.user.profile.username = x.data.username;
                    self.user.profile.role = x.data.role;
                    self.user.profile.id = x.data.id;
                    self.user.tried = x.data.tried;
                    self.user.passed = x.data.passed;
                    self.user.chat = x.data.chat;
                    self.preferences.language = x.data.preferredLanguage || 'C++';
                    self.control.chatIframeUrl = x.data.chat;
                } else {
                    self.user.isSignedIn = false;
                }
            });
        }
        else {
            this.user.isSignedIn = false;
        }

        qv.createView('/api/user/message', null, 30000)
            .fetch(x => {
                if (x.data) {
                    self.control.chatInterval = setInterval(function () {
                        if ($('#back-to-top').hasClass('msg-alert'))
                            $('#back-to-top').removeClass('msg-alert');
                        else
                            $('#back-to-top').addClass('msg-alert');
                    }, 1000);
                } else {
                    if (self.control.chatInterval) {
                        clearInterval(self.control.chatInterval);
                        $('#back-to-top').removeClass('msg-alert');
                    }
                }
            });
    },
    watch: {
        title: function (val) {
            $('title').text(val + ' - JoyOI Online Judge');
        },
        fullScreen: function (val) {
            if (val) {
                $('body').addClass('full-screen');
            } else {
                $('body').removeClass('full-screen');
            }
        },
        'host.api': function (val) {
            if (qv)
                qv.__host = val;
        },
        deep: true
    },
    methods: {
        toggleLoginBox: function () {
            if (this.layout.loginBoxOpened) {
                this.layout.loginBoxOpened = false;
            } else {
                this.layout.loginBoxOpened = true;
            }
        },
        loginFocusIn: function (selector) {
            $(selector).parent('label').addClass('login-focus-label');
        },
        loginFocusOut: function (selector) {
            $(selector).parent('label').removeClass('login-focus-label');
        },
        login: function () {
            var self = this;
            app.notification('pending', '正在登录...');
            qv.put('/api/user/session', { username: $('#username').val(), password: $('#password').val() })
                .then(function (result) {
                    document.cookie = result.data.cookie;
                    self.user.isSignedIn = true;
                    return qv.get('/api/user/session/info');
                })
                .then(x => {
                    self.user.profile.username = x.data.username;
                    self.user.profile.role = x.data.role;
                    self.user.profile.id = x.data.id;
                    self.user.tried = x.data.tried;
                    self.user.passed = x.data.passed;
                    self.user.chat = x.data.chat;
                    self.preferences.language = x.data.preferredLanguage;
                    self.control.chatIframeUrl = x.data.chat;
                    self.notification("succeeded", "登录成功");
                    self.toggleLoginBox();
                })
                .catch(err => {
                    self.notification("error", "登录失败", err.responseJSON.msg);
                });
        },
        logout: function () {
            document.cookie += '; Expires=' + new Date(0).toUTCString();
            this.user.isSignedIn = false;
            app.notification('succeeded', '注销成功', '您已经注销了Joy OI的登录状态');
        },
        marked: function (str) {
            return filterXSS(marked(str || ""))
        },
        xss: function (str) {
            return filterXSS(str);
        },
        notification: function (level, title, detail) {
            this.control.notifications.push({ level: level, title: title, detail: detail });
            if (this.control.currentNotification && this.control.currentNotification.level === 'pending') {
                this.control.notificationLock = false;
            }
            this._showNotification();
        },
        redirect: function (name, path, params) {
            if (name && !path)
                path = name;
            LazyRouting.RedirectTo(name, path, params);
        },
        toLocalTime: function (timeStr) {
            return moment(new Date(timeStr + 'Z')).format('YYYY-MM-DD HH:mm:ss');
        },
        toggleChatBox: function () {
            if ($('.chat-iframe').hasClass('active')) {
                $('.chat-iframe').removeClass('active');
                $('#back-to-top').css('margin-right', 0);
            } else {
                $('.chat-iframe').addClass('active');
                $('#back-to-top').css('margin-right', 350);
            }
        },
        _showNotification: function () {
            var self = this;
            if (!this.control.notificationLock && this.control.notifications.length) {
                this.control.notificationLock = true;
                var notification = this.control.notifications[0];
                this.control.notifications = this.control.notifications.slice(1);
                this.control.currentNotification = notification;
                setTimeout(function () {
                    self.control.currentNotification = null;
                    setTimeout(function () {
                        self.control.notificationLock = false;
                        if (self.control.notifications.length) {
                            self._showNotification();
                        }
                    }, 250);
                }, 4000);
            }
        }
    }
});

router.beforeEach((to, from, next) => {
    $('.xdsoft_datetimepicker').remove();
    app.fullScreen = false;
    next();
});

router.afterEach(() => {
    app.showUrlCover = router.history.current.fullPath != '/' && router.history.current.fullPath != '/home';
});
<|endoftext|>


<commit_before>'use strict';

module.exports = function(Chart) {

	var helpers = Chart.helpers;

	var defaultConfig = {
		position: 'left',
		ticks: {
			callback: Chart.Ticks.formatters.linear
		}
	};

	var FinancialLinearScale = Chart.scaleService.getScaleConstructor('linear').extend({

		determineDataLimits: function() {
			var me = this;
			var chart = me.chart;
			var data = chart.data;
			var datasets = data.datasets;
			var isHorizontal = me.isHorizontal();

			function IDMatches(meta) {
				return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
			}

			// First Calculate the range
			me.min = null;
			me.max = null;

			// Regular charts use x, y values
			// For the financial chart we have rawValue.h (hi) and rawValue.l (low) for each point
			helpers.each(datasets, function(dataset, datasetIndex) {
				var meta = chart.getDatasetMeta(datasetIndex);
				if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
					helpers.each(dataset.data, function(rawValue, index) {
						var high = rawValue.h;
						var low = rawValue.l;

						if (me.min === null) {
							me.min = low;
						} else if (low < me.min) {
							me.min = low;
						}

						if (me.max === null) {
							me.max = high;
						} else if (high > me.max) {
							me.max = high;
						}
					});
				}
			});

			// Add whitespace around bars. Axis shouldn't go exactly from min to max
            me.min = me.min - me.min * 0.05;
            me.max = me.max * 1.05;

			// Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
			this.handleTickRangeOptions();
		}
	});
	Chart.scaleService.registerScaleType('financialLinear', FinancialLinearScale, defaultConfig);

};
<commit_msg>Use consistent math for min/max whitespace<commit_after>'use strict';

module.exports = function(Chart) {

	var helpers = Chart.helpers;

	var defaultConfig = {
		position: 'left',
		ticks: {
			callback: Chart.Ticks.formatters.linear
		}
	};

	var FinancialLinearScale = Chart.scaleService.getScaleConstructor('linear').extend({

		determineDataLimits: function() {
			var me = this;
			var chart = me.chart;
			var data = chart.data;
			var datasets = data.datasets;
			var isHorizontal = me.isHorizontal();

			function IDMatches(meta) {
				return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
			}

			// First Calculate the range
			me.min = null;
			me.max = null;

			// Regular charts use x, y values
			// For the financial chart we have rawValue.h (hi) and rawValue.l (low) for each point
			helpers.each(datasets, function(dataset, datasetIndex) {
				var meta = chart.getDatasetMeta(datasetIndex);
				if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
					helpers.each(dataset.data, function(rawValue, index) {
						var high = rawValue.h;
						var low = rawValue.l;

						if (me.min === null) {
							me.min = low;
						} else if (low < me.min) {
							me.min = low;
						}

						if (me.max === null) {
							me.max = high;
						} else if (high > me.max) {
							me.max = high;
						}
					});
				}
			});

			// Add whitespace around bars. Axis shouldn't go exactly from min to max
            me.min = me.min - me.min * 0.05;
            me.max = me.max + me.max * 0.05;

			// Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
			this.handleTickRangeOptions();
		}
	});
	Chart.scaleService.registerScaleType('financialLinear', FinancialLinearScale, defaultConfig);

};
<|endoftext|>


<commit_before>//Leaflet-SVGIcon
//SVG icon for any marker class
//Ilya Atkin
//ilya.atkin@unh.edu

L.DivIcon.SVGIcon = L.DivIcon.extend({
    options: {
        "circleText": "",
        "className": "svg-icon",
        "circleAnchor": null, //defaults to [iconSize.x/2, iconSize.x/2]
        "circleColor": null, //defaults to color
        "circleOpacity": null, // defaults to opacity
        "circleFillColor": "rgb(255,255,255)",
        "circleFillOpacity": null, //default to opacity
        "circleRatio": 0.5,
        "circleWeight": null, //defaults to weight
        "color": "rgb(0,102,255)",
        "fillColor": null, // defaults to color
        "fillOpacity": 0.4,
        "fontColor": "rgb(0, 0, 0)",
        "fontOpacity": "1",
        "fontSize": null, // defaults to iconSize.x/4
        "iconAnchor": null, //defaults to [iconSize.x/2, iconSize.y] (point tip)
        "iconSize": L.point(32,48),
        "opacity": 1,
        "popupAnchor": null,
        "weight": 2
    },
    initialize: function(options) {
        options = L.Util.setOptions(this, options)

        //iconSize needs to be converted to a Point object if it is not passed as one
        options.iconSize = L.point(options.iconSize)

        //in addition to setting option dependant defaults, Point-based options are converted to Point objects
        if (!options.circleAnchor) {
            options.circleAnchor = L.point(Number(options.iconSize.x)/2, Number(options.iconSize.x)/2)
        }
        else {
            options.circleAnchor = L.point(options.circleAnchor)
        }
        if (!options.circleColor) {
            options.circleColor = options.color
        }
        if (!options.circleFillOpacity) {
            options.circleFillOpacity = options.opacity
        }
        if (!options.circleOpacity) {
            options.circleOpacity = options.opacity
        }
        if (!options.circleWeight) {
            options.circleWeight = options.weight
        }
        if (!options.fillColor) {
            options.fillColor = options.color
        }
        if (!options.fontSize) {
            options.fontSize = Number(options.iconSize.x/4)
        }
        if (!options.iconAnchor) {
            options.iconAnchor = L.point(Number(options.iconSize.x)/2, Number(options.iconSize.y))
        }
        else {
            options.iconAnchor = L.point(options.iconAnchor)
        }
        if (!options.popupAnchor) {
            options.popupAnchor = L.point(0, (-0.75)*(options.iconSize.y))
        }
        else {
            options.popupAnchor = L.point(options.popupAnchor)
        }

        var path = this._createPath()
        var circle = this._createCircle()

        options.html = this._createSVG()
    },
    _createCircle: function() {
        var cx = Number(this.options.circleAnchor.x)
        var cy = Number(this.options.circleAnchor.y)
        var radius = this.options.iconSize.x/2 * Number(this.options.circleRatio)
        var fill = this.options.circleFillColor
        var fillOpacity = this.options.circleFillOpacity
        var stroke = this.options.circleColor
        var strokeOpacity = this.options.circleOpacity
        var strokeWidth = this.options.circleWeight
        var className = this.options.className + "-circle"

        var circle = '<circle class="' + className + '" cx="' + cx + '" cy="' + cy + '" r="' + radius +
            '" fill="' + fill + '" fill-opacity="'+ fillOpacity +
            '" stroke="' + stroke + '" stroke-opacity=' + strokeOpacity + '" stroke-width="' + strokeWidth + '"/>'

        return circle
    },
    _createPathDescription: function() {
        var height = Number(this.options.iconSize.y)
        var width = Number(this.options.iconSize.x)
        var weight = Number(this.options.weight)
        var margin = weight / 2

        var startPoint = "M " + margin + " " + (width/2) + " "
        var leftLine = "L " + (width/2) + " " + (height - weight) + " "
        var rightLine = "L " + (width - margin) + " " + (width/2) + " "
        var arc = "A " + (width/4) + " " + (width/4) + " 0 0 0 " + margin + " " + (width/2) + " Z"

        var d = startPoint + leftLine + rightLine + arc

        return d
    },
    _createPath: function() {
        var pathDescription = this._createPathDescription()
        var strokeWidth = this.options.weight
        var stroke = this.options.color
        var strokeOpacity = this.options.Opacity
        var fill = this.options.fillColor
        var fillOpacity = this.options.fillOpacity
        var className = this.options.className + "-path"

        var path = '<path class="' + className + '" d="' + pathDescription +
            '" stroke-width="' + strokeWidth + '" stroke="' + stroke + '" stroke-opacity="' + strokeOpacity +
            '" fill="' + fill + '" fill-opacity="' + fillOpacity + '"/>'

        return path
    },
    _createSVG: function() {
        var path = this._createPath()
        var circle = this._createCircle()
        var text = this._createText()
        var className = this.options.className + "-svg"

        var style = "width:" + this.options.iconSize.x + "; height:" + this.options.iconSize.y + ";"

        var svg = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" class="' + className + '" style="' + style + '">' + path + circle + text + '</svg>'

        return svg
    },
    _createText: function() {
        var fontSize = this.options.fontSize + "px"
        var lineHeight = Number(this.options.fontSize)

        var x = Number(this.options.iconSize.x) / 2
        var y = x + (lineHeight * 0.35) //35% was found experimentally
        var circleText = this.options.circleText
        var textColor = this.options.fontColor.replace("rgb(", "rgba(").replace(")", "," + this.options.fontOpacity + ")")

        var text = '<text text-anchor="middle" x="' + x + '" y="' + y + '" style="font-size: ' + fontSize + '" fill="' + textColor + '">' + circleText + '</text>'

        return text
    }
})

L.divIcon.svgIcon = function(options) {
    return new L.DivIcon.SVGIcon(options)
}

L.Marker.SVGMarker = L.Marker.extend({
    options: {
        "iconFactory": L.divIcon.svgIcon,
        "iconOptions": {}
    },
    initialize: function(latlng, options) {
        options = L.Util.setOptions(this, options)
        options.icon = options.iconFactory(options.iconOptions)
        this._latlng = latlng
    },
    onAdd: function(map) {
        L.Marker.prototype.onAdd.call(this, map)
    },
    setStyle: function(style) {
        if (this._icon) {
            var svg = this._icon.children[0]
            var iconBody = this._icon.children[0].children[0]
            var iconCircle = this._icon.children[0].children[1]

            if (style.color && !style.iconOptions) {
                var stroke = style.color.replace("rgb","rgba").replace(")", ","+this.options.icon.options.opacity+")")
                var fill = style.color.replace("rgb","rgba").replace(")", ","+this.options.icon.options.fillOpacity+")")
                iconBody.setAttribute("stroke", stroke)
                iconBody.setAttribute("fill", fill)
                iconCircle.setAttribute("stroke", stroke)

                this.options.icon.fillColor = fill
                this.options.icon.color = stroke
                this.options.icon.circleColor = stroke
            }
            if (style.opacity) {
                this.setOpacity(style.opacity)
            }
            if (style.iconOptions) {
                if (style.color) { style.iconOptions.color = style.color }
                iconOptions = L.Util.setOptions(this.options.icon, style.iconOptions)
                this.setIcon(L.divIcon.svgIcon(iconOptions))
            }
        }
    }
})

L.marker.svgMarker = function(latlng, options) {
    return new L.Marker.SVGMarker(latlng, options)
}
<commit_msg>Remove global variable<commit_after>//Leaflet-SVGIcon
//SVG icon for any marker class
//Ilya Atkin
//ilya.atkin@unh.edu

L.DivIcon.SVGIcon = L.DivIcon.extend({
    options: {
        "circleText": "",
        "className": "svg-icon",
        "circleAnchor": null, //defaults to [iconSize.x/2, iconSize.x/2]
        "circleColor": null, //defaults to color
        "circleOpacity": null, // defaults to opacity
        "circleFillColor": "rgb(255,255,255)",
        "circleFillOpacity": null, //default to opacity
        "circleRatio": 0.5,
        "circleWeight": null, //defaults to weight
        "color": "rgb(0,102,255)",
        "fillColor": null, // defaults to color
        "fillOpacity": 0.4,
        "fontColor": "rgb(0, 0, 0)",
        "fontOpacity": "1",
        "fontSize": null, // defaults to iconSize.x/4
        "iconAnchor": null, //defaults to [iconSize.x/2, iconSize.y] (point tip)
        "iconSize": L.point(32,48),
        "opacity": 1,
        "popupAnchor": null,
        "weight": 2
    },
    initialize: function(options) {
        options = L.Util.setOptions(this, options)

        //iconSize needs to be converted to a Point object if it is not passed as one
        options.iconSize = L.point(options.iconSize)

        //in addition to setting option dependant defaults, Point-based options are converted to Point objects
        if (!options.circleAnchor) {
            options.circleAnchor = L.point(Number(options.iconSize.x)/2, Number(options.iconSize.x)/2)
        }
        else {
            options.circleAnchor = L.point(options.circleAnchor)
        }
        if (!options.circleColor) {
            options.circleColor = options.color
        }
        if (!options.circleFillOpacity) {
            options.circleFillOpacity = options.opacity
        }
        if (!options.circleOpacity) {
            options.circleOpacity = options.opacity
        }
        if (!options.circleWeight) {
            options.circleWeight = options.weight
        }
        if (!options.fillColor) {
            options.fillColor = options.color
        }
        if (!options.fontSize) {
            options.fontSize = Number(options.iconSize.x/4)
        }
        if (!options.iconAnchor) {
            options.iconAnchor = L.point(Number(options.iconSize.x)/2, Number(options.iconSize.y))
        }
        else {
            options.iconAnchor = L.point(options.iconAnchor)
        }
        if (!options.popupAnchor) {
            options.popupAnchor = L.point(0, (-0.75)*(options.iconSize.y))
        }
        else {
            options.popupAnchor = L.point(options.popupAnchor)
        }

        var path = this._createPath()
        var circle = this._createCircle()

        options.html = this._createSVG()
    },
    _createCircle: function() {
        var cx = Number(this.options.circleAnchor.x)
        var cy = Number(this.options.circleAnchor.y)
        var radius = this.options.iconSize.x/2 * Number(this.options.circleRatio)
        var fill = this.options.circleFillColor
        var fillOpacity = this.options.circleFillOpacity
        var stroke = this.options.circleColor
        var strokeOpacity = this.options.circleOpacity
        var strokeWidth = this.options.circleWeight
        var className = this.options.className + "-circle"

        var circle = '<circle class="' + className + '" cx="' + cx + '" cy="' + cy + '" r="' + radius +
            '" fill="' + fill + '" fill-opacity="'+ fillOpacity +
            '" stroke="' + stroke + '" stroke-opacity=' + strokeOpacity + '" stroke-width="' + strokeWidth + '"/>'

        return circle
    },
    _createPathDescription: function() {
        var height = Number(this.options.iconSize.y)
        var width = Number(this.options.iconSize.x)
        var weight = Number(this.options.weight)
        var margin = weight / 2

        var startPoint = "M " + margin + " " + (width/2) + " "
        var leftLine = "L " + (width/2) + " " + (height - weight) + " "
        var rightLine = "L " + (width - margin) + " " + (width/2) + " "
        var arc = "A " + (width/4) + " " + (width/4) + " 0 0 0 " + margin + " " + (width/2) + " Z"

        var d = startPoint + leftLine + rightLine + arc

        return d
    },
    _createPath: function() {
        var pathDescription = this._createPathDescription()
        var strokeWidth = this.options.weight
        var stroke = this.options.color
        var strokeOpacity = this.options.Opacity
        var fill = this.options.fillColor
        var fillOpacity = this.options.fillOpacity
        var className = this.options.className + "-path"

        var path = '<path class="' + className + '" d="' + pathDescription +
            '" stroke-width="' + strokeWidth + '" stroke="' + stroke + '" stroke-opacity="' + strokeOpacity +
            '" fill="' + fill + '" fill-opacity="' + fillOpacity + '"/>'

        return path
    },
    _createSVG: function() {
        var path = this._createPath()
        var circle = this._createCircle()
        var text = this._createText()
        var className = this.options.className + "-svg"

        var style = "width:" + this.options.iconSize.x + "; height:" + this.options.iconSize.y + ";"

        var svg = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" class="' + className + '" style="' + style + '">' + path + circle + text + '</svg>'

        return svg
    },
    _createText: function() {
        var fontSize = this.options.fontSize + "px"
        var lineHeight = Number(this.options.fontSize)

        var x = Number(this.options.iconSize.x) / 2
        var y = x + (lineHeight * 0.35) //35% was found experimentally
        var circleText = this.options.circleText
        var textColor = this.options.fontColor.replace("rgb(", "rgba(").replace(")", "," + this.options.fontOpacity + ")")

        var text = '<text text-anchor="middle" x="' + x + '" y="' + y + '" style="font-size: ' + fontSize + '" fill="' + textColor + '">' + circleText + '</text>'

        return text
    }
})

L.divIcon.svgIcon = function(options) {
    return new L.DivIcon.SVGIcon(options)
}

L.Marker.SVGMarker = L.Marker.extend({
    options: {
        "iconFactory": L.divIcon.svgIcon,
        "iconOptions": {}
    },
    initialize: function(latlng, options) {
        options = L.Util.setOptions(this, options)
        options.icon = options.iconFactory(options.iconOptions)
        this._latlng = latlng
    },
    onAdd: function(map) {
        L.Marker.prototype.onAdd.call(this, map)
    },
    setStyle: function(style) {
        if (this._icon) {
            var svg = this._icon.children[0]
            var iconBody = this._icon.children[0].children[0]
            var iconCircle = this._icon.children[0].children[1]

            if (style.color && !style.iconOptions) {
                var stroke = style.color.replace("rgb","rgba").replace(")", ","+this.options.icon.options.opacity+")")
                var fill = style.color.replace("rgb","rgba").replace(")", ","+this.options.icon.options.fillOpacity+")")
                iconBody.setAttribute("stroke", stroke)
                iconBody.setAttribute("fill", fill)
                iconCircle.setAttribute("stroke", stroke)

                this.options.icon.fillColor = fill
                this.options.icon.color = stroke
                this.options.icon.circleColor = stroke
            }
            if (style.opacity) {
                this.setOpacity(style.opacity)
            }
            if (style.iconOptions) {
                if (style.color) { style.iconOptions.color = style.color }
                var iconOptions = L.Util.setOptions(this.options.icon, style.iconOptions)
                this.setIcon(L.divIcon.svgIcon(iconOptions))
            }
        }
    }
})

L.marker.svgMarker = function(latlng, options) {
    return new L.Marker.SVGMarker(latlng, options)
}
<|endoftext|>


<commit_before>"use strict";
//
// A PhantomJS script used to check that the hosted examples load
// without errors. This script is executed by the Makefile's
// check-examples target.

var args = require('system').args;
if (args.length != 2) {
  phantom.exit(1);
}
var examplePath = args[1];
var page = require('webpage').create();
var exitCode = 0;
page.onError = function(msg, trace) {
  var msgStack = ['JavaScript ERROR: ' + msg];
  if (trace) {
    msgStack.push('TRACE:');
    trace.forEach(function(t) {
      msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
    });
  }
  console.error(msgStack.join('\n'));
  exitCode = 2;
};
page.onConsoleMessage = function(msg, lineNum, sourceId) {
  console.log('console: ' + msg + ' (from line #' + lineNum + ' in "' + sourceId + '")');
  exitCode = 2;
};
page.onAlert = function(msg) {
  console.log('alert: ' + msg);
  exitCode = 2;
};
page.onResourceError = function(resourceError) {
  console.log('Resource error: ' + resourceError.errorCode + ', ' + resourceError.url);
  exitCode = 2;
};
page.onUrlChanged = function(url) {
  console.log('URL changed: ' + url);
};
page.open(examplePath, function(s) {
  if (s != 'success') {
    console.error('PAGE LOAD ERROR');
    phantom.exit(2);
  }

  setTimeout(function() {
//    page.render(examplePath + '.png')
    var consoleControl = require('console-control-strings');

    var color = exitCode == 0 ? 'green' : 'red';
    console.log(
      consoleControl.color([color, "bold"]) +
      "EXIT with " + exitCode +
      consoleControl.color('reset')
    );
    phantom.exit(exitCode);
  }, 3000)
});
<commit_msg>Ignore google referer error<commit_after>"use strict";
//
// A PhantomJS script used to check that the hosted examples load
// without errors. This script is executed by the Makefile's
// check-examples target.

var args = require('system').args;
if (args.length != 2) {
  phantom.exit(1);
}
var examplePath = args[1];
var page = require('webpage').create();
var exitCode = 0;
page.onError = function(msg, trace) {
  var msgStack = ['JavaScript ERROR: ' + msg];
  if (trace) {
    msgStack.push('TRACE:');
    trace.forEach(function(t) {
      if (t.file.startsWith('https://maps.googleapis.com/maps/api/js')) {
        // Ignore google referer error
        return;
      }
      msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
    });
  }
  console.error(msgStack.join('\n'));
  exitCode = 2;
};
page.onConsoleMessage = function(msg, lineNum, sourceId) {
  console.log('console: ' + msg + ' (from line #' + lineNum + ' in "' + sourceId + '")');
  exitCode = 2;
};
page.onAlert = function(msg) {
  console.log('alert: ' + msg);
  exitCode = 2;
};
page.onResourceError = function(resourceError) {
  console.log('Resource error: ' + resourceError.errorCode + ', ' + resourceError.url);
  exitCode = 2;
};
page.onUrlChanged = function(url) {
  console.log('URL changed: ' + url);
};
page.open(examplePath, function(s) {
  if (s != 'success') {
    console.error('PAGE LOAD ERROR');
    phantom.exit(2);
  }

  setTimeout(function() {
//    page.render(examplePath + '.png')
    var consoleControl = require('console-control-strings');

    var color = exitCode == 0 ? 'green' : 'red';
    console.log(
      consoleControl.color([color, "bold"]) +
      "EXIT with " + exitCode +
      consoleControl.color('reset')
    );
    phantom.exit(exitCode);
  }, 3000)
});
<|endoftext|>


<commit_before>{
  /* global angular */
  angular
    .module(APP_NAME)
    .directive('passwordMatch', passwordMatch);

  passwordMatch.$inject = [];

  function passwordMatch() {
    var directive = {
      restrict: 'A',
      scope: true,
      require: 'ngModel',
      link: linkFn
    }

    return directive;

    function linkFn(scope, elem, attrs, control) {
      var checker = function() {

        //get the value of the first password
        var e1 = scope.$eval(attrs.ngModel);

        //get the value of the other password
        var e2 = scope.$eval(attrs.passwordMatch);
        return e1 && e2 && e1 === e2 && e1.length >= e2.length;
      };
      scope.$watch(checker, function(n) {

        //set the form control to valid if both
        //passwords are the same, else invalid
        control.$setValidity('passwordMatch', n);
      });
    }

  }

}
<commit_msg>feature/RHP_102-set-form-validity-properly-when-using-password-match<commit_after>{
  /* global angular */
  angular
    .module(APP_NAME)
    .directive('passwordMatch', passwordMatch);

  passwordMatch.$inject = [];

  function passwordMatch() {
    var directive = {
      restrict: 'A',
      scope: true,
      require: 'ngModel',
      link: linkFn
    }

    return directive;

    function linkFn(scope, elem, attrs, control) {
      var checker = function() {

        //get the value of the first password
        var e1 = scope.$eval(attrs.ngModel);

        //get the value of the other password
        var e2 = scope.$eval(attrs.passwordMatch);
        return e1 && e2 && e1 === e2 && e1.length >= e2.length;
      };
      scope.$watch(checker, function(n) {

        //set the form control to valid if both
        //passwords are the same, else invalid
        control.$setValidity('passwordMatch', n || false);
      });
    }

  }

}
<|endoftext|>


<commit_before>/**
 * 简单的复选面板, 适用于数据量少的情况， 与valuechooser的区别是allvaluechooser setValue和getValue返回的是所有值
 * 封装了字段处理逻辑
 *
 * Created by GUY on 2015/10/29.
 * @class BI.AllValueChooserPane
 * @extends BI.AbstractAllValueChooser
 */
BI.AllValueChooserPane = BI.inherit(BI.AbstractAllValueChooser, {

    _defaultConfig: function () {
        return BI.extend(BI.AllValueChooserPane.superclass._defaultConfig.apply(this, arguments), {
            baseCls: "bi-all-value-chooser-pane",
            width: 200,
            height: 30,
            items: null,
            itemsCreator: BI.emptyFn,
            cache: true
        });
    },

    _init: function () {
        BI.AllValueChooserPane.superclass._init.apply(this, arguments);
        var self = this, o = this.options;
        if (BI.isNotNull(o.items)) {
            this.items = o.items;
        }
        this.list = BI.createWidget({
            type: "bi.multi_select_list",
            element: this,
            itemsCreator: BI.bind(this._itemsCreator, this),
            valueFormatter: BI.bind(this._valueFormatter, this),
            width: o.width,
            height: o.height
        });

        this.list.on(BI.MultiSelectList.EVENT_CHANGE, function () {
            self.fireEvent(BI.AllValueChooserPane.EVENT_CHANGE);
        });
    },

    setValue: function (v) {
        this.list.setValue({
            type: BI.Selection.Multi,
            value: v || []
        });
    },

    getValue: function () {
        var val = this.list.getValue() || {};
        if (val.type === BI.Selection.All) {
            return val.assist;
        }
        return val.value || [];
    },

    populate: function (items) {
        // 直接用combo的populate不会作用到AbstractValueChooser上
        this.items = items;
        this.list.populate();
    }
});
BI.AllValueChooserPane.EVENT_CHANGE = "EVENT_CHANGE";
BI.shortcut("bi.all_value_chooser_pane", BI.AllValueChooserPane);
<commit_msg>revert<commit_after>/**
 * 简单的复选面板, 适用于数据量少的情况， 与valuechooser的区别是allvaluechooser setValue和getValue返回的是所有值
 * 封装了字段处理逻辑
 *
 * Created by GUY on 2015/10/29.
 * @class BI.AllValueChooserPane
 * @extends BI.AbstractAllValueChooser
 */
BI.AllValueChooserPane = BI.inherit(BI.AbstractAllValueChooser, {

    _defaultConfig: function () {
        return BI.extend(BI.AllValueChooserPane.superclass._defaultConfig.apply(this, arguments), {
            baseCls: "bi-all-value-chooser-pane",
            width: 200,
            height: 30,
            items: null,
            itemsCreator: BI.emptyFn,
            cache: true
        });
    },

    _init: function () {
        BI.AllValueChooserPane.superclass._init.apply(this, arguments);
        var self = this, o = this.options;
        this.list = BI.createWidget({
            type: "bi.multi_select_list",
            element: this,
            itemsCreator: BI.bind(this._itemsCreator, this),
            valueFormatter: BI.bind(this._valueFormatter, this),
            width: o.width,
            height: o.height
        });

        this.list.on(BI.MultiSelectList.EVENT_CHANGE, function () {
            self.fireEvent(BI.AllValueChooserPane.EVENT_CHANGE);
        });

        if (BI.isNotNull(o.items)) {
            this.items = o.items;
            this.list.populate();
        }
    },

    setValue: function (v) {
        this.list.setValue({
            type: BI.Selection.Multi,
            value: v || []
        });
    },

    getValue: function () {
        var val = this.list.getValue() || {};
        if (val.type === BI.Selection.All) {
            return val.assist;
        }
        return val.value || [];
    },

    populate: function (items) {
        // 直接用combo的populate不会作用到AbstractValueChooser上
        this.items = items;
        this.list.populate();
    }
});
BI.AllValueChooserPane.EVENT_CHANGE = "EVENT_CHANGE";
BI.shortcut("bi.all_value_chooser_pane", BI.AllValueChooserPane);
<|endoftext|>


<commit_before>"use strict";

var _ = require("lodash");
var bluebird= require("bluebird");
var db= {};
module.exports = function(){
	var mongoose = require("mongoose");
	mongoose.Promise = bluebird;
	var util= require("util");
	var options = {
		db: { native_parser: true },
		server: { poolSize: 20, keepAlive: 1 }
	};

	var connString= util.format("mongodb://%s:%s@%s/%s?authSource=%s",
		config.mongo.user,
		config.mongo.pass,
		config.mongo.host,
		config.mongo.database,
		config.mongo.user
	);

	connString= util.format("mongodb://localhost/message");

	mongoose.connect(connString);

	var fs= require("fs");
	var path= require("path");
	var normalizedPath = path.join(__dirname, "");

	fs
	.readdirSync(normalizedPath)
	.forEach(function(file) {
		if (file == "index.js" || path.extname(file)!=".js") return;

		var model= require("./"+file);
		db= _.merge(db, model);
	});

	return db;
};<commit_msg>test ci<commit_after>"use strict";

var _ = require("lodash");
var bluebird= require("bluebird");
var db= {};
module.exports = function(){
	var mongoose = require("mongoose");
	mongoose.Promise = bluebird;
	var util= require("util");
	var options = {
		db: { native_parser: true },
		server: { poolSize: 20, keepAlive: 1 }
	};

	var connString= util.format("mongodb://%s:%s@%s/%s?authSource=%s",
		config.mongo.user,
		config.mongo.pass,
		config.mongo.host,
		config.mongo.database,
		config.mongo.user
	);

	connString= util.format("mongodb://localhost/message");

	mongoose.connect(connString );

	var fs= require("fs");
	var path= require("path");
	var normalizedPath = path.join(__dirname, "");

	fs
	.readdirSync(normalizedPath)
	.forEach(function(file) {
		if (file == "index.js" || path.extname(file)!=".js") return;

		var model= require("./"+file);
		db= _.merge(db, model);
	});

	return db;
};<|endoftext|>


<commit_before>var child_process = require('child_process'),
    fs = require('fs'),
    glob = require('glob'),
    growl = require('growl'),
    path = require('path'),
    util = require('util'),
    wrench = require('wrench');

// Recursive mkdir
// mkdirsSync(path, [mode=(0777^umask)]) -> pathsCreated
function mkdir(dirname, mode) {
  if (mode === undefined) {
    mode = 0777 ^ process.umask();
  }
  var pathsNotFound = [];
  var fn = dirname;
  while (true) {
    try {
      var stats = fs.statSync(fn);
      if (stats.isDirectory()) {
        break;
      }
      throw new Error('Unable to create directory at ' + fn);
    }
    catch (e) {
      pathsNotFound.push(fn);
      fn = path.dirname(fn);
    }
  }
  for (var i = pathsNotFound.length - 1; i > -1; i--) {
    var fn = pathsNotFound[i];
    console.log('mkdir:\t\033[90mmaking directory\033[0m ' + fn);
    fs.mkdirSync(fn, mode);
  }
}

function streamData(prefix, data) {
  var lines = data.toString().split(/\r\n|\n|\r/g);
  for (var i = 0, len = lines.length - 1; i < len; i++) {
    util.print(prefix);
    util.print(lines[i]);
    util.print('\n');
  }
  if (lines[lines.length - 1]) {
    util.print(prefix);
    util.print(lines[lines.length - 1]);
  }
}

exports.build = function(options) {
  var complete = options.complete;

  mkdir(options.dir);

  var args = [
    __dirname + '/node_modules/lumbar/bin/lumbar',
    options.watch ? 'watch' : 'build',
    '--config', options.configFile || './config/dev.json',
    '--use', __dirname + '/node_modules/lumbar-long-expires',
    '--use', __dirname + '/node_modules/lumbar-tester',
    '--with', '{"includeTests": ' + !options.removeTests + '}',
    '--use', __dirname + '/node_modules/lumbar-style-doc',
    '--with', '{"removeDocs": ' + !!options.removeTests + '}',
    '--use', 'conditional',
    '--with', '{"env": "' + (options.minimize ? 'production' : 'dev') + '"}',
    './lumbar.json',
    (options.dir || '.')
  ];
  if (options.package) {
    args.push('--package');
    args.push(options.package);
  }
  if (options.minimize) {
    args.push('--minimize');
  }

  var lumbar = child_process.spawn('node', args);
  lumbar.stdout.on('data', function (data) {
    streamData('lumbar: ', data);
  });
  lumbar.stderr.on('data', function (data) {
    streamData('lumbar err: ', data);
  });

  lumbar.on('exit', function(code) {
    if (!complete) {
      growl('Lumbar Borked', { title: 'Lumbar Borked', sticky: true });
    } else {
      complete(code);
    }
  });
  return lumbar;
};

exports.startServer = function(options) {
  var test = !!options.test,
      onData = options.data,
      complete = options.complete;

  if (options.mocks) {
    process.env.ENABLE_MOCKS = options.mocks;
  }
  var args = [
    __dirname + '/node_modules/mock-server/bin/mock-server',
    exports.projectDir,
    '--proxy-server=' + options.proxy,
    '--port=' + (test ? 58080 : 8080),
    '--secure-port=' + (test ? 58081 : 8081)
  ];
  if (exports.forceCORS) {
    args.push('--force-cors');
  }

  var server = child_process.spawn('node', args, {
    env: process.env
  });
  server.stdout.on('data', function (data) {
    if (onData) {
      onData(data);
    }

    // Do not output module, etc requests if in test mode
    if (!test || !/GET \/r\/phoenix/.test(data)) {
      streamData((test ? '  ' : '') + 'server: ', data);
    }
  });
  server.stderr.on('data', function (data) {
    if (onData) {
      onData(data);
    }
    streamData((test ? '  ' : '') + 'server: ', data);
  });

  if (!test) {
    server.on('exit', function(code) {
      growl('Server Borked', { title: 'Server Borked', sticky: true });

      if (complete) {
        complete(code);
      }
    });
  }

  // If we die we're taking the server with us (to prevent ports from hanging around)
  process.on('exit', function() {
    if (server) {
      server.kill();
    }
  });

  return server;
};

exports.watch = function(server, mocks) {
  glob.sync('build/dev').forEach(wrench.rmdirSyncRecursive);

  var run;
  exports.startServer({
    proxy: server,
    mocks: mocks,
    data: function() {
      if (run) {
        return;
      }
      run = true;

      exports.build({
        dir: 'build/dev',
        watch: true,
        complete: function(code) {
          process.exit(code);
        }
      });
    },
    complete: function(code) {
      process.exit(code);
    }
  });
};

desc('The default task. Executes init');
task('default', ['lumbar'], function() {});

desc('Process all lumbar modules.');
task('lumbar', [], function() {
  exports.build({
    dir: 'build/dev',
    complete: complete
  });
}, true);

desc('Builds production packages');
task('release', [], function(prefix, pkg) {
  prefix = prefix || 'phoenix';

  exports.build({
    dir: 'build/' + prefix,
    package: pkg,
    minimize: true,
    removeTests: true,
    configFile: './config/production.json',
    complete: function(code) {
      if (code) {
        process.exit(code);
      } else {
        complete();
      }
    }
  });
});

desc('Cleans any generated content out of the application');
task('clean', [], function() {
  glob.sync('build').forEach(wrench.rmdirSyncRecursive);
});

desc('Builds the app in production test mode.');
task('heroku-test', [], function() {
  exports.build({
    dir: 'build/test',
    minimize: true,
    configFile: './config/production.json',
    complete: complete
  });
}, true);

desc('Initializes the file change watcher for stylus scripts');
task('watch', [], function(server, mocks) {
  exports.watch(exports.serverName.apply(exports, arguments), mocks);
});

desc('Starts up the server in normal mode');
task('start', [], function(server, mocks) {
  exports.startServer({proxy: exports.serverName.apply(exports, arguments), mocks: mocks});
});

desc('Testing');
task('test-runner', [], function(webOnly, xunit) {
  var superCode = 0;

  function runPhantom(platform, androidUserAgent, xunit, callback) {
    console.log('Running platform: ' + platform + ' androidUserAgent: ' + (!!androidUserAgent));
    var userAgent = androidUserAgent ?
            'Mozilla/5.0 (Linux; U; Android 2.3.6; en-us; Nexus S Build/GRK39F) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1'
            : 'Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3',
        phantom;
    if (exports.mochaTests) {
      var args = ['-A', userAgent, 'http://localhost:58080/r/phoenix/' + platform + '/test.html'];
      if (xunit) {
        args.push('-R', 'xunit');
      }
      phantom = child_process.spawn(__dirname + '/node_modules/.bin/mocha-phantomjs', args);
    } else {
      phantom = child_process.spawn('phantomjs', [__dirname + '/test/run-qunit.js', 'http://localhost:58080/r/phoenix/' + platform + '/test.html', userAgent]);
    }

    var buffer = '';
    phantom.stdout.on('data', function (data) {
      if (exports.mochaTests && xunit) {
        buffer += data;
      } else {
        streamData('  phantom: ', data);
      }
    });
    phantom.stderr.on('data', function (data) {
      streamData('  phantom err: ', data);
    });
    phantom.on('exit', function(code) {
      superCode = superCode | code;
      callback(code, buffer);
    });
  }

  var run;
  exports.startServer({
    proxy: exports.serverName.call(exports),
    mocks: true,
    test: true,
    data: function() {
      if (run) {
        return;
      }
      run = true;

      (function exec() {
        var platform = exports.testPlatforms.shift();
        if (webOnly && !platform.webOnly) {
          process.exit(superCode);
          return;
        }

        runPhantom(platform.platform, platform.androidUA, xunit, function(code, buffer) {
          if (exports.mochaTests && xunit) {
            fs.writeFile('build/' + platform.platform + (platform.androidUA ? '_android' : '') + '.xml', buffer);
          }

          if (!exports.testPlatforms.length) {
            process.exit(superCode);
          } else {
            exec();
          }
        });
      })();
    }
  });
});

desc('Testing');
task('test', ['lumbar', 'test-runner'], function() {});

task('test-xunit', ['lumbar'], function() {
  jake.Task['test-runner'].invoke(undefined, true);
});
<commit_msg>Force sync file output<commit_after>var child_process = require('child_process'),
    fs = require('fs'),
    glob = require('glob'),
    growl = require('growl'),
    path = require('path'),
    util = require('util'),
    wrench = require('wrench');

// Recursive mkdir
// mkdirsSync(path, [mode=(0777^umask)]) -> pathsCreated
function mkdir(dirname, mode) {
  if (mode === undefined) {
    mode = 0777 ^ process.umask();
  }
  var pathsNotFound = [];
  var fn = dirname;
  while (true) {
    try {
      var stats = fs.statSync(fn);
      if (stats.isDirectory()) {
        break;
      }
      throw new Error('Unable to create directory at ' + fn);
    }
    catch (e) {
      pathsNotFound.push(fn);
      fn = path.dirname(fn);
    }
  }
  for (var i = pathsNotFound.length - 1; i > -1; i--) {
    var fn = pathsNotFound[i];
    console.log('mkdir:\t\033[90mmaking directory\033[0m ' + fn);
    fs.mkdirSync(fn, mode);
  }
}

function streamData(prefix, data) {
  var lines = data.toString().split(/\r\n|\n|\r/g);
  for (var i = 0, len = lines.length - 1; i < len; i++) {
    util.print(prefix);
    util.print(lines[i]);
    util.print('\n');
  }
  if (lines[lines.length - 1]) {
    util.print(prefix);
    util.print(lines[lines.length - 1]);
  }
}

exports.build = function(options) {
  var complete = options.complete;

  mkdir(options.dir);

  var args = [
    __dirname + '/node_modules/lumbar/bin/lumbar',
    options.watch ? 'watch' : 'build',
    '--config', options.configFile || './config/dev.json',
    '--use', __dirname + '/node_modules/lumbar-long-expires',
    '--use', __dirname + '/node_modules/lumbar-tester',
    '--with', '{"includeTests": ' + !options.removeTests + '}',
    '--use', __dirname + '/node_modules/lumbar-style-doc',
    '--with', '{"removeDocs": ' + !!options.removeTests + '}',
    '--use', 'conditional',
    '--with', '{"env": "' + (options.minimize ? 'production' : 'dev') + '"}',
    './lumbar.json',
    (options.dir || '.')
  ];
  if (options.package) {
    args.push('--package');
    args.push(options.package);
  }
  if (options.minimize) {
    args.push('--minimize');
  }

  var lumbar = child_process.spawn('node', args);
  lumbar.stdout.on('data', function (data) {
    streamData('lumbar: ', data);
  });
  lumbar.stderr.on('data', function (data) {
    streamData('lumbar err: ', data);
  });

  lumbar.on('exit', function(code) {
    if (!complete) {
      growl('Lumbar Borked', { title: 'Lumbar Borked', sticky: true });
    } else {
      complete(code);
    }
  });
  return lumbar;
};

exports.startServer = function(options) {
  var test = !!options.test,
      onData = options.data,
      complete = options.complete;

  if (options.mocks) {
    process.env.ENABLE_MOCKS = options.mocks;
  }
  var args = [
    __dirname + '/node_modules/mock-server/bin/mock-server',
    exports.projectDir,
    '--proxy-server=' + options.proxy,
    '--port=' + (test ? 58080 : 8080),
    '--secure-port=' + (test ? 58081 : 8081)
  ];
  if (exports.forceCORS) {
    args.push('--force-cors');
  }

  var server = child_process.spawn('node', args, {
    env: process.env
  });
  server.stdout.on('data', function (data) {
    if (onData) {
      onData(data);
    }

    // Do not output module, etc requests if in test mode
    if (!test || !/GET \/r\/phoenix/.test(data)) {
      streamData((test ? '  ' : '') + 'server: ', data);
    }
  });
  server.stderr.on('data', function (data) {
    if (onData) {
      onData(data);
    }
    streamData((test ? '  ' : '') + 'server: ', data);
  });

  if (!test) {
    server.on('exit', function(code) {
      growl('Server Borked', { title: 'Server Borked', sticky: true });

      if (complete) {
        complete(code);
      }
    });
  }

  // If we die we're taking the server with us (to prevent ports from hanging around)
  process.on('exit', function() {
    if (server) {
      server.kill();
    }
  });

  return server;
};

exports.watch = function(server, mocks) {
  glob.sync('build/dev').forEach(wrench.rmdirSyncRecursive);

  var run;
  exports.startServer({
    proxy: server,
    mocks: mocks,
    data: function() {
      if (run) {
        return;
      }
      run = true;

      exports.build({
        dir: 'build/dev',
        watch: true,
        complete: function(code) {
          process.exit(code);
        }
      });
    },
    complete: function(code) {
      process.exit(code);
    }
  });
};

desc('The default task. Executes init');
task('default', ['lumbar'], function() {});

desc('Process all lumbar modules.');
task('lumbar', [], function() {
  exports.build({
    dir: 'build/dev',
    complete: complete
  });
}, true);

desc('Builds production packages');
task('release', [], function(prefix, pkg) {
  prefix = prefix || 'phoenix';

  exports.build({
    dir: 'build/' + prefix,
    package: pkg,
    minimize: true,
    removeTests: true,
    configFile: './config/production.json',
    complete: function(code) {
      if (code) {
        process.exit(code);
      } else {
        complete();
      }
    }
  });
});

desc('Cleans any generated content out of the application');
task('clean', [], function() {
  glob.sync('build').forEach(wrench.rmdirSyncRecursive);
});

desc('Builds the app in production test mode.');
task('heroku-test', [], function() {
  exports.build({
    dir: 'build/test',
    minimize: true,
    configFile: './config/production.json',
    complete: complete
  });
}, true);

desc('Initializes the file change watcher for stylus scripts');
task('watch', [], function(server, mocks) {
  exports.watch(exports.serverName.apply(exports, arguments), mocks);
});

desc('Starts up the server in normal mode');
task('start', [], function(server, mocks) {
  exports.startServer({proxy: exports.serverName.apply(exports, arguments), mocks: mocks});
});

desc('Testing');
task('test-runner', [], function(webOnly, xunit) {
  var superCode = 0;

  function runPhantom(platform, androidUserAgent, xunit, callback) {
    console.log('Running platform: ' + platform + ' androidUserAgent: ' + (!!androidUserAgent));
    var userAgent = androidUserAgent ?
            'Mozilla/5.0 (Linux; U; Android 2.3.6; en-us; Nexus S Build/GRK39F) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1'
            : 'Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3',
        phantom;
    if (exports.mochaTests) {
      var args = ['-A', userAgent, 'http://localhost:58080/r/phoenix/' + platform + '/test.html'];
      if (xunit) {
        args.push('-R', 'xunit');
      }
      phantom = child_process.spawn(__dirname + '/node_modules/.bin/mocha-phantomjs', args);
    } else {
      phantom = child_process.spawn('phantomjs', [__dirname + '/test/run-qunit.js', 'http://localhost:58080/r/phoenix/' + platform + '/test.html', userAgent]);
    }

    var buffer = '';
    phantom.stdout.on('data', function (data) {
      if (exports.mochaTests && xunit) {
        buffer += data;
      } else {
        streamData('  phantom: ', data);
      }
    });
    phantom.stderr.on('data', function (data) {
      streamData('  phantom err: ', data);
    });
    phantom.on('exit', function(code) {
      superCode = superCode | code;
      callback(code, buffer);
    });
  }

  var run;
  exports.startServer({
    proxy: exports.serverName.call(exports),
    mocks: true,
    test: true,
    data: function() {
      if (run) {
        return;
      }
      run = true;

      (function exec() {
        var platform = exports.testPlatforms.shift();
        if (webOnly && !platform.webOnly) {
          process.exit(superCode);
          return;
        }

        runPhantom(platform.platform, platform.androidUA, xunit, function(code, buffer) {
          if (exports.mochaTests && xunit) {
            fs.writeFileSync('build/' + platform.platform + (platform.androidUA ? '_android' : '') + '.xml', buffer);
          }

          if (!exports.testPlatforms.length) {
            process.exit(superCode);
          } else {
            exec();
          }
        });
      })();
    }
  });
});

desc('Testing');
task('test', ['lumbar', 'test-runner'], function() {});

task('test-xunit', ['lumbar'], function() {
  jake.Task['test-runner'].invoke(undefined, true);
});
<|endoftext|>


<commit_before>var util = require('util'),
    _ = require('underscore'),
    moment = require('moment');

var SessionForm = require('./form'),
    CostModel = require('../models/costs');

var ConfirmForm = function (options) {
    SessionForm.call(this, options);
};

util.inherits(ConfirmForm, SessionForm);

function join(obj, keys, separator) {
    separator = separator || ' ';
    return _.chain(obj).pick(keys).filter(_.identity).value().join(separator);
}

function currency(cost) {
    cost = cost % 1 ? cost.toFixed(2) : cost;
    return '£' + cost;
}

// find the path for the step containing a given field
ConfirmForm.prototype.getEditStep = function (field) {
    var step = _.find(Object.keys(this.options.steps), function (path) {
        var s = this.options.steps[path];
        return s.fields && s.fields.indexOf(field) > -1;
    }, this);
    if (step == '/address') {
        step +='-manual';
    }
    return step && (step + '/edit');
};

ConfirmForm.prototype.getValues = function (req, res, callback) {
    SessionForm.prototype.getValues.call(this, req, res, function (err, values) {
        if (err) {
            callback(err);
        } else {
            this.createBreakdown(req, values, callback);
        }
    }.bind(this));
};

ConfirmForm.prototype.createBreakdown = function (req, values, callback) {
    var model = new CostModel();
    model.set(values);
    var response = _.extend({}, values, { sections: [] });

    response.sections.push({
        className: 'old-passport-details',
        title: 'Old passport',
        fields: [
            {
                step: this.getEditStep('passport-number'),
                title: 'Passport number',
                value: values['passport-number']
            },
            {
                step: this.getEditStep('expiry-year'),
                title: 'Expiry date',
                value: moment(values['expiry-year'] + '-' + values['expiry-month'] + '-01', 'YYYY-MM-DD').format('MMMM YYYY')
            }
        ]
    });

    var newPassportFields = [];
    newPassportFields.push(
        {
            step: this.getEditStep('title'),
            title: 'Title',
              value: values['title']
          //  value: values['title'] === 'Other' ? values['other-title'] : values['title']
        },
        {
            step: this.getEditStep('name'),
            title: 'Name',
            value: join(values, ['name', 'lastname'])
        },
        {
            step: this.getEditStep('previous-names'),
            title: 'Previous names',
            value: values['previous-name'] ? values['previous-names'] : 'You have never been known by any other names'
        },
        {
            step: this.getEditStep('gender'),
            title: 'Gender',
            value: values['gender'] === 'M' ? 'Male' : values['gender'] === 'F' ? 'Female' : ''
        },
        {
            step: this.getEditStep('age-year'),
            title: 'Date of birth',
            value: moment(values['age-year'] + '-' + values['age-month'] + '-' + values['age-day'], 'YYYY-MM-DD').format('D MMMM YYYY')
        },
        {
            step: this.getEditStep('town-of-birth'),
            title: 'Town of birth',
            value: values['town-of-birth']
        }

    );

    if(values['country-of-birth']){
      newPassportFields.push(
        {
          step: this.getEditStep('country-of-birth'),
          title: 'Country of birth',
          value: values['country-of-birth']
      }
      );
    }

    if (values['can-sign']) {
        newPassportFields.push(
            {
                step: this.getEditStep('can-sign'),
                title: 'Signature',
                value: 'You'll sign your passport when you receive it.'
            }
        );
    } else {
        newPassportFields.push(
            {
                step: this.getEditStep('no-sign-reason'),
                title: 'Signature',
                value: values['no-sign-reason'] ? 'You can’t sign your passport:
' + values['no-sign-reason'] : 'You can’t sign your passport'
            }
        );
    }

    newPassportFields.push(
        {
            step: this.getEditStep('passport-details-correct'),
            title: 'Personal details',
            value: 'Your personal details haven’t changed'
        },
        {
            title: 'Your photo',
            custom: '

'
        },
        {
            step: this.getEditStep('recognisable'),
            title: 'Your appearance',
            value: 'You can be recognised as the same person'
        }
    );

    response.sections.push({
        className: 'new-passport-details',
        title: 'New passport',
        fields: newPassportFields
    });

    response.sections.push({
        className: 'application-details',
        title: 'Application',
        fields: [
            {
                step: this.getEditStep('postcode'),
                title: 'Address',
                /*value: join(values, ['address1', 'address2', 'town', 'postcode'], '
')*/
                value: function(){
                  var country = req.sessionModel.get('application-country');
                  var output = join(values, ['address1', 'address2','town', 'postcode'], '
');
                  if (country == 'FR'){ output += '
France';}
                  else if (country == 'DE'){ output += '
Germany';}
                  else if (country == 'IL'){ output += '
Israel';}
                  else if (country == 'BE'){ output += '
Belgium';}
                  else if (country == 'NL'){ output += '
Netherlands';}
                  else if (country == 'ES'){ output += '
Spain';}
                /*  output += country;*/
                  return output;
                }
            },
            {
                step: this.getEditStep('email'),
                title: 'Contact details',
                /*value: join(values, ['email','country-code', 'mobile'], '

')*/
                value: function() {
                  var output = join(values, ['email'], '

');
                  output += '

';
                  output += join(values, ['application-country-code', 'mobile']);
                  return output;
                }
            },
            {
                step: this.getEditStep('braille'),
                title: 'Braille',
                value: function () {
                    var output = [];
                    output.push(values['braille'] ? 'You require a braille sticker' : 'You don’t require a braille sticker');
                    return output.join('

');
                }
            }
        ]
    });
//appointment details
response.sections.push({
    className: 'appointment-details',
    title: 'Appointment',
    fields: [
        {
            step: this.getEditStep('postcode'),
            title: 'Date and time',
            value: function() {
              var output = [];
              output.push('Saturday, 11 February 2017
1:30pm');
              return output;
            }
        },
        {
            step: this.getEditStep('postcode'),
            title: 'Passport office',
            value: function() {
              var output = [];
              output.push('London
Globe House
89 Eccleston Square
London
SW1V 1PN');
              return output;
            }
        }
    ]
});

//end of appointment

    response.sections.push({
        className: 'cost-details',
        title: 'Cost',
        fields: [
            {
                step: this.getEditStep('braille'),
                title: 'New passport',
                value: function () {
                    var output = [];
                    if (values['passport-options-dps'] == '48') {
                        var cost = model.largePassport();
                        cost = currency(cost);
                        if (!values.veteran) {
                            cost += ' extra';
                        }

                        output.push('Jumbo passport ');
                        output.push('£137');
                    } else {
                        output.push('Standard passport');
                        output.push('£128');
                    }
                    return output.join('
');
                }
            },
            {
                step: values.veteran ? null : this.getEditStep('secure-return'),
                title: values.veteran ? 'Delivery' : 'Old passport',
                value: function () {
                        var output = 'You need to bring your old passport to the appointment.';
                        return output;
                }
            },
            {
                className: 'cost',
                title: 'Total',
                value: function () {
                    return currency(values.cost);
                }
            }
        ]
    });
    callback(null, response);
};

module.exports = ConfirmForm;
<commit_msg>Correct time and date for testing scenario<commit_after>var util = require('util'),
    _ = require('underscore'),
    moment = require('moment');

var SessionForm = require('./form'),
    CostModel = require('../models/costs');

var ConfirmForm = function (options) {
    SessionForm.call(this, options);
};

util.inherits(ConfirmForm, SessionForm);

function join(obj, keys, separator) {
    separator = separator || ' ';
    return _.chain(obj).pick(keys).filter(_.identity).value().join(separator);
}

function currency(cost) {
    cost = cost % 1 ? cost.toFixed(2) : cost;
    return '£' + cost;
}

// find the path for the step containing a given field
ConfirmForm.prototype.getEditStep = function (field) {
    var step = _.find(Object.keys(this.options.steps), function (path) {
        var s = this.options.steps[path];
        return s.fields && s.fields.indexOf(field) > -1;
    }, this);
    if (step == '/address') {
        step +='-manual';
    }
    return step && (step + '/edit');
};

ConfirmForm.prototype.getValues = function (req, res, callback) {
    SessionForm.prototype.getValues.call(this, req, res, function (err, values) {
        if (err) {
            callback(err);
        } else {
            this.createBreakdown(req, values, callback);
        }
    }.bind(this));
};

ConfirmForm.prototype.createBreakdown = function (req, values, callback) {
    var model = new CostModel();
    model.set(values);
    var response = _.extend({}, values, { sections: [] });

    response.sections.push({
        className: 'old-passport-details',
        title: 'Old passport',
        fields: [
            {
                step: this.getEditStep('passport-number'),
                title: 'Passport number',
                value: values['passport-number']
            },
            {
                step: this.getEditStep('expiry-year'),
                title: 'Expiry date',
                value: moment(values['expiry-year'] + '-' + values['expiry-month'] + '-01', 'YYYY-MM-DD').format('MMMM YYYY')
            }
        ]
    });

    var newPassportFields = [];
    newPassportFields.push(
        {
            step: this.getEditStep('title'),
            title: 'Title',
              value: values['title']
          //  value: values['title'] === 'Other' ? values['other-title'] : values['title']
        },
        {
            step: this.getEditStep('name'),
            title: 'Name',
            value: join(values, ['name', 'lastname'])
        },
        {
            step: this.getEditStep('previous-names'),
            title: 'Previous names',
            value: values['previous-name'] ? values['previous-names'] : 'You have never been known by any other names'
        },
        {
            step: this.getEditStep('gender'),
            title: 'Gender',
            value: values['gender'] === 'M' ? 'Male' : values['gender'] === 'F' ? 'Female' : ''
        },
        {
            step: this.getEditStep('age-year'),
            title: 'Date of birth',
            value: moment(values['age-year'] + '-' + values['age-month'] + '-' + values['age-day'], 'YYYY-MM-DD').format('D MMMM YYYY')
        },
        {
            step: this.getEditStep('town-of-birth'),
            title: 'Town of birth',
            value: values['town-of-birth']
        }

    );

    if(values['country-of-birth']){
      newPassportFields.push(
        {
          step: this.getEditStep('country-of-birth'),
          title: 'Country of birth',
          value: values['country-of-birth']
      }
      );
    }

    if (values['can-sign']) {
        newPassportFields.push(
            {
                step: this.getEditStep('can-sign'),
                title: 'Signature',
                value: 'You'll sign your passport when you receive it.'
            }
        );
    } else {
        newPassportFields.push(
            {
                step: this.getEditStep('no-sign-reason'),
                title: 'Signature',
                value: values['no-sign-reason'] ? 'You can’t sign your passport:
' + values['no-sign-reason'] : 'You can’t sign your passport'
            }
        );
    }

    newPassportFields.push(
        {
            step: this.getEditStep('passport-details-correct'),
            title: 'Personal details',
            value: 'Your personal details haven’t changed'
        },
        {
            title: 'Your photo',
            custom: '

'
        },
        {
            step: this.getEditStep('recognisable'),
            title: 'Your appearance',
            value: 'You can be recognised as the same person'
        }
    );

    response.sections.push({
        className: 'new-passport-details',
        title: 'New passport',
        fields: newPassportFields
    });

    response.sections.push({
        className: 'application-details',
        title: 'Application',
        fields: [
            {
                step: this.getEditStep('postcode'),
                title: 'Address',
                /*value: join(values, ['address1', 'address2', 'town', 'postcode'], '
')*/
                value: function(){
                  var country = req.sessionModel.get('application-country');
                  var output = join(values, ['address1', 'address2','town', 'postcode'], '
');
                  if (country == 'FR'){ output += '
France';}
                  else if (country == 'DE'){ output += '
Germany';}
                  else if (country == 'IL'){ output += '
Israel';}
                  else if (country == 'BE'){ output += '
Belgium';}
                  else if (country == 'NL'){ output += '
Netherlands';}
                  else if (country == 'ES'){ output += '
Spain';}
                /*  output += country;*/
                  return output;
                }
            },
            {
                step: this.getEditStep('email'),
                title: 'Contact details',
                /*value: join(values, ['email','country-code', 'mobile'], '

')*/
                value: function() {
                  var output = join(values, ['email'], '

');
                  output += '

';
                  output += join(values, ['application-country-code', 'mobile']);
                  return output;
                }
            },
            {
                step: this.getEditStep('braille'),
                title: 'Braille',
                value: function () {
                    var output = [];
                    output.push(values['braille'] ? 'You require a braille sticker' : 'You don’t require a braille sticker');
                    return output.join('

');
                }
            }
        ]
    });
//appointment details
response.sections.push({
    className: 'appointment-details',
    title: 'Appointment',
    fields: [
        {
            step: this.getEditStep('postcode'),
            title: 'Date and time',
            value: function() {
              var output = [];
              output.push('Saturday, 25 February 2017
12:30pm');
              return output;
            }
        },
        {
            step: this.getEditStep('postcode'),
            title: 'Passport office',
            value: function() {
              var output = [];
              output.push('London
Globe House
89 Eccleston Square
London
SW1V 1PN');
              return output;
            }
        }
    ]
});

//end of appointment

    response.sections.push({
        className: 'cost-details',
        title: 'Cost',
        fields: [
            {
                step: this.getEditStep('braille'),
                title: 'New passport',
                value: function () {
                    var output = [];
                    if (values['passport-options-dps'] == '48') {
                        var cost = model.largePassport();
                        cost = currency(cost);
                        if (!values.veteran) {
                            cost += ' extra';
                        }

                        output.push('Jumbo passport ');
                        output.push('£137');
                    } else {
                        output.push('Standard passport');
                        output.push('£128');
                    }
                    return output.join('
');
                }
            },
            {
                step: values.veteran ? null : this.getEditStep('secure-return'),
                title: values.veteran ? 'Delivery' : 'Old passport',
                value: function () {
                        var output = 'You need to bring your old passport to the appointment.';
                        return output;
                }
            },
            {
                className: 'cost',
                title: 'Total',
                value: function () {
                    return currency(values.cost);
                }
            }
        ]
    });
    callback(null, response);
};

module.exports = ConfirmForm;
<|endoftext|>


<commit_before>/*
Mag.JS AddOns v0.22.4
http://github.com/magnumjs/mag.js
(c) Michael Glazer
License: MIT
*/
!function(e,t,a,n){"use strict";function r(e,t){for(var a=Object.keys(e),n=0,r=a.length;r>n;++n){var i=a[n];t(i,e[i])}}function i(e){return e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}e.noop=function(){},e.copy=e.utils.copy,e.merge=e.utils.merge,e.isEmpty=function(e){return 0===Object.keys(e).length},e.show=function(t,a){var n=typeof t;if("object"!==n){var r={_config:function(e){e.style.display=t?"block":"none"}};return"object"==typeof a&&e.merge(a,r),r}"object"==n?t.willload=function(e,t){t.style.display="block"}:t.willupdate=function(e,t,n){t.style.display=n[a]?"block":"none"}},e.deferred=function(){var e={};return e.promise=new Promise(function(t,a){e.resolve=t,e.reject=a}),e},e.when=function(e,t){return Promise.all(e).then(t)},e.request=function(t){var a=e.deferred();t.initialValue&&(a.promise.initialValue=t.initialValue);var n=JSON.stringify(t);if(t.cache){var r=e.cache(n);if(r)return a.resolve(r),a.promise}if(e.request.queue[n])return e.request.queue[n];e.request.queue[n]=a.promise;var i=new XMLHttpRequest,u=(t.method||"GET").toUpperCase(),o="GET"!==u&&t.data?t.data:"";if(i.onload=function(r){var u=i.getResponseHeader("content-type")||"",o=r.target.responseText;u.indexOf("json")>-1&&(o=JSON.parse(o)),t.cache&&e.cache(n,o,t.cacheTime,t.cacheType),delete e.request.queue[n];var s=i.getAllResponseHeaders();a.resolve(o,s)},i.onerror=function(e){a.reject(e)},i.open(u,t.url),t.headers)for(var s=0;s<t.headers.length;s++){var c=t.headers[s];for(var l in c)i.setRequestHeader(l,c[l])}return i.send(o),a.promise},e.request.queue={},e.cache=function(a,n,r,i){var u=t[i||"sessionStorage"];if(1==arguments.length){if(e.cache.data[a])return e.cache.data[a].data;var o=u.getItem(a);return o?(e.cache.data[a]=JSON.parse(o),e.cache.data[a].data):0}e.cache.data[a]&&e.cache.data[a].id&&clearTimeout(e.cache.data[a].id);var s=setTimeout(function(t){u.removeItem(t),delete e.cache.data[t]}.bind({},a),r||6e5);e.cache.data[a]={id:s,data:n},u.setItem(a,JSON.stringify(e.cache.data[a]))},e.cache.data={},e.requestWithFeedback=function(t){var n=JSON.stringify(t);if(!e.requestWithFeedback.cache[n]){for(var r,i=a.querySelectorAll(".loader"),u=0;r=i[u];u++)r.style.display="block";var o=function(t){if(delete e.requestWithFeedback.cache[n],0==Object.keys(e.requestWithFeedback.cache).length)for(var a,r=0;a=i[r];r++)a.style.display="none";return t};e.requestWithFeedback.cache[n]=e.request(t),e.requestWithFeedback.cache[n].then(o,function(e){throw o(e),e})}return e.requestWithFeedback.cache[n]},e.requestWithFeedback.cache={},e.disable=function(t,a){var n=a&&a._config?a._config:function(){},r={_config:function(e){n.apply(this,arguments),t()?e.setAttribute("disabled","disabled"):e.removeAttribute("disabled")}};return a&&e.merge(a,r),r},e.find=function(t,n){var r=a.getElementById(t);return e.fill.find(r,n)},e.toMenu=function(e,t){return e.map(function(e,a){return{_text:e,_value:a,_selected:t===a||t===e?!0:null}})},e.namespace=function(t,a){var n=t.split("."),r=n.shift();return a=a||this,a[r]=a[r]||{},n.length?e.namespace(n.join("."),a[r]):a[r]},e.route=function(e){function t(e,t){i.push({parts:e.split("/"),handler:t})}function a(t){e.location.hash=t}function r(){for(var t=e.location.hash.substr(1),a=t.split("/"),r=a.length,u=0;u<i.length;u++){var o=i[u];if(o.parts.length===r){for(var s=[],c=0;r>c;c++)if(":"===o.parts[c].substr(0,1))s.push(a[c]);else if(o.parts[c]!==a[c])break;if(c===r)return o.handler.apply(n,s),n}}}var i=[];return e.onhashchange=r,{addRoute:t,load:a,start:r}}(t),e.hookin("attributes","key",function(e){e.value=null}),e.hookin("attributes","style",function(e){if("object"==typeof e.value){var t=e.node.getAttribute("style")||"",a="";r(e.value,function(e,t){a+=i(e)+":"+(isNaN(t)?t:t+"px")+";"}),e.value=t&&~t.indexOf(a)?t:t+a}}),e.hookin("attributes","className",function(e){e.key="class";var t=e.value,a=e.node.classList+"";if("string"==typeof e.value)t=e.value.split(" ");else if("object"==typeof e.value){for(var r in t)e.node.classList.toggle(r,t[r]);return e.value=e.node.classList+"",n}e.value=e.node.classList+"";for(var r in t){var i=t[r];i.trim()&&e.node.classList.length>0&&!e.node.classList.contains(i.trim())?e.value=e.node.classList+" "+i:i.trim()&&0==e.node.classList.length&&(e.value+=i+" ")}e.value.trim()!==a&&(e.change=1),e.value=e.value.trim()}),e.hookin("values","*",function(t){var a=typeof t.value;if(null==t.value);else if("function"===a&&t.value.toJSON)t.change=1,t.value=t.value();else if("object"==a&&"function"==typeof t.value.then){var n=e.utils.items.getItem(e.fill.id);t.value.then(function(a){e.mod.getState(n)[t.key]=a,e.redraw(e.getNode(e.fill.id),n,1)}),t.value.initialValue&&(t.change=1,t.value=t.value.initialValue)}}),e.getId=function(t){return e.utils.items.getItemVal(t)},e.prop=function(e){var t=function(){return arguments.length&&(e=arguments[0]),e};return t.toJSON=function(){return e},t},e.withProp=function(e,t){return function(a){a=a||event;var n=a.currentTarget||this;t(e in n?n[e]:n.getAttribute(e))}}}(mag,window||global||this,document);
<commit_msg>Update mag.addons.0.22.min.js<commit_after>/*
Mag.JS AddOns v0.22.3
http://github.com/magnumjs/mag.js
(c) Michael Glazer
License: MIT
*/
!function(a,b,c,d){"use strict";function e(a,b){for(var c=Object.keys(a),d=0,e=c.length;d<e;++d){var f=c[d];b(f,a[f])}}function f(a){return a.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}a.noop=function(){},a.copy=a.utils.copy,a.merge=a.utils.merge,a.isEmpty=function(a){if(!a||0==a.length)return!0;if("Object]"==a.toString().substr(-7)){for(var b in a)if(a.hasOwnProperty(b))return!1;return!0}return a.trim()},a.show=function(b,c){var d=typeof b;if("object"!==d){var e={_config:function(a){a.style.display=b?"block":"none"}};return"object"==typeof c&&a.merge(c,e),e}"object"==d?b.willload=function(a,b,c){b.style.display="block"}:b.willupdate=function(a,b,d){b.style.display=d[c]?"block":"none"}},a.deferred=function(){var a={};return a.promise=new Promise(function(b,c){a.resolve=b,a.reject=c}),a},a.when=function(a,b){return Promise.all(a).then(b)},a.request=function(b){var c=a.deferred();b.initialValue&&(c.promise.initialValue=b.initialValue);var d=JSON.stringify(b);if(b.cache){var e=a.cache(d);if(e)return c.resolve(e),c.promise}if(a.request.queue[d])return a.request.queue[d];a.request.queue[d]=c.promise;var f=new XMLHttpRequest,g=(b.method||"GET").toUpperCase(),h="GET"!==g&&b.data?b.data:"";if(f.onload=function(e){var g=f.getResponseHeader("content-type")||"",h=e.target.responseText;g.indexOf("json")>-1&&(h=JSON.parse(h)),b.cache&&a.cache(d,h,b.cacheTime,b.cacheType),delete a.request.queue[d];var i=f.getAllResponseHeaders();c.resolve(h,i)},f.onerror=function(a){c.reject(a)},f.open(g,b.url),b.withCredentials&&(f.withCredentials=b.withCredentials),b.headers)for(var i=0;i<b.headers.length;i++){var j=b.headers[i];for(var k in j)f.setRequestHeader(k,j[k])}return f.send(h),c.promise},a.request.queue={},a.cache=function(c,d,e,f){var g=b[f||"sessionStorage"];if(1==arguments.length){if(a.cache.data[c])return a.cache.data[c].data;var h=g.getItem(c);return h?(a.cache.data[c]=JSON.parse(h),a.cache.data[c].data):0}a.cache.data[c]&&a.cache.data[c].id&&clearTimeout(a.cache.data[c].id);var i=setTimeout(function(b){g.removeItem(b),delete a.cache.data[b]}.bind({},c),e||6e5);a.cache.data[c]={id:i,data:d},g.setItem(c,JSON.stringify(a.cache.data[c]))},a.cache.data={},a.requestWithFeedback=function(b){var d=JSON.stringify(b);if(!a.requestWithFeedback.cache[d]){for(var g,e=c.querySelectorAll(".loader"),f=0;g=e[f];f++)g.style.display="block";var h=function(b){if(delete a.requestWithFeedback.cache[d],0==Object.keys(a.requestWithFeedback.cache).length)for(var f,c=0;f=e[c];c++)f.style.display="none";return b};a.requestWithFeedback.cache[d]=a.request(b),a.requestWithFeedback.cache[d].then(h,function(a){throw h(a),a})}return a.requestWithFeedback.cache[d]},a.requestWithFeedback.cache={},a.disable=function(b,c){var d=c&&c._config?c._config:function(){},e={_config:function(a){d.apply(this,arguments),b()?a.setAttribute("disabled","disabled"):a.removeAttribute("disabled")}};return c&&a.merge(c,e),e},a.find=function(b,d){var e=c.getElementById(b);return a.fill.find(e,d)},a.toMenu=function(a,b){return a.map(function(a,c){return{_text:a,_value:c,_selected:b===c||b===a||null}})},a.namespace=function(b,c){var d=b.split("."),e=d.shift();return c=c||this,c[e]=c[e]||{},d.length?a.namespace(d.join("."),c[e]):c[e]},a.route=function(a){function c(a,c){b.push({parts:a.split("/"),handler:c})}function e(b){a.location.hash=b}function f(){for(var c=a.location.hash.substr(1),e=c.split("/"),f=e.length,g=0;g<b.length;g++){var h=b[g];if(h.parts.length===f){for(var i=[],j=0;j<f;j++)if(":"===h.parts[j].substr(0,1))i.push(e[j]);else if(h.parts[j]!==e[j])break;if(j===f)return void h.handler.apply(d,i)}}}var b=[];return a.onhashchange=f,{addRoute:c,load:e,start:f}}(b),a.hookin("attributes","key",function(a){a.value=null}),a.hookin("attributes","style",function(a){if("object"==typeof a.value){var b=a.node.getAttribute("style")||"",c="";e(a.value,function(a,b){c+=f(a)+":"+(isNaN(b)?b:b+"px")+";"}),b&&~b.indexOf(c)?a.value=b:a.value=b+c}}),a.hookin("attributes","className",function(a){a.key="class";var b=a.value,c=a.node.classList+"";if("string"==typeof a.value)b=a.value.split(" ");else if("object"==typeof a.value){for(var d in b)a.node.classList.toggle(d,b[d]);return void(a.value=a.node.classList+"")}a.value=a.node.classList+"";for(var d in b){var e=b[d];e.trim()&&a.node.classList.length>0&&!a.node.classList.contains(e.trim())?a.value=a.node.classList+" "+e:e.trim()&&0==a.node.classList.length&&(a.value+=e+" ")}a.value.trim()!==c&&(a.change=1),a.value=a.value.trim()});var g=[];a.hookin("values","*",function(b){var c=typeof b.value;null==b.value||("function"===c&&b.value.toJSON?(b.change=1,b.value=b.value()):"object"==c&&"function"==typeof b.value.then&&(g[a.fill.id+b.key]||(g[a.fill.id+b.key]=1,b.value.then(function(c,d,e){if(c){var f=a.utils.items.getItem(c);~f&&(a.mod.getState(f)[d]=e,a.redraw(a.getNode(c),f,1),g[c+b.key]=0)}return e}.bind(null,a.fill.id,b.key))),b.value.initialValue&&(b.change=1,b.value=b.value.initialValue)))}),a.getId=function(b){return a.utils.items.getItemVal(b)},a.prop=function(a){var b=function(){return arguments.length&&(a=arguments[0]),a};return b.toJSON=function(){return a},b},a.withProp=function(a,b){return function(c){c=c||event;var d=c.currentTarget||this;b(a in d?d[a]:d.getAttribute(a))}}}(mag,window||global||this,document);
<|endoftext|>


<commit_before>import { Component, PropTypes } from "react";
import { connect } from "react-apollo";
import gql from "graphql-tag";

import { nav, give as giveActions } from "../../../../store";
import Loading from "../../../../components/loading";

import Layout from "./Layout";

// XXX remove cache: false once we feel good about caching
const mapQueriesToProps = () => ({
  data: {
    forceFetch: true,
    query: gql`
      query PaymentDetails {
        accounts: savedPayments(cache: false) {
          id: entityId
          name
          payment {
            id
            accountNumber
            paymentType
          }
        }
      }
    `,
  },
});
const defaultAccounts = [];
@connect({ mapQueriesToProps })
export default class GiveNow extends Component {

  state = { accounts: [] }

  componentWillMount() {
    this.props.dispatch(nav.setLevel("BASIC_CONTENT"));
  }

  componentWillUnmount() {
    this.props.dispatch(nav.setLevel("TOP"));
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.data.loading && !nextProps.data.loading) {
      this.setState({ accounts: nextProps.data.accounts });
    }
  }

  remove = (e) => {
    e.preventDefault();
    const { id } = e.target;

    const accounts = this.state.accounts.filter(x => x.id != id);

    this.setState({ accounts });
    Meteor.call("PaymentAccounts.remove", id, (err, response) => {
      // XXX mutation
      this.props.data.refetch(); // clear out data store for newly missing account
    });
  }

  render() {
    const { accounts } = this.state;
    return <Layout loading={this.props.data.loading} details={accounts} remove={this.remove} />;
  }
}
<commit_msg>linte settings pyaments index<commit_after>import { Component, PropTypes } from "react";
import { connect } from "react-apollo";
import gql from "graphql-tag";

import { nav } from "../../../../store";

import Layout from "./Layout";

// XXX remove cache: false once we feel good about caching
const mapQueriesToProps = () => ({
  data: {
    forceFetch: true,
    query: gql`
      query PaymentDetails {
        accounts: savedPayments(cache: false) {
          id: entityId
          name
          payment {
            id
            accountNumber
            paymentType
          }
        }
      }
    `,
  },
});
@connect({ mapQueriesToProps })
export default class GiveNow extends Component {

  static propTypes = {
    dispatch: PropTypes.function.isRequired,
    data: {
      loading: PropTypes.boolean.isRequired,
      refetch: PropTypes.function.isRequired,
    },
  }

  state = { accounts: [] }

  componentWillMount() {
    this.props.dispatch(nav.setLevel("BASIC_CONTENT"));
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.data.loading && !nextProps.data.loading) {
      this.setState({ accounts: nextProps.data.accounts });
    }
  }

  componentWillUnmount() {
    this.props.dispatch(nav.setLevel("TOP"));
  }

  remove = (e) => {
    e.preventDefault();
    const { id } = e.target;

    const accounts = this.state.accounts.filter(x => x.id !== id);

    this.setState({ accounts });
    Meteor.call("PaymentAccounts.remove", id, () => {
      // XXX mutation
      this.props.data.refetch(); // clear out data store for newly missing account
    });
  }

  render() {
    const { accounts } = this.state;
    return <Layout loading={this.props.data.loading} details={accounts} remove={this.remove} />;
  }
}
<|endoftext|>


<commit_before>Sn0GWBT7
N[sYw1F*u2t0l9IvH>Lf
Sy-!+Xuؤ)iM
Rlrغ'(A78fKF%1{\{ejF1s1On*ǌ٘LS"cQj0==::LHuDQɛAř)d9Z8Xa-Έw\F4ӫY{قMX`m}ruTXLI븛\}f[[ ?ַ?o	o}E]tq<P,l[iMitBC,ckyG|
%'$^\E.Ly].s
Z[cc9nֈipoZ!5v0t2'#!swd87\n©{Ó?dWZm>cLug/C^|*R2	cy'@<commit_msg>These shouldn't be in git<commit_after><|endoftext|>