<commit_before>var BrowserWindow = require('browser-window');
var Fs = require('fire-fs');
var Shell = require('shell');
var DevTools = require('./dev-tools');

function _getDefaultMainMenu () {
    return [
        // Help
        {
           label: 'Help',
           id: 'help',
           submenu: [
               {
                   label: 'Documentation',
                   click: function () {
                       Shell.openExternal('http://docs.fireball-x.com/');
                       Shell.beep();
                   }
               },
               {
                   label: 'Discussion Group',
                   click: function () {
                       Shell.openExternal('http://fireball-x.com/chat');
                       Shell.beep();
                   }
               },
               { type: 'separator' },
               {
                   label: 'Report Issue',
                   click: function () {
                       Shell.openExternal('https://github.com/fireball-x/fireball/issues/');
                       Shell.beep();
                   }
               },
               {
                   label: 'Subscribe',
                   click: function () {
                       Shell.openExternal('http://eepurl.com/bh5w3z');
                       Shell.beep();
                   }
               },
               { type: 'separator' },
               {
                   label: 'About Fireball',
                   click: function () {
                        var aboutWindow = new Editor.Window('about', {
                            'title': 'About Fireball',
                            'width': 400,
                            'height': 180,
                            'always-on-top': true,
                            'show': false,
                            'resizable': false,
                        });

                        mainWindow = Editor.mainWindow;
                        var postion_ = mainWindow.nativeWin.getPosition();
                        var size_ = mainWindow.nativeWin.getSize();
                        aboutWindow.load( 'app://canvas-studio/page/app-about.html' );
                        var x = (postion_[0] + size_[0]/2 - 200);
                        var y = (postion_[1] + size_[1]/2 - 90);
                        aboutWindow.nativeWin.setPosition(Math.floor(x),Math.floor(y));
                        aboutWindow.show();
                        aboutWindow.nativeWin.on('blur',function () {
                            aboutWindow.close();
                        });
                   }
               },
           ]
        },

        // Fireball
        {
            label: 'Editor Framework',
            position: 'before=help',
            submenu: [
                {
                    label: 'About Fireball',
                    click: function () {
                        Editor.info('Fireball v0.5 alpha2 20150717');
                    }
                },
                { type: 'separator' },
                {
                    label: 'Hide',
                    accelerator: 'CmdOrCtrl+H',
                    selector: 'hide:'
                },
                {
                    label: 'Hide Others',
                    accelerator: 'CmdOrCtrl+Shift+H',
                    selector: 'hideOtherApplications:'
                },
                {
                    label: 'Show All',
                    selector: 'unhideAllApplications:'
                },
                { type: 'separator' },
                {
                    label: 'Quit',
                    accelerator: 'CmdOrCtrl+Q',
                    click: function () {
                        Editor.Window.saveWindowStates();
                        Editor.quit();
                    }
                },
            ]
        },

        // File
        {
            label: 'File',
            submenu: [
                {
                    label: 'Open Project...',
                    click: function () {
                        Editor.App.runDashboard();
                    }
                },
                { type: 'separator' },
                {
                    label: 'New Scene',
                    accelerator: 'CmdOrCtrl+N',
                    click: function () {
                        Editor.sendToPanel('scene.panel', 'scene:new-scene');
                    }
                },
                {
                    label: 'Save Scene',
                    accelerator: 'CmdOrCtrl+S',
                    click: function () {
                        Editor.showDialogSaveScene();
                    }
                },
                { type: 'separator' },
            ]
        },

        // Edit
        {
            label: 'Edit',
            submenu: [
                {
                   label: 'Undo',
                   accelerator: 'CmdOrCtrl+Z',
                   selector: 'undo:'
                },
                {
                   label: 'Redo',
                   accelerator: 'Shift+CmdOrCtrl+Z',
                   selector: 'redo:'
                },
                { type: 'separator' },
                {
                   label: 'Cut',
                   accelerator: 'CmdOrCtrl+X',
                   selector: 'cut:'
                },
                {
                   label: 'Copy',
                   accelerator: 'CmdOrCtrl+C',
                   selector: 'copy:'
                },
                {
                   label: 'Paste',
                   accelerator: 'CmdOrCtrl+V',
                   selector: 'paste:'
                },
                {
                   label: 'Select All',
                   accelerator: 'CmdOrCtrl+A',
                   selector: 'selectAll:'
                },
                { type: 'separator' },
                {
                   label: 'Play',
                   accelerator: 'CmdOrCtrl+P',
                   click: function () {
                       Editor.sendToMainWindow('editor:toggle-play');
                   },
                },
            ]
        },

        // Window
        {
            label: 'Window',
            id: 'window',
            submenu: Editor.isDarwin ?
            [
                {
                    label: 'Minimize',
                    accelerator: 'CmdOrCtrl+M',
                    selector: 'performMiniaturize:',
                },
                {
                    label: 'Close',
                    accelerator: 'CmdOrCtrl+W',
                    selector: 'performClose:',
                },
                { type: 'separator' },
                {
                    label: 'Bring All to Front',
                    selector: 'arrangeInFront:'
                },
            ] :
            [
                {
                    label: "Close",
                    accelerator: 'CmdOrCtrl+W',
                    click: function () {
                        Editor.Window.saveWindowStates();
                        Editor.quit();
                    },
                }
            ]
        },

        // Panel
        {
            label: 'Panel',
            id: 'panel',
            submenu: [
            ]
        },

        // Layout
        {
            label: 'Layout',
            id: 'layout',
            submenu: [
                {
                    label: 'Default',
                    click: function () {
                        var layoutInfo;
                        if ( Fs.existsSync(Editor._defaultLayout) ) {
                            try {
                                layoutInfo = JSON.parse(Fs.readFileSync(Editor._defaultLayout));
                            } catch (err) {
                                Editor.error( 'Failed to load default layout: %s', err.message );
                                layoutInfo = null;
                            }
                        }
                        if ( layoutInfo) {
                            Editor.sendToMainWindow( 'editor:reset-layout', layoutInfo);
                        }
                    }
                },
                {
                    label: 'Assets',
                    click: function () {
                        var path = Editor.url('app://canvas-studio/static/layout/assetdb.json');
                        var layoutInfo;
                        if ( Fs.existsSync(path) ) {
                            try {
                                layoutInfo = JSON.parse(Fs.readFileSync(path));
                            } catch (err) {
                                Editor.error( 'Failed to load default layout: %s', err.message );
                                layoutInfo = null;
                            }
                        }
                        if ( layoutInfo) {
                            Editor.sendToMainWindow( 'editor:reset-layout', layoutInfo);
                        }
                    }
                },
                { type: 'separator' },
                {
                    label: 'Empty',
                    click: function () {
                        Editor.sendToMainWindow( 'editor:reset-layout', null);
                    }
                },
            ]
        },

        // Developer
        {
            label: 'Developer',
            id: 'developer',
            submenu: [
                {
                    label: 'Command Palette',
                    accelerator: 'CmdOrCtrl+:',
                    click: function() {
                        Editor.mainWindow.focus();
                        Editor.sendToMainWindow('cmdp:show');
                    }
                },
                { type: 'separator' },
                {
                    label: 'Reload',
                    accelerator: 'CmdOrCtrl+R',
                    click: function() {
                        Editor.stashedScene = null;
                        BrowserWindow.getFocusedWindow().reload();
                    }
                },
                {
                    label: 'Reload Ignoring Cache',
                    accelerator: 'CmdOrCtrl+Shift+R',
                    click: function() {
                        Editor.stashedScene = null;
                        BrowserWindow.getFocusedWindow().reloadIgnoringCache();
                    }
                },
                {
                    label: 'Reload Editor.App',
                    click: function() {
                        Editor.App.reload();
                    }
                },
                {
                    label: 'Compile',
                    accelerator: 'F7',
                    click: function() {
                        Editor.Compiler.compileAndReload();
                    }
                },
                { type: 'separator' },
                {
                    label: 'Inspect Element',
                    accelerator: 'CmdOrCtrl+Shift+C',
                    click: function() {
                        var nativeWin = BrowserWindow.getFocusedWindow();
                        var editorWin = Editor.Window.find(nativeWin);
                        if ( editorWin ) {
                            editorWin.sendToPage( 'window:inspect' );
                        }
                    }
                },
                {
                    label: 'Developer Tools',
                    accelerator: 'CmdOrCtrl+Alt+I',
                    click: function() {
                        var win = BrowserWindow.getFocusedWindow();
                        win.openDevTools();
                        DevTools.highlightHeaderLater(win);
                    }
                },
                {
                    label: 'Debug Core',
                    type: 'checkbox',
                    checked: false,
                    click: function() {
                        Editor.Debugger.toggle();
                    }
                },
                { type: 'separator' },
                {
                    label: 'Generate UUID',
                    click: function() {
                        var uuid = require('node-uuid');
                        Editor.log(uuid.v4());
                    }
                },
                {
                    label: 'Remove All Meta Files',
                    click: function() {
                        Editor.assetdb._rmMetas( function () {
                            Editor.success('Meta files removed');
                        });
                    }
                },
                { type: 'separator' },
                {
                    label: 'Run Tests (editor-framework)',
                    accelerator: 'CmdOrCtrl+Alt+T',
                    click: function() {
                        var testRunner = Editor.require('editor-framework://core/test-runner');
                        testRunner.liveRun( Editor.url('editor-framework://test/') );
                    }
                },
                {
                    label: 'Human Tests',
                    submenu: [
                        { type: 'separator' },
                        {
                            label: 'Throw an Uncaught Exception',
                            click: function() {
                                throw new Error('editor-framework Unknown Error');
                            }
                        },
                        {
                            label: 'send2panel \'foo:bar\' foobar.panel',
                            click: function() {
                                Editor.sendToPanel( "foobar.panel", "foo:bar" );
                            }
                        },
                    ],
                },
                { type: 'separator' },
                {
                    label: 'UI Preview',
                    submenu: [
                    ],
                },
                { type: 'separator' },
            ]
        },
    ];
}

