text:
module.controller('GlobalCtrl', function($scope, $http, Auth, WhoAmI, Current, $location, Notifications, ServerInfo) {
    $scope.addMessage = function() {
        Notifications.success("test");
    };

    $scope.authUrl = authUrl;
    $scope.resourceUrl = resourceUrl;
    $scope.auth = Auth;
    $scope.serverInfo = ServerInfo.get();

    function hasAnyAccess() {
        var realmAccess = Auth.user && Auth.user['realm_access'];
        if (realmAccess) {
            for (var p in realmAccess){
                return true;
            }
            return false;
        } else {
            return false;
        }
    }

    WhoAmI.get(function (data) {
        Auth.user = data;
        Auth.loggedIn = true;
        Auth.hasAnyAccess = hasAnyAccess();
    });

    function getAccess(role) {
        if (!Current.realm) {
            return false;
        }

        var realmAccess = Auth.user && Auth.user['realm_access'];
        if (realmAccess) {
            realmAccess = realmAccess[Current.realm.realm];
            if (realmAccess) {
                return realmAccess.indexOf(role) >= 0;
            }
        }
        return false;
    }

    $scope.access = {
        get createRealm() {
            return Auth.user && Auth.user.createRealm;
        },

        get viewRealm() {
            return getAccess('view-realm') || this.manageRealm;
        },

        get viewClients() {
            return getAccess('view-clients') || this.manageClients;
        },

        get viewUsers() {
            return getAccess('view-users') || this.manageClients;
        },

        get viewEvents() {
            return getAccess('view-events') || this.manageClients;
        },

        get manageRealm() {
            return getAccess('manage-realm');
        },

        get manageClients() {
            return getAccess('manage-clients');
        },

        get manageUsers() {
            return getAccess('manage-users');
        },

        get manageEvents() {
            return getAccess('manage-events');
        },
        get impersonation() {
            return getAccess('impersonation');
        }
    };

    $scope.$watch(function() {
        return $location.path();
    }, function() {
        $scope.fragment = $location.path();
        $scope.path = $location.path().substring(1).split("/");
    });
});

module.controller('HomeCtrl', function(Realm, Auth, $location) {
    Realm.query(null, function(realms) {
        var realm;
        if (realms.length == 1) {
            realm = realms[0].realm;
        } else if (realms.length == 2) {
            if (realms[0].realm == Auth.user.realm) {
                realm = realms[1].realm;
            } else if (realms[1].realm == Auth.user.realm) {
                realm = realms[0].realm;
            }
        }
        if (realm) {
            $location.url('/realms/' + realm);
        } else {
            $location.url('/realms');
        }
    });
});

module.controller('RealmTabCtrl', function(Dialog, $scope, Current, Realm, Notifications, $location) {
    $scope.removeRealm = function() {
        Dialog.confirmDelete(Current.realm.realm, 'realm', function() {
            Realm.remove({ id : Current.realm.realm }, function() {
                Current.realms = Realm.query();
                Notifications.success("The realm has been deleted.");
                $location.url("/");
            });
        });
    };
});

module.controller('ServerInfoCtrl', function($scope, ServerInfo) {
    ServerInfo.reload();

    $scope.serverInfo = ServerInfo.get();

    $scope.$watch($scope.serverInfo, function() {
        $scope.providers = [];
        for(var spi in $scope.serverInfo.providers) {
            var p = angular.copy($scope.serverInfo.providers[spi]);
            p.name = spi;
            $scope.providers.push(p)
        }
    });

    $scope.serverInfoReload = function() {
        ServerInfo.reload();
    }
});

module.controller('RealmListCtrl', function($scope, Realm, Current) {
    $scope.realms = Realm.query();
    Current.realms = $scope.realms;
});

module.controller('RealmDropdownCtrl', function($scope, Realm, Current, Auth, $location) {
//    Current.realms = Realm.get();
    $scope.current = Current;

    $scope.changeRealm = function(selectedRealm) {
        $location.url("/realms/" + selectedRealm);
    }
});

module.controller('RealmCreateCtrl', function($scope, Current, Realm, $upload, $http, WhoAmI, $location, Dialog, Notifications, Auth) {
    console.log('RealmCreateCtrl');

    Current.realm = null;

    $scope.realm = {
        enabled: true
    };

    $scope.changed = false;
    $scope.files = [];

    var oldCopy = angular.copy($scope.realm);

    $scope.onFileSelect = function($files) {
        $scope.files = $files;
    };

    $scope.clearFileSelect = function() {
        $scope.files = null;
    }

    $scope.uploadFile = function() {
        //$files: an array of files selected, each file has name, size, and type.
        for (var i = 0; i < $scope.files.length; i++) {
            var $file = $scope.files[i];
            $scope.upload = $upload.upload({
                url: authUrl + '/admin/realms', //upload.php script, node.js route, or servlet url
                // method: POST or PUT,
                // headers: {'headerKey': 'headerValue'}, withCredential: true,
                data: {myObj: ""},
                file: $file
                /* set file formData name for 'Content-Desposition' header. Default: 'file' */
                //fileFormDataName: myFile,
                /* customize how data is added to formData. See #40#issuecomment-28612000 for example */
                //formDataAppender: function(formData, key, val){}
            }).progress(function(evt) {
                    console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
                }).success(function(data, status, headers) {
                    Realm.query(function(data) {
                        Current.realms = data;

                        WhoAmI.get(function(user) {
                            Auth.user = user;

                            Notifications.success("The realm has been uploaded.");

                            var location = headers('Location');
                            if (location) {
                                $location.url("/realms/" + location.substring(location.lastIndexOf('/') + 1));
                            } else {
                                $location.url("/realms");
                            }
                        });
                    });
                })
            .error(function() {
                    Notifications.error("The realm can not be uploaded. Please verify the file.");

                });
            //.then(success, error, progress);
        }
    };

    $scope.$watch('realm', function() {
        if (!angular.equals($scope.realm, oldCopy)) {
            $scope.changed = true;
        }
    }, true);

    $scope.save = function() {
        var realmCopy = angular.copy($scope.realm);
        Realm.create(realmCopy, function() {
            Realm.query(function(data) {
                Current.realms = data;

                WhoAmI.get(function(user) {
                    Auth.user = user;

                    $location.url("/realms/" + realmCopy.realm);
                    Notifications.success("The realm has been created.");
                });
            });
        });
    };

    $scope.cancel = function() {
        window.history.back();
    };
});

module.controller('RealmDetailCtrl', function($scope, Current, Realm, realm, serverInfo, $http, $location, Dialog, Notifications, WhoAmI, Auth) {
    $scope.createRealm = !realm.realm;
    $scope.serverInfo = serverInfo;

    if (Current.realm == null || Current.realm.realm != realm.realm) {
        for (var i = 0; i < Current.realms.length; i++) {
            if (realm.realm == Current.realms[i].realm) {
                Current.realm = Current.realms[i];
                break;
            }
        }
    }
    for (var i = 0; i < Current.realms.length; i++) {
        if (Current.realms[i].realm == realm.realm) {
            Current.realm = Current.realms[i];
        }
    }
    $scope.realm = angular.copy(realm);

    var oldCopy = angular.copy($scope.realm);

    $scope.changed = $scope.create;

    $scope.$watch('realm', function() {
        if (!angular.equals($scope.realm, oldCopy)) {
            $scope.changed = true;
        }
    }, true);

    $scope.save = function() {
        var realmCopy = angular.copy($scope.realm);
        $scope.changed = false;
        var nameChanged = !angular.equals($scope.realm.realm, oldCopy.realm)
        Realm.update({ id : oldCopy.realm}, realmCopy, function () {
            var data = Realm.query(function () {
                Current.realms = data;
                for (var i = 0; i < Current.realms.length; i++) {
                    if (Current.realms[i].realm == realmCopy.realm) {
                        Current.realm = Current.realms[i];
                        oldCopy = angular.copy($scope.realm);
                    }
                }
            });

            if (nameChanged) {
                WhoAmI.get(function(user) {
                    Auth.user = user;

                    $location.url("/realms/" + realmCopy.realm);
                    Notifications.success("Your changes have been saved to the realm.");
                });
            } else {
                $location.url("/realms/" + realmCopy.realm);
                Notifications.success("Your changes have been saved to the realm.");
            }
        });
    };

    $scope.reset = function() {
        $scope.realm = angular.copy(oldCopy);
        $scope.changed = false;
    };

    $scope.cancel = function() {
        window.history.back();
    };
});

function genericRealmUpdate($scope, Current, Realm, realm, serverInfo, $http, $location, Dialog, Notifications, url) {
    $scope.realm = angular.copy(realm);
    $scope.serverInfo = serverInfo;
    $scope.registrationAllowed = $scope.realm.registrationAllowed;

    var oldCopy = angular.copy($scope.realm);

    $scope.changed = false;

    $scope.$watch('realm', function() {
        if (!angular.equals($scope.realm, oldCopy)) {
            $scope.changed = true;
        }
    }, true);

    $scope.save = function() {
        var realmCopy = angular.copy($scope.realm);
        console.log('updating realm...');
        $scope.changed = false;
        console.log('oldCopy.realm - ' + oldCopy.realm);
        Realm.update({ id : oldCopy.realm}, realmCopy, function () {
            var data = Realm.query(function () {
                Current.realms = data;
                for (var i = 0; i < Current.realms.length; i++) {
                    if (Current.realms[i].realm == realmCopy.realm) {
                        Current.realm = Current.realms[i];
                        oldCopy = angular.copy($scope.realm);
                    }
                }
            });
            $location.url(url);
            Notifications.success("Your changes have been saved to the realm.");
            $scope.registrationAllowed = $scope.realm.registrationAllowed;
        });
    };

    $scope.reset = function() {
        $scope.realm = angular.copy(oldCopy);
        $scope.changed = false;
    };

    $scope.cancel = function() {
        //$location.url("/realms");
        window.history.back();
    };

}

module.controller('DefenseHeadersCtrl', function($scope, Current, Realm, realm, serverInfo, $http, $location, Dialog, Notifications) {
    genericRealmUpdate($scope, Current, Realm, realm, serverInfo, $http, $location, Dialog, Notifications, "/realms/" + realm.realm + "/defense/headers");
});

module.controller('RealmLoginSettingsCtrl', function($scope, Current, Realm, realm, serverInfo, $http, $location, Dialog, Notifications) {
    genericRealmUpdate($scope, Current, Realm, realm, serverInfo, $http, $location, Dialog, Notifications, "/realms/" + realm.realm + "/login-settings");
});

module.controller('RealmOtpPolicyCtrl', function($scope, Current, Realm, realm, serverInfo, $http, $location, Dialog, Notifications) {
    genericRealmUpdate($scope, Current, Realm, realm, serverInfo, $http, $location, Dialog, Notifications, "/realms/" + realm.realm + "/authentication/otp-policy");
});

