<commit_before>// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2015-01-06 using
// generator-karma 0.8.3

module.exports = function (config) {
    'use strict';

    config.set({
        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,

        // base path, that will be used to resolve files and exclude
        basePath: './',

        // testing framework to use (jasmine/mocha/qunit/...)
        frameworks: ['jasmine'],

        // list of files / patterns to load in the browser
        files: [
            'bower_components/angular/angular.min.js',
            'bower_components/angular-mocks/angular-mocks.js',
            'src/**/*.js',
            'tests/**/*.js'
        ],

        // list of files / patterns to exclude
        exclude: [],

        // web server port
        port: 8080,

        // Start these browsers, currently available:
        // - Chrome
        // - ChromeCanary
        // - Firefox
        // - Opera
        // - Safari (only Mac)
        // - PhantomJS
        // - IE (only Windows)
        browsers: [
          'PhantomJS'
        ],

        // Which plugins to enable
        plugins: [
          'karma-phantomjs-launcher',
          'karma-jasmine',
          'karma-junit-reporter',
          'karma-story-reporter',
          'karma-coverage'
        ],

        // Continuous Integration mode
        // if true, it capture browsers, run tests and exit
        singleRun: false,

        colors: true,

        // level of logging
        // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
        logLevel: config.LOG_INFO,

        reporters: ['coverage', 'junit', 'story'],

        preprocessors: {
            'js/*.js': ['coverage']
        },

        junitReporter: {
            outputDir: 'test-reports/',
            outputFile: 'karma-results.xml',
            useBrowserName: false
        },

        coverageReporter:
            instrumenterOptions: {
                istanbul: { noCompact: true }
            },
            reporters: [
                { type: 'clover', dir: 'test-reports/', subdir: '.', file: 'clover.xml' },
                { type: 'cobertura', dir: 'test-reports/', subdir: '.', file: 'cobertura.xml' },
                { type: 'html', dir: 'test-reports/', subdir: '.' },
                { type: 'text' },
                { type: 'text-summary' },
                { type: 'lcovonly', dir: 'tests/test-reports/', subdir: '.',  file: 'lcov.info'}
            ]
        }

    });
};
<commit_msg>fixing issue with karma config<commit_after>// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2015-01-06 using
// generator-karma 0.8.3

module.exports = function (config) {
    'use strict';

    config.set({
        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,

        // base path, that will be used to resolve files and exclude
        basePath: './',

        // testing framework to use (jasmine/mocha/qunit/...)
        frameworks: ['jasmine'],

        // list of files / patterns to load in the browser
        files: [
            'bower_components/angular/angular.min.js',
            'bower_components/angular-mocks/angular-mocks.js',
            'src/**/*.js',
            'tests/**/*.js'
        ],

        // list of files / patterns to exclude
        exclude: [],

        // web server port
        port: 8080,

        // Start these browsers, currently available:
        // - Chrome
        // - ChromeCanary
        // - Firefox
        // - Opera
        // - Safari (only Mac)
        // - PhantomJS
        // - IE (only Windows)
        browsers: [
          'PhantomJS'
        ],

        // Which plugins to enable
        plugins: [
          'karma-phantomjs-launcher',
          'karma-jasmine',
          'karma-junit-reporter',
          'karma-story-reporter',
          'karma-coverage'
        ],

        // Continuous Integration mode
        // if true, it capture browsers, run tests and exit
        singleRun: false,

        colors: true,

        // level of logging
        // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
        logLevel: config.LOG_INFO,

        reporters: ['coverage', 'junit', 'story'],

        preprocessors: {
            'js/*.js': ['coverage']
        },

        junitReporter: {
            outputDir: 'test-reports/',
            outputFile: 'karma-results.xml',
            useBrowserName: false
        },

        coverageReporter: {
            instrumenterOptions: {
                istanbul: { noCompact: true }
            },
            reporters: [
                { type: 'clover', dir: 'test-reports/', subdir: '.', file: 'clover.xml' },
                { type: 'cobertura', dir: 'test-reports/', subdir: '.', file: 'cobertura.xml' },
                { type: 'html', dir: 'test-reports/', subdir: '.' },
                { type: 'text' },
                { type: 'text-summary' },
                { type: 'lcovonly', dir: 'tests/test-reports/', subdir: '.',  file: 'lcov.info'}
            ]
        }

    });
};
<|endoftext|>


<commit_before>'use strict';

var fs = require("fs"),
	path = require("path"),
	_ = require('../../util/underscore');