//
module.exports = _getDefaultMainMenu;
<commit_msg>update display version in about panel.<commit_after>var BrowserWindow = require('browser-window');
var Fs = require('fire-fs');
var Shell = require('shell');
var DevTools = require('./dev-tools');

function _getDefaultMainMenu () {
    return [
        // Help
        {
           label: 'Help',
           id: 'help',
           submenu: [
               {
                   label: 'Documentation',
                   click: function () {
                       Shell.openExternal('http://docs.fireball-x.com/');
                       Shell.beep();
                   }
               },
               {
                   label: 'Discussion Group',
                   click: function () {
                       Shell.openExternal('http://fireball-x.com/chat');
                       Shell.beep();
                   }
               },
               { type: 'separator' },
               {
                   label: 'Report Issue',
                   click: function () {
                       Shell.openExternal('https://github.com/fireball-x/fireball/issues/');
                       Shell.beep();
                   }
               },
               {
                   label: 'Subscribe',
                   click: function () {
                       Shell.openExternal('http://eepurl.com/bh5w3z');
                       Shell.beep();
                   }
               },
               { type: 'separator' },
               {
                   label: 'About Fireball',
                   click: function () {
                        var aboutWindow = new Editor.Window('about', {
                            'title': 'About Fireball',
                            'width': 400,
                            'height': 180,
                            'always-on-top': true,
                            'show': false,
                            'resizable': false,
                        });

                        mainWindow = Editor.mainWindow;
                        var postion_ = mainWindow.nativeWin.getPosition();
                        var size_ = mainWindow.nativeWin.getSize();
                        aboutWindow.load( 'app://canvas-studio/page/app-about.html' );
                        var x = (postion_[0] + size_[0]/2 - 200);
                        var y = (postion_[1] + size_[1]/2 - 90);
                        aboutWindow.nativeWin.setPosition(Math.floor(x),Math.floor(y));
                        aboutWindow.show();
                        aboutWindow.nativeWin.on('blur',function () {
                            aboutWindow.close();
                        });
                   }
               },
           ]
        },

        // Fireball
        {
            label: 'Editor Framework',
            position: 'before=help',
            submenu: [
                {
                    label: 'About Fireball',
                    click: function () {
                        Editor.info('Fireball v0.5 alpha3 20150727');
                    }
                },
                { type: 'separator' },
                {
                    label: 'Hide',
                    accelerator: 'CmdOrCtrl+H',
                    selector: 'hide:'
                },
                {
                    label: 'Hide Others',
                    accelerator: 'CmdOrCtrl+Shift+H',
                    selector: 'hideOtherApplications:'
                },
                {
                    label: 'Show All',
                    selector: 'unhideAllApplications:'
                },
                { type: 'separator' },
                {
                    label: 'Quit',
                    accelerator: 'CmdOrCtrl+Q',
                    click: function () {
                        Editor.Window.saveWindowStates();
                        Editor.quit();
                    }
                },
            ]
        },

        // File
        {
            label: 'File',
            submenu: [
                {
                    label: 'Open Project...',
                    click: function () {
                        Editor.App.runDashboard();
                    }
                },
                { type: 'separator' },
                {
                    label: 'New Scene',
                    accelerator: 'CmdOrCtrl+N',
                    click: function () {
                        Editor.sendToPanel('scene.panel', 'scene:new-scene');
                    }
                },
                {
                    label: 'Save Scene',
                    accelerator: 'CmdOrCtrl+S',
                    click: function () {
                        Editor.showDialogSaveScene();
                    }
                },
                { type: 'separator' },
            ]
        },

        // Edit
        {
            label: 'Edit',
            submenu: [
                {
                   label: 'Undo',
                   accelerator: 'CmdOrCtrl+Z',
                   selector: 'undo:'
                },
                {
                   label: 'Redo',
                   accelerator: 'Shift+CmdOrCtrl+Z',
                   selector: 'redo:'
                },
                { type: 'separator' },
                {
                   label: 'Cut',
                   accelerator: 'CmdOrCtrl+X',
                   selector: 'cut:'
                },
                {
                   label: 'Copy',
                   accelerator: 'CmdOrCtrl+C',
                   selector: 'copy:'
                },
                {
                   label: 'Paste',
                   accelerator: 'CmdOrCtrl+V',
                   selector: 'paste:'
                },
                {
                   label: 'Select All',
                   accelerator: 'CmdOrCtrl+A',
                   selector: 'selectAll:'
                },
                { type: 'separator' },
                {
                   label: 'Play',
                   accelerator: 'CmdOrCtrl+P',
                   click: function () {
                       Editor.sendToMainWindow('editor:toggle-play');
                   },
                },
            ]
        },

        // Window
        {
            label: 'Window',
            id: 'window',
            submenu: Editor.isDarwin ?
            [
                {
                    label: 'Minimize',
                    accelerator: 'CmdOrCtrl+M',
                    selector: 'performMiniaturize:',
                },
                {
                    label: 'Close',
                    accelerator: 'CmdOrCtrl+W',
                    selector: 'performClose:',
                },
                { type: 'separator' },
                {
                    label: 'Bring All to Front',
                    selector: 'arrangeInFront:'
                },
            ] :
            [
                {
                    label: "Close",
                    accelerator: 'CmdOrCtrl+W',
                    click: function () {
                        Editor.Window.saveWindowStates();
                        Editor.quit();
                    },
                }
            ]
        },

        // Panel
        {
            label: 'Panel',
            id: 'panel',
            submenu: [
            ]
        },

        // Layout
        {
            label: 'Layout',
            id: 'layout',
            submenu: [
                {
                    label: 'Default',
                    click: function () {
                        var layoutInfo;
                        if ( Fs.existsSync(Editor._defaultLayout) ) {
                            try {
                                layoutInfo = JSON.parse(Fs.readFileSync(Editor._defaultLayout));
                            } catch (err) {
                                Editor.error( 'Failed to load default layout: %s', err.message );
                                layoutInfo = null;
                            }
                        }
                        if ( layoutInfo) {
                            Editor.sendToMainWindow( 'editor:reset-layout', layoutInfo);
                        }
                    }
                },
                {
                    label: 'Assets',
                    click: function () {
                        var path = Editor.url('app://canvas-studio/static/layout/assetdb.json');
                        var layoutInfo;
                        if ( Fs.existsSync(path) ) {
                            try {
                                layoutInfo = JSON.parse(Fs.readFileSync(path));
                            } catch (err) {
                                Editor.error( 'Failed to load default layout: %s', err.message );
                                layoutInfo = null;
                            }
                        }
                        if ( layoutInfo) {
                            Editor.sendToMainWindow( 'editor:reset-layout', layoutInfo);
                        }
                    }
                },
                { type: 'separator' },
                {
                    label: 'Empty',
                    click: function () {
                        Editor.sendToMainWindow( 'editor:reset-layout', null);
                    }
                },
            ]
        },

        // Developer
        {
            label: 'Developer',
            id: 'developer',
            submenu: [
                {
                    label: 'Command Palette',
                    accelerator: 'CmdOrCtrl+:',
                    click: function() {
                        Editor.mainWindow.focus();
                        Editor.sendToMainWindow('cmdp:show');
                    }
                },
                { type: 'separator' },
                {
                    label: 'Reload',
                    accelerator: 'CmdOrCtrl+R',
                    click: function() {
                        Editor.stashedScene = null;
                        BrowserWindow.getFocusedWindow().reload();
                    }
                },
                {
                    label: 'Reload Ignoring Cache',
                    accelerator: 'CmdOrCtrl+Shift+R',
                    click: function() {
                        Editor.stashedScene = null;
                        BrowserWindow.getFocusedWindow().reloadIgnoringCache();
                    }
                },
                {
                    label: 'Reload Editor.App',
                    click: function() {
                        Editor.App.reload();
                    }
                },
                {
                    label: 'Compile',
                    accelerator: 'F7',
                    click: function() {
                        Editor.Compiler.compileAndReload();
                    }
                },
                { type: 'separator' },
                {
                    label: 'Inspect Element',
                    accelerator: 'CmdOrCtrl+Shift+C',
                    click: function() {
                        var nativeWin = BrowserWindow.getFocusedWindow();
                        var editorWin = Editor.Window.find(nativeWin);
                        if ( editorWin ) {
                            editorWin.sendToPage( 'window:inspect' );
                        }
                    }
                },
                {
                    label: 'Developer Tools',
                    accelerator: 'CmdOrCtrl+Alt+I',
                    click: function() {
                        var win = BrowserWindow.getFocusedWindow();
                        win.openDevTools();
                        DevTools.highlightHeaderLater(win);
                    }
                },
                {
                    label: 'Debug Core',
                    type: 'checkbox',
                    checked: false,
                    click: function() {
                        Editor.Debugger.toggle();
                    }
                },
                { type: 'separator' },
                {
                    label: 'Generate UUID',
                    click: function() {
                        var uuid = require('node-uuid');
                        Editor.log(uuid.v4());
                    }
                },
                {
                    label: 'Remove All Meta Files',
                    click: function() {
                        Editor.assetdb._rmMetas( function () {
                            Editor.success('Meta files removed');
                        });
                    }
                },
                { type: 'separator' },
                {
                    label: 'Run Tests (editor-framework)',
                    accelerator: 'CmdOrCtrl+Alt+T',
                    click: function() {
                        var testRunner = Editor.require('editor-framework://core/test-runner');
                        testRunner.liveRun( Editor.url('editor-framework://test/') );
                    }
                },
                {
                    label: 'Human Tests',
                    submenu: [
                        { type: 'separator' },
                        {
                            label: 'Throw an Uncaught Exception',
                            click: function() {
                                throw new Error('editor-framework Unknown Error');
                            }
                        },
                        {
                            label: 'send2panel \'foo:bar\' foobar.panel',
                            click: function() {
                                Editor.sendToPanel( "foobar.panel", "foo:bar" );
                            }
                        },
                    ],
                },
                { type: 'separator' },
                {
                    label: 'UI Preview',
                    submenu: [
                    ],
                },
                { type: 'separator' },
            ]
        },
    ];
}