module.controller('RealmThemeCtrl', function($scope, Current, Realm, realm, serverInfo, $http, $location, Dialog, Notifications) {
    genericRealmUpdate($scope, Current, Realm, realm, serverInfo, $http, $location, Dialog, Notifications, "/realms/" + realm.realm + "/theme-settings");

    $scope.supportedLocalesOptions = {
        'multiple' : true,
        'simple_tags' : true,
        'tags' : ['en', 'de', 'pt-BR', 'it']
    };

    $scope.$watch('realm.supportedLocales', function(oldVal, newVal) {
        if(angular.isUndefined(newVal) || (angular.isArray(newVal) && newVal.length == 0)){
            $scope.realm.defaultLocale = undefined;
        }
    }, true);
});

module.controller('RealmCacheCtrl', function($scope, Current, Realm, realm, serverInfo, $http, $location, Dialog, Notifications) {
    genericRealmUpdate($scope, Current, Realm, realm, serverInfo, $http, $location, Dialog, Notifications, "/realms/" + realm.realm + "/cache-settings");
});

module.controller('RealmPasswordPolicyCtrl', function($scope, Realm, realm, $http, $location, Dialog, Notifications, PasswordPolicy) {
    console.log('RealmPasswordPolicyCtrl');

    $scope.realm = realm;

    var oldCopy = angular.copy($scope.realm);

    $scope.allPolicies = PasswordPolicy.allPolicies;
    $scope.policyMessages = PasswordPolicy.policyMessages;

    $scope.policy = PasswordPolicy.parse(realm.passwordPolicy);
    var oldPolicy = angular.copy($scope.policy);

    $scope.addPolicy = function(policy){
        if (!$scope.policy) {
            $scope.policy = [];
        }
        if (policy.name === 'regexPattern') {
            for (var i in $scope.allPolicies) {
                var p = $scope.allPolicies[i];
                if (p.name === 'regexPattern') {
                    $scope.allPolicies[i] = { name: 'regexPattern', value: '' };
                }
            }
        }
        $scope.policy.push(policy);
    }

    $scope.removePolicy = function(index){
        $scope.policy.splice(index, 1);
    }

    $scope.changed = false;

    $scope.$watch('realm', function() {
        if (!angular.equals($scope.realm, oldCopy)) {
            $scope.changed = true;
        }
    }, true);

    $scope.$watch('policy', function(oldVal, newVal) {
        if (!angular.equals($scope.policy, oldPolicy)) {
            $scope.realm.passwordPolicy = PasswordPolicy.toString($scope.policy);
            $scope.changed = true;
        }
    }, true);

    $scope.save = function() {
        $scope.changed = false;

        Realm.update($scope.realm, function () {
            $location.url("/realms/" + realm.realm + "/authentication/password-policy");
            Notifications.success("Your changes have been saved to the realm.");
            oldCopy = angular.copy($scope.realm);
            oldPolicy = angular.copy($scope.policy);
        });
    };

    $scope.reset = function() {
        $scope.realm = angular.copy(oldCopy);
        $scope.policy = angular.copy(oldPolicy);
        $scope.changed = false;
    };
});

module.controller('RealmDefaultRolesCtrl', function ($scope, Realm, realm, clients, roles, Notifications, ClientRole, Client) {

    console.log('RealmDefaultRolesCtrl');

    $scope.realm = realm;

    $scope.availableRealmRoles = [];
    $scope.selectedRealmRoles = [];
    $scope.selectedRealmDefRoles = [];

    $scope.clients = angular.copy(clients);
    for (var i = 0; i < clients.length; i++) {
        if (clients[i].name == 'account') {
            $scope.client = $scope.clients[i];
            break;
        }
    }

    $scope.availableClientRoles = [];
    $scope.selectedClientRoles = [];
    $scope.selectedClientDefRoles = [];

    if (!$scope.realm.hasOwnProperty('defaultRoles') || $scope.realm.defaultRoles === null) {
        $scope.realm.defaultRoles = [];
    }

    // Populate available roles. Available roles are neither already assigned
    for (var i = 0; i < roles.length; i++) {
        var item = roles[i].name;

        if ($scope.realm.defaultRoles.indexOf(item) < 0) {
            $scope.availableRealmRoles.push(item);
        }
    }

    $scope.addRealmDefaultRole = function () {

        // Remove selected roles from the Available roles and add them to realm default roles (move from left to right).
        for (var i = 0; i < $scope.selectedRealmRoles.length; i++) {
            var selectedRole = $scope.selectedRealmRoles[i];

            $scope.realm.defaultRoles.push(selectedRole);

            var index = $scope.availableRealmRoles.indexOf(selectedRole);
            if (index > -1) {
                $scope.availableRealmRoles.splice(index, 1);
            }
        }

        $scope.selectedRealmRoles = [];

        // Update/save the realm with new default roles.
        Realm.update($scope.realm, function () {
            Notifications.success("Realm default roles updated.");
        });
    };

    $scope.deleteRealmDefaultRole = function () {

        // Remove selected roles from the realm default roles and add them to available roles (move from right to left).
        for (var i = 0; i < $scope.selectedRealmDefRoles.length; i++) {
            $scope.availableRealmRoles.push($scope.selectedRealmDefRoles[i]);

            var index = $scope.realm.defaultRoles.indexOf($scope.selectedRealmDefRoles[i]);
            if (index > -1) {
                $scope.realm.defaultRoles.splice(index, 1);
            }
        }

        $scope.selectedRealmDefRoles = [];

        // Update/save the realm with new default roles.
        //var realmCopy = angular.copy($scope.realm);
        Realm.update($scope.realm, function () {
            Notifications.success("Realm default roles updated.");
        });
    };

    $scope.changeClient = function () {

        $scope.selectedClientRoles = [];
        $scope.selectedClientDefRoles = [];

        // Populate available roles for selected client
        if ($scope.client) {
            var appDefaultRoles = ClientRole.query({realm: $scope.realm.realm, client: $scope.client.id}, function () {

                if (!$scope.client.hasOwnProperty('defaultRoles') || $scope.client.defaultRoles === null) {
                    $scope.client.defaultRoles = [];
                }

                $scope.availableClientRoles = [];

                for (var i = 0; i < appDefaultRoles.length; i++) {
                    var roleName = appDefaultRoles[i].name;
                    if ($scope.client.defaultRoles.indexOf(roleName) < 0) {
                        $scope.availableClientRoles.push(roleName);
                    }
                }
            });
        } else {
            $scope.availableClientRoles = null;
        }
    };

    $scope.addClientDefaultRole = function () {

        // Remove selected roles from the app available roles and add them to app default roles (move from left to right).
        for (var i = 0; i < $scope.selectedClientRoles.length; i++) {
            var role = $scope.selectedClientRoles[i];

            var idx = $scope.client.defaultRoles.indexOf(role);
            if (idx < 0) {
                $scope.client.defaultRoles.push(role);
            }

            idx = $scope.availableClientRoles.indexOf(role);

            if (idx != -1) {
                $scope.availableClientRoles.splice(idx, 1);
            }
        }

        $scope.selectedClientRoles = [];

        // Update/save the selected client with new default roles.
        Client.update({
            realm: $scope.realm.realm,
            client: $scope.client.id
        }, $scope.client, function () {
            Notifications.success("Your changes have been saved to the client.");
        });
    };

    $scope.rmClientDefaultRole = function () {

        // Remove selected roles from the app default roles and add them to app available roles (move from right to left).
        for (var i = 0; i < $scope.selectedClientDefRoles.length; i++) {
            var role = $scope.selectedClientDefRoles[i];
            var idx = $scope.client.defaultRoles.indexOf(role);
            if (idx != -1) {
                $scope.client.defaultRoles.splice(idx, 1);
            }
            idx = $scope.availableClientRoles.indexOf(role);
            if (idx < 0) {
                $scope.availableClientRoles.push(role);
            }
        }

        $scope.selectedClientDefRoles = [];

        // Update/save the selected client with new default roles.
        Client.update({
            realm: $scope.realm.realm,
            client: $scope.client.id
        }, $scope.client, function () {
            Notifications.success("Your changes have been saved to the client.");
        });
    };

});

module.controller('IdentityProviderTabCtrl', function(Dialog, $scope, Current, Notifications, $location) {
    $scope.removeIdentityProvider = function() {
        Dialog.confirmDelete($scope.identityProvider.alias, 'provider', function() {
            $scope.identityProvider.$remove({
                realm : Current.realm.realm,
                alias : $scope.identityProvider.alias
            }, function() {
                $location.url("/realms/" + Current.realm.realm + "/identity-provider-settings");
                Notifications.success("The identity provider has been deleted.");
            });
        });
    };
});