module.exports={
	buildBackendRouter:function(){
		var routes = {};
		for(var uri in this._config.routes){
			var routeConfig = this._config.routes[uri];
			var middlewares = [];
			var uriTmp = uri.split(" ");
			var actionTmp = routeConfig.action.split(".");

			uri = uriTmp[0]+" "+uriTmp[1];

			// ensureDataACLPermission middleware
			if(uri.slice(0,3) == "get"){
				var middleware = "FUNC_START app.openbiz.ensureDataACLPermission('ACCESS')"+" FUNC_END";
				middlewares.push(middleware);
			}else{
				var middleware = "FUNC_START app.openbiz.ensureDataACLPermission('MANAGE')"+" FUNC_END";
				middlewares.push(middleware);
			}

			// ensurePermission middleware
			if(routeConfig.hasOwnProperty('permissions')){
				for(var i=0; i<routeConfig.permissions.length;i++){
					var middleware = "FUNC_START app.openbiz.ensurePermission('"+routeConfig.permissions[i]+"')"+" FUNC_END";
					middlewares.push(middleware);
				}
			}

			// ensureExists middleware
			if(uriTmp[1].indexOf("/:id")!=-1){
				var ensureExists = "FUNC_START app.getController('"+actionTmp[0]+"').ensureExists FUNC_END";
				middlewares.push(ensureExists);
			}

			var middleware = "FUNC_START app.getController('"+actionTmp[0]+"')."+actionTmp[1]+" FUNC_END";
			middlewares.push(middleware);

			routes[uri] = middlewares;
		}

		var data = {
			"ROUTES":JSON.stringify( routes ,null ,"  " )
		}
		var file = path.join(this._config.options.output,"app","modules",this._config.name,"routes.js");
		if(fs.existsSync(file) && this._config.options.override==false) return this;
		var template = _.template(fs.readFileSync(
					path.resolve(__dirname,"../../../templates/module/backend/router/router-template.js")
					,{encoding:'utf-8'}));

		fs.writeFileSync(file, template(data)
					.replace(/"FUNC_START/g,"")
					.replace(/FUNC_END"/g,"")
					, 'utf-8');
		if(this._config.options.verbose) console.log("\tFile "+file.replace(path.dirname(this._config.options.output),"")+" ...... created");
		return this;
	},
	buildFrontendRouter:function(){
		var file = path.join(this._config.options.output,"ui","modules",this._config.name,"router.js");
		if(fs.existsSync(file) && this._config.options.override==false) return this;
		var data = {
			APP_NAME : this._config.app.name,
			APP_URL : this._config.app.url,
			MODULE_NAME: this._config.name,
			ROUTES:[]
		};
		for(var i=0;i<this._config.views.length;i++){
			var PARAMETERS = "";
			var tmp = this._config.views[i].url.match(/(\(\?)?:\w+/g);
			if(tmp !=null){
				PARAMETERS = tmp.join(",").replace(/:/g,"");
			}

			var route = {
				URL:  this._config.views[i].url,
				VIEW_NAME: this._config.views[i].name,
				FUNCTION: "show"+this._config.views[i].name.charAt(0).toUpperCase()+this._config.views[i].name.slice(1),
				PARAMETERS: PARAMETERS
			}
			data.ROUTES.push(route);
		}
		var template = _.template(fs.readFileSync(
					path.resolve(__dirname,"../../../templates/module/frontend/router/router-template.js")
					,{encoding:'utf-8'}));
		fs.writeFileSync(file, template(data), 'utf-8');
		if(this._config.options.verbose) console.log("\tFile "+file.replace(path.dirname(this._config.options.output),"")+" ...... created");
	},
	buildFrontendMain:function(){
		var file = path.join(this._config.options.output,"ui","modules",this._config.name,"main.js");
		if(fs.existsSync(file) && this._config.options.override==false) return this;
		var template = _.template(fs.readFileSync(
					path.resolve(__dirname,"../../../templates/module/frontend/main-template.js")
					,{encoding:'utf-8'}));
		fs.writeFileSync(file, template(), 'utf-8');
		if(this._config.options.verbose) console.log("\tFile "+file.replace(path.dirname(this._config.options.output),"")+" ...... created");
	}
}<commit_msg>update<commit_after>'use strict';

var fs = require("fs"),
	path = require("path"),
	_ = require('../../util/underscore');

module.exports={
	buildBackendRouter:function(){
		var routes = {};
		for(var uri in this._config.routes){
			var routeConfig = this._config.routes[uri];
			var middlewares = [];
			var uriTmp = uri.split(" ");
			var actionTmp = routeConfig.action.split(".");

			uri = uriTmp[0]+" "+uriTmp[1];

			// ensurePermission middleware
			if(routeConfig.hasOwnProperty('permissions')){
				for(var i=0; i<routeConfig.permissions.length;i++){
					var middleware = "FUNC_START app.openbiz.ensurePermission('"+routeConfig.permissions[i]+"')"+" FUNC_END";
					middlewares.push(middleware);
				}
			}

			// ensureExists middleware
			if(uriTmp[1].indexOf("/:id")!=-1){
				var ensureExists = "FUNC_START app.getController('"+actionTmp[0]+"').ensureExists FUNC_END";
				middlewares.push(ensureExists);
				// ensureDataACLPermission middleware
				if(uri.slice(0,3) == "get"){
					var middleware = "FUNC_START app.openbiz.ensureDataACLPermission('ACCESS')"+" FUNC_END";
					middlewares.push(middleware);
				}else{
					var middleware = "FUNC_START app.openbiz.ensureDataACLPermission('MANAGE')"+" FUNC_END";
					middlewares.push(middleware);
				}
			}

			var middleware = "FUNC_START app.getController('"+actionTmp[0]+"')."+actionTmp[1]+" FUNC_END";
			middlewares.push(middleware);

			routes[uri] = middlewares;
		}

		var data = {
			"ROUTES":JSON.stringify( routes ,null ,"  " )
		}
		var file = path.join(this._config.options.output,"app","modules",this._config.name,"routes.js");
		if(fs.existsSync(file) && this._config.options.override==false) return this;
		var template = _.template(fs.readFileSync(
					path.resolve(__dirname,"../../../templates/module/backend/router/router-template.js")
					,{encoding:'utf-8'}));

		fs.writeFileSync(file, template(data)
					.replace(/"FUNC_START/g,"")
					.replace(/FUNC_END"/g,"")
					, 'utf-8');
		if(this._config.options.verbose) console.log("\tFile "+file.replace(path.dirname(this._config.options.output),"")+" ...... created");
		return this;
	},
	buildFrontendRouter:function(){
		var file = path.join(this._config.options.output,"ui","modules",this._config.name,"router.js");
		if(fs.existsSync(file) && this._config.options.override==false) return this;
		var data = {
			APP_NAME : this._config.app.name,
			APP_URL : this._config.app.url,
			MODULE_NAME: this._config.name,
			ROUTES:[]
		};
		for(var i=0;i<this._config.views.length;i++){
			var PARAMETERS = "";
			var tmp = this._config.views[i].url.match(/(\(\?)?:\w+/g);
			if(tmp !=null){
				PARAMETERS = tmp.join(",").replace(/:/g,"");
			}

			var route = {
				URL:  this._config.views[i].url,
				VIEW_NAME: this._config.views[i].name,
				FUNCTION: "show"+this._config.views[i].name.charAt(0).toUpperCase()+this._config.views[i].name.slice(1),
				PARAMETERS: PARAMETERS
			}
			data.ROUTES.push(route);
		}
		var template = _.template(fs.readFileSync(
					path.resolve(__dirname,"../../../templates/module/frontend/router/router-template.js")
					,{encoding:'utf-8'}));
		fs.writeFileSync(file, template(data), 'utf-8');
		if(this._config.options.verbose) console.log("\tFile "+file.replace(path.dirname(this._config.options.output),"")+" ...... created");
	},
	buildFrontendMain:function(){
		var file = path.join(this._config.options.output,"ui","modules",this._config.name,"main.js");
		if(fs.existsSync(file) && this._config.options.override==false) return this;
		var template = _.template(fs.readFileSync(
					path.resolve(__dirname,"../../../templates/module/frontend/main-template.js")
					,{encoding:'utf-8'}));
		fs.writeFileSync(file, template(), 'utf-8');
		if(this._config.options.verbose) console.log("\tFile "+file.replace(path.dirname(this._config.options.output),"")+" ...... created");
	}
}<|endoftext|>


<commit_before>// Karma configuration
// Generated on Wed Apr 23 2014 16:38:49 GMT+0200 (CEST)

module.exports = function (config) {
  config.set({

    // base path, that will be used to resolve files and exclude
    basePath: '',

    // frameworks to use
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      // Src
      'src/**/module.js',
      'src/**/*.js',

      // Test
      'test/unit/**/*.js',

      // Match all templates for nghtml2js
      'src/**/*.html'
    ],

    // list of files to exclude
    exclude: [

    ],

    // test results reporter to use
    // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera (has to be installed with `npm install karma-opera-launcher`)
    // - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
    // - PhantomJS
    // - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
    browsers: ['Chrome'],

    // If browser does not capture in given timeout [ms], kill it
    captureTimeout: 60000,

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false,

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'src/**/*.html': 'ng-html2js'
    },

    ngHtml2JsPreprocessor: {
      stripPrefix: 'src/',
      moduleName: 'templates'
    }
  });
};
<commit_msg>add angular and angular-mocks to karma.conf.js<commit_after>// Karma configuration
// Generated on Wed Apr 23 2014 16:38:49 GMT+0200 (CEST)

module.exports = function (config) {
  config.set({

    // base path, that will be used to resolve files and exclude
    basePath: '',

    // frameworks to use
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'bower_components/angular/angular.js',
      'bower_components/angular-mocks/angular-mocks.js',
      // Src
      'src/**/module.js',
      'src/**/*.js',

      // Test
      'test/unit/**/*.js',

      // Match all templates for nghtml2js
      'src/**/*.html'
    ],

    // list of files to exclude
    exclude: [

    ],

    // test results reporter to use
    // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera (has to be installed with `npm install karma-opera-launcher`)
    // - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
    // - PhantomJS
    // - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
    browsers: ['Chrome'],

    // If browser does not capture in given timeout [ms], kill it
    captureTimeout: 60000,

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false,

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'src/**/*.html': 'ng-html2js'
    },

    ngHtml2JsPreprocessor: {
      stripPrefix: 'src/',
      moduleName: 'templates'
    }
  });
};
<|endoftext|>


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

    angular.module("spotdesk", ["ngMaterial", "ngCookies", "ui.router", "md.data.table"])

        // Main configuration
        .config(["$httpProvider", "$mdThemingProvider",
            function($httpProvider , $mdThemingProvider){
                $httpProvider.interceptors.push("authInterceptor");

                // Theming is not allowed due to CSP
                $mdThemingProvider.theme("default")
                    .primaryPalette("green")
                    .accentPalette("pink");
            }
        ])

        .factory("$adminMessage", ["$mdDialog", function ($mdDialog) {
            var srvc = this;

            srvc.error = function (errorMessage) {
                $mdDialog.show(
                    $mdDialog.alert()
                        .parent(angular.element(document.getElementById("content")))
                        .clickOutsideToClose(true)
                        .title('error')
                        .textContent(errorMessage)
                        .ariaLabel('Error')
                        .ok('OK')
                );
            };

            return srvc;
        }])

        // Authentication service
        .factory("$auth", ["$http", "$cookies", "$state", "$adminMessage", "authInterceptor",
            function ($http, $cookies, $state, $adminMessage, authInterceptor) {
                var srvc = this;

                srvc.persistToken = false;
                srvc.token = null;

                srvc.loggedIn = function() {
                    // Check login status
                    var status = srvc.token !== null;
                    if (status) {
                        return true;
                    }

                    // Check cookie for persisted login status
                    var cookieToken = $cookies.get("spotdesk-authorization");
                    if (cookieToken) {
                        srvc.token = cookieToken;
                        return true;
                    }

                    // No current login
                    return false;
                };

                srvc.updateToken = function (token) {
                    srvc.token = token;
                    if (srvc.persistToken) {
                        $cookies.put("spotdesk-authorization", token);
                    } else {
                        $cookies.remove("spotdesk-authorization");
                    }
                };

                srvc.login = function (username, password, persist) {
                    srvc.persistToken = persist && true;
                    $http.post("/login", {
                        user: username,
                        pass: password
                    }).then(function successCallback() {
                        if (!srvc.loggedIn()) {
                            $adminMessage.error("auth_login_failed");
                        }
                        $state.reload();
                    }, function errorCallback() {
                        $adminMessage.error("auth_login_failed");
                    });
                };

                authInterceptor.$auth = srvc;
                return srvc;
            }
        ])

        // Intercepts all requests to add session token and to capture refreshed session tokens
        .factory("authInterceptor", function () {
            var interceptor = {
                $auth: null,
                request: function (config) {
                    if (!interceptor.$auth || !interceptor.$auth.loggedIn() || config.url[0] !== "/") {
                        return config;
                    }

                    config.headers["SpotDesk-Authorization"] = interceptor.$auth.token;
                    return config;
                },

                response: function (response) {
                    if (interceptor.$auth && response.headers("SpotDesk-Authorization")) {
                        interceptor.$auth.updateToken(response.headers("SpotDesk-Authorization"));
                    }
                    if (response.status === 401) {
                        interceptor.$auth.persistToken = false;
                        interceptor.$auth.updateToken(null);
                    }
                    return response;
                }
            };
            return interceptor;
        })

        // Controller for the entire layout
        .controller("mainController", ["$mdSidenav", "$auth", "$title", "$adminMessage",
            function ($mdSidenav, $auth, $title, $adminMessage) {
                var ctrl = this;

                ctrl.loggedIn = $auth.loggedIn;
                ctrl.user = {
                    name: null,
                    pass: null,
                    persist: false
                };

                ctrl.login = function () {
                    if (!ctrl.user.name || !ctrl.user.pass) {
                        $adminMessage.error("auth_missing_field");
                        return;
                    }

                    $auth.login(ctrl.user.name, ctrl.user.pass, ctrl.user.persist);
                };

                ctrl.showTitle = function () {
                    if ($auth.loggedIn()) {
                        return $title.get();
                    }
                    return "Login";
                };

                ctrl.toggleSideNav = function() {
                    $mdSidenav("left").toggle();
                };
            }
        ]);
})();<commit_msg>Removing leftover comment.<commit_after>(function () {
    "use strict";

    angular.module("spotdesk", ["ngMaterial", "ngCookies", "ui.router", "md.data.table"])

        // Main configuration
        .config(["$httpProvider", "$mdThemingProvider",
            function($httpProvider , $mdThemingProvider){
                $httpProvider.interceptors.push("authInterceptor");

                $mdThemingProvider.theme("default")
                    .primaryPalette("green")
                    .accentPalette("pink");
            }
        ])

        .factory("$adminMessage", ["$mdDialog", function ($mdDialog) {
            var srvc = this;

            srvc.error = function (errorMessage) {
                $mdDialog.show(
                    $mdDialog.alert()
                        .parent(angular.element(document.getElementById("content")))
                        .clickOutsideToClose(true)
                        .title('error')
                        .textContent(errorMessage)
                        .ariaLabel('Error')
                        .ok('OK')
                );
            };

            return srvc;
        }])

        // Authentication service
        .factory("$auth", ["$http", "$cookies", "$state", "$adminMessage", "authInterceptor",
            function ($http, $cookies, $state, $adminMessage, authInterceptor) {
                var srvc = this;

                srvc.persistToken = false;
                srvc.token = null;

                srvc.loggedIn = function() {
                    // Check login status
                    var status = srvc.token !== null;
                    if (status) {
                        return true;
                    }

                    // Check cookie for persisted login status
                    var cookieToken = $cookies.get("spotdesk-authorization");
                    if (cookieToken) {
                        srvc.token = cookieToken;
                        return true;
                    }

                    // No current login
                    return false;
                };

                srvc.updateToken = function (token) {
                    srvc.token = token;
                    if (srvc.persistToken) {
                        $cookies.put("spotdesk-authorization", token);
                    } else {
                        $cookies.remove("spotdesk-authorization");
                    }
                };

                srvc.login = function (username, password, persist) {
                    srvc.persistToken = persist && true;
                    $http.post("/login", {
                        user: username,
                        pass: password
                    }).then(function successCallback() {
                        if (!srvc.loggedIn()) {
                            $adminMessage.error("auth_login_failed");
                        }
                        $state.reload();
                    }, function errorCallback() {
                        $adminMessage.error("auth_login_failed");
                    });
                };

                authInterceptor.$auth = srvc;
                return srvc;
            }
        ])

        // Intercepts all requests to add session token and to capture refreshed session tokens
        .factory("authInterceptor", function () {
            var interceptor = {
                $auth: null,
                request: function (config) {
                    if (!interceptor.$auth || !interceptor.$auth.loggedIn() || config.url[0] !== "/") {
                        return config;
                    }

                    config.headers["SpotDesk-Authorization"] = interceptor.$auth.token;
                    return config;
                },

                response: function (response) {
                    if (interceptor.$auth && response.headers("SpotDesk-Authorization")) {
                        interceptor.$auth.updateToken(response.headers("SpotDesk-Authorization"));
                    }
                    if (response.status === 401) {
                        interceptor.$auth.persistToken = false;
                        interceptor.$auth.updateToken(null);
                    }
                    return response;
                }
            };
            return interceptor;
        })

        // Controller for the entire layout
        .controller("mainController", ["$mdSidenav", "$auth", "$title", "$adminMessage",
            function ($mdSidenav, $auth, $title, $adminMessage) {
                var ctrl = this;

                ctrl.loggedIn = $auth.loggedIn;
                ctrl.user = {
                    name: null,
                    pass: null,
                    persist: false
                };

                ctrl.login = function () {
                    if (!ctrl.user.name || !ctrl.user.pass) {
                        $adminMessage.error("auth_missing_field");
                        return;
                    }

                    $auth.login(ctrl.user.name, ctrl.user.pass, ctrl.user.persist);
                };

                ctrl.showTitle = function () {
                    if ($auth.loggedIn()) {
                        return $title.get();
                    }
                    return "Login";
                };

                ctrl.toggleSideNav = function() {
                    $mdSidenav("left").toggle();
                };
            }
        ]);
})();<|endoftext|>