//
module.exports = _getDefaultMainMenu;
<|endoftext|>


<commit_before>import path from "path";
import express from "express";
import session from "express-session";
import bodyParser from "body-parser";
import connectMongo from "connect-mongo";
import secrets from "./secrets";

const MongoStore = connectMongo(session);

export default function(app, passport) {
	app.set("port", 3000)
	app.set("host", "localhost")

	// X-Powered-By header has no functional value.
	// Keeping it makes it easier for an attacker to build the site's profile
	// It can be removed safely
	app.disable("x-powered-by")

	app.use(bodyParser.json())
	app.use(bodyParser.urlencoded({ extended: true }))
	app.use(express.static(path.join(process.cwd(), 'public')));

	const sess = {
		resave: true,
		saveUninitialized: true,
		secret: secrets.sessionSecret,
		proxy: false,
		name: "sessionId",
		cookie: {
			httpOnly: true,
			secure: false
		},
		store: new MongoStore({
			url: secrets.db,
			autoReconnect: true
		})
	}

	var node_env = process.env.NODE_ENV;
	console.log('--------------------------');
	console.log('===> 😊  Starting Server . . .');
	console.log('===>  Environment: ' + node_env);
	if(node_env === 'production') {
		console.log('===> 🚦  Note: In order for authentication to work in production');
		console.log('===>           you will need a secure HTTPS connection');
		sess.cookie.secure = true; // Serve secure cookies
	}

	app.use(session(sess))

	app.use(passport.initialize())
	app.use(passport.session())

}
<commit_msg>deployment<commit_after>import path from "path";
import express from "express";
import session from "express-session";
import bodyParser from "body-parser";
import connectMongo from "connect-mongo";
import secrets from "./secrets";

const MongoStore = connectMongo(session);

export default function(app, passport) {
	app.set("port", 3000)
	app.set("host", "localhost")

	// X-Powered-By header has no functional value.
	// Keeping it makes it easier for an attacker to build the site's profile
	// It can be removed safely
	app.disable("x-powered-by")

	app.use(bodyParser.json())
	app.use(bodyParser.urlencoded({ extended: true }))
	app.use(express.static(path.join(process.cwd(), 'public')));

	const sess = {
		resave: true,
		saveUninitialized: true,
		secret: secrets.sessionSecret,
		proxy: false,
		name: "sessionId",
		cookie: {
			httpOnly: true,
			secure: false
		},
		store: new MongoStore({
			url: secrets.db,
			autoReconnect: true
		})
	}

	var node_env = process.env.NODE_ENV;
	console.log('--------------------------');
	console.log('===> 😊  Starting Server . . .');
	console.log('===>  Environment: ' + node_env);
	if(node_env === 'production') {
		console.log('===> 🚦  Note: In order for authentication to work in production');
		console.log('===>           you will need a secure HTTPS connection');
		sess.cookie.secure = true; // Serve secure cookies
	}

	app.use(session(sess))

	app.use(passport.initialize())
	app.use(passport.session())

}
<|endoftext|>


<commit_before>(function (angular) {
    "use strict";

    angular.module("mfl.facilities.services", [
        "sil.api.wrapper"
    ])

    .service("mfl.facilities.wrappers", ["api", function (api) {
        this.facilities = api.setBaseUrl("api/facilities/facilities/");
        this.filterOptions = api.setBaseUrl("api/common/filtering_summaries/");
        this.constituencies = api.setBaseUrl("api/common/constituencies");
        this.facilitiesList = api.setBaseUrl("api/facilities/facilities_list");
        this.constituencies = api.setBaseUrl("api/common/constituencies");
        this.wards = api.setBaseUrl("api/common/wards");
        this.counties = api.setBaseUrl("api/common/counties");
        this.towns = api.setBaseUrl("api/common/towns");
        this.contact_types = api.setBaseUrl("api/common/contact_types/");
        this.contacts = api.setBaseUrl("api/common/contacts/");
        this.physical_address = api.setBaseUrl("api/common/address/");
        this.facility_contacts = api.setBaseUrl("api/facilities/contacts/");
        this.services = api.setBaseUrl("api/facilities/services/");
        this.option = api.setBaseUrl("api/facilities/options/");
        this.service_option = api.setBaseUrl("api/facilities/service_options/");
        this.facility_service = api.setBaseUrl("api/facilities/facility_services/");
        this.utils = function(){
            return {
                cleanFormData : function(data){
                    _.each(data, function(val, key){
                        if(_.isObject(val)){
                            data[key] = val.id;
                        }
                    });
                    return data;
                },
                createLock: function(stateParams, state){
                    if(_.isEmpty(stateParams.facilityId)){
                        state.go("facilities.create.basic");
                    }
                },
                resolvePromise: function(scope,scopeObj, key, promise){
                    promise.success(function(data){
                        scopeObj[key] = data.results||data;
                    }).error(function(error){
                        scope.alert = error.error_msg;
                    });
                },
                getError: function(error){
                    return error.error_msg.error;
                }
            };
        }();
    }]);

})(angular);
<commit_msg>minor bug fix<commit_after>(function (angular) {
    "use strict";

    angular.module("mfl.facilities.services", [
        "sil.api.wrapper"
    ])

    .service("mfl.facilities.wrappers", ["api", function (api) {
        this.facilities = api.setBaseUrl("api/facilities/facilities/");
        this.filterOptions = api.setBaseUrl("api/common/filtering_summaries/");
        this.constituencies = api.setBaseUrl("api/common/constituencies");
        this.facilitiesList = api.setBaseUrl("api/facilities/facilities_list");
        this.constituencies = api.setBaseUrl("api/common/constituencies");
        this.wards = api.setBaseUrl("api/common/wards");
        this.counties = api.setBaseUrl("api/common/counties");
        this.towns = api.setBaseUrl("api/common/towns");
        this.contact_types = api.setBaseUrl("api/common/contact_types/");
        this.contacts = api.setBaseUrl("api/common/contacts/");
        this.physical_address = api.setBaseUrl("api/common/address/");
        this.facility_contacts = api.setBaseUrl("api/facilities/contacts/");
        this.services = api.setBaseUrl("api/facilities/services/");
        this.option = api.setBaseUrl("api/facilities/options/");
        this.service_option = api.setBaseUrl("api/facilities/service_options/");
        this.facility_service = api.setBaseUrl("api/facilities/facility_services/");
        this.utils = function(){
            return {
                cleanFormData : function(data){
                    _.each(data, function(val, key){
                        if(_.isObject(val)){
                            data[key] = val.id;
                        }
                    });
                    return data;
                },
                createLock: function(stateParams, state){
                    if(_.isEmpty(stateParams.facilityId)){
                        state.go("facilities.create.basic");
                    }
                },
                resolvePromise: function(scope,scopeObj, key, promise){
                    promise.success(function(data){
                        scopeObj[key] = data.results;
                    }).error(function(error){
                        scope.alert = error.error_msg;
                    });
                },
                getError: function(error){
                    return error.error_msg.error;
                }
            };
        }();
    }]);

})(angular);
<|endoftext|>