module.controller('RealmIdentityProviderCtrl', function($scope, $filter, $upload, $http, $route, realm, instance, providerFactory, IdentityProvider, serverInfo, $location, Notifications, Dialog) {
    console.log('RealmIdentityProviderCtrl');

    $scope.realm = angular.copy(realm);

    $scope.initProvider = function() {
        if (instance && instance.alias) {

        } else {
            $scope.identityProvider.updateProfileFirstLoginMode = "on";
        }

    };

    $scope.initSamlProvider = function() {
        $scope.nameIdFormats = [
            /*
            {
                format: "urn:oasis:names:tc:SAML:2.0:nameid-format:transient",
                name: "Transient"
            },
            */
            {
                format: "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent",
                name: "Persistent"

            },
            {
                format: "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress",
                name: "Email"

            },
            {
                format: "urn:oasis:names:tc:SAML:2.0:nameid-format:kerberos",
                name: "Kerberos"

            },
            {
                format: "urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName",
                name: "X.509 Subject Name"

            },
            {
                format: "urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName",
                name: "Windows Domain Qualified Name"

            },
            {
                format: "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified",
                name: "Unspecified"

            }
        ];
        $scope.signatureAlgorithms = [
            "RSA_SHA1",
            "RSA_SHA256",
            "RSA_SHA512",
            "DSA_SHA1"
        ];
        if (instance && instance.alias) {

        } else {
            $scope.identityProvider.config.nameIDPolicyFormat = $scope.nameIdFormats[0].format;
            $scope.identityProvider.config.signatureAlgorithm = $scope.signatureAlgorithms[1];
            $scope.identityProvider.updateProfileFirstLoginMode = "off";
        }
    }

    $scope.hidePassword = true;
    $scope.fromUrl = {
        data: ''
    };

    if (instance && instance.alias) {
        $scope.identityProvider = angular.copy(instance);
        $scope.newIdentityProvider = false;
    } else {
        $scope.identityProvider = {};
        $scope.identityProvider.config = {};
        $scope.identityProvider.alias = providerFactory.id;
        $scope.identityProvider.providerId = providerFactory.id;
        $scope.identityProvider.enabled = true;
        $scope.identityProvider.updateProfileFirstLoginMode = "off";
        $scope.identityProvider.authenticateByDefault = false;
        $scope.newIdentityProvider = true;
    }

    $scope.changed = $scope.newIdentityProvider;

    $scope.$watch('identityProvider', function() {
        if (!angular.equals($scope.identityProvider, instance)) {
            $scope.changed = true;
        }
    }, true);

    $scope.serverInfo = serverInfo;

    $scope.allProviders = angular.copy(serverInfo.identityProviders);

    $scope.configuredProviders = angular.copy(realm.identityProviders);

    $scope.$watch(function() {
        return $location.path();
    }, function() {
        $scope.path = $location.path().substring(1).split("/");
    });

    $scope.files = [];
    $scope.importFile = false;
    $scope.importUrl = false;

    $scope.onFileSelect = function($files) {
        $scope.importFile = true;
        $scope.files = $files;
    };

    $scope.clearFileSelect = function() {
        $scope.importUrl = false;
        $scope.importFile = false;
        $scope.files = null;
    };

    var setConfig = function(data) {
        for (var key in data) {
            $scope.identityProvider.config[key] = data[key];
        }
    }

    $scope.uploadFile = function() {
        if (!$scope.identityProvider.alias) {
            Notifications.error("You must specify an alias");
            return;
        }
        var input = {
            providerId: providerFactory.id
        }
        //$files: an array of files selected, each file has name, size, and type.
        for (var i = 0; i < $scope.files.length; i++) {
            var $file = $scope.files[i];
            $scope.upload = $upload.upload({
                url: authUrl + '/admin/realms/' + realm.realm + '/identity-provider/import-config',
                // method: POST or PUT,
                // headers: {'headerKey': 'headerValue'}, withCredential: true,
                data: input,
                file: $file
                /* set file formData name for 'Content-Desposition' header. Default: 'file' */
                //fileFormDataName: myFile,
                /* customize how data is added to formData. See #40#issuecomment-28612000 for example */
                //formDataAppender: function(formData, key, val){}
            }).progress(function(evt) {
                console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
            }).success(function(data, status, headers) {
                setConfig(data);
                $scope.clearFileSelect();
                Notifications.success("The IDP metadata has been loaded from file.");
            }).error(function() {
                Notifications.error("The file can not be uploaded. Please verify the file.");
            });
        }
    };

    $scope.importFrom = function() {
        if (!$scope.identityProvider.alias) {
            Notifications.error("You must specify an alias");
            return;
        }
        var input = {
            fromUrl: $scope.fromUrl.data,
            providerId: providerFactory.id
        }
        $http.post(authUrl + '/admin/realms/' + realm.realm + '/identity-provider/import-config', input)
            .success(function(data, status, headers) {
                setConfig(data);
                $scope.fromUrl.data = '';
                $scope.importUrl = false;
                Notifications.success("Imported config information from url.");
            }).error(function() {
                Notifications.error("Config can not be imported. Please verify the url.");
            });
    };
    $scope.$watch('fromUrl.data', function(newVal, oldVal){
        if ($scope.fromUrl.data && $scope.fromUrl.data.length > 0) {
            $scope.importUrl = true;
        } else{
            $scope.importUrl = false;
        }
    });

    $scope.$watch('configuredProviders', function(configuredProviders) {
        if (configuredProviders) {
            $scope.configuredProviders = angular.copy(configuredProviders);

            for (var j = 0; j < configuredProviders.length; j++) {
                var configProvidedId = configuredProviders[j].providerId;

                for (var i in $scope.allProviders) {
                    var provider = $scope.allProviders[i];

                    if (provider.groupName == 'Social' && (provider.id == configProvidedId)) {
                        $scope.allProviders.splice(i, 1);
                        break;
                    }
                }
            }
        }
    }, true);

    $scope.callbackUrl = encodeURI($location.absUrl().replace(/\/admin.*/, "/realms/") + realm.realm + "/broker/") ;

    $scope.addProvider = function(provider) {
        $location.url("/create/identity-provider/" + realm.realm + "/" + provider.id);
    };

    $scope.save = function() {
        if ($scope.newIdentityProvider) {
            if (!$scope.identityProvider.alias) {
                Notifications.error("You must specify an alias");
                return;
            }
            IdentityProvider.save({
                realm: $scope.realm.realm, alias: ''
            }, $scope.identityProvider, function () {
                $location.url("/realms/" + realm.realm + "/identity-provider-settings/provider/" + $scope.identityProvider.providerId + "/" + $scope.identityProvider.alias);
                Notifications.success("The " + $scope.identityProvider.alias + " provider has been created.");
            });
        } else {
            IdentityProvider.update({
                realm: $scope.realm.realm,
                id: $scope.identityProvider.internalId
            }, $scope.identityProvider, function () {
                $route.reload();
                Notifications.success("The " + $scope.identityProvider.alias + " provider has been update.");
            });
        }
    };

    $scope.cancel = function() {
        if ($scope.newIdentityProvider) {
            $location.url("/realms/" + realm.realm + "/identity-provider-settings");
        } else {
            $route.reload();
        }
    };

    $scope.reset = function() {
        $scope.identityProvider = {};
        $scope.configuredProviders = angular.copy($scope.realm.identityProviders);
    };

    $scope.showPassword = function(flag) {
        $scope.hidePassword = flag;
    };

    $scope.removeIdentityProvider = function(identityProvider) {
        Dialog.confirmDelete(identityProvider.alias, 'provider', function() {
            IdentityProvider.remove({
                realm : realm.realm,
                alias : identityProvider.alias
            }, function() {
                $route.reload();
                Notifications.success("The identity provider has been deleted.");
            });
        });
    };

});

module.controller('RealmIdentityProviderExportCtrl', function(realm, identityProvider, $scope, $http, IdentityProviderExport) {
    $scope.realm = realm;
    $scope.identityProvider = identityProvider;
    $scope.download = null;
    $scope.exported = "";
    $scope.exportedType = "";

    var url = IdentityProviderExport.url({realm: realm.realm, alias: identityProvider.alias}) ;
    $http.get(url).success(function(data, status, headers, config) {
        $scope.exportedType = headers('Content-Type');
        $scope.exported = data;
    });

    $scope.download = function() {
        var suffix = "txt";
        if ($scope.exportedType == 'application/xml') {
            suffix = 'xml';
        } else if ($scope.exportedType == 'application/json') {
            suffix = 'json';
        }
        saveAs(new Blob([$scope.exported], { type: $scope.exportedType }), 'keycloak.' + suffix);
    }
});

module.controller('RealmTokenDetailCtrl', function($scope, Realm, realm, $http, $location, $route, Dialog, Notifications, TimeUnit) {
    console.log('RealmTokenDetailCtrl');

    $scope.realm = realm;

    $scope.realm.accessTokenLifespanUnit = TimeUnit.autoUnit(realm.accessTokenLifespan);
    $scope.realm.accessTokenLifespan = TimeUnit.toUnit(realm.accessTokenLifespan, $scope.realm.accessTokenLifespanUnit);
    $scope.$watch('realm.accessTokenLifespanUnit', function(to, from) {
        $scope.realm.accessTokenLifespan = TimeUnit.convert($scope.realm.accessTokenLifespan, from, to);
    });

    $scope.realm.ssoSessionIdleTimeoutUnit = TimeUnit.autoUnit(realm.ssoSessionIdleTimeout);
    $scope.realm.ssoSessionIdleTimeout = TimeUnit.toUnit(realm.ssoSessionIdleTimeout, $scope.realm.ssoSessionIdleTimeoutUnit);
    $scope.$watch('realm.ssoSessionIdleTimeoutUnit', function(to, from) {
        $scope.realm.ssoSessionIdleTimeout = TimeUnit.convert($scope.realm.ssoSessionIdleTimeout, from, to);
    });

    $scope.realm.ssoSessionMaxLifespanUnit = TimeUnit.autoUnit(realm.ssoSessionMaxLifespan);
    $scope.realm.ssoSessionMaxLifespan = TimeUnit.toUnit(realm.ssoSessionMaxLifespan, $scope.realm.ssoSessionMaxLifespanUnit);
    $scope.$watch('realm.ssoSessionMaxLifespanUnit', function(to, from) {
        $scope.realm.ssoSessionMaxLifespan = TimeUnit.convert($scope.realm.ssoSessionMaxLifespan, from, to);
    });

    $scope.realm.accessCodeLifespanUnit = TimeUnit.autoUnit(realm.accessCodeLifespan);
    $scope.realm.accessCodeLifespan = TimeUnit.toUnit(realm.accessCodeLifespan, $scope.realm.accessCodeLifespanUnit);
    $scope.$watch('realm.accessCodeLifespanUnit', function(to, from) {
        $scope.realm.accessCodeLifespan = TimeUnit.convert($scope.realm.accessCodeLifespan, from, to);
    });

    $scope.realm.accessCodeLifespanLoginUnit = TimeUnit.autoUnit(realm.accessCodeLifespanLogin);
    $scope.realm.accessCodeLifespanLogin = TimeUnit.toUnit(realm.accessCodeLifespanLogin, $scope.realm.accessCodeLifespanLoginUnit);
    $scope.$watch('realm.accessCodeLifespanLoginUnit', function(to, from) {
        $scope.realm.accessCodeLifespanLogin = TimeUnit.convert($scope.realm.accessCodeLifespanLogin, from, to);
    });

    $scope.realm.accessCodeLifespanUserActionUnit = TimeUnit.autoUnit(realm.accessCodeLifespanUserAction);
    $scope.realm.accessCodeLifespanUserAction = TimeUnit.toUnit(realm.accessCodeLifespanUserAction, $scope.realm.accessCodeLifespanUserActionUnit);
    $scope.$watch('realm.accessCodeLifespanUserActionUnit', function(to, from) {
        $scope.realm.accessCodeLifespanUserAction = TimeUnit.convert($scope.realm.accessCodeLifespanUserAction, from, to);
    });

    var oldCopy = angular.copy($scope.realm);
    $scope.changed = false;

    $scope.$watch('realm', function() {
        if (!angular.equals($scope.realm, oldCopy)) {
            $scope.changed = true;
        }
    }, true);

    $scope.save = function() {
        var realmCopy = angular.copy($scope.realm);
        delete realmCopy["accessTokenLifespanUnit"];
        delete realmCopy["ssoSessionMaxLifespanUnit"];
        delete realmCopy["accessCodeLifespanUnit"];
        delete realmCopy["ssoSessionIdleTimeoutUnit"];
        delete realmCopy["accessCodeLifespanUserActionUnit"];
        delete realmCopy["accessCodeLifespanLoginUnit"];

        realmCopy.accessTokenLifespan = TimeUnit.toSeconds($scope.realm.accessTokenLifespan, $scope.realm.accessTokenLifespanUnit)
        realmCopy.ssoSessionIdleTimeout = TimeUnit.toSeconds($scope.realm.ssoSessionIdleTimeout, $scope.realm.ssoSessionIdleTimeoutUnit)
        realmCopy.ssoSessionMaxLifespan = TimeUnit.toSeconds($scope.realm.ssoSessionMaxLifespan, $scope.realm.ssoSessionMaxLifespanUnit)
        realmCopy.accessCodeLifespan = TimeUnit.toSeconds($scope.realm.accessCodeLifespan, $scope.realm.accessCodeLifespanUnit)
        realmCopy.accessCodeLifespanUserAction = TimeUnit.toSeconds($scope.realm.accessCodeLifespanUserAction, $scope.realm.accessCodeLifespanUserActionUnit)
        realmCopy.accessCodeLifespanLogin = TimeUnit.toSeconds($scope.realm.accessCodeLifespanLogin, $scope.realm.accessCodeLifespanLoginUnit)

        Realm.update(realmCopy, function () {
            $route.reload();
            Notifications.success("The changes have been saved to the realm.");
        });
    };

    $scope.reset = function() {
        $route.reload();
    };
});