<commit_before>// Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', 'angular-cli'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-remap-istanbul'),
      require('angular-cli/plugins/karma'),
      require('karma-osx-reporter')
    ],
    files: [
      { pattern: './src/test.ts', watched: false }
    ],
    preprocessors: {
      './src/test.ts': ['angular-cli']
    },
    mime: {
      'text/x-typescript': ['ts','tsx']
    },
    remapIstanbulReporter: {
      reports: {
        html: 'coverage',
        lcovonly: './coverage/coverage.lcov'
      }
    },
    angularCli: {
      config: './angular-cli.json',
      environment: 'dev'
    },
    reporters: config.angularCli && config.angularCli.codeCoverage
              ? ['progress', 'karma-remap-istanbul', 'osx']
              : ['progress', 'osx'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};
<commit_msg>added osx notifications and spec reporter<commit_after>// Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', 'angular-cli'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-remap-istanbul'),
      require('angular-cli/plugins/karma'),
      require('karma-osx-reporter'),
      require('karma-spec-reporter')
    ],
    files: [
      { pattern: './src/test.ts', watched: false }
    ],
    preprocessors: {
      './src/test.ts': ['angular-cli']
    },
    mime: {
      'text/x-typescript': ['ts','tsx']
    },
    remapIstanbulReporter: {
      reports: {
        html: 'coverage',
        lcovonly: './coverage/coverage.lcov'
      }
    },
    angularCli: {
      config: './angular-cli.json',
      environment: 'dev'
    },
    reporters: config.angularCli && config.angularCli.codeCoverage
              ? ['spec', 'karma-remap-istanbul', 'osx']
              : ['spec', 'osx'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};
<|endoftext|>


<commit_before>(function(C2C, $) {

  // Mountain wilderness contest stuff
  var mw_contest_associate = $('#mw_contest_associate');

  function mw_associate() {
    var indicator = $('#indicator');

    indicator.show();
    $.post('/documents/addAssociation/main_id/' + $('#id').val() +
           '/document_module/articles/document_id/' + C2C.mw_contest_article_id
    ).always(function() {
      indicator.hide();
    }).fail(function(data) {
      mw_contest_associate.prop('checked', false);
      C2C.showFailure();
    });
  }

  function mw_de_associate() {
    var indicator = $('#indicator');

    indicator.show();
    $.post('/documents/removeAssociation/main_oc_id/' + $('#id').val() +
           '/linked_id/' + C2C.mw_contest_article_id + '/type/oc/strict/1'
    ).always(function() {
      indicator.hide();
    }).done(function(data) {
      mw_contest_associate.prop('checked', false);
    }).fail(function() {
      mw_contest_associate.prop('checked', true);
      C2C.showFailure();
    });
  }

  function switch_mw_contest_visibility() {
    var mw_contest = $('#mw_contest');

    if (mw_contest.length) {
      if ($('#outing_with_public_transportation').is(':checked')) {
        mw_contest.show();
      } else {
        // hide mw div, uncheck contest checkbox
        mw_contest.hide();

        if (!$('#pseudo_id').length && mw_contest_associate.is(':checked')) {
          // de-associated
          mw_de_associate();
        }
      }
    }
  }

  function switch_mw_contest_association() {
    if (!$('#pseudo_id').length) {
      if (mw_contest_associate.is(':checked')) {
        // associate
        mw_associate();
      } else {
        // de-associated
        mw_de_associate();
      }
    }
  }

  // be sure to hide fields on startup if needed
  switch_mw_contest_visibility();

  // register events
  $('#outing_with_public_transportation').on('change', switch_mw_contest_visibility);
  mw_contest_associate.on('change', switch_mw_contest_association);

})(window.C2C = window.C2C || {}, jQuery);
<commit_msg>document type must be properly specified<commit_after>(function(C2C, $) {

  // Mountain wilderness contest stuff
  var mw_contest_associate = $('#mw_contest_associate');

  function mw_associate() {
    var indicator = $('#indicator');

    indicator.show();
    $.post('/outings/addAssociation/main_id/' + $('#id').val() +
           '/document_module/articles/document_id/' + C2C.mw_contest_article_id
    ).always(function() {
      indicator.hide();
    }).fail(function(data) {
      mw_contest_associate.prop('checked', false);
      C2C.showFailure();
    });
  }

  function mw_de_associate() {
    var indicator = $('#indicator');

    indicator.show();
    $.post('/outings/removeAssociation/main_oc_id/' + $('#id').val() +
           '/linked_id/' + C2C.mw_contest_article_id + '/type/oc/strict/1'
    ).always(function() {
      indicator.hide();
    }).done(function(data) {
      mw_contest_associate.prop('checked', false);
    }).fail(function() {
      mw_contest_associate.prop('checked', true);
      C2C.showFailure();
    });
  }

  function switch_mw_contest_visibility() {
    var mw_contest = $('#mw_contest');

    if (mw_contest.length) {
      if ($('#outing_with_public_transportation').is(':checked')) {
        mw_contest.show();
      } else {
        // hide mw div, uncheck contest checkbox
        mw_contest.hide();

        if (!$('#pseudo_id').length && mw_contest_associate.is(':checked')) {
          // de-associated
          mw_de_associate();
        }
      }
    }
  }

  function switch_mw_contest_association() {
    if (!$('#pseudo_id').length) {
      if (mw_contest_associate.is(':checked')) {
        // associate
        mw_associate();
      } else {
        // de-associated
        mw_de_associate();
      }
    }
  }

  // be sure to hide fields on startup if needed
  switch_mw_contest_visibility();

  // register events
  $('#outing_with_public_transportation').on('change', switch_mw_contest_visibility);
  mw_contest_associate.on('change', switch_mw_contest_association);

})(window.C2C = window.C2C || {}, jQuery);
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Mon Jan 25 2016 10:09:26 GMT+0000 (GMT Standard Time)