<commit_before>/*
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

var path = require('path');
var helpers = require('yeoman-test');
var assert = require('yeoman-assert');
var shell = require('shelljs');

//See http://yeoman.io/authoring/testing.html

// test with all defaults first.
test();

var appTypes = [
    "Rest API",
    'Command Line'
];

var entityStores = [
    'Cassandra',
    'File',
    'DerbySQL',
    'Geode',
    'H2SQL',
    'Hazelcast',
    'JClouds',
    'Jdbm',
    'LevelDB',
    'MongoDB',
    'MySQL',
    'Preferences',
    'Redis',
    'Riak',
    'PostgreSQL',
    'SQLite',
    'Memory'   // Somehow the last EntityStore is used in subsequent test arrays. Pick the fastest.
];

var indexings = [
    'Rdf',
    'ElasticSearch',
    'Solr',
    'SQL'
];

var cachings = [
    'None',
    'Memcache',
    'EhCache'
];

var metricses = [
    'None',
    'Codahale'
];

var featuresset = [
    [],
    ['jmx'],
    ['mixin scripting'],
    ['security'],
    ['jmx', 'mixin scripting'],
    ['jmx', 'scripting'],
    ['mixin scripting', 'scripting'],
    ['jmx', 'mixin scripting', 'scripting']
];

appTypes.forEach(function (appType) {
    test(appType, "Memory", "Rdf", "Memcache", "Codahale", "[]");
});

entityStores.forEach(function (entityStore) {
    test("Rest API", entityStore, "Rdf", "Memcache", "Codahale", "[]");
});

indexings.forEach(function (indexing) {
    test("Rest API", "Memory", indexing, "Memcache", "Codahale", "[]");
});

cachings.forEach(function (caching) {
    test("Rest API", "Memory", "Rdf", caching, "Codahale", "[]");
});

metricses.forEach(function (metrics) {
    test("Rest API", "Memory", "Rdf", "Memcache", metrics, "[]");
});

featuresset.forEach(function (feature) {
    test("Rest API", "Memory", "Rdf", "Memcache", "Codahale", feature);
});

// All Tests !!!!
if(process.env.TEST_ALL === 'yes') {
    appTypes.forEach(function (appType) {
        entityStores.forEach(function (entitystore) {
            indexings.forEach(function (indexing) {
                cachings.forEach(function (caching) {
                    metricses.forEach(function (metrics) {
                        featuresset.forEach(function (features) {
                            test(appType, entitystore, indexing, caching, metrics, features)
                        });
                    });
                });
            });
        });
    });
}

function test(appType, entityStore, indexing, caching, metrics, features) {
    describe('polygene-generator', function () {
        var testName = appType + ' with '
            + entityStore + ' EntityStore - '
            + indexing + ' Indexing - '
            + caching + ' Caching - '
            + metrics + ' Metrics';
        if(features && features.length > 0) {
            testName += ' - ' + features.toString().replace(new RegExp(',', 'g'), ' - ');
        }
        var testDirName = testName.replace(new RegExp(' - ', 'g'), '_').replace(new RegExp(' ', 'g'), '_');
        it(testName,
            function () {
                this.timeout(30000);
                return helpers.run(path.join(__dirname, '../app'))
                    .inDir(path.join(__dirname, '../build/npm-test/' + testDirName))
                    .withPrompts({
                        name: 'TestProject',
                        packageName: 'org.apache.polygene.generator.test',
                        applicationtype: appType,
                        entitystore: entityStore,
                        indexing: indexing,
                        caching: caching,
                        metrics: metrics,
                        features: features
                    })
                    .then(buildAndVerify);
            });
    });
}

function buildAndVerify(dir) {
    assert.file(['gradlew', 'settings.gradle', 'build.gradle']);
    assert(shell.exec(path.join(dir, 'gradlew') + ' check --init-script ../../stagedMavenRepoInitScript.gradle').code == 0);
}
<commit_msg>:tools:generator do not repeat tests when TEST_ALL is set<commit_after>/*
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

var path = require('path');
var helpers = require('yeoman-test');
var assert = require('yeoman-assert');
var shell = require('shelljs');

//See http://yeoman.io/authoring/testing.html

var appTypes = [
    "Rest API",
    'Command Line'
];

var entityStores = [
    'Cassandra',
    'File',
    'DerbySQL',
    'Geode',
    'H2SQL',
    'Hazelcast',
    'JClouds',
    'Jdbm',
    'LevelDB',
    'MongoDB',
    'MySQL',
    'Preferences',
    'Redis',
    'Riak',
    'PostgreSQL',
    'SQLite',
    'Memory'   // Somehow the last EntityStore is used in subsequent test arrays. Pick the fastest.
];

var indexings = [
    'Rdf',
    'ElasticSearch',
    'Solr',
    'SQL'
];

var cachings = [
    'None',
    'Memcache',
    'EhCache'
];

var metricses = [
    'None',
    'Codahale'
];

var featuresset = [
    [],
    ['jmx'],
    ['mixin scripting'],
    ['security'],
    ['jmx', 'mixin scripting'],
    ['jmx', 'scripting'],
    ['mixin scripting', 'scripting'],
    ['jmx', 'mixin scripting', 'scripting']
];

// test with all defaults first.
test();

if(process.env.TEST_ALL === 'yes') {
    // All Tests !!!!
    appTypes.forEach(function (appType) {
        entityStores.forEach(function (entitystore) {
            indexings.forEach(function (indexing) {
                cachings.forEach(function (caching) {
                    metricses.forEach(function (metrics) {
                        featuresset.forEach(function (features) {
                            test(appType, entitystore, indexing, caching, metrics, features)
                        });
                    });
                });
            });
        });
    });
} else {
    // Subset
    appTypes.forEach(function (appType) {
        test(appType, "Memory", "Rdf", "Memcache", "Codahale", "[]");
    });

    entityStores.forEach(function (entityStore) {
        test("Rest API", entityStore, "Rdf", "Memcache", "Codahale", "[]");
    });

    indexings.forEach(function (indexing) {
        test("Rest API", "Memory", indexing, "Memcache", "Codahale", "[]");
    });

    cachings.forEach(function (caching) {
        test("Rest API", "Memory", "Rdf", caching, "Codahale", "[]");
    });

    metricses.forEach(function (metrics) {
        test("Rest API", "Memory", "Rdf", "Memcache", metrics, "[]");
    });

    featuresset.forEach(function (feature) {
        test("Rest API", "Memory", "Rdf", "Memcache", "Codahale", feature);
    });
}

function test(appType, entityStore, indexing, caching, metrics, features) {
    describe('polygene-generator', function () {
        var testName = appType + ' with '
            + entityStore + ' EntityStore - '
            + indexing + ' Indexing - '
            + caching + ' Caching - '
            + metrics + ' Metrics';
        if(features && features.length > 0) {
            testName += ' - ' + features.toString().replace(new RegExp(',', 'g'), ' - ');
        }
        var testDirName = testName.replace(new RegExp(' - ', 'g'), '_').replace(new RegExp(' ', 'g'), '_');
        it(testName,
            function () {
                this.timeout(30000);
                return helpers.run(path.join(__dirname, '../app'))
                    .inDir(path.join(__dirname, '../build/npm-test/' + testDirName))
                    .withPrompts({
                        name: 'TestProject',
                        packageName: 'org.apache.polygene.generator.test',
                        applicationtype: appType,
                        entitystore: entityStore,
                        indexing: indexing,
                        caching: caching,
                        metrics: metrics,
                        features: features
                    })
                    .then(buildAndVerify);
            });
    });
}

function buildAndVerify(dir) {
    assert.file(['gradlew', 'settings.gradle', 'build.gradle']);
    assert(shell.exec(path.join(dir, 'gradlew') + ' check --init-script ../../stagedMavenRepoInitScript.gradle').code == 0);
}
<|endoftext|>


<commit_before>game.module('game.meteor_warning')
.require('game.b2dvec')
.body(function() {
    game.addAsset('warning.png');

    game.createClass('MeteorWarning', {
        init: function(x, y, size, velocity) {
            this.sprite = new game.Sprite('warning.png', x, y, {width: size, height: size, anchor: {x: 0.5, y: 0.5}});
            this.sprite.addTo(game.scene.stage);
            game.scene.addObject(this);
            this.velocity = velocity;
            this.size = size;

            this.blinkTime = 1800;
            this.blinkInterval = this.blinkTime / 10;
            this.blinkIntervalElapsed = 0;
            this.getEdgePos();
        },

        update: function() {
            this.blinkTime -= 1000 * game.system.delta;
            this.blinkIntervalElapsed += 1000 * game.system.delta;

            if (this.blinkTime <= 0) {
                this.sprite.remove();
                game.scene.removeObject(this);
            }
            // if (this.blinkIntervalElapsed >= this.blinkInterval) {
            //     this.blinkIntervalElapsed = 0;
            //     this.sprite.visible = !this.sprite.visible;
            // }
        },

        getEdgePos: function() {
            var pos = this.sprite.position;
            var fraction = 0;

            // if (pos.x < 0 && pos.y > 0) {
            //     fraction = pos.x / this.velocity.x;
            //     pos.y = this.velocity.y * fraction;
            // } else if (pos.x > game.system.width && pos.y > 0) {
            //     fraction = (pos.x - game.system.width) / this.velocity.x;
            //     pos.y = this.velocity.y * fraction;
            // } else if (pos.y < 0 && pos.x > 0 && pos.x < game.system.width) {
            //     fraction = pos.y / this.velocity.y;
            //     pos.x = this.velocity.x * fraction;
            // }

            if (pos.x < 0) {
                pos.x = 0;
            } else if (pos.x + this.size > game.system.width) {
                pos.x = game.system.width - this.size;
            }
            if (pos.y < 0) {
                pos.y = 0;
            }

            this.sprite.position.x = pos.x;
            this.sprite.position.y = pos.y;
        }
    });
});<commit_msg>fix warning positioning<commit_after>game.module('game.meteor_warning')
.require('game.b2dvec')
.body(function() {
    game.addAsset('warning.png');

    game.createClass('MeteorWarning', {
        init: function(x, y, size, velocity) {
            this.sprite = new game.Sprite('warning.png', x, y, {width: size, height: size, anchor: {x: 0.5, y: 0.5}});
            this.sprite.addTo(game.scene.stage);
            game.scene.addObject(this);
            this.velocity = velocity;
            this.size = size;

            this.blinkTime = 1800;
            this.blinkInterval = this.blinkTime / 10;
            this.blinkIntervalElapsed = 0;
            this.getEdgePos();
        },

        update: function() {
            this.blinkTime -= 1000 * game.system.delta;
            this.blinkIntervalElapsed += 1000 * game.system.delta;

            if (this.blinkTime <= 0) {
                this.sprite.remove();
                game.scene.removeObject(this);
            }
            if (this.blinkIntervalElapsed >= this.blinkInterval) {
                this.blinkIntervalElapsed = 0;
                this.sprite.visible = !this.sprite.visible;
            }
        },

        getEdgePos: function() {
            var pos = this.sprite.position;
            var fraction = 0;

            if (pos.x - this.size < 0) {
                pos.x = 0 + this.size;
            } else if (pos.x + this.size > game.system.width) {
                pos.x = game.system.width - this.size;
            }
            if (pos.y - this.size / 2 < 0) {
                pos.y = 0 + this.size / 2;
            }

            this.sprite.position.x = pos.x;
            this.sprite.position.y = pos.y;
        }
    });
});<|endoftext|>


<commit_before>#!/usr/bin/env node

var vsprintf = require("sprintf-js").vsprintf,
    stats = require('stats-lite'),
    _ = require('underscore'),
    program = require('commander'),
    db = require('./db'),
    data = {},
    bins = [25, 50, 100, 250, 500, 999.99],
    contributorTypes, query;

program.option('--html', 'HTML output')
    .option('--since <date>', 'Donations since date')
    .option('--office <office>', 'Include only offices that match string')
    .option('--threshold <threshold>', 'Report only committees receiving at least threshold [10000]', 10000)
    .parse(process.argv);

query = db.select(
        'office',
        'contributions.committee_name',
        'candidate_name',
        db.raw("sum(case when state = 'DC' then amount else 0 end) as dc_amount"),
        db.raw("sum(case when contributor_type in ('Individual', 'Candidate') then amount else 0 end) as ind_amount"),
        db.raw("sum(case when state = 'DC' and contributor_type in ('Individual', 'Candidate') then amount else 0 end) as dc_ind_amount")
    )
    .count('* as contributions')
    .sum('amount as amount')
    .from('contributions')
    .innerJoin('committees', 'contributions.committee_name', 'committees.committee_name')
    .where(1, 1);
addFilters(query);
query.groupBy('office', 'contributions.committee_name', 'candidate_name')
    .orderBy('office')
    .orderBy('candidate_name')
    .then(function (rows) {
        rows.forEach(function (row) {
            //console.log(row.committee_name);
            row.amountList = [];
            row.amountByType = {};
            row.binAmounts = bins.map(function () { return 0; }).concat([0]);
            row.dc_ind_contributors = 0;
            data[row.committee_name] = row;
        });
        getStats();
    });

function getStats() {
    getContributorTypes()
        .then(function () {
            var query = db.select('committee_name', 'normalized', 'state')
                    .sum('amount as subtotal')
                    .from('contributions'),
                start = 0;
            addFilters(query);
            query.groupBy('committee_name', 'normalized', 'state')
                .having('subtotal', '>', 0)
                .then(function (rows) {
                    var prevOffice = '',
                        officeRegex = program.office ? new RegExp(program.office, 'i') : null,
                        headers, format, officeFormat;

                    if (program.html) {
                        headers = '
\n
' +
                            'Candidate	' +
                            'Contri-
butions	' +
                            'Contrib-
utors	' +
                            'DC Ind
Contbr	' +
                            'Amount	' +
                            'Mean	' +
                            'Median	' +
                            '%Ind	' +
                            '%DC	' +
                            '%DCInd	';
                        format = '
%s	' +
                            '%s	' +
                            '%s	' +
                            '%s	' +
                            '$%s	' +
                            '$%s	' +
                            '$%s	' +
                            '%s	' +
                            '%s	' +
                            '%s	';
                        officeFormat = '
%s
';
                        bins.forEach(function (end) {
                            headers += '' + start + '-
' + end + '	';
                            format += '%s	';
                            start = (end + 0.01).toFixed(2);
                        });
                        headers += '' + start + '+	';
                        format += '%s	';
                        headers += '
';
                        format += '
';
                    }
                    else {
                        headers = 'Candidate             Contributions  Contributors  DCIndContbr    ' +
                            'Amount   Mean  Median  %Ind %DC %DCInd';
                        format = '%-20s %14s %13s %12s %9s  %5s  %6s  %4s %3s %6s';
                        officeFormat = '%s';
                        bins.forEach(function (end) {
                            var header = start + '-' + end;
                            headers += '  ' + header;
                            format += '  %' + header.length + 's';
                            start = (end + 0.01).toFixed(2);
                        });
                        headers += '  ' + start + '+';
                        format += '  %' + (start.length + 1) + 's';
                    }
                    console.log(headers);
                    rows.forEach(function (row) {
                        var i;
                        data[row.committee_name].amountList.push(row.subtotal);
                        for (i = 0; i < bins.length; i++) {
                            if (row.subtotal <= bins[i]) {
                                data[row.committee_name].binAmounts[i] += row.subtotal;
                                break;
                            }
                        }
                        if (i >= bins.length) {
                            data[row.committee_name].binAmounts[i] += row.subtotal;
                        }
                        if (row.state == 'DC') {
                            data[row.committee_name].dc_ind_contributors++;
                        }
                    });
                    _.each(data, function (c) {
                        var values = [
                                c.candidate_name,
                                numberFormat(c.contributions),
                                numberFormat(c.amountList.length),
                                numberFormat(c.dc_ind_contributors),
                                numberFormat(c.amount)
                            ],
                            start = 0;
                        if (c.amount < program.threshold || (officeRegex && !officeRegex.test(c.office))) {
                            return;
                        }
                        c.amountList = c.amountList.sort(function (a, b) { return a - b; });
                        values.push(
                            numberFormat(stats.mean(c.amountList)),
                            numberFormat(stats.median(c.amountList)),
                            numberFormat(100 * c.ind_amount / c.amount),
                            numberFormat(100 * c.dc_amount / c.amount),
                            numberFormat(100 * c.dc_ind_amount / c.amount)
                            //c.amountList[0],
                            //c.amountList[c.amountList.length - 1]
                        );
                        bins.forEach(function (end, i) {
                            values.push((100 * c.binAmounts[i] / c.amount).toFixed(2));
                        });
                        values.push((100 * c.binAmounts[bins.length] / c.amount).toFixed(2));
                        if (c.office !== prevOffice) {
                            console.log(vsprintf(officeFormat, [c.office.toUpperCase()]));
                        }
                        console.log(vsprintf(format, values));
                        //console.log(c.binCounts);
                        prevOffice = c.office;
                    });
                    if (program.html) {
                        console.log('
\n');
                    }
                    //printCrossCandidateContributions();
                    process.exit();
                });
        });
}

function getContributorTypes() {
    var query = db.distinct('contributor_type')
        .from('contributions');
    addFilters(query);
    return query.orderBy('contributor_type')
        .then(function (rows) {
            var subquery;
            contributorTypes = _.pluck(rows, 'contributor_type');
            //console.log(contributorTypes);
            subquery = db.select('committee_name', 'contributor_type')
                .sum('amount as amount')
                .from('contributions');
            addFilters(subquery);
            return subquery.groupBy('committee_name', 'contributor_type')
                .then(function (rows) {
                    rows.forEach(function (c) {
                        data[c.committee_name].amountByType[c.contributor_type] = c.amount;
                    });
                });
        });
}

function addFilters(query) {
    if (program.since) {
        query = query.andWhere('receipt_date', '>=', program.since);
    }
}

function numberFormat(x) {
    return Math.round(x).toLocaleString();
}

function printCrossCandidateContributions() {
    var makeContributorQueryFn = function (alias) {
        return function () {
            this.select('contributions.committee_name', 'candidate_name', 'normalized')
                .sum('amount as subtotal')
                .from('contributions')
                .innerJoin('committees', 'committees.committee_name', 'contributions.committee_name')
                .having('subtotal', '>=', 100)
                .groupBy('contributions.committee_name', 'candidate_name', 'normalized')
                .as(alias);
        };
    };
    return db.select('c1.candidate_name as candidate1', 'c2.candidate_name as candidate2')
        .sum('c1.subtotal as subtotal1')
        .sum('c2.subtotal as subtotal2')
        .count('* as contributors')
        .from(makeContributorQueryFn('c1'))
        .innerJoin(makeContributorQueryFn('c2'), 'c1.normalized', 'c2.normalized')
        .groupBy('candidate1', 'candidate2')
        .orderBy('candidate1')
        .orderBy('subtotal1', 'desc')
        .then(function (rows) {
            var prev = '',
                total;
            rows.forEach(function (row) {
                if (prev !== row.candidate1) {
                    console.log(row.candidate1);
                    total = row.subtotal1;
                    prev = row.candidate1;
                }
                //else {
                    console.log(vsprintf('  %20s %5d %8s %5.2f%%', [
                        row.candidate2,
                        row.contributors,
                        '$' + Math.round(row.subtotal1).toLocaleString(),
                        100 * (row.subtotal1 / total),
                        row.subtotal2
                    ]));
                //}
            });
            process.exit();
        });
}
<commit_msg>add --csv option (which actually gives TSV, but that's good enough for now)<commit_after>#!/usr/bin/env node

var vsprintf = require("sprintf-js").vsprintf,
    stats = require('stats-lite'),
    _ = require('underscore'),
    program = require('commander'),
    db = require('./db'),
    data = {},
    bins = [25, 50, 100, 250, 500, 999.99],
    contributorTypes, query;

program.option('--html', 'HTML output')
    .option('--csv', 'CSV output')
    .option('--since <date>', 'Donations since date')
    .option('--office <office>', 'Include only offices that match string')
    .option('--threshold <threshold>', 'Report only committees receiving at least threshold [10000]', 10000)
    .parse(process.argv);

query = db.select(
        'office',
        'contributions.committee_name',
        'candidate_name',
        db.raw("sum(case when state = 'DC' then amount else 0 end) as dc_amount"),
        db.raw("sum(case when contributor_type in ('Individual', 'Candidate') then amount else 0 end) as ind_amount"),
        db.raw("sum(case when state = 'DC' and contributor_type in ('Individual', 'Candidate') then amount else 0 end) as dc_ind_amount")
    )
    .count('* as contributions')
    .sum('amount as amount')
    .from('contributions')
    .innerJoin('committees', 'contributions.committee_name', 'committees.committee_name')
    .where(1, 1);
addFilters(query);
query.groupBy('office', 'contributions.committee_name', 'candidate_name')
    .orderBy('office')
    .orderBy('candidate_name')
    .then(function (rows) {
        rows.forEach(function (row) {
            //console.log(row.committee_name);
            row.amountList = [];
            row.amountByType = {};
            row.binAmounts = bins.map(function () { return 0; }).concat([0]);
            row.dc_ind_contributors = 0;
            data[row.committee_name] = row;
        });
        getStats();
    });

function getStats() {
    getContributorTypes()
        .then(function () {
            var query = db.select('committee_name', 'normalized', 'state')
                    .sum('amount as subtotal')
                    .from('contributions'),
                start = 0,
                columnCount;
            addFilters(query);
            query.groupBy('committee_name', 'normalized', 'state')
                .having('subtotal', '>', 0)
                .then(function (rows) {
                    var prevOffice = '',
                        officeRegex = program.office ? new RegExp(program.office, 'i') : null,
                        headers, format, officeFormat;

                    if (program.html) {
                        headers = '
\n
' +
                            'Candidate	' +
                            'Contri-
butions	' +
                            'Contrib-
utors	' +
                            'DC Ind
Contbr	' +
                            'Amount	' +
                            'Mean	' +
                            'Median	' +
                            '%Ind	' +
                            '%DC	' +
                            '%DCInd	';
                        format = '
%s	' +
                            '%s	' +
                            '%s	' +
                            '%s	' +
                            '$%s	' +
                            '$%s	' +
                            '$%s	' +
                            '%s	' +
                            '%s	' +
                            '%s	';
                        officeFormat = '
%s
';
                        bins.forEach(function (end) {
                            headers += '' + start + '-
' + end + '	';
                            format += '%s	';
                            start = (end + 0.01).toFixed(2);
                        });
                        headers += '' + start + '+	';
                        format += '%s	';
                        headers += '
';
                        format += '
';
                    }
                    else if (program.csv) {
                        headers = [
                            'Candidate',
                            'Contributions',
                            'Contributors',
                            'DCIndContbr',
                            'Amount',
                            'Mean',
                            'Median',
                            '%Ind',
                            '%DC',
                            '%DCInd'
                        ].join('\t');
                        columnCount = 11 + bins.length;
                        format = Array(columnCount).fill('%s').join('\t');
                        officeFormat = '%s';
                        bins.forEach(function (end) {
                            headers += '\t' + start + '-' + end;
                            start = (end + 0.01).toFixed(2);
                        });
                        headers += '\t' + start + '+';
                    }
                    else {
                        headers = 'Candidate             Contributions  Contributors  DCIndContbr    ' +
                            'Amount   Mean  Median  %Ind %DC %DCInd';
                        format = '%-20s %14s %13s %12s %9s  %5s  %6s  %4s %3s %6s';
                        officeFormat = '%s';
                        bins.forEach(function (end) {
                            var header = start + '-' + end;
                            headers += '  ' + header;
                            format += '  %' + header.length + 's';
                            start = (end + 0.01).toFixed(2);
                        });
                        headers += '  ' + start + '+';
                        format += '  %' + (start.length + 1) + 's';
                    }
                    console.log(headers);
                    rows.forEach(function (row) {
                        var i;
                        data[row.committee_name].amountList.push(row.subtotal);
                        for (i = 0; i < bins.length; i++) {
                            if (row.subtotal <= bins[i]) {
                                data[row.committee_name].binAmounts[i] += row.subtotal;
                                break;
                            }
                        }
                        if (i >= bins.length) {
                            data[row.committee_name].binAmounts[i] += row.subtotal;
                        }
                        if (row.state == 'DC') {
                            data[row.committee_name].dc_ind_contributors++;
                        }
                    });
                    _.each(data, function (c) {
                        var values = [
                                c.candidate_name,
                                numberFormat(c.contributions),
                                numberFormat(c.amountList.length),
                                numberFormat(c.dc_ind_contributors),
                                numberFormat(c.amount)
                            ],
                            start = 0;
                        if (c.amount < program.threshold || (officeRegex && !officeRegex.test(c.office))) {
                            return;
                        }
                        c.amountList = c.amountList.sort(function (a, b) { return a - b; });
                        values.push(
                            numberFormat(stats.mean(c.amountList)),
                            numberFormat(stats.median(c.amountList)),
                            numberFormat(100 * c.ind_amount / c.amount),
                            numberFormat(100 * c.dc_amount / c.amount),
                            numberFormat(100 * c.dc_ind_amount / c.amount)
                            //c.amountList[0],
                            //c.amountList[c.amountList.length - 1]
                        );
                        bins.forEach(function (end, i) {
                            values.push((100 * c.binAmounts[i] / c.amount).toFixed(2));
                        });
                        values.push((100 * c.binAmounts[bins.length] / c.amount).toFixed(2));
                        if (c.office !== prevOffice && !program.csv) {
                            console.log(vsprintf(officeFormat, [c.office.toUpperCase()]));
                        }
                        console.log(vsprintf(format, values));
                        //console.log(c.binCounts);
                        prevOffice = c.office;
                    });
                    if (program.html) {
                        console.log('
\n');
                    }
                    //printCrossCandidateContributions();
                    process.exit();
                });
        });
}

function getContributorTypes() {
    var query = db.distinct('contributor_type')
        .from('contributions');
    addFilters(query);
    return query.orderBy('contributor_type')
        .then(function (rows) {
            var subquery;
            contributorTypes = _.pluck(rows, 'contributor_type');
            //console.log(contributorTypes);
            subquery = db.select('committee_name', 'contributor_type')
                .sum('amount as amount')
                .from('contributions');
            addFilters(subquery);
            return subquery.groupBy('committee_name', 'contributor_type')
                .then(function (rows) {
                    rows.forEach(function (c) {
                        data[c.committee_name].amountByType[c.contributor_type] = c.amount;
                    });
                });
        });
}

function addFilters(query) {
    if (program.since) {
        query = query.andWhere('receipt_date', '>=', program.since);
    }
}

function numberFormat(x) {
    return Math.round(x).toLocaleString();
}

function printCrossCandidateContributions() {
    var makeContributorQueryFn = function (alias) {
        return function () {
            this.select('contributions.committee_name', 'candidate_name', 'normalized')
                .sum('amount as subtotal')
                .from('contributions')
                .innerJoin('committees', 'committees.committee_name', 'contributions.committee_name')
                .having('subtotal', '>=', 100)
                .groupBy('contributions.committee_name', 'candidate_name', 'normalized')
                .as(alias);
        };
    };
    return db.select('c1.candidate_name as candidate1', 'c2.candidate_name as candidate2')
        .sum('c1.subtotal as subtotal1')
        .sum('c2.subtotal as subtotal2')
        .count('* as contributors')
        .from(makeContributorQueryFn('c1'))
        .innerJoin(makeContributorQueryFn('c2'), 'c1.normalized', 'c2.normalized')
        .groupBy('candidate1', 'candidate2')
        .orderBy('candidate1')
        .orderBy('subtotal1', 'desc')
        .then(function (rows) {
            var prev = '',
                total;
            rows.forEach(function (row) {
                if (prev !== row.candidate1) {
                    console.log(row.candidate1);
                    total = row.subtotal1;
                    prev = row.candidate1;
                }
                //else {
                    console.log(vsprintf('  %20s %5d %8s %5.2f%%', [
                        row.candidate2,
                        row.contributors,
                        '$' + Math.round(row.subtotal1).toLocaleString(),
                        100 * (row.subtotal1 / total),
                        row.subtotal2
                    ]));
                //}
            });
            process.exit();
        });
}
<|endoftext|>


<commit_before>/*    Copyright 2016 Firewalla LLC
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
'use strict';

const log = require('../net2/logger.js')(__filename);

const Sensor = require('./Sensor.js').Sensor;

const sem = require('../sensor/SensorEventManager.js').getInstance();

const extensionManager = require('./ExtensionManager.js')

const f = require('../net2/Firewalla.js');

const userConfigFolder = f.getUserConfigFolder();
const dnsConfigFolder = `${userConfigFolder}/dns`;
const safeSearchConfigFile = `${dnsConfigFolder}/safeSearch.conf`;

const configKey = "ext.safeSearch.config";

const updateInterval = 3600 * 1000 // once per hour

const rclient = require('../util/redis_manager.js').getConfig();

const domainBlock = require('../control/DomainBlock.js');

const domainMapping = {
  youtube_strict: {
    "restrict.youtube.com": [
      "www.youtube.com",
      "m.youtube.com",
      "youtubei.googleapis.com",
      "youtube.googleapis.com",
      "www.youtube-nocookie.com"
    ]
  },
  youtube_moderate: {
    "restrictmoderate.youtube.com": [
      "www.youtube.com",
      "m.youtube.com",
      "youtubei.googleapis.com",
      "youtube.googleapis.com",
      "www.youtube-nocookie.com"
    ]
  },
  google: {
    "forcesafesearch.google.com": [
      "www.google.com"
    ]
  },
  bing: {
    "strict.bing.com": [
      "www.bing.com"
    ]
  }
}

class SafeSearchPlugin extends Sensor {

  scheduledJob() {
    if(ipv6.hasConfig() &&
       ipv6.config.updatePublicIP) {
      ipv6.updatePublicIP()
    }
  }

  run() {
    this.cachedDomainResult = {};

    extensionManager.registerExtension("safeSearch", this, {
      applyPolicy: this.applyPolicy,
      start: this.start,
      stop: this.stop,
      setConfig: this.setConfig,
      getConfig: this.loadConfig
    })
  }

  applyPolicy(policy) {
    log.info("Applying policy:", policy, {})
    if(policy === true) {
      return this.start()
    } else {
      return this.stop()
    }
  }

  // {
  //   google: "on", // "on", "off"
  //   youtube: "strict", // "strict", "moderate", "off"
  //   bing: "on" // "on", "off"
  // }

  async loadConfig() {
    const configString = await rclient.getAsync(configKey);
    if(configString) {
      return JSON.parse(configString);
    } else {
      return null;
    }
  }

  async saveConfig(config) {
    return rclient.setAsync(configKey, JSON.stringify(config));
  }

  async resolveDNS() {

  }

  getMappingKey(type, value) {
    switch(type) {
    case "google":
      return "google";
    case "bing":
      return "bing";
    case "youtube":
      switch(value) {
        case "strict":
          return "youtube_strict";
        case "moderate":
          return "youtube_moderate";
        default:
          return null;
      }
    default:
      return null;
    }
  }

  getMappingResult(key) {
    if(key) {
      return domainMapping[key];
    } else {
      return null;
    }
  }

  addToCache(domain ,result) {
    if(this.cachedDomainResult[domain]) {
      // do nothing
      return;
    }

    this.cachedDomainResult[domain] = result;

    setTimeout(() => {
      delete this.cachedDomainResult[domain];
    }, updateInterval);
  }

  async getDNSMasqEntry(domainToBeRedirect, ipAddress) {
    return `address=/${domainToBeRedirect}/${ipAddress}`;
  }

  async processMappingResult(mappingEntry) {

  }

  async generateConfigFile() {
    const config = await this.loadConfig();

    const entries = [];

    for(const type in config) {
      const value = config[type];
      const key = this.getMappingKey(type, value);
      const result = this.getMappingResult(key);
      if(result) {

      }
    }

  }
  async start() {

  }

  stop() {
    return async(() => {
      await (ipv6.stop())
      clearTimeout(this.timer)
      this.timer = null
    })()
  }
}

module.exports = SafeSearchPlugin
<commit_msg>safe search plugin<commit_after>/*    Copyright 2016 Firewalla LLC
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
'use strict';

const log = require('../net2/logger.js')(__filename);

const Sensor = require('./Sensor.js').Sensor;

const sem = require('../sensor/SensorEventManager.js').getInstance();

const extensionManager = require('./ExtensionManager.js')

const f = require('../net2/Firewalla.js');

const userConfigFolder = f.getUserConfigFolder();
const dnsConfigFolder = `${userConfigFolder}/dns`;
const safeSearchConfigFile = `${dnsConfigFolder}/safeSearch.conf`;

const configKey = "ext.safeSearch.config";

const updateInterval = 3600 * 1000 // once per hour

const rclient = require('../util/redis_manager.js').getConfig();

const domainBlock = require('../control/DomainBlock.js');

const fs = require('fs');
const Promise = require('bluebird');
Promise.promisifyAll(fs);

const DNSMASQ = require('../extension/dnsmasq/dnsmasq.js');
const dnsmasq = new DNSMASQ();

const domainMapping = {
  youtube_strict: {
    "restrict.youtube.com": [
      "www.youtube.com",
      "m.youtube.com",
      "youtubei.googleapis.com",
      "youtube.googleapis.com",
      "www.youtube-nocookie.com"
    ]
  },
  youtube_moderate: {
    "restrictmoderate.youtube.com": [
      "www.youtube.com",
      "m.youtube.com",
      "youtubei.googleapis.com",
      "youtube.googleapis.com",
      "www.youtube-nocookie.com"
    ]
  },
  google: {
    "forcesafesearch.google.com": [
      "www.google.com"
    ]
  },
  bing: {
    "strict.bing.com": [
      "www.bing.com"
    ]
  }
}

class SafeSearchPlugin extends Sensor {

  scheduledJob() {
    if(ipv6.hasConfig() &&
       ipv6.config.updatePublicIP) {
      ipv6.updatePublicIP()
    }
  }

  run() {
    this.cachedDomainResult = {};

    extensionManager.registerExtension("safeSearch", this, {
      applyPolicy: this.applyPolicy,
      start: this.start,
      stop: this.stop
    })
  }

  async applyPolicy(policy) {
    log.info("Applying policy:", policy)

    const state = policy && policy.state;

    if(state === true) {
      return this.start(policy.config)
    } else {
      return this.stop();
    }
  }

  // {
  //   google: "on", // "on", "off"
  //   youtube: "strict", // "strict", "moderate", "off"
  //   bing: "on" // "on", "off"
  // }

  getMappingKey(type, value) {
    switch(type) {
    case "google":
      return "google";
    case "bing":
      return "bing";
    case "youtube":
      switch(value) {
        case "strict":
          return "youtube_strict";
        case "moderate":
          return "youtube_moderate";
        default:
          return null;
      }
    default:
      return null;
    }
  }

  getMappingResult(key) {
    if(key) {
      return domainMapping[key];
    } else {
      return null;
    }
  }

  addToCache(domain ,result) {
    if(this.cachedDomainResult[domain]) {
      // do nothing
      return;
    }

    this.cachedDomainResult[domain] = result;

    setTimeout(() => {
      delete this.cachedDomainResult[domain];
    }, updateInterval);
  }

  async getDNSMasqEntry(domainToBeRedirect, ipAddress) {
    return `address=/${domainToBeRedirect}/${ipAddress}`;
  }

  async processMappingResult(mappingEntry) {
    const safeDomains = Object.keys(mappingEntry);

    const entries = await Promise.all(safeDomains.map(async (safeDomain) => {
      const ips = await domainBlock.resolveDomain(safeDomain);

      if(ips.length > 0) {
        const ip = ips[0];
        const domainsToBeRedirect = mappingEntry[safeDomain];
        await Promise.all(domainsToBeRedirect.map(async (domain) => {
          return this.getDNSMasqEntry(domain, ip);
        }));
      }
    }));

    const concat = (x,y) => x.concat(y)
    const flatMap = (f,xs) => xs.map(f).reduce(concat, [])

    const flattedEntries = flatMap(x => x, entries);

    return flattedEntries;
  }

  async generateConfigFile(config) {
    let entries = [];

    for(const type in config) {
      const value = config[type];
      if(value === 'off') {
        continue;
      }

      const key = this.getMappingKey(type, value);
      const result = this.getMappingResult(key);
      if(result) {
        entries = entries.concat(this.processMappingResult(result));
      }
    }

    await fs.writeFileAsync(safeSearchConfigFile, JSON.stringify(entries.join("\n")));
  }

  async deleteConfigFile() {
    return fs.unlinkAsync(safeSearchConfigFile).catch(() => undefined);
  }

  async start(config) {
    await this.generateConfigFile(config);
    await dnsmasq.start(true);
    return;
  }

  async stop() {
    await this.deleteConfigFile();
    await dnsmasq.start(true);
  }
}

module.exports = SafeSearchPlugin
<|endoftext|>


<commit_before>/* eslint-disable react/prop-types */
/* globals window CustomEvent */
import React, { createElement } from "react"
import { Transition } from "react-transition-group"
import createHistory from "history/createBrowserHistory"