module.controller('RealmKeysDetailCtrl', function($scope, Realm, realm, $http, $location, Dialog, Notifications) {
    $scope.realm = realm;

    $scope.generate = function() {
        Dialog.confirmGenerateKeys($scope.realm.realm, 'realm', function() {
                Realm.update({ realm: realm.realm, publicKey : 'GENERATE' }, function () {
                Notifications.success('New keys generated for realm.');
                Realm.get({ id : realm.realm }, function(updated) {
                    $scope.realm = updated;
                })
            });
        });
    };
});

module.controller('RealmSessionStatsCtrl', function($scope, realm, stats, RealmClientSessionStats, RealmLogoutAll, Notifications) {
    $scope.realm = realm;
    $scope.stats = stats;

    $scope.logoutAll = function() {
        RealmLogoutAll.save({realm : realm.realm}, function (globalReqResult) {
            var successCount = globalReqResult.successRequests ? globalReqResult.successRequests.length : 0;
            var failedCount  = globalReqResult.failedRequests ? globalReqResult.failedRequests.length : 0;

            if (failedCount > 0) {
                var msgStart = successCount>0 ? 'Successfully logout all users under: ' + globalReqResult.successRequests + ' . ' : '';
                Notifications.error(msgStart + 'Failed to logout users under: ' + globalReqResult.failedRequests + '. Verify availability of failed hosts and try again');
            } else {
                window.location.reload();
            }
        });
    };
});

module.controller('RealmRevocationCtrl', function($scope, Realm, RealmPushRevocation, realm, $http, $location, Dialog, Notifications) {
    $scope.realm = angular.copy(realm);

    var setNotBefore = function() {
        if ($scope.realm.notBefore == 0) {
            $scope.notBefore = "None";
        } else {
            $scope.notBefore = new Date($scope.realm.notBefore * 1000);
        }
    };

    setNotBefore();

    var reset = function() {
        Realm.get({ id : realm.realm }, function(updated) {
            $scope.realm = updated;
            setNotBefore();
        })

    };

    $scope.clear = function() {
        Realm.update({ realm: realm.realm, notBefore : 0 }, function () {
            $scope.notBefore = "None";
            Notifications.success('Not Before cleared for realm.');
            reset();
        });
    }
    $scope.setNotBeforeNow = function() {
        Realm.update({ realm: realm.realm, notBefore : new Date().getTime()/1000}, function () {
            Notifications.success('Not Before set for realm.');
            reset();
        });
    }
    $scope.pushRevocation = function() {
        RealmPushRevocation.save({ realm: realm.realm}, function (globalReqResult) {
            var successCount = globalReqResult.successRequests ? globalReqResult.successRequests.length : 0;
            var failedCount  = globalReqResult.failedRequests ? globalReqResult.failedRequests.length : 0;

            if (successCount==0 && failedCount==0) {
                Notifications.warn('No push sent. No admin URI configured or no registered cluster nodes available');
            } else if (failedCount > 0) {
                var msgStart = successCount>0 ? 'Successfully push notBefore to: ' + globalReqResult.successRequests + ' . ' : '';
                Notifications.error(msgStart + 'Failed to push notBefore to: ' + globalReqResult.failedRequests + '. Verify availability of failed hosts and try again');
            } else {
                Notifications.success('Successfully push notBefore to all configured clients');
            }
        });
    }

});

module.controller('RoleListCtrl', function($scope, $route, Dialog, Notifications, realm, roles, RoleById) {
    $scope.realm = realm;
    $scope.roles = roles;

    $scope.removeRole = function (role) {
        Dialog.confirmDelete(role.name, 'role', function () {
            RoleById.remove({
                realm: realm.realm,
                role: role.id
            }, function () {
                $route.reload();
                Notifications.success("The role has been deleted.");
            });
        });
    };
});

module.controller('RoleDetailCtrl', function($scope, realm, role, roles, clients,
                                             Role, ClientRole, RoleById, RoleRealmComposites, RoleClientComposites,
                                             $http, $location, Dialog, Notifications) {
    $scope.realm = realm;
    $scope.role = angular.copy(role);
    $scope.create = !role.name;

    $scope.changed = $scope.create;

    $scope.save = function() {
        console.log('save');
        if ($scope.create) {
            Role.save({
                realm: realm.realm
            }, $scope.role, function (data, headers) {
                $scope.changed = false;
                role = angular.copy($scope.role);

                Role.get({ realm: realm.realm, role: role.name }, function(role) {
                    var id = role.id;
                    $location.url("/realms/" + realm.realm + "/roles/" + id);
                    Notifications.success("The role has been created.");
                });
            });
        } else {
            $scope.update();
        }
    };

    $scope.remove = function () {
        Dialog.confirmDelete($scope.role.name, 'role', function () {
            $scope.role.$remove({
                realm: realm.realm,
                role: $scope.role.id
            }, function () {
                $location.url("/realms/" + realm.realm + "/roles");
                Notifications.success("The role has been deleted.");
            });
        });
    };

    $scope.cancel = function () {
        $location.url("/realms/" + realm.realm + "/roles");
    };

    roleControl($scope, realm, role, roles, clients,
        ClientRole, RoleById, RoleRealmComposites, RoleClientComposites,
        $http, $location, Notifications, Dialog);
});

module.controller('RealmSMTPSettingsCtrl', function($scope, Current, Realm, realm, $http, $location, Dialog, Notifications) {
    console.log('RealmSMTPSettingsCtrl');

    var booleanSmtpAtts = ["auth","ssl","starttls"];

    $scope.realm = realm;

    if ($scope.realm.smtpServer) {
        $scope.realm.smtpServer = typeObject($scope.realm.smtpServer);
    };

    var oldCopy = angular.copy($scope.realm);
    $scope.changed = false;

    $scope.$watch('realm', function() {
        if (!angular.equals($scope.realm, oldCopy)) {
            $scope.changed = true;
        }
    }, true);

    $scope.save = function() {
        var realmCopy = angular.copy($scope.realm);
        realmCopy['smtpServer'] = detypeObject(realmCopy.smtpServer);
        $scope.changed = false;
        Realm.update(realmCopy, function () {
            $location.url("/realms/" + realm.realm + "/smtp-settings");
            Notifications.success("Your changes have been saved to the realm.");
        });
    };

    $scope.reset = function() {
        $scope.realm = angular.copy(oldCopy);
        $scope.changed = false;
    };

    /* Convert string attributes containing a boolean to actual boolean type + convert an integer string (port) to integer. */
    function typeObject(obj){
        for (var att in obj){
            if (booleanSmtpAtts.indexOf(att) < 0)
                continue;
            if (obj[att] === "true"){
                obj[att] = true;
            } else if (obj[att] === "false"){
                obj[att] = false;
            }
        }

        obj['port'] = parseInt(obj['port']);

        return obj;
    }

    /* Convert all non-string values to strings to invert changes caused by the typeObject function. */
    function detypeObject(obj){
        for (var att in obj){
            if (booleanSmtpAtts.indexOf(att) < 0)
                continue;
            if (obj[att] === true){
                obj[att] = "true";
            } else if (obj[att] === false){
                obj[att] = "false"
            }
        }

        obj['port'] = obj['port'].toString();

        return obj;
    }
});

module.controller('RealmEventsConfigCtrl', function($scope, eventsConfig, RealmEventsConfig, RealmEvents, RealmAdminEvents, realm, serverInfo, $location, Notifications, TimeUnit, Dialog) {
    $scope.realm = realm;

    $scope.eventsConfig = eventsConfig;

    $scope.eventsConfig.expirationUnit = TimeUnit.autoUnit(eventsConfig.eventsExpiration);
    $scope.eventsConfig.eventsExpiration = TimeUnit.toUnit(eventsConfig.eventsExpiration, $scope.eventsConfig.expirationUnit);
    $scope.$watch('eventsConfig.expirationUnit', function(to, from) {
        if ($scope.eventsConfig.eventsExpiration) {
            $scope.eventsConfig.eventsExpiration = TimeUnit.convert($scope.eventsConfig.eventsExpiration, from, to);
        }
    });

    $scope.eventListeners = Object.keys(serverInfo.providers.eventsListener.providers);

    $scope.eventSelectOptions = {
        'multiple': true,
        'simple_tags': true,
        'tags': serverInfo.enums['eventType']
    };

    var oldCopy = angular.copy($scope.eventsConfig);
    $scope.changed = false;

    $scope.$watch('eventsConfig', function() {
        if (!angular.equals($scope.eventsConfig, oldCopy)) {
            $scope.changed = true;
        }
    }, true);

    $scope.save = function() {
        $scope.changed = false;

        var copy = angular.copy($scope.eventsConfig)
        delete copy['expirationUnit'];

        copy.eventsExpiration = TimeUnit.toSeconds($scope.eventsConfig.eventsExpiration, $scope.eventsConfig.expirationUnit);

        RealmEventsConfig.update({
            id : realm.realm
        }, copy, function () {
            $location.url("/realms/" + realm.realm + "/events-settings");
            Notifications.success("Your changes have been saved to the realm.");
        });
    };

    $scope.reset = function() {
        $scope.eventsConfig = angular.copy(oldCopy);
        $scope.changed = false;
    };

    $scope.clearEvents = function() {
        Dialog.confirmDelete($scope.realm.realm, 'events', function() {
            RealmEvents.remove({ id : $scope.realm.realm }, function() {
                Notifications.success("The events has been cleared.");
            });
        });
    };

    $scope.clearAdminEvents = function() {
        Dialog.confirmDelete($scope.realm.realm, 'admin-events', function() {
            RealmAdminEvents.remove({ id : $scope.realm.realm }, function() {
                Notifications.success("The admin events has been cleared.");
            });
        });
    };
});

module.controller('RealmEventsCtrl', function($scope, RealmEvents, realm, serverInfo) {
    $scope.realm = realm;
    $scope.page = 0;

    $scope.eventSelectOptions = {
        'multiple': true,
        'simple_tags': true,
        'tags': serverInfo.enums['eventType']
    };

    $scope.query = {
        id : realm.realm,
        max : 5,
        first : 0
    }

    $scope.update = function() {
    	$scope.query.first = 0;
        for (var i in $scope.query) {
            if ($scope.query[i] === '') {
                delete $scope.query[i];
           }
        }
        $scope.events = RealmEvents.query($scope.query);
    }

    $scope.reset = function() {
    	$scope.query.first = 0;
    	$scope.query.max = 5;
    	$scope.query.type = '';
    	$scope.query.client = '';
    	$scope.query.user = '';
    	$scope.query.dateFrom = '';
    	$scope.query.dateTo = '';

    	$scope.update();
    }

    $scope.queryUpdate = function() {
        for (var i in $scope.query) {
            if ($scope.query[i] === '') {
                delete $scope.query[i];
           }
        }
        $scope.events = RealmEvents.query($scope.query);
    }

    $scope.firstPage = function() {
        $scope.query.first = 0;
        $scope.queryUpdate();
    }

    $scope.previousPage = function() {
        $scope.query.first -= parseInt($scope.query.max);
        if ($scope.query.first < 0) {
            $scope.query.first = 0;
        }
        $scope.queryUpdate();
    }

    $scope.nextPage = function() {
        $scope.query.first += parseInt($scope.query.max);
        $scope.queryUpdate();
    }

    $scope.update();
});