module.exports = function(config) {
  var cfg = {

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'lib/components/angular/angular.js',
      'lib/components/angular-mocks/angular-mocks.js',
      'js/app.ctrl.js',
      'js/*.js',
      'tests/*.spec.js'
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'js/*.js': ['coverage']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress', 'coverage'],

    coverageReporter: {
      type : 'html',
      dir : 'node_modules/coverage/'
    },

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Firefox'],

    customLaunchers: {
        Chrome_travis_ci: {
            base: 'Chrome',
            flags: ['--no-sandbox']
        }
    },

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  };

  //Uncomment to use Chromium for the tests on TravisCI.
  // if (process.env.TRAVIS) {
  //     cfg.browsers = ['Chrome_travis_ci'];
  // }

  config.set(cfg);
};
<commit_msg>Update Karma dependencies so the main module can be tested<commit_after>// Karma configuration
// Generated on Mon Jan 25 2016 10:09:26 GMT+0000 (GMT Standard Time)

module.exports = function(config) {
  var cfg = {

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'lib/components/angular/angular.js',
      'lib/components/angular-mocks/angular-mocks.js',

      'lib/components/angular-highlightjs/build/angular-highlightjs.min.js',
      'lib/components/angular-bootstrap/ui-bootstrap-tpls.min.js',
      'lib/components/angular-smart-table/dist/smart-table.min.js',
      'lib/components/angular-bootstrap-file-field/dist/angular-bootstrap-file-field.min.js',
      'lib/components/angular-animate/angular-animate.min.js',
      'lib/components/AngularJS-Toaster/toaster.min.js',
      'lib/components/angulartics/dist/angulartics.min.js',
      'lib/components/angulartics-google-analytics/dist/angulartics-google-analytics.min.js',

      'js/app.ctrl.js',
      'js/*.js',
      'tests/*.spec.js'
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'js/*.js': ['coverage']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress', 'coverage'],

    coverageReporter: {
      type : 'html',
      dir : 'node_modules/coverage/'
    },

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Firefox'],

    customLaunchers: {
        Chrome_travis_ci: {
            base: 'Chrome',
            flags: ['--no-sandbox']
        }
    },

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  };

  //Uncomment to use Chromium for the tests on TravisCI.
  // if (process.env.TRAVIS) {
  //     cfg.browsers = ['Chrome_travis_ci'];
  // }

  config.set(cfg);
};
<|endoftext|>


<commit_before>// http 服务器
var httpServer = function (req, res, next) {
    if (req.url.indexOf('/api/test/upload/ok') > -1) {

        res.end(JSON.stringify({
            code: 200
        }));

    } else {
        next();
    }
};

var files = [
    {
        pattern: 'lib/**/*.js',
        included: false
    },
    {
        pattern: 'src/**/*',
        included: false
    },
    {
        pattern: 'test/**/*.js',
        included: false
    },
    'lib/requirejs/config.js',
    // 加载初始化视图测试
    'karma.conf.require.js'
];

if (process.argv.slice(-1)[0].match(/--test\=(.*)$/)) {
    files[2].pattern = 'test/' + RegExp.$1;
}

// Karma configuration
// Generated on Sun Jan 24 2016 23:22:35 GMT+0800 (CST)
module.exports = function (config) {
    config.set({
        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',
        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: [
            'jasmine',
            'requirejs'
        ],
        // list of files / patterns to load in the browser
        files: files,
        // list of files to exclude
        exclude: [],
        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            'src/**/*.js': 'coverage'
        },

        coverageReporter: {
            // specify a common output directory
            dir: '.',
            reporters: [
                // { type: 'html', subdir: 'report-html' },
                {
                    type: 'lcov',
                    subdir: 'coverage'
                },
                {
                    type: 'text-summary'
                }
            ]
        },
        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: [
            'progress',
            // 'coverage'
        ],
        // web server port
        port: 9876,
        // enable / disable colors in the output (reporters and logs)
        colors: true,
        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,
        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,
        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: [
            'PhantomJS'
        ],
        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: true,
        // Concurrency level
        // how many browser should be started simultaneous
        concurrency: Infinity,

        middleware: ['httpServer'],
         // plugins
        plugins: ['karma-*', {
            'middleware:httpServer': [
                'factory', function () {
                    return httpServer;
                }
            ]
        }]
    });
};
<commit_msg>update: 添加测试提示<commit_after>// http 服务器
var httpServer = function (req, res, next) {
    if (req.url.indexOf('/api/test/upload/ok') > -1) {

        res.end(JSON.stringify({
            code: 200
        }));

    } else {
        next();
    }
};

var files = [
    {
        pattern: 'lib/**/*.js',
        included: false
    },
    {
        pattern: 'src/**/*',
        included: false
    },
    {
        pattern: 'test/**/*.js',
        included: false
    },
    'lib/requirejs/config.js',
    // 加载初始化视图测试
    'karma.conf.require.js'
];

if (process.argv.slice(-1)[0].match(/--test\=(.*)$/)) {
    files[2].pattern = 'test/' + RegExp.$1;
    console.log([
        '============',
        '开始测试：' + files[2].pattern,
        '============'
    ].join('\n'));
}

// Karma configuration
// Generated on Sun Jan 24 2016 23:22:35 GMT+0800 (CST)
module.exports = function (config) {
    config.set({
        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',
        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: [
            'jasmine',
            'requirejs'
        ],
        // list of files / patterns to load in the browser
        files: files,
        // list of files to exclude
        exclude: [],
        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            'src/**/*.js': 'coverage'
        },

        coverageReporter: {
            // specify a common output directory
            dir: '.',
            reporters: [
                // { type: 'html', subdir: 'report-html' },
                {
                    type: 'lcov',
                    subdir: 'coverage'
                },
                {
                    type: 'text-summary'
                }
            ]
        },
        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: [
            'progress',
            // 'coverage'
        ],
        // web server port
        port: 9876,
        // enable / disable colors in the output (reporters and logs)
        colors: true,
        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,
        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,
        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: [
            'PhantomJS'
        ],
        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: true,
        // Concurrency level
        // how many browser should be started simultaneous
        concurrency: Infinity,

        middleware: ['httpServer'],
         // plugins
        plugins: ['karma-*', {
            'middleware:httpServer': [
                'factory', function () {
                    return httpServer;
                }
            ]
        }]
    });
};
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Mon Mar 20 2017 15:06:42 GMT+0100 (CET)

const angular = require('rollup-plugin-angular');
const commonjs = require('rollup-plugin-commonjs');
const html = require('rollup-plugin-html');
const nodeResolve = require('rollup-plugin-node-resolve');
const typescript = require('rollup-plugin-typescript');

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'test/*.ts',
      'src/*.spec.ts'
    ],

    plugins: [
      require('karma-chrome-launcher'),
      require('karma-coverage'),
      require('karma-rollup-preprocessor'),
      require('karma-jasmine'),
      require('karma-typescript')
    ],

    // list of files to exclude
    exclude: [],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'test/*.ts': ['rollup'],
      'src/*.spec.ts': ['rollup'],
    },

    rollupPreprocessor: {
      context: 'this',
      // will help to prevent conflicts between different tests entries
      moduleName: 'ngxmarkdown',
      format: 'iife',
      sourceMap: false,
      // rollup settings. See Rollup documentation
      plugins: [
        angular(),
        commonjs(),
        nodeResolve({
          // use "es2015" field for ES2015 modules with ES2015 code,
          // if possible
          es2015: true, // Default: false

          // use "module" field for ES2015 modules with ES5 code,
          // if possible
          module: true, // Default: true

          // use "jsnext:main" if possible
          // – see https://github.com/rollup/rollup/wiki/jsnext:main
          jsnext: true,  // Default: false

          // use "main" field or index.js, even if it's not an ES6 module
          // (needs to be converted from CommonJS to ES6
          // – see https://github.com/rollup/rollup-plugin-commonjs
          main: true,  // Default: true

          extensions: [ '.js', '.json', '.ts' ]
        }),
        typescript({
          typescript: require('./node_modules/typescript')
        })
      ]
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    mime: {
      'text/x-typescript': ['ts','tsx']
    },

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
}
<commit_msg>test: remove ts extension<commit_after>// Karma configuration
// Generated on Mon Mar 20 2017 15:06:42 GMT+0100 (CET)

const angular = require('rollup-plugin-angular');
const commonjs = require('rollup-plugin-commonjs');
const html = require('rollup-plugin-html');
const nodeResolve = require('rollup-plugin-node-resolve');
const typescript = require('rollup-plugin-typescript');

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'test/*.ts',
      'src/*.spec.ts'
    ],

    plugins: [
      require('karma-chrome-launcher'),
      require('karma-coverage'),
      require('karma-rollup-preprocessor'),
      require('karma-jasmine'),
      require('karma-typescript')
    ],

    // list of files to exclude
    exclude: [],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'test/*.ts': ['rollup'],
      'src/*.spec.ts': ['rollup'],
    },

    rollupPreprocessor: {
      context: 'this',
      // will help to prevent conflicts between different tests entries
      moduleName: 'ngxmarkdown',
      format: 'iife',
      sourceMap: false,
      // rollup settings. See Rollup documentation
      plugins: [
        angular(),
        commonjs(),
        nodeResolve({
          // use "es2015" field for ES2015 modules with ES2015 code,
          // if possible
          es2015: true, // Default: false

          // use "module" field for ES2015 modules with ES5 code,
          // if possible
          module: true, // Default: true

          // use "jsnext:main" if possible
          // – see https://github.com/rollup/rollup/wiki/jsnext:main
          jsnext: true,  // Default: false

          // use "main" field or index.js, even if it's not an ES6 module
          // (needs to be converted from CommonJS to ES6
          // – see https://github.com/rollup/rollup-plugin-commonjs
          main: true,  // Default: true

          extensions: [ '.js', '.json' ]
        }),
        typescript({
          typescript: require('./node_modules/typescript')
        })
      ]
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    mime: {
      'text/x-typescript': ['ts','tsx']
    },

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
}
<|endoftext|>