import getTransitionStyle from "./src/utils/getTransitionStyle"

const timeout = 250
const historyExitingEventType = `history::exiting`

const getUserConfirmation = (pathname, callback) => {
  const event = new CustomEvent(historyExitingEventType, { detail: { pathname } })
  window.dispatchEvent(event)
  setTimeout(() => {
    callback(true)
  }, timeout)
}
const history = createHistory({ getUserConfirmation })
// block must return a string to conform
history.block((location, action) => location.pathname)
exports.replaceHistory = () => history

class ReplaceComponentRenderer extends React.Component {
  constructor(props) {
    super(props)
    this.state = { exiting: false, nextPageResources: {} }
    this.listenerHandler = this.listenerHandler.bind(this)
  }

  listenerHandler(event) {
    const nextPageResources = this.props.loader.getResourcesForPathname(
      event.detail.pathname,
      nextPageResources => this.setState({ nextPageResources })
    ) || {}
    this.setState({ exiting: true, nextPageResources })
  }

  componentDidMount() {
    window.addEventListener(historyExitingEventType, this.listenerHandler)
  }

  componentWillUnmount() {
    window.removeEventListener(historyExitingEventType, this.listenerHandler)
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.location.key !== nextProps.location.key) {
      this.setState({ exiting: false, nextPageResources: {} })
    }
  }

  render() {
    const transitionProps = {
      timeout: {
        enter: 0,
        exit: timeout,
      },
      appear: true,
      in: !this.state.exiting,
      key: this.props.location.key,
    }
    return (
      <Transition {...transitionProps}>
      {
        (status) => createElement(this.props.pageResources.component, {
          ...this.props,
          ...this.props.pageResources.json,
          transition: {
            status,
            timeout,
            style: getTransitionStyle({ status, timeout }),
            nextPageResources: this.state.nextPageResources,
          },
        })
      }
      </Transition>
    )
  }
}