module.controller('RealmAdminEventsCtrl', function($scope, RealmAdminEvents, realm, serverInfo, $modal, $filter) {
    $scope.realm = realm;
    $scope.page = 0;

    $scope.query = {
    	id : realm.realm,
        max : 5,
        first : 0
    }

    $scope.adminEnabledEventOperationsOptions = {
        'multiple': true,
        'simple_tags': true,
        'tags': serverInfo.enums['operationType']
    };

    $scope.update = function() {
    	$scope.query.first = 0;
        for (var i in $scope.query) {
            if ($scope.query[i] === '') {
                delete $scope.query[i];
           }
        }
        $scope.events = RealmAdminEvents.query($scope.query);
    }

    $scope.reset = function() {
    	$scope.query.first = 0;
    	$scope.query.max = 5;
    	$scope.query.operationTypes = '';
    	$scope.query.resourcePath = '';
    	$scope.query.authRealm = '';
    	$scope.query.authClient = '';
    	$scope.query.authUser = '';
    	$scope.query.authIpAddress = '';
    	$scope.query.dateFrom = '';
    	$scope.query.dateTo = '';

    	$scope.update();
    }

    $scope.queryUpdate = function() {
        for (var i in $scope.query) {
            if ($scope.query[i] === '') {
                delete $scope.query[i];
           }
        }
        $scope.events = RealmAdminEvents.query($scope.query);
    }

    $scope.firstPage = function() {
        $scope.query.first = 0;
        $scope.queryUpdate();
    }

    $scope.previousPage = function() {
        $scope.query.first -= parseInt($scope.query.max);
        if ($scope.query.first < 0) {
            $scope.query.first = 0;
        }
        $scope.queryUpdate();
    }

    $scope.nextPage = function() {
        $scope.query.first += parseInt($scope.query.max);
        $scope.queryUpdate();
    }

    $scope.update();

    $scope.viewRepresentation = function(event) {
        $modal.open({
            templateUrl: resourceUrl + '/partials/modal/realm-events-admin-representation.html',
            controller: 'RealmAdminEventsModalCtrl',
            resolve: {
                event: function () {
                    return event;
                }
            }
        })
    }

    $scope.viewAuth = function(event) {
        $modal.open({
            templateUrl: resourceUrl + '/partials/modal/realm-events-admin-auth.html',
            controller: 'RealmAdminEventsModalCtrl',
            resolve: {
                event: function () {
                    return event;
                }
            }
        })
    }
});

module.controller('RealmAdminEventsModalCtrl', function($scope, $filter, event) {
    $scope.event = event;
});

module.controller('RealmBruteForceCtrl', function($scope, Realm, realm, $http, $location, Dialog, Notifications, TimeUnit) {
    console.log('RealmBruteForceCtrl');

    $scope.realm = realm;

    $scope.realm.waitIncrementUnit = TimeUnit.autoUnit(realm.waitIncrementSeconds);
    $scope.realm.waitIncrement = TimeUnit.toUnit(realm.waitIncrementSeconds, $scope.realm.waitIncrementUnit);
    $scope.$watch('realm.waitIncrementUnit', function(to, from) {
        $scope.realm.waitIncrement = TimeUnit.convert($scope.realm.waitIncrement, from, to);
    });

    $scope.realm.minimumQuickLoginWaitUnit = TimeUnit.autoUnit(realm.minimumQuickLoginWaitSeconds);
    $scope.realm.minimumQuickLoginWait = TimeUnit.toUnit(realm.minimumQuickLoginWaitSeconds, $scope.realm.minimumQuickLoginWaitUnit);
    $scope.$watch('realm.minimumQuickLoginWaitUnit', function(to, from) {
        $scope.realm.minimumQuickLoginWait = TimeUnit.convert($scope.realm.minimumQuickLoginWait, from, to);
    });

    $scope.realm.maxFailureWaitUnit = TimeUnit.autoUnit(realm.maxFailureWaitSeconds);
    $scope.realm.maxFailureWait = TimeUnit.toUnit(realm.maxFailureWaitSeconds, $scope.realm.maxFailureWaitUnit);
    $scope.$watch('realm.maxFailureWaitUnit', function(to, from) {
        $scope.realm.maxFailureWait = TimeUnit.convert($scope.realm.maxFailureWait, from, to);
    });

    $scope.realm.maxDeltaTimeUnit = TimeUnit.autoUnit(realm.maxDeltaTimeSeconds);
    $scope.realm.maxDeltaTime = TimeUnit.toUnit(realm.maxDeltaTimeSeconds, $scope.realm.maxDeltaTimeUnit);
    $scope.$watch('realm.maxDeltaTimeUnit', function(to, from) {
        $scope.realm.maxDeltaTime = TimeUnit.convert($scope.realm.maxDeltaTime, from, to);
    });

    var oldCopy = angular.copy($scope.realm);
    $scope.changed = false;

    $scope.$watch('realm', function() {
        if (!angular.equals($scope.realm, oldCopy)) {
            $scope.changed = true;
        }
    }, true);

    $scope.save = function() {
        var realmCopy = angular.copy($scope.realm);
        delete realmCopy["waitIncrementUnit"];
        delete realmCopy["waitIncrement"];
        delete realmCopy["minimumQuickLoginWaitUnit"];
        delete realmCopy["minimumQuickLoginWait"];
        delete realmCopy["maxFailureWaitUnit"];
        delete realmCopy["maxFailureWait"];
        delete realmCopy["maxDeltaTimeUnit"];
        delete realmCopy["maxDeltaTime"];

        realmCopy.waitIncrementSeconds = TimeUnit.toSeconds($scope.realm.waitIncrement, $scope.realm.waitIncrementUnit)
        realmCopy.minimumQuickLoginWaitSeconds = TimeUnit.toSeconds($scope.realm.minimumQuickLoginWait, $scope.realm.minimumQuickLoginWaitUnit)
        realmCopy.maxFailureWaitSeconds = TimeUnit.toSeconds($scope.realm.maxFailureWait, $scope.realm.maxFailureWaitUnit)
        realmCopy.maxDeltaTimeSeconds = TimeUnit.toSeconds($scope.realm.maxDeltaTime, $scope.realm.maxDeltaTimeUnit)

        $scope.changed = false;
        Realm.update(realmCopy, function () {
            oldCopy = angular.copy($scope.realm);
            $location.url("/realms/" + realm.realm + "/defense/brute-force");
            Notifications.success("Your changes have been saved to the realm.");
        });
    };

    $scope.reset = function() {
        $scope.realm = angular.copy(oldCopy);
        $scope.changed = false;
    };
});

module.controller('IdentityProviderMapperListCtrl', function($scope, realm, identityProvider, mapperTypes, mappers) {
    $scope.realm = realm;
    $scope.identityProvider = identityProvider;
    $scope.mapperTypes = mapperTypes;
    $scope.mappers = mappers;
});

module.controller('IdentityProviderMapperCtrl', function($scope, realm,  identityProvider, mapperTypes, mapper, IdentityProviderMapper, Notifications, Dialog, $location) {
    $scope.realm = realm;
    $scope.identityProvider = identityProvider;
    $scope.create = false;
    $scope.mapper = angular.copy(mapper);
    $scope.changed = false;
    $scope.mapperType = mapperTypes[mapper.identityProviderMapper];
    $scope.$watch(function() {
        return $location.path();
    }, function() {
        $scope.path = $location.path().substring(1).split("/");
    });

    $scope.$watch('mapper', function() {
        if (!angular.equals($scope.mapper, mapper)) {
            $scope.changed = true;
        }
    }, true);

    $scope.save = function() {
        IdentityProviderMapper.update({
            realm : realm.realm,
            alias: identityProvider.alias,
            mapperId : mapper.id
        }, $scope.mapper, function() {
            $scope.changed = false;
            mapper = angular.copy($scope.mapper);
            $location.url("/realms/" + realm.realm + '/identity-provider-mappers/' + identityProvider.alias + "/mappers/" + mapper.id);
            Notifications.success("Your changes have been saved.");
        });
    };

    $scope.reset = function() {
        $scope.mapper = angular.copy(mapper);
        $scope.changed = false;
    };

    $scope.cancel = function() {
        //$location.url("/realms");
        window.history.back();
    };

    $scope.remove = function() {
        Dialog.confirmDelete($scope.mapper.name, 'mapper', function() {
            IdentityProviderMapper.remove({ realm: realm.realm, alias: mapper.identityProviderAlias, mapperId : $scope.mapper.id }, function() {
                Notifications.success("The mapper has been deleted.");
                $location.url("/realms/" + realm.realm + '/identity-provider-mappers/' + identityProvider.alias + "/mappers");
            });
        });
    };

});

module.controller('IdentityProviderMapperCreateCtrl', function($scope, realm, identityProvider, mapperTypes, IdentityProviderMapper, Notifications, Dialog, $location) {
    $scope.realm = realm;
    $scope.identityProvider = identityProvider;
    $scope.create = true;
    $scope.mapper = { identityProviderAlias: identityProvider.alias, config: {}};
    $scope.mapperTypes = mapperTypes;

    $scope.$watch(function() {
        return $location.path();
    }, function() {
        $scope.path = $location.path().substring(1).split("/");
    });

    $scope.save = function() {
        $scope.mapper.identityProviderMapper = $scope.mapperType.id;
        IdentityProviderMapper.save({
            realm : realm.realm, alias: identityProvider.alias
        }, $scope.mapper, function(data, headers) {
            var l = headers().location;
            var id = l.substring(l.lastIndexOf("/") + 1);
            $location.url("/realms/" + realm.realm + '/identity-provider-mappers/' + identityProvider.alias + "/mappers/" + id);
            Notifications.success("Mapper has been created.");
        });
    };

    $scope.cancel = function() {
        //$location.url("/realms");
        window.history.back();
    };

});

module.controller('RealmFlowBindingCtrl', function($scope, flows, Current, Realm, realm, serverInfo, $http, $location, Dialog, Notifications) {
    $scope.flows = [];
    $scope.clientFlows = [];
    for (var i=0 ; i<flows.length ; i++) {
        if (flows[i].providerId == 'client-flow') {
            $scope.clientFlows.push(flows[i]);
        } else {
            $scope.flows.push(flows[i]);
        }
    }

    genericRealmUpdate($scope, Current, Realm, realm, serverInfo, $http, $location, Dialog, Notifications, "/realms/" + realm.realm + "/authentication/flow-bindings");
});