<commit_before>'use strict';

module.exports = function(config) {
    config.set({

        // base path, that will be used to resolve files and exclude
        basePath: '',

        // frameworks to use
        frameworks: ['jasmine-jquery', 'browserify', 'jasmine'],

        // list of files / patterns to load in the browser
        // NOTE: do NOT include jasmine here because grunt-karma already does
        files: ['client/src/js/vendor.js', 'client/spec/**/*spec.js'],

        // list of files to exclude
        exclude: [

        ],

        // test results reporter to use
        // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
        reporters: ['spec'],

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,

        // Start these browsers, currently available:
        // - Chrome
        // - ChromeCanary
        // - Firefox
        // - Opera (has to be installed with `npm install karma-opera-launcher`)
        // - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
        // - PhantomJS
        // - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
        browsers: ['PhantomJS'],

        // If browser does not capture in given timeout [ms], kill it
        captureTimeout: 60000,

        // Continuous Integration mode
        // if true, it capture browsers, run tests and exit
        singleRun: true,

        // Browserify

        preprocessors: {
          'client/spec/**/*spec.js': ['browserify'],
          'client/src/js/vendor.js': ['browserify']
        },

        browserify: {
          debug: true,
          transform: ['hbsfy']
        }

    });
};
<commit_msg>Maybe this will fix the build?<commit_after>'use strict';

module.exports = function(config) {
    config.set({

        // base path, that will be used to resolve files and exclude
        basePath: '',

        // frameworks to use
        frameworks: ['jasmine-jquery', 'browserify', 'jasmine'],

        // list of files / patterns to load in the browser
        // NOTE: do NOT include jasmine here because grunt-karma already does
        files: ['client/src/js/vendor.js', 'client/spec/**/*spec.js'],

        // list of files to exclude
        exclude: [

        ],

        // test results reporter to use
        // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
        reporters: ['spec'],

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,

        // Start these browsers, currently available:
        // - Chrome
        // - ChromeCanary
        // - Firefox
        // - Opera (has to be installed with `npm install karma-opera-launcher`)
        // - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
        // - PhantomJS
        // - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
        browsers: ['PhantomJS'],

        // If browser does not capture in given timeout [ms], kill it
        captureTimeout: 60000,

        // Continuous Integration mode
        // if true, it capture browsers, run tests and exit
        singleRun: true,

        // Browserify

        preprocessors: {
          'client/spec/**/*spec.js': ['browserify'],
          'client/src/js/vendor.js': ['browserify']
        },

        browserify: {
          debug: true,
          transform: ['hbsfy']
        },

        plugins: [
          'karma-phantomjs-launcher',
          'karma-jasmine-jquery',
          'karma-jasmine'
        ]

    });
};
<|endoftext|>


<commit_before>module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine'],
    files: [
      'test/**/*.spec.js'
    ],
    exclude: [],
    preprocessors: {
      'test/**/*.spec.js': ['webpack']
    },
    webpack: {
      module: {
        loaders: [
          {test: /\.js$/, loaders: ['babel'], exclude: /node_modules/}
        ]
      }
    },
    reporters: ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['PhantomJS'],
    singleRun: false
  });
};
<commit_msg>fix karma config<commit_after>module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine'],
    files: [
      'test/**/*.spec.js'
    ],
    exclude: [],
    preprocessors: {
      'test/**/*.spec.js': ['webpack']
    },
    webpack: {
      module: {
        loaders: [
          {test: /\.js$/, loaders: ['babel'], exclude: /node_modules/}
        ]
      }
    },
    reporters: ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};
<|endoftext|>


<commit_before>// This config is used in both the
// frontend as well as the web server.

// see https://github.com/askmike/gekko/blob/stable/docs/installing_gekko_on_a_server.md

const CONFIG = {
  headless: true,
  api: {
    host: '127.0.0.1',
    port: 3000,
    timeout: 120000 // 2 minutes
  },
  ui: {
    ssl: true,
    host: 'v22017105055054583.bestsrv.de',
    port: 443,
    path: '/'
  },
  adapter: 'sqlite'
}

if (typeof window === 'undefined')
  module.exports = CONFIG;
else
  window.CONFIG = CONFIG;<commit_msg>Update UIconfig.js<commit_after>// This config is used in both the
// frontend as well as the web server.

// see https://github.com/askmike/gekko/blob/stable/docs/installing_gekko_on_a_server.md

const CONFIG = {
  headless: true,
  api: {
    host: '127.0.0.1',
    port: 8080,
    timeout: 120000 // 2 minutes
  },
  ui: {
    ssl: false,
        host: 'http://gekko-gekko.1d35.starter-us-east-1.openshiftapps.com', // Set this to the IP of the machine that will run Gekko
        port: 8080,
        path: '/'
  },
  adapter: 'sqlite'
}

if (typeof window === 'undefined')
  module.exports = CONFIG;
else
  window.CONFIG = CONFIG;
<|endoftext|>


<commit_before>var page = {
    attr: {},
    view: {},
    event: {},
    model: {}
};

// 滚动条的位置大于该比例
page.attr.autoLoadRatio = 0.9;
// 是否已经没有图片了
page.attr.picEnd = false;
page.attr.lastPictureId = 1;
// 本次异步加载的图片的加载状态，0表示全部加载完成
page.attr.picLoadStatus = 0;
// 同一段时间只能加载一次列表
page.attr.picListOneLoad = true;
// 上下文菜单出现的时候，滚动条位置
page.attr.scrollTopForContextMenu = 0;

// 初始化上下文菜单
page.view.initContextMenu = function () {
    var contextMenu = document.getElementById('contextMenu');
    var menuItems = contextMenu.children;
    for (var i in menuItems) {
        menuItems[i].onclick = page.event.onMenuClick;
    }
}

// 取消上下文菜单
page.view.cleanContextMenu = function () {
    document.getElementById('contextMenu').style.display = 'none';
}

page.view.addPicture = function (limit, startId) {
    var url = '/controller/getPictures?limit=';
    if (limit) {
        url += limit;
    }
    if (startId || startId == 0) {
        url += '&startId=' + startId;
    }

    page.model.getJSON(url, function (data) {
        if (data.status == 0) {
            var pictures = data.pictures;
            var display = document.getElementById('display');
            page.attr.picLoadStatus = pictures.length;
            for (var i in pictures) {
                display.appendChild(page.view.createImage(pictures[i]));
            }
            page.attr.lastPictureId = pictures.pop().id;
            page.attr.picListOneLoad = true;
        } else if (data.status == 1) {
            page.attr.picEnd = true;
        }
    });
};

page.view.createImage = function (pic) {
    var src = pic.file;
    var img = document.createElement('img');
    // 设置事件
    img.onload = page.event.onPictureLoad;
    img.onerror = page.event.onPictureLoad;
    img.oncontextmenu = page.event.onRightClick;
    img.onclick = page.view.cleanContextMenu;

    // 设置属性
    img.setAttribute('src', src);
    var title = pic.laud + '赞，' + pic.tread + '踩';
    img.setAttribute('title', title);
    img.setAttribute('name', pic.id);

    return img;
}

page.event.onPageLoad = function () {
    // 设置dispaly的minHeight
    //var minHeight = document.documentElement.clientHeight - document.getElementById('header').offsetHeight - document.getElementById('buttom').offsetHeight;
    var minHeight = document.documentElement.clientHeight - document.getElementById('buttom').offsetHeight;
    if (minHeight < 0) {
        minHeight = 0;
    }
    document.getElementById('display').style.minHeight = minHeight + 'px';

    page.view.initContextMenu();

    page.view.addPicture(10);

    window.onscroll = function (e) {
        page.event.onNearEnd(e);
        page.event.onScrollChange(e);
    }
};

page.event.onNearEnd = function () {
    var top = document.body.scrollTop;
    var height = document.body.offsetHeight - window.innerHeight;
    // 同一时刻只能加载一次列表
    if (!page.attr.picListOneLoad) {
        return;
    }

    // 满足大于指定的比例，还有图片可以加载，上次图片已经加载完成
    if (top / height > page.attr.autoLoadRatio && !page.attr.picEnd && !page.attr.picLoadStatus) {
        page.attr.picListOneLoad = false;
        page.view.addPicture(10, page.attr.lastPictureId - 1);
    }
};

page.event.onRightClick = function (e) {
    page.attr.clickedImg = this;
    var contextMenu = document.getElementById('contextMenu');
    contextMenu.style.left = (5 + e.x) + 'px';
    contextMenu.style.top = (2 + e.y) + 'px';
    contextMenu.style.display = 'block';

    page.attr.scrollTopForContextMenu = document.body.scrollTop;

    return false;
};