// eslint-disable-next-line react/display-name
exports.replaceComponentRenderer = ({ props, loader }) => {
  if (props.layout) {
    return undefined
  }
  return createElement(ReplaceComponentRenderer, { ...props, loader })
}<commit_msg>Update gatsby-browser.js (#3694)<commit_after>/* eslint-disable react/prop-types */
/* globals window CustomEvent */
import React, { createElement } from "react"
import { Transition } from "react-transition-group"
import createHistory from "history/createBrowserHistory"

import getTransitionStyle from "./src/utils/getTransitionStyle"

const timeout = 250
const historyExitingEventType = `history::exiting`

const getUserConfirmation = (pathname, callback) => {
  const event = document.createEvent("CustomEvent");
  event.initCustomEvent(historyExitingEventType, false, false, { detail: { pathname } });
  window.dispatchEvent(event)
  setTimeout(() => {
    callback(true)
  }, timeout)
}
const history = createHistory({ getUserConfirmation })
// block must return a string to conform
history.block((location, action) => location.pathname)
exports.replaceHistory = () => history

class ReplaceComponentRenderer extends React.Component {
  constructor(props) {
    super(props)
    this.state = { exiting: false, nextPageResources: {} }
    this.listenerHandler = this.listenerHandler.bind(this)
  }

  listenerHandler(event) {
    const nextPageResources = this.props.loader.getResourcesForPathname(
      event.detail.pathname,
      nextPageResources => this.setState({ nextPageResources })
    ) || {}
    this.setState({ exiting: true, nextPageResources })
  }

  componentDidMount() {
    window.addEventListener(historyExitingEventType, this.listenerHandler)
  }

  componentWillUnmount() {
    window.removeEventListener(historyExitingEventType, this.listenerHandler)
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.location.key !== nextProps.location.key) {
      this.setState({ exiting: false, nextPageResources: {} })
    }
  }

  render() {
    const transitionProps = {
      timeout: {
        enter: 0,
        exit: timeout,
      },
      appear: true,
      in: !this.state.exiting,
      key: this.props.location.key,
    }
    return (
      <Transition {...transitionProps}>
      {
        (status) => createElement(this.props.pageResources.component, {
          ...this.props,
          ...this.props.pageResources.json,
          transition: {
            status,
            timeout,
            style: getTransitionStyle({ status, timeout }),
            nextPageResources: this.state.nextPageResources,
          },
        })
      }
      </Transition>
    )
  }
}

// eslint-disable-next-line react/display-name
exports.replaceComponentRenderer = ({ props, loader }) => {
  if (props.layout) {
    return undefined
  }
  return createElement(ReplaceComponentRenderer, { ...props, loader })
}
<|endoftext|>