module.controller('CreateFlowCtrl', function($scope, realm,
                                             AuthenticationFlows,
                                             Notifications, $location) {
    $scope.realm = realm;
    $scope.flow = {
        alias: "",
        providerId: "basic-flow",
        description: "",
        topLevel: true,
        builtIn: false
    }

    $scope.save = function() {
        AuthenticationFlows.save({realm: realm.realm, flow: ""}, $scope.flow, function() {
            $location.url("/realms/" + realm.realm + "/authentication/flows/" + $scope.flow.alias);
            Notifications.success("Flow Created.");
        })
    }
    $scope.cancel = function() {
        $location.url("/realms/" + realm.realm + "/authentication/flows");
    };
});

module.controller('CreateExecutionFlowCtrl', function($scope, realm, topFlow, parentFlow, formProviders,
                                                      CreateExecutionFlow,
                                                      Notifications, $location) {
    $scope.realm = realm;
    $scope.formProviders = formProviders;

    var defaultFlowType = parentFlow.providerId == 'client-flow' ? 'client-flow' : 'basic-flow';
    $scope.flow = {
        alias: "",
        type: defaultFlowType,
        description: ""
    }
    $scope.provider = {};
    if (formProviders.length > 0) {
        $scope.provider = formProviders[0];
    }

    $scope.save = function() {
        $scope.flow.provider = $scope.provider.id;
        CreateExecutionFlow.save({realm: realm.realm, alias: parentFlow.alias}, $scope.flow, function() {
            $location.url("/realms/" + realm.realm + "/authentication/flows/" + topFlow);
            Notifications.success("Flow Created.");
        })
    }
    $scope.cancel = function() {
        $location.url("/realms/" + realm.realm + "/authentication/flows/" + topFlow);
    };
});

module.controller('CreateExecutionCtrl', function($scope, realm, topFlow, parentFlow, formActionProviders, authenticatorProviders, clientAuthenticatorProviders,
                                                      CreateExecution,
                                                      Notifications, $location) {
    $scope.realm = realm;
    $scope.parentFlow = parentFlow;
    console.log('parentFlow.providerId: ' + parentFlow.providerId);
    if (parentFlow.providerId == 'form-flow') {
        $scope.providers = formActionProviders;
    } else if (parentFlow.providerId == 'client-flow') {
        $scope.providers = clientAuthenticatorProviders;
    } else {
        $scope.providers = authenticatorProviders;
    }

    $scope.provider = {};
    if ($scope.providers.length > 0) {
        $scope.provider = $scope.providers[0];
    }

    $scope.save = function() {
        var execution = {
            provider: $scope.provider.id
        }
        CreateExecution.save({realm: realm.realm, alias: parentFlow.alias}, execution, function() {
            $location.url("/realms/" + realm.realm + "/authentication/flows/" + topFlow);
            Notifications.success("Execution Created.");
        })
    }
    $scope.cancel = function() {
        $location.url("/realms/" + realm.realm + "/authentication/flows/" + topFlow);
    };
});

module.controller('AuthenticationFlowsCtrl', function($scope, $route, realm, flows, selectedFlow,
                                                      AuthenticationFlows, AuthenticationFlowsCopy, AuthenticationFlowExecutions,
                                                      AuthenticationExecution, AuthenticationExecutionRaisePriority, AuthenticationExecutionLowerPriority,
                                                      $modal, Notifications, CopyDialog, $location) {
    $scope.realm = realm;
    $scope.flows = flows;
    if (flows.length > 0) {
        $scope.flow = flows[0];
        if (selectedFlow) {
            for (var i = 0; i < flows.length; i++) {
                if (flows[i].alias == selectedFlow) {
                    $scope.flow = flows[i];
                    break;
                }
            }
        }
    }

    var setupForm = function() {
        AuthenticationFlowExecutions.query({realm: realm.realm, alias: $scope.flow.alias}, function(data) {
            $scope.executions = data;
            $scope.choicesmax = 0;
            $scope.levelmax = 0;
            for (var i = 0; i < $scope.executions.length; i++ ) {
                var execution = $scope.executions[i];
                if (execution.requirementChoices.length > $scope.choicesmax) {
                    $scope.choicesmax = execution.requirementChoices.length;
                }
                if (execution.level > $scope.levelmax) {
                    $scope.levelmax = execution.level;
                }
            }
            $scope.levelmaxempties = [];
            for (j = 0; j < $scope.levelmax; j++) {
                $scope.levelmaxempties.push(j);

            }
            for (var i = 0; i < $scope.executions.length; i++ ) {
                var execution = $scope.executions[i];
                execution.empties = [];
                for (j = 0; j < $scope.choicesmax - execution.requirementChoices.length; j++) {
                    execution.empties.push(j);
                }
                execution.preLevels = [];
                for (j = 0; j < execution.level; j++) {
                    execution.preLevels.push(j);
                }
                execution.postLevels = [];
                for (j = execution.level; j < $scope.levelmax; j++) {
                    execution.postLevels.push(j);
                }
            }
        })
    };

    $scope.copyFlow = function() {
        CopyDialog.open('Copy Authentication Flow', $scope.flow.alias, function(name) {
            AuthenticationFlowsCopy.save({realm: realm.realm, alias: $scope.flow.alias}, {
               newName: name
            }, function() {
                $location.url("/realms/" + realm.realm + '/authentication/flows/' + name);
                Notifications.success("Flow copied.");
            })
        })
    };

    $scope.removeFlow = function() {
        console.log('Remove flow:' + $scope.flow.alias);
        AuthenticationFlows.remove({realm: realm.realm, flow: $scope.flow.id}, function() {
            $location.url("/realms/" + realm.realm + '/authentication/flows');
            Notifications.success("Flow removed");

        })

    };

    $scope.addFlow = function() {
        $location.url("/realms/" + realm.realm + '/authentication/flows/' + $scope.flow.id + '/create/flow/execution/' + $scope.flow.id);

    }

    $scope.addSubFlow = function(execution) {
        $location.url("/realms/" + realm.realm + '/authentication/flows/' + execution.flowId + '/create/flow/execution/' + $scope.flow.alias);

    }

    $scope.addSubFlowExecution = function(execution) {
        $location.url("/realms/" + realm.realm + '/authentication/flows/' + execution.flowId + '/create/execution/' + $scope.flow.alias);

    }

    $scope.addExecution = function() {
        $location.url("/realms/" + realm.realm + '/authentication/flows/' + $scope.flow.id + '/create/execution/' + $scope.flow.id);

    }

    $scope.createFlow = function() {
        $location.url("/realms/" + realm.realm + '/authentication/create/flow');
    }

    $scope.updateExecution = function(execution) {
        var copy = angular.copy(execution);
        delete copy.empties;
        delete copy.levels;
        delete copy.preLevels;
        delete copy.postLevels;
        AuthenticationFlowExecutions.update({realm: realm.realm, alias: $scope.flow.alias}, copy, function() {
            Notifications.success("Auth requirement updated");
            setupForm();
        });

    };

    $scope.removeExecution = function(execution) {
        console.log('removeExecution: ' + execution.id);
        AuthenticationExecution.remove({realm: realm.realm, execution: execution.id}, function() {
            Notifications.success("Execution removed");
            setupForm();
        })
    }

    $scope.raisePriority = function(execution) {
        AuthenticationExecutionRaisePriority.save({realm: realm.realm, execution: execution.id}, function() {
            Notifications.success("Priority raised");
            setupForm();
        })
    }

    $scope.lowerPriority = function(execution) {
        AuthenticationExecutionLowerPriority.save({realm: realm.realm, execution: execution.id}, function() {
            Notifications.success("Priority lowered");
            setupForm();
        })
    }

    $scope.setupForm = setupForm;

    setupForm();

});

module.controller('RequiredActionsCtrl', function($scope, realm, unregisteredRequiredActions,
                                                  $modal, $route,
                                                  RegisterRequiredAction, RequiredActions, Notifications) {
    console.log('RequiredActionsCtrl');
    $scope.realm = realm;
    $scope.unregisteredRequiredActions = unregisteredRequiredActions;
    $scope.requiredActions = [];
    var setupRequiredActionsForm = function() {
        console.log('setupRequiredActionsForm');
        RequiredActions.query({realm: realm.realm}, function(data) {
            $scope.requiredActions = [];
            for (var i = 0; i < data.length; i++) {
                $scope.requiredActions.push(data[i]);
            }
        });
    };

    $scope.updateRequiredAction = function(action) {
        RequiredActions.update({realm: realm.realm, alias: action.alias}, action, function() {
            Notifications.success("Required action updated");
            setupRequiredActionsForm();
        });
    }

    $scope.register = function() {
        var controller = function($scope, $modalInstance) {
            $scope.unregisteredRequiredActions = unregisteredRequiredActions;
            $scope.selected = {
                selected: $scope.unregisteredRequiredActions[0]
            }
            $scope.ok = function () {
                $modalInstance.close();
                RegisterRequiredAction.save({realm: realm.realm}, $scope.selected.selected);
                $route.reload();
            };
            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        }
        $modal.open({
            templateUrl: resourceUrl + '/partials/modal/unregistered-required-action-selector.html',
            controller: controller,
            resolve: {
            }
        });
    }

    setupRequiredActionsForm();

});

module.controller('AuthenticationConfigCtrl', function($scope, realm, configType, config, AuthenticationConfig, Notifications, Dialog, $location) {
    $scope.realm = realm;
    $scope.configType = configType;
    $scope.create = false;
    $scope.config = angular.copy(config);
    $scope.changed = false;

    $scope.$watch(function() {
        return $location.path();
    }, function() {
        $scope.path = $location.path().substring(1).split("/");
    });

    $scope.$watch('config', function() {
        if (!angular.equals($scope.config, config)) {
            $scope.changed = true;
        }
    }, true);

    $scope.save = function() {
        AuthenticationConfig.update({
            realm : realm.realm,
            config : config.id
        }, $scope.config, function() {
            $scope.changed = false;
            config = angular.copy($scope.config);
            $location.url("/realms/" + realm.realm + '/authentication/config/' + configType.providerId + "/" + config.id);
            Notifications.success("Your changes have been saved.");
        });
    };

    $scope.reset = function() {
        $scope.config = angular.copy(config);
        $scope.changed = false;
    };

    $scope.cancel = function() {
        //$location.url("/realms");
        window.history.back();
    };

    $scope.remove = function() {
        Dialog.confirmDelete($scope.config.alias, 'config', function() {
            AuthenticationConfig.remove({ realm: realm.realm, config : $scope.config.id }, function() {
                Notifications.success("The config has been deleted.");
                $location.url("/realms/" + realm.realm + '/authentication/flows');
            });
        });
    };

});