page.event.onMenuClick = function (e) {
    alert(this.getAttribute('do') + '-' + page.attr.clickedImg.getAttribute('name'));

}

page.event.onPictureLoad = function () {
    page.attr.picLoadStatus--;
    console.log('page.attr.picLoadStatus ' + page.attr.picLoadStatus);
};

page.event.onScrollChange = function () {
    var scrollTop = document.body.scrollTop;

    if (Math.abs(page.attr.scrollTopForContextMenu - scrollTop) > 10) {
        page.view.cleanContextMenu();
    }

}

page.model.getJSON = function (url, succ, fail) {
    var ajax = null;
    if (window.XMLHttpRequest) {
        ajax = new XMLHttpRequest();
    } else {
        ajax = new ActiveXObject('Microsoft.XMLHTTP');
    }

    ajax.open('GET', url, true);
    ajax.onreadystatechange = function () {
        if (ajax.readyState == 4) {
            if (ajax.status == 200) {
                succ(JSON.parse(ajax.responseText));
            } else {
                if (faild) {
                    faild(ajax.status);
                }
            }
        }
    };
    ajax.send();
};

window.onload = function () {
    page.event.onPageLoad();
};<commit_msg>修复点击图片外无法取消上下文菜单的问题<commit_after>var page = {
    attr: {},
    view: {},
    event: {},
    model: {}
};

// 滚动条的位置大于该比例
page.attr.autoLoadRatio = 0.9;
// 是否已经没有图片了
page.attr.picEnd = false;
page.attr.lastPictureId = 1;
// 本次异步加载的图片的加载状态，0表示全部加载完成
page.attr.picLoadStatus = 0;
// 同一段时间只能加载一次列表
page.attr.picListOneLoad = true;
// 上下文菜单出现的时候，滚动条位置
page.attr.scrollTopForContextMenu = 0;

// 初始化上下文菜单
page.view.initContextMenu = function () {
    var contextMenu = document.getElementById('contextMenu');
    var menuItems = contextMenu.children;
    for (var i in menuItems) {
        menuItems[i].onclick = page.event.onMenuClick;
    }
}

// 取消上下文菜单
page.view.cleanContextMenu = function () {
    document.getElementById('contextMenu').style.display = 'none';
}

page.view.addPicture = function (limit, startId) {
    var url = '/controller/getPictures?limit=';
    if (limit) {
        url += limit;
    }
    if (startId || startId == 0) {
        url += '&startId=' + startId;
    }

    page.model.getJSON(url, function (data) {
        if (data.status == 0) {
            var pictures = data.pictures;
            var display = document.getElementById('display');
            page.attr.picLoadStatus = pictures.length;
            for (var i in pictures) {
                display.appendChild(page.view.createImage(pictures[i]));
            }
            page.attr.lastPictureId = pictures.pop().id;
            page.attr.picListOneLoad = true;
        } else if (data.status == 1) {
            page.attr.picEnd = true;
        }
    });
};

page.view.createImage = function (pic) {
    var src = pic.file;
    var img = document.createElement('img');
    // 设置事件
    img.onload = page.event.onPictureLoad;
    img.onerror = page.event.onPictureLoad;
    img.oncontextmenu = page.event.onRightClick;

    // 设置属性
    img.setAttribute('src', src);
    var title = pic.laud + '赞，' + pic.tread + '踩';
    img.setAttribute('title', title);
    img.setAttribute('name', pic.id);

    return img;
}

page.event.onPageLoad = function () {
    // 设置dispaly的minHeight
    //var minHeight = document.documentElement.clientHeight - document.getElementById('header').offsetHeight - document.getElementById('buttom').offsetHeight;
    var minHeight = document.documentElement.clientHeight - document.getElementById('buttom').offsetHeight;
    if (minHeight < 0) {
        minHeight = 0;
    }
    document.getElementById('display').style.minHeight = minHeight + 'px';

    page.view.initContextMenu();

    page.view.addPicture(10);

    window.onscroll = function (e) {
        page.event.onNearEnd(e);
        page.event.onScrollChange(e);
    };
    document.body.onclick = page.view.cleanContextMenu;
};

page.event.onNearEnd = function () {
    var top = document.body.scrollTop;
    var height = document.body.offsetHeight - window.innerHeight;
    // 同一时刻只能加载一次列表
    if (!page.attr.picListOneLoad) {
        return;
    }

    // 满足大于指定的比例，还有图片可以加载，上次图片已经加载完成
    if (top / height > page.attr.autoLoadRatio && !page.attr.picEnd && !page.attr.picLoadStatus) {
        page.attr.picListOneLoad = false;
        page.view.addPicture(10, page.attr.lastPictureId - 1);
    }
};

page.event.onRightClick = function (e) {
    page.attr.clickedImg = this;
    var contextMenu = document.getElementById('contextMenu');
    contextMenu.style.left = (5 + e.x) + 'px';
    contextMenu.style.top = (2 + e.y) + 'px';
    contextMenu.style.display = 'block';

    page.attr.scrollTopForContextMenu = document.body.scrollTop;

    return false;
};

page.event.onMenuClick = function (e) {
    alert(this.getAttribute('do') + '-' + page.attr.clickedImg.getAttribute('name'));

}

page.event.onPictureLoad = function () {
    page.attr.picLoadStatus--;
    console.log('page.attr.picLoadStatus ' + page.attr.picLoadStatus);
};

page.event.onScrollChange = function () {
    var scrollTop = document.body.scrollTop;

    if (Math.abs(page.attr.scrollTopForContextMenu - scrollTop) > 10) {
        page.view.cleanContextMenu();
    }

}

page.model.getJSON = function (url, succ, fail) {
    var ajax = null;
    if (window.XMLHttpRequest) {
        ajax = new XMLHttpRequest();
    } else {
        ajax = new ActiveXObject('Microsoft.XMLHTTP');
    }

    ajax.open('GET', url, true);
    ajax.onreadystatechange = function () {
        if (ajax.readyState == 4) {
            if (ajax.status == 200) {
                succ(JSON.parse(ajax.responseText));
            } else {
                if (faild) {
                    faild(ajax.status);
                }
            }
        }
    };
    ajax.send();
};

window.onload = function () {
    page.event.onPageLoad();
};<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 *  WSO2 Inc. 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.
 */

/**
 * This file includes javascript functions that can be used for form input validation.
 * This file expects dialog/js/dialog.js to be included while including this script.
 */

/**
 * Returns the regular expression for the provided pattern key.
 * If no regex is defined for the provided input returns the provided input as a regex
 *
 * @param pattern regex pattern key or undefined regex as a string
 */