module.controller('AuthenticationConfigCreateCtrl', function($scope, realm, configType, execution, AuthenticationExecutionConfig, Notifications, Dialog, $location) {
    $scope.realm = realm;
    $scope.create = true;
    $scope.config = { config: {}};
    $scope.configType = configType;

    $scope.$watch(function() {
        return $location.path();
    }, function() {
        $scope.path = $location.path().substring(1).split("/");
    });

    $scope.save = function() {
        AuthenticationExecutionConfig.save({
            realm : realm.realm,
            execution: execution
        }, $scope.config, function(data, headers) {
            var l = headers().location;
            var id = l.substring(l.lastIndexOf("/") + 1);
            var url = "/realms/" + realm.realm + '/authentication/config/' + configType.providerId + "/" + id;
            console.log('redirect url: ' + url);
            $location.url(url);
            Notifications.success("Config has been created.");
        });
    };

    $scope.cancel = function() {
        //$location.url("/realms");
        window.history.back();
    };

});

redpajama_set_name: RedPajamaGithub


The Division of Nephrology at Seattle Children's provides direct inpatient and outpatient nephrologic care and diagnoses to infants, children, adolescents and young adults. In addition, both clinical and basic science research are an integral component of daily activities within the division.
We treat renal problems in neonates, infants, children, adolescents and young adults. Our goals are focus on optimal growth, good nutrition and quality of life for our patients. Our team includes clinic, transplant and dialysis nurses, dietitians, nephrology physicians, nurse practitioners and social workers. Our support and follow-up services include education and counseling for patients and their families. Specialized services include a dialysis unit, home dialysis training and a kidney transplantation program.
Members of the division are also actively engaged in basic science research. Our primary areas of interest pertain to the cellular and molecular mechanisms of chronic kidney disease. The three major overlapping themes being explored by our basic science faculty are: 1. Inflammation and response to renal injury, 2. Matrix biology and fibrogenesis, and 3. Vascular biology, atherosclerosis, and angiogenesis.
The goal of the Pediatric Nephrology Fellowship Program is to produce Physician Scientist and Clinical Investigators to assume leadership roles in the field of academic Pediatric Nephrology. This goal is accomplished by an intense year of clinical training in all aspects of Pediatric Nephrology practice, followed by two years of comprehensive training in either basic science research or clinical investigation. The clinical research program allows the fellow to obtain an MS from the School of Public Health and Epidemiology in addition to pursuing clinical investigation in the pediatric nephrology population. The fellowship program fulfills all requirements for Board Certification in Pediatric Nephrology.
For more information, please visit the Nephrology Fellowship webpage.


Posting up to 4 photos. Visible on Desktop & Mobile Versions. Upload a banner.Banner can be displayed by State, City or Sitewide. Posting up to 8 photos. Visible on Desktop & Mobile Versions. VIP Badge and VIP placement.
This is an upgraded post with an nice look. Plus you will get an animated thumbnail at the top of your city homepage in a which will show in rotation with other VIP members. You gain access to unlimited updates and 8 photos.
Must have a Premium Ad. A banner is the most valuable and visible form of advertising on Escortservice.org. Our banners are carefully designed to your specifications by our own publishing department.
Similar to Craigslist ,Backpage and Incall.org, these type of posts are quick and simple. These posts also have the option to automatically repost your ad every day. Every time you repost your ad, your ad moves to the top of the posting section.


I know, it sounds disgusting, BUT IT'S NOT. This is coming from a girl who would gag at having to eat lettuce a few years ago....and here I am sucking down this green stuff like it's going out of style. Below you will find a "base" recipe which I created and can truly be tweaked to meet YOUR taste buds or dietary restrictions. Keep checking back because I will be posting some of my favorite types of green smoothies on here within the next week: Cocoa Raspberry, Paradise packed with Antioxidants, and the Purple Drank.
this fruit part is very important, if you skimp on this part of the recipe, you will more than likely be able to taste the spinach, and instead will feel like you are drinking salad, which is not the kind of smoothie I like..
- fruit can be frozen which will thicken up the smoothie or you can use fresh!
- GET CREATIVE - everyone has different tastes, what I like (a PB&J Green smoothie) you may find gross, so use this as a loose guide to help kick start your own green smoothie addiction, it's a great way to incorporate more veggies into your diet!


text:
package org.powlab.jeye.tests.strings;

public class StringBuilderTest1 {
    public String test1(int a, int b, int c) {
        return "this " + a + "is" + b + " c? " + c;
    }

}


buy dining room set – Turn your house into a home with buy dining room set from Decor deaux! Personalize your space with buy dining room set accessories in a wide variety of style. From pillows to vases and everything in between, we have all of the little details you need to make your home your own.


text:
Home World War II
"Ang Pasko ay Sumapit" Composer in Thrilling Escape from the Japanese in Cuenca in 1945
December 14, 2018 Batangas History
Image sources: Photo of Josefino Cenizal from Discogs.com. Photo of Japanese soldiers and tank from the United States National Archives.
[In this article: Josefino Cenizal, World War II Batangas, Cuenca Batangas, Lipa Batangas, Ang Pasko ay Sumapit, WWII escape from Japanese, Free Philippines newspaper]
Filipinos as a rule learn to sing the Christmas carol "Ang Pasko ay Sumapit" (Christmas has come) almost instinctively from an early age. In the present day, however, it is all but forgotten that the carol's melody was composed by one Josefino Cenizal, a multi-sided artistic genius from the town of Tanza in Cavite. The carol's lyrics were provided by his friend, the late national artist Levi Celerio1.
Apart from being a composer, Cenizal was a famous pre-war actor and director2. His most well-known directorial works were Rosa Birhen (Rose the Virgin, 1940), Bicol Express (1957) and Milagrosong Kamay (Miraculous Hand, 1961). He was married to a famous post-war actress, Olivia Cenizal. He died in 20153 at the age of 95.
But his illustrious career could have been cut short had the Japanese caught up with him in April 1945. In January, the Americans landed troops in Lingayen and Nasugbu. Cenizal had written a victory song celebrating these landings, and for doing so, the Japanese placed a price over his head.
By April, he was in Cuenca in Batangas, presumably in hiding. The town of Lipa had already been liberated, although the Japanese had withdrawn to nearby Mount Malepunyo for a final stand. In Cuenca, fighting still raged at Mt. Maculot, where the Japanese Army was dug in deep.
Japanese intelligence must have gotten word that Cenizal was in Cuenca and sent seven Japanese soldiers after him. The latter managed to get out, but his inadequately fuelled car stalled while he was on his way to Lipa, safe under the protection of the United States Army.
What ensued was documented in a short item published in the 18 April 1945 edition of the Free Philippines newspaper4, which described the thrilling getaway as Cenizal's "most dramatic role in the stage of life…"
Below is the full text of the news item:
"Josefino Cenizal, well-known figure in pre-war college and local movie circles, played his most dramatic role in the stage of life recently when he fled from Cuenca, Batangas, in an inadequately fuelled car chased by seven Japanese armed with tommy-gun, rifles and hand-grenades.
"The Japanese had set a price of several thousand pesos was set on his head for writing a victory song revolving around the landing of the Americans in Luzon.
"Cenizal's car stalled en route to just liberated Lipa, and the Japanese fired from their pursuing car. An American patrol detachment rushed out of the woods near the road and killed all seven Japanese in a short fight."
The newspaper item with the rescue of Josefino Cenizal.
↓ Scroll down to the bottom of this page to leave a comment.
1 "Unknown man behind PH immortal yuletide music 'Ang Pasko Ay Sumapit' is 98," by Tina Arceo-Dumalao, published 2014, online at the Philippine Daily Inquirer.
2 "Josefino Cenizal," Wikipedia.
3 "Josefino Cenizal (1919–2015)," IMDB.
4 "Yanks Rescue Cenizal from Pursuing Japs," published 18 April 1945 in "Manila Free Philippines Part 1," online at the Internet Archive.

redpajama_set_name: RedPajamaCommonCrawl


Denim shopping is something many of us put off—wiggling into a pair of skinnies in a starkly lit changing room isn't exactly fun. But I went into the Topshop changing rooms armed with as many jeans as the team would let me take in, so I can tell you the pairs that you should try and what I loved about them.
I'm going to be honest: On the hanger, these looked quite terrifying to a straight-leg–only kinda girl like me. They have very wide trouser legs, however, on the body, they look much less extreme and the pants widen at a very flattering point on the thigh. Off the body, they look like they are wide from the crotch down. I went up a size in these, going for a size 8 instead of my usual 6.
The word "balloon" is not something I'd want to use to describe my jeans, and when I saw these, I thought they would look ridiculously pantaloon-like, but actually, they somehow work on and don't look too baggy.
The flared Jamie jeans are an older style and have all of the leg-lengthening qualities of traditional flares but aren't too wide, so they aren't as "retro" or intimidating as other styles.
The Dree is another existing style in Topshop's denim catalog and is one of my favorite styles. These cropped kick-flares have a flattering high waistband and frayed hems—this spring Topshop has introduced them in several lighter washes.
These really are statement jeans, as they have a super-wide leg and thus won't be for everyone, but I like the fit of the waist, and they'd look great with both ankle boots and sandals.
«Next Post He Wants to Cater to Me, but is that Enough?


text:
Model Rocket Height
답안 제출
문제 정보
문제 ID
시간 제한
메모리 제한
정답 횟수 (비율)
1000ms
VOCList
Greater New York Regional 2007
보기 기하
Just when you thought we had run out of model rocket height problems…
Yet another method used to determine the height achieved by a model rocket is the vertical line method. Two observers A and B are spaced D feet apart along a base line along one edge of the flat test field. The launch platform is equidistant from observers A and B and L feet from the base line. Each observer has a theodolite or some other device for measuring angle above the horizontal (elevation angle) of a distant object and the azimuth angle (the angle the vertical plane of the sight line makes with the line from A through B measured counter-clockwise). Each measuring device is on a stand. A's device is HA feet above the level of the launch platform and B's device is HB feet above the level of the launch platform. When a rocket is fired, near the top of its flight, it deploys a parachute and emits a puff of smoke. Each observer measures the elevation angle and azimuth angle of the puff of smoke from their location. If the peak location is on the wrong side of the baseline or outside the lines determined by A and B perpendicular to the base line, it is out of bounds and disqualified. From this information, the height of the rocket may be determined as follows:
Each sight line determines a vertical plane. These two planes intersect in a vertical line (thus the name of the method). Each sight line intersects this vertical line in a point. If these points are more than ERRDIST feet apart, an error is assumed and the flight is rejected. Otherwise, the point halfway between the two points where a sight line intersects the vertical line is computed. The rocket height is the distance of this midpoint above the launch platform.
You must write a program which, given the parameters D (the distance in feet between observers A and B), L (the distance in feet from the base line to the launch platform), HA (the distance of the measuring device A above the launch platform in feet), HB (the distance of the measuring device B above the launch platform in feet), ERRDIST (the maximum distance between the intersection points of a sight line with the vertical line), α (the elevation angle of the rocket in degrees measured by the left observer A), β (the elevation angle of the rocket in degrees observed by the right observer B), γ (the azimuth angle in degrees measured by the left observer A) and δ (the azimuth angle in degrees measured by the right observer B), computes the height of the rocket above the launch platform in feet to the nearest foot.
The first line of input contains a single integer N, (1 ≤ N ≤ 1000) which is the number of datasets that follow.
The second line contains the parameters D, L, HA, HB and ERRDIST in that order as (floating point) decimal values. These values would be measured once at the beginning of the day and remain fixed through all rocket shots.
Each succeeding line of input represents a single dataset. Each dataset will contain the angles α, β, γ and δ in that order (measured in degrees) as (floating point) decimal values for a rocket shot.
For each dataset of four angles, the output consists of a single line . If angles α, β and γ are not
strictly between 0 and 90 degrees or δ is not strictly between 90 degrees and 180 degrees, the line should contain the dataset number, a space and the word "DISQUALIFIED" (without the quotes). Otherwise, if the distance between the intersection points of a sight line with the vertical line is more that ERRDIST feet, the line should contain the dataset number, a space and the word "ERROR" (without the quotes). Otherwise, the line should contain the dataset number, a space and the height above the launch platform in feet to the nearest foot.
예제 입력
100.0 300.0 5.25 2.92 5.00
40.1 36.2 35.3 151.6
예제 출력
4 DISQUALIFIED
0개의 댓글이 있습니다.
정회원 권한이 있어야 커멘트를 다실 수 있습니다. 정회원이 되시려면 온라인 저지에서 5문제 이상을 푸시고, 가입 후 7일 이상이 지나셔야 합니다. 현재 문제를 푸셨습니다.


A man suspected of attacking people on the Taipei MRT is detained at the Jiangzicui Station by local police yesterday.
A 21-year-old student allegedly killed four people and injured 22 yesterday in a random killing spree on a train of the Taipei Mass Rapid Transit (MRT) system's Bannan Line.
The four victims were a 47-year-old woman, a 62-year-old woman and two men aged 20 and 30. They had reportedly lost all vital signs before they were rushed to the New Taipei City Hospital's Banciao Branch, the Taipei Hospital and the Far Eastern Memorial Hospital respectively.
It was the first deadly attack on an MRT train since the Taipei commuter rail system went into commercial service in 1996.
According to New Taipei City Police Department Director-General Chen Kuo-en (陳國恩), Cheng boarded an MRT train heading to the Taipei Nangang Exhibition Center at the Jiangzicui Station earlier in the afternoon and alighted at the Sun Yat-sen Memorial Hall Station.
He subsequently hopped on the ill-fated train heading to the Banciao Station before carrying out the killing spree, Chen added.
Taipei Mayor Hau Lung-bin (郝龍斌) said that for the next two weeks, the city government planned to deploy 80 special police officers to MRT stations to conduct routine patrols, to assist the 143 MRT police officers.
"Our priority is to restore order and security at MRT stations to make sure that our passengers do not feel afraid when taking the metro," Hau said.
New Taipei City Deputy Mayor Hou You-yi (侯友宜) said the city government had instructed all available police officers to patrol the areas surrounding the city's 34 MRT stations shortly after the incident, in an effort to tighten security.
Taipei Rapid Transit Corp (台北捷運公司) general manager Tan Gwa-guang (譚國光) said the company would give NT$4 million (US$132,000) in compensation to the families of the victims and would take care of all medical expenses incurred by the injured passengers.
This story has been viewed 46692 times.


text:
Mixed-Use Projects Headed to Design Review
SEATTLE-Two residential-over-retail developments proposed for the Ballard neighborhood--one containing 60 units and the other 55 units--will be scrutinized by the city's Design Review Board next week.
By Gina Binole | December 02, 2002 at 01:01 AM
SEATTLE-Two multifamily developments proposed for Northwest Seattle will receive their preliminary recommendations from the city's Design Review Board next week.Tukwila, Wash.-based Schneider Homes is seeking design approvals for a four-story, mixed-use building at 14300 Greenwood Ave. The building would contain 60 residential units, ground floor commercial space and parking for 100. The site is zoned Neighborhood Commercial 2 with a 40′ height limit. Neal Thompson is the project architect. Gerald Schneider of Schneider Homes was not immediately available for comment on Monday.
Nearby, at the northwest corner of North 85th Street and Dayton Avenue North in the Ballard neighborhood, a 55-unit project is proposed. Proposed for 424 North 85th St., the building would be four stories tall and include 3,466 sf of ground floor commercial space and parking for 74 within the structure. The majority of the site is zoned Neighborhood Commercial 3 with a 40′ height limit with the northern tip of the site zoned single-family. Project designer Steve Lampert of Driscol Architects did not immediately return a phone call seeking more information, including the name of the developer and the project timeline.
At the Design Review Board meetings for both projects, scheduled for Monday, Dec. 9 at the Ballard High School library, the applicants will present information about the proposed design and how it responds to the Design Guideline priorities established at Early Design Guidance Board meetings that occurred earlier this year.
Elsewhere in Ballard, Continental-Bentall is planning to develop Bridgewater Condos, a 172-unit residential development that includes 7,200-sf of ground floor commercial space and three levels of parking. The 46,000-sf property is located at 5614 17th Av NW, one block off Market Street, the main east-west arterial through the area. The city approved designs for the estimated $22-million project in August. The preliminary timeline is to complete the project during the first half of 2004.
GlobeSt. APARTMENTS SPRING 2021Event
Join 1000+ of the industry's top owners, investors, developers, brokers & financiers at THE MULTIFAMILY EVENT OF THE YEAR!


text:
from django.conf.urls import patterns, include, url
from messages.views import index, topic
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'MessageBoard.views.home', name='home'),
    # url(r'^MessageBoard/', include('MessageBoard.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', index, name="index"),
    url(r'^topic/(?P<topic_id>\d+)/$', topic, name="topic"),

)


Please note that the following shows have special show hours. If a show is NOT mentioned here, then it follows the typical hours above.
+ How Much Do Tickets Cost?
"Discounted Tickets" cost $6.00 (credit card only) if purchased online in advance.
"Standard Tickets" are $8.00 (cash only) at the door.
Military, Wholesale buyers and Schools receive special admission. Please see "Are There Any Discounts For Admission?" for more information.
+ Are There Any Discounts For Admission?
Military members (active and veteran) and their immediate family members receive free admission to the show. Please bring your current Military ID to the show to gain entrance. Thank you for your service!
Registered wholesale buyers receive free admission after their first trip to the show. Make sure to stop register/check-in at the wholesale registration desk to get on our wholesale list. For further instructions on wholesale registration, please visit our WHOLESALE REGISTRATION page.
We provide registered schools free admission and access to the wholesale section (where applicable). To register your school, please visit our TEACHER REGISTRATION page.
+ Are There Any Age/General Restrictions?
Children under the age of 9 are not permitted in the show.
Strollers And Photography are not allowed inside the show.
+ Are InterGem Shows Open To The Public?
Yes, all REGULAR InterGem shows are open to the public. However, wholesale only sections within the shows are not open to the public. To enter the wholesale section, you must register as a wholesale buyer. For more information about registering as a wholesale buyer, please visit our WHOLESALE REGISTRATION page.
InterGem Denver Trade Show: Our annual Denver Trade show during Denver Jewelry Week (September) is not open to the public. You must be a registered wholesale buyer to enter the show. All other InterGem Denver Shows are open to the public.
GLDA Las Vegas Wholesale Show: Our annual Las Vegas Wholesale show during Las Vegas Jewelry Week (May-June) is not open to the public. You must be a registered wholesale buyer to enter the show.
+ How Do I Know If A Show Is Cancelled?
InterGem rarely cancels any planned show. If a show must be cancelled due to inclimate weather or any other reason, we will make it abundantly clear on our website.
+ What Are "Wholesale Sections?
We have designated "Wholesale Sections" within most, but not all, shows. This area provides business owners and wholesale buyers the oppotunity to make large purchases with specialized tax relief in states that are applicable. These sections are not open to the public. To gain entrance to a wholesale section you must be a registered wholesale buyer. For more information on registering, please visit our WHOLESALE REGISTRATION page.
+ What Are "Bead Shows?
Designated "Bead Shows" are specialized shows for jewelry makers and crafters. These shows are restricted to bead and jewelry supply dealers. You will be able to find a huge selection of supplies to create your own jewelry, accessories and decor. Bead shows DO NOT have a wholesale section and are open to the public.
+ What Are "GLDA Shows?
Gem & Lapidary Dealers Association (GLDA) shows are wholesale jewelry shows for business owners and wholesale buyers. These shows correspond with Las Vegas Jewelry Week (May-June) which is an annual event in "Sin City" where wholesale buyers converge to stock up on merchandise and supplies. These shows are NOT open to the public and require registration.
Questions About Our Shows? Contact Us.


The Master of Comparative Law degree is designed to allow Penn Law LL.M. graduates to pursue advanced coursework.
LL.C.M. candidates may have the option of pursuing a "concentration" in a particular field. If a LL.C.M. candidate completes a significant number of courses in a particular field, the student can request that their transcript note a concentration in that field. With the approval of the Graduate Studies Committee, a LL.C.M. student on a concentration track may substitute other relevant and appropriate courses for those designated as part of a concentration track.
b) receive the grade of "F" with credit in no more than three semester hours.
LL.M. and LL.C.M candidates shall be referred to the Committee on Academic Standing when they receive two or more grades of "F" in their first semester.


You may not think that eating on your patio is a picnic, but anytime you eat outdoors, by definition, you are picnicking. If you decide to eat the lunch you brought to function in the park on a nice working day, you are getting a picnic lunch.
One of the very best players in New York Knicks history, Harry Gallatin was a member of the group during its early times as a franchise. Gallatin performed in New York from 1948 to 1957, creating 7 consecutive All-Star appearances as one of the NBA's elite gamers at the time. An additional undersized center, Gallatin was nonetheless a prolific rebounder, averaging 12.one for each sport with the Knicks and holding the 18th highest typical in NBA history. From 1951 to 1953, Gallatin led the Knicks to 3 straight NBA Finals appearances, though they by no means gained a title during his profession.
In a record-setting day for college aces inc. baseball, the Buckeyes lost to the Florida State Seminoles 37-6. While the score appears like something you would see in the fall, it is in fact a baseball score.
With this baseball agents method, Simonedes numbered places in his house. He began in the doorway and then logically proceeded about his house. He reviewed these products so many occasions mentally that if you requested him what was quantity 25, then he could immediately tell you what piece of furniture that number corresponded to.
Following their look in the 2010 College World Series, Oklahoma enters the aces baseball agents season with their highest rating since 1995. In 1994, they won the National Championship.
Luis Gonzalez was a journeyman outfielder with a career high of seventy two RBI in 1 year when the 1999 season dawned and his fortunes rose significantly. He started a string of 5 seasons in which the fewest runs batted in he experienced was 103. At his zenith in 2001, Luis was third in the MVP voting of the senior circuit when he hit 57 home runs for Arizona, two dozen more than he had ever had or would have, and garnered 142 runs batted in. Gonzalez experienced four of his 5 .300 campaigns in that extend, culminating with that 2001 anomaly when he batted .325 and walked 100 times.
I'm not here with any answers to why there are not more blacks playing baseball. I do think that baseball has done an admirable occupation of hiring black managers and coaches. But it needs to discover away to back into the grass roots degree of the black neighborhood and assist younger children realize what a great game it is to perform whether it be in the streets with a pillow for bases or a Major League Stadium with forty,00 followers.