function getPattern(pattern) {
    var regex;
    switch (pattern) {
        case "digits-only":
            regex = /^[0-9]+/;
            break;
        case "alphabetic-only":
            regex = /^[a-zA-Z]+/;
            break;
        case "alphanumerics-only":
            regex = /^[a-zA-Z0-9]+/;
            break;
        case "url":
            regex = /^(([^:/?#]+):)?(([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
            break;
        case "email":
            regex = /^(.+)@(.+)$/;
            break;
        case "whitespace-exists":
            regex = /.*\s+.*/;
            break;
        case "uri-reserved-exists":
            regex = /.*[:/\?#\[\]@!\$&'\(\)\*\+,;=]+.*/;
            break;
        case "uri-unsafe-exists":
            regex = /.*[<>%\{\}\|\^~\[\]`]+.*/;
            break;
        case "html-meta-exists":
            regex = /.*[&<>"'/]+.*/;
            break;
        case "xml-meta-exists":
            regex = /.*[&<>"']+.*/;
            break;
        case "http-url":
            regex = /^(http:)([^/?#])?(:)?(([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
            break;
        case "https-url":
            regex = /^(https:)([^/?#])?(:)?(([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
            break;
        case "ftp-url":
            regex = /^(ftp:)([^/?#])?(:)?(([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
            break;
        default:
            regex = new RegExp(pattern);
            break;
    }

    return regex;
}

/**
 * Checks if the provided input value is valid against the given white list pattern array
 *
 * @param input input value
 * @param whiteListPatterns white list pattern array
 * @returns {boolean} true if input value is valid
 */
function isWhiteListed(input, whiteListPatterns) {

    var isValid = false;
    var pattern;
    var whiteListPatternsArray = whiteListPatterns.toString().split(',');
    for (var i = 0; i < whiteListPatternsArray.length; i++) {
        pattern = getPattern(whiteListPatternsArray[i]);
        isValid = pattern.test(input);
        if (isValid) {
            break;
        }
    }

    return isValid;
}

/**
 * Checks if the provided input value is valid against the given black list pattern array
 *
 * @param input input value
 * @param blackListPatterns black list pattern array
 * @returns {boolean} true if input value is valid
 */
function isNotBlackListed(input, blackListPatterns) {

    var isValid = false;
    var pattern;
    for (var i = 0; i < blackListPatterns.length; i++) {
        pattern = getPattern(blackListPatterns[i]);
        isValid = !pattern.test(input);

        if (!isValid) {
            break;
        }
    }

    return isValid;
}

/**
 * Returns a comma separated string of patterns given by the patterns array
 *
 * @param patterns
 * @returns {string}
 */
function getPatternString(patterns) {

    var patternString = "";
    for (var i = 0; i < patterns.length; i++) {
        patternString += getPattern(patterns[i]).toString();
        if ((patterns.length - 1) != i) {
            patternString += ", ";
        }
    }

    return patternString;
}

/**
 * Extracts the given validator object and show the confirmation dialog.
 * Expects handleYes, handleNo, closeCallback as specified in dialog.js
 * @param validationObj validator object
 * @param msg   custom message
 * @param handleYes function to be called upon user clicking yes
 * @param handleNo  function to be called upon user clicking no
 * @param closeCallback
 * @returns {boolean} true if object contains isValid = true
 */
function isValidConfirmationDialog(validationObj, msg, handleYes, handleNo, closeCallback){
    if (validationObj['isValid'] === true) {
        return true;
    }

    var label = validationObj['label'];
    var whiteListPatterns = validationObj['whiteListPatterns'];
    var blackListPatterns = validationObj['blackListPatterns'];

    var message = msg.replace('{0}', label).replace('{1}', whiteListPatterns === "" ? 'NONE' : whiteListPatterns)
        .replace('{2}', blackListPatterns === "" ? 'NONE' : blackListPatterns);

    CARBON.showConfirmationDialog(message, handleYes, handleNo, closeCallback);
    return false;
}
/**
 * Extracts the given validator object
 *
 * @param validationObj validator object
 * @param msg custom message
 * @returns {boolean} true if object contains isValid = true
 */
function isValid(validationObj, msg) {

    if (validationObj['isValid'] === true) {
        return true;
    }

    var label = validationObj['label'];
    var whiteListPatterns = validationObj['whiteListPatterns'];
    var blackListPatterns = validationObj['blackListPatterns'];

    var message = msg.replace('{0}', label).replace('{1}', whiteListPatterns === "" ? 'NONE' : whiteListPatterns)
        .replace('{2}', blackListPatterns === "" ? 'NONE' : blackListPatterns);

    CARBON.showErrorDialog(message);
    return false;
}

/**
 * Validates the given input element against white list or black list patterns
 *
 * @param inputElement input element to be evaluated
 * @returns {{isValid: boolean, label: string, whiteListPatterns: string, blackListPatterns: string}}
 */
function validateInput(inputElement) {

    var value = inputElement.value;

    var whiteListPatternString = "";
    var blackListPatternString = "";
    var labelString = "";

    if (value != null && value != 'null') {
        var whiteListPatterns = inputElement.getAttribute('white-list-patterns');
        var blackListPatterns = inputElement.getAttribute('black-list-patterns');

        if ((whiteListPatterns === null || whiteListPatterns === "") &&
            (blackListPatterns === null || blackListPatterns === "")) {
            return {
                isValid: true,
                label: labelString,
                whiteListPatterns: whiteListPatternString,
                blackListPatterns: blackListPatternString
            };
        }

        var isValid = false;
        var whiteListed = false;
        var notBlackListed = false;
        var whiteListPatternsProvided = false;
        var blackListPatternsProvided = false;

        if (whiteListPatterns != null && whiteListPatterns != "") {
            whiteListPatternsProvided = true;
            var patternArray = whiteListPatterns.split(' ');
            whiteListed = isWhiteListed(value, patternArray);
            whiteListPatternString = getPatternString(patternArray);
        }

        if (blackListPatterns != null && blackListPatterns != "") {
            blackListPatternsProvided = true;
            var patternArray = blackListPatterns.split(' ');
            notBlackListed = isNotBlackListed(value, patternArray);
            blackListPatternString = getPatternString(patternArray);
        }

        if (whiteListPatternsProvided && blackListPatternsProvided) {
            isValid = whiteListed || notBlackListed;
        } else if (whiteListPatternsProvided) {
            isValid = whiteListed;
        } else if (blackListPatternsProvided) {
            isValid = notBlackListed;
        }

        if (isValid === true) {
            return {
                isValid: true,
                label: labelString,
                whiteListPatterns: whiteListPatternString,
                blackListPatterns: blackListPatternString
            };
        } else {
            labelString = inputElement.getAttribute('label');
            if (labelString == null || labelString == "") {
                labelString = inputElement.getAttribute('name');
            }
            return {
                isValid: false,
                label: labelString,
                whiteListPatterns: whiteListPatternString,
                blackListPatterns: blackListPatternString
            };
        }
    }
}

/**
 * Validates all input elements of the form which defines attributes for white list or black list patterns against them.
 *
 * @param form Form to be validated
 * @returns {{isValid: boolean, label: string, whiteListPatterns: string, blackListPatterns: string}}
 */
function validateForm(form) {

    var allInputs = form.getElementsByTagName('input');
    var len = allInputs.length;

    for (var i = 0; i < len; i++) {
        var validationObj = validateInput(allInputs[i]);

        if (validationObj['isValid'] === true) {
            continue;
        } else {
            return validationObj;
        }
    }

    return {
        isValid: true,
        label: "",
        whiteListPatterns: "",
        blackListPatterns: ""
    };
}

/**
 * Validates the given input element against white list or black list patterns and returns true if input is valid
 * and pops up an confirmation dialog to ask user's confirmation if input is invalid.
 *
 * @param inputElement input element to be evaluated
 * @param msg Message to be popped up if validations fails. If message contains {0}, {1} and {2},
 * they are replaced by the input label, white list patterns and black list patterns respectively.
 * @param handleYes function to be called upon user clicking yes
 * @param handleNo function to be called upon user clicking no
 * @param closeCallback
 * @returns {boolean} true if successfully validated
 */

function doValidateInputToConfirm(inputElement, msg, handleYes, handleNo, closeCallback) {

    return isValidConfirmationDialog(validateInput(inputElement), msg , handleYes, handleNo, closeCallback);
}
/**
 * Validates the given input element against white list or black list patterns and returns true if input is valid
 * and pops up an error message if input is invalid.
 *
 * @param inputElement input element to be evaluated
 * @param msg Message to be popped up if validations fails. If message contains {0}, {1} and {2},
 * they are replaced by the input label, white list patterns and black list patterns respectively.
 * @returns {boolean} true if successfully validated
 */
function doValidateInput(inputElement, msg) {

    return isValid(validateInput(inputElement), msg);
}

/**
 * Validates all input elements of the form which defines attributes for white list or black list patterns against them,
 * and returns true if all inputs are valid and pops up an error message if inputs are invalid.
 *
 * @param form
 * @param msg Message to be popped up if validations fails. If message contains {0}, {1} and {2},
 * they are replaced by the input label, white list patterns and black list patterns respectively.
 * @returns {boolean} true if successfully validated
 */
function doValidateForm(form, msg) {

    return isValid(validateForm(form), msg);
}<commit_msg>IDENTITY-3948 reverting commit f4629c8eb6f4881bd57c74912231124b322c3345<commit_after>/*
 * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 *  WSO2 Inc. 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.
 */

/**
 * This file includes javascript functions that can be used for form input validation.
 * This file expects dialog/js/dialog.js to be included while including this script.
 */

/**
 * Returns the regular expression for the provided pattern key.
 * If no regex is defined for the provided input returns the provided input as a regex
 *
 * @param pattern regex pattern key or undefined regex as a string
 */
function getPattern(pattern) {
    var regex;
    switch (pattern) {
        case "digits-only":
            regex = /^[0-9]+/;
            break;
        case "alphabetic-only":
            regex = /^[a-zA-Z]+/;
            break;
        case "alphanumerics-only":
            regex = /^[a-zA-Z0-9]+/;
            break;
        case "url":
            regex = /^(([^:/?#]+):)?(([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
            break;
        case "email":
            regex = /^(.+)@(.+)$/;
            break;
        case "whitespace-exists":
            regex = /.*\s+.*/;
            break;
        case "uri-reserved-exists":
            regex = /.*[:/\?#\[\]@!\$&'\(\)\*\+,;=]+.*/;
            break;
        case "uri-unsafe-exists":
            regex = /.*[<>%\{\}\|\^~\[\]`]+.*/;
            break;
        case "html-meta-exists":
            regex = /.*[&<>"'/]+.*/;
            break;
        case "xml-meta-exists":
            regex = /.*[&<>"']+.*/;
            break;
        case "http-url":
            regex = /^(http:)([^/?#])?(:)?(([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
            break;
        case "https-url":
            regex = /^(https:)([^/?#])?(:)?(([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
            break;
        case "ftp-url":
            regex = /^(ftp:)([^/?#])?(:)?(([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
            break;
        default:
            regex = new RegExp(pattern);
            break;
    }

    return regex;
}

/**
 * Checks if the provided input value is valid against the given white list pattern array
 *
 * @param input input value
 * @param whiteListPatterns white list pattern array
 * @returns {boolean} true if input value is valid
 */
function isWhiteListed(input, whiteListPatterns) {

    var isValid = false;
    var pattern;
    for (var i = 0; i < whiteListPatterns.length; i++) {
        pattern = getPattern(whiteListPatterns[i]);
        isValid = pattern.test(input);
        if (isValid) {
            break;
        }
    }

    return isValid;
}

/**
 * Checks if the provided input value is valid against the given black list pattern array
 *
 * @param input input value
 * @param blackListPatterns black list pattern array
 * @returns {boolean} true if input value is valid
 */
function isNotBlackListed(input, blackListPatterns) {

    var isValid = false;
    var pattern;
    for (var i = 0; i < blackListPatterns.length; i++) {
        pattern = getPattern(blackListPatterns[i]);
        isValid = !pattern.test(input);

        if (!isValid) {
            break;
        }
    }

    return isValid;
}

/**
 * Returns a comma separated string of patterns given by the patterns array
 *
 * @param patterns
 * @returns {string}
 */
function getPatternString(patterns) {

    var patternString = "";
    for (var i = 0; i < patterns.length; i++) {
        patternString += getPattern(patterns[i]).toString();
        if ((patterns.length - 1) != i) {
            patternString += ", ";
        }
    }

    return patternString;
}

/**
 * Extracts the given validator object and show the confirmation dialog.
 * Expects handleYes, handleNo, closeCallback as specified in dialog.js
 * @param validationObj validator object
 * @param msg   custom message
 * @param handleYes function to be called upon user clicking yes
 * @param handleNo  function to be called upon user clicking no
 * @param closeCallback
 * @returns {boolean} true if object contains isValid = true
 */
function isValidConfirmationDialog(validationObj, msg, handleYes, handleNo, closeCallback){
    if (validationObj['isValid'] === true) {
        return true;
    }

    var label = validationObj['label'];
    var whiteListPatterns = validationObj['whiteListPatterns'];
    var blackListPatterns = validationObj['blackListPatterns'];

    var message = msg.replace('{0}', label).replace('{1}', whiteListPatterns === "" ? 'NONE' : whiteListPatterns)
        .replace('{2}', blackListPatterns === "" ? 'NONE' : blackListPatterns);

    CARBON.showConfirmationDialog(message, handleYes, handleNo, closeCallback);
    return false;
}
/**
 * Extracts the given validator object
 *
 * @param validationObj validator object
 * @param msg custom message
 * @returns {boolean} true if object contains isValid = true
 */
function isValid(validationObj, msg) {

    if (validationObj['isValid'] === true) {
        return true;
    }

    var label = validationObj['label'];
    var whiteListPatterns = validationObj['whiteListPatterns'];
    var blackListPatterns = validationObj['blackListPatterns'];

    var message = msg.replace('{0}', label).replace('{1}', whiteListPatterns === "" ? 'NONE' : whiteListPatterns)
        .replace('{2}', blackListPatterns === "" ? 'NONE' : blackListPatterns);

    CARBON.showErrorDialog(message);
    return false;
}

/**
 * Validates the given input element against white list or black list patterns
 *
 * @param inputElement input element to be evaluated
 * @returns {{isValid: boolean, label: string, whiteListPatterns: string, blackListPatterns: string}}
 */
function validateInput(inputElement) {

    var value = inputElement.value;

    var whiteListPatternString = "";
    var blackListPatternString = "";
    var labelString = "";

    if (value != null && value != 'null') {
        var whiteListPatterns = inputElement.getAttribute('white-list-patterns');
        var blackListPatterns = inputElement.getAttribute('black-list-patterns');

        if ((whiteListPatterns === null || whiteListPatterns === "") &&
            (blackListPatterns === null || blackListPatterns === "")) {
            return {
                isValid: true,
                label: labelString,
                whiteListPatterns: whiteListPatternString,
                blackListPatterns: blackListPatternString
            };
        }

        var isValid = false;
        var whiteListed = false;
        var notBlackListed = false;
        var whiteListPatternsProvided = false;
        var blackListPatternsProvided = false;

        if (whiteListPatterns != null && whiteListPatterns != "") {
            whiteListPatternsProvided = true;
            var patternArray = whiteListPatterns.split(' ');
            whiteListed = isWhiteListed(value, patternArray);
            whiteListPatternString = getPatternString(patternArray);
        }

        if (blackListPatterns != null && blackListPatterns != "") {
            blackListPatternsProvided = true;
            var patternArray = blackListPatterns.split(' ');
            notBlackListed = isNotBlackListed(value, patternArray);
            blackListPatternString = getPatternString(patternArray);
        }

        if (whiteListPatternsProvided && blackListPatternsProvided) {
            isValid = whiteListed || notBlackListed;
        } else if (whiteListPatternsProvided) {
            isValid = whiteListed;
        } else if (blackListPatternsProvided) {
            isValid = notBlackListed;
        }

        if (isValid === true) {
            return {
                isValid: true,
                label: labelString,
                whiteListPatterns: whiteListPatternString,
                blackListPatterns: blackListPatternString
            };
        } else {
            labelString = inputElement.getAttribute('label');
            if (labelString == null || labelString == "") {
                labelString = inputElement.getAttribute('name');
            }
            return {
                isValid: false,
                label: labelString,
                whiteListPatterns: whiteListPatternString,
                blackListPatterns: blackListPatternString
            };
        }
    }
}

/**
 * Validates all input elements of the form which defines attributes for white list or black list patterns against them.
 *
 * @param form Form to be validated
 * @returns {{isValid: boolean, label: string, whiteListPatterns: string, blackListPatterns: string}}
 */
function validateForm(form) {

    var allInputs = form.getElementsByTagName('input');
    var len = allInputs.length;

    for (var i = 0; i < len; i++) {
        var validationObj = validateInput(allInputs[i]);

        if (validationObj['isValid'] === true) {
            continue;
        } else {
            return validationObj;
        }
    }

    return {
        isValid: true,
        label: "",
        whiteListPatterns: "",
        blackListPatterns: ""
    };
}

/**
 * Validates the given input element against white list or black list patterns and returns true if input is valid
 * and pops up an confirmation dialog to ask user's confirmation if input is invalid.
 *
 * @param inputElement input element to be evaluated
 * @param msg Message to be popped up if validations fails. If message contains {0}, {1} and {2},
 * they are replaced by the input label, white list patterns and black list patterns respectively.
 * @param handleYes function to be called upon user clicking yes
 * @param handleNo function to be called upon user clicking no
 * @param closeCallback
 * @returns {boolean} true if successfully validated
 */

function doValidateInputToConfirm(inputElement, msg, handleYes, handleNo, closeCallback) {

    return isValidConfirmationDialog(validateInput(inputElement), msg , handleYes, handleNo, closeCallback);
}
/**
 * Validates the given input element against white list or black list patterns and returns true if input is valid
 * and pops up an error message if input is invalid.
 *
 * @param inputElement input element to be evaluated
 * @param msg Message to be popped up if validations fails. If message contains {0}, {1} and {2},
 * they are replaced by the input label, white list patterns and black list patterns respectively.
 * @returns {boolean} true if successfully validated
 */
function doValidateInput(inputElement, msg) {

    return isValid(validateInput(inputElement), msg);
}

/**
 * Validates all input elements of the form which defines attributes for white list or black list patterns against them,
 * and returns true if all inputs are valid and pops up an error message if inputs are invalid.
 *
 * @param form
 * @param msg Message to be popped up if validations fails. If message contains {0}, {1} and {2},
 * they are replaced by the input label, white list patterns and black list patterns respectively.
 * @returns {boolean} true if successfully validated
 */
function doValidateForm(form, msg) {

    return isValid(validateForm(form), msg);
}<|endoftext|>


<commit_before>console.log('----------------------------- Variables -----------------------------');

<commit_msg>added Variables file/section<commit_after>console.log('----------------------------- Variables -----------------------------');

//------------ ES5
var nameOld = 'Jane';
var titleOld = 'Software Engineer';
var hourlyWageOld = 40;

//------------ ES6
const nameNew = 'Jane'; // When the variable isn't expected to change throughout the lifespan of the application.
// we can not chane the value nameNew later on like this: nameNew = 'Abby';
let titleNew = 'Software Engineer' // When the variable is expected to change at some point in the application. This is similar to the old var variable
titleNew = 'Senior Software Engineer';
let hourlyWageNew = 40;
hourlyWageNew = 40;

<|endoftext|>


<commit_before>import React from 'react';
import Relay from 'react-relay';

import PrInfoContainer from './pr-info-container';

export class PrList extends React.Component {
  static propTypes = {
    query: React.PropTypes.shape({
      repository: React.PropTypes.object,
    }),
  }

  render() {
    const repo = this.props.query.repository;
    if (!repo.pullRequests.edges.length) {
      return null; // TODO: no PRs
    }
    const pr = repo.pullRequests.edges[0].node;
    return (
      <PrInfoContainer repository={repo} pullRequest={pr} />
    );
  }
}

export default Relay.createContainer(PrList, {
  initialVariables: {
    repoOwner: null,
    repoName: null,
    branchName: null,
  },

  fragments: {
    query: () => Relay.QL`
      fragment on Query {
        repository(owner: $repoOwner, name: $repoName) {
          ${PrInfoContainer.getFragment('repository')}
          pullRequests(first: 30, headRefName: $branchName) {
            edges {
              node {
                ${PrInfoContainer.getFragment('pullRequest')}
              }
            }
          }
        }
      }
    `,
  },
});
<commit_msg>Handle no repo found<commit_after>import React from 'react';
import Relay from 'react-relay';

import PrInfoContainer from './pr-info-container';

export class PrList extends React.Component {
  static propTypes = {
    query: React.PropTypes.shape({
      repository: React.PropTypes.object,
    }),
  }

  render() {
    const repo = this.props.query.repository;
    if (!repo || !repo.pullRequests.edges.length) {
      return null; // TODO: no PRs
    }
    const pr = repo.pullRequests.edges[0].node;
    return (
      <PrInfoContainer repository={repo} pullRequest={pr} />
    );
  }
}

export default Relay.createContainer(PrList, {
  initialVariables: {
    repoOwner: null,
    repoName: null,
    branchName: null,
  },

  fragments: {
    query: () => Relay.QL`
      fragment on Query {
        repository(owner: $repoOwner, name: $repoName) {
          ${PrInfoContainer.getFragment('repository')}
          pullRequests(first: 30, headRefName: $branchName) {
            edges {
              node {
                ${PrInfoContainer.getFragment('pullRequest')}
              }
            }
          }
        }
      }
    `,
  },
});
<|endoftext|>