<commit_before>function showHideTableSection(parentid,status){
    $.post({
        url : 'inc/infrastructure/KVM/TableState.php',
        data: {
            parentid: parentid,
            status: status,
        },
    });
}
//==================================================================
function updateVMLock(vmid,lock){
    $.post({
        url : 'inc/infrastructure/KVM/LockVM.php',
        data: {
            vm: vmid,
            lock: lock,
        },
        success: function(data){
            formatAlertMessage(data);
        },
    });
}
//==================================================================
function lockVM(vmid){
    if ($("#copy-disk-from-source-button-"+vmid ).hasClass( 'disabled' )){
        updateVMLock(vmid,'false');
        $("#lock-vm-button-"+vmid).html("VM locked:");
        $("#copy-disk-from-source-button-"+vmid).removeClass('disabled');
        $(".lockable-vm-buttons-"+vmid).removeClass('disabled');
        $("#PopulateMachinesButton-"+vmid).removeClass('disabled');
    }
    else{
        updateVMLock(vmid,'true');
        $("#lock-vm-button-"+vmid).html("VM locked:");
        $("#copy-disk-from-source-button-"+vmid).addClass('disabled');
        $(".lockable-vm-buttons-"+vmid).addClass('disabled');
        $("#PopulateMachinesButton-"+vmid).addClass('disabled');
    }
}
//==================================================================
function reloadKVMVmTable(){
    $( "#main_table" ).load( "inc/infrastructure/KVM/DrawTable.php" );
}
//==================================================================
function checkVMStatus(vm, state, is_parent){
    function runQuery(){
        $.post({
            url: 'inc/infrastructure/KVM/GetVMState.php',
                data: {
                    vm: vm,
                    is_parent: is_parent,
                },
                success: function(data) {
                    var required_state = '';
                    if(state == 'mass_on' || state == 'up')
                        required_state = 'running';
                    else
                        required_state = 'shut';
                    reply = jQuery.parseJSON(data);
                    if (is_parent){ // if there are multiple machines (using mass_x button from initial machine)
                        item_count = reply.length;
                        $.each(reply, function(i, obj){
                            if (obj['state'] == required_state){// if machine is in required state, update information in table
                                $("#VMStatusText-" + obj.id).html(obj.state_html);
                                $("#PowerProgressBar-" + obj.id).addClass('hide');
                                --item_count;
                            }
                            else{
                                $("#PowerProgressBar-" + obj.id).removeClass('hide');
                            }
                        });
                        if (item_count > 0){ // if there are still machines in unwanted state, re-run query
                            setTimeout(function() {runQuery()}, 4000);
                        }
                    }
                    else{// if it is a single VM power cycle
                        if (reply.state == required_state){
                            $("#VMStatusText-" + reply.id).html(reply.state_html);
                            $("#PowerProgressBar-" + reply.id).addClass('hide');
                        }
                        else{
                            $("#PowerProgressBar-" + reply.id).removeClass('hide');
                            setTimeout(function() {runQuery()}, 4000);
                        }
                    }
                },
            });
        }
    runQuery();
}
//==================================================================
$(document).ready(function(){
    $('#main_table').on("click", "a.DeleteVMButton", function() { //since table items are dynamically generated, we will not get ordinary .click() event
        var vm = $(this).attr('data-vm');
        var hypervisor = $(this).attr('data-hypervisor');
        var action = $(this).attr('data-action');
        var parent = $(this).attr('data-parent');
        $.confirm({
            title: 'Alert!',
            content: 'Are you sure?',
            animation: 'opacity',
            buttons: {
                yes: {
                    btnClass: 'btn-danger',
                    action: function(){
                        $('#PleaseWaitDialog').modal('show');
                        $.post({
                            url: 'inc/infrastructure/KVM/DeleteVM.php',
                            data: {
                                vm: vm,
                                hypervisor: hypervisor,
                                action: action,
                                parent: parent
                            },
                            success: function(data) {
                                formatAlertMessage(data)
                                refresh_screen();
                                $('#PleaseWaitDialog').modal('hide');
                            },
                        });
                    }
                },
                no: {
                    btnClass: 'btn-primary',
                }
            }
        });
    });
//==================================================================
    $('#create-vm-button-click').click(function() {
        $("#new_vm_creation_info_box").addClass('hide');
        if(!$('#new_vm')[0].checkValidity()){
            $('#new_vm').find('input[type="submit"]').click();
        }
        else{
            $("#new_vm_creation_info_box").removeClass('hide');
            $("#new_vm_creation_info_box").html("Creating VM please wait.");
            $(".create_vm_buttons").addClass('disabled');
            var machinename = $('#machinename').val();
            if ($('#machine_type').val()=='import')
                machinename = $('#source-machine').val();
                $.ajax({
                    type : 'POST',
                    url : 'inc/infrastructure/KVM/CreateVM.php',
                    data: {
                        machine_type: $('#machine_type').val(),
                        hypervisor: $('#hypervisor').val(),
                        source_volume: $('#source_volume').val(),
                        source_drivepath: $('#source_drivepath').val(),
                        source_drive_size: $('#source_drive_size').val(),
                        iso_image: $('#iso_image').val(),
                        iso_path: $('#iso_path').val(),
                        numsock: $('#numsock').val(),
                        numcore: $('#numcore').val(),
                        numram: $('#numram').val(),
                      network: $('#network').val(),
                        machinename: machinename,
                        machinecount: $('#machinecount').val(),
                        os_type: $('#os_type').val(),
                        os_version: $('#os_version').val(),
                        vmname: $('#machinename').val(),
                        source_hypervisor: $('#source-hypervisor').val(),
                    },
                    success:function (data) {
                        if ($('#machine_type').val() != 'initialmachine') // initial machine uses redirect to disk_copy.php so no json messages here
                            formatAlertMessage(data);
                        $(".create_vm_buttons").removeClass('disabled');
                        $("#new_vm_creation_info_box").addClass('hide');
                        refresh_screen();
                    }
                });
            }
        });

    $('#main_table').on("click", "a.HypervisorMaintenanceButton", function() { //since table items are dynamically generated, we will not get ordinary .click() event
        var hypervisor = $(this).data('hypervisor');
        var maintenance = $(this).data('maintenance');
        var $this = $(this); //need to move reference for ajax callback as $(this) will not work in ajax 'success:'
        $.post({
            url: 'inc/infrastructure/KVM/HypervisorMaintenance.php',
                data: {
                    maintenance: maintenance,
                    hypervisor: hypervisor,
                },
                success: function(data) {
                    if (maintenance == 1){
                        $this.data('maintenance', '0');
                        $this.removeClass('glyphicon-ok-circle');
                        $this.removeClass('btn-success');
                        $this.addClass('glyphicon-ban-circle');
                        $this.addClass('btn-default');
                        $('#hypervisor-table-' + hypervisor).addClass('hypervisor-screen-disabled');
                    }
                    else{
                        $this.data('maintenance', '1');
                        $this.removeClass('glyphicon-ban-circle btn-default');
                        $this.addClass('glyphicon-ok-circle btn-success');
                        $('#hypervisor-table-' + hypervisor).removeClass('hypervisor-screen-disabled');
                      }
                    formatAlertMessage(data);
                    refresh_screen();
                    $('#PleaseWaitDialog').modal('hide');
                },
        });
    });

    $('#main_table').on("click", "a.LockVMButton", function() { //since table items are dynamically generated, we will not get ordinary .click() event
        lockVM($(this).data('id'));
    });

    $('#main_table').on("click", ".MaintenanceCheckbox", function() { //since table items are dynamically generated, we will not get ordinary .click() event
        var vm = $(this).data('id');
        $.post({
            url: 'inc/infrastructure/KVM/VMMaintenance.php',
                data: {
                    source: vm,
                    action: 'single',
                },
                success: function(data) {
                    formatAlertMessage(data);
                },
        });
    });

    $('#main_table').on("click", ".SnapshotCheckbox", function() { //since table items are dynamically generated, we will not get ordinary .click() event
        var vm = $(this).data('id');
        $.post({
            url: 'inc/infrastructure/KVM/VMSnapshot.php',
                data: {
                    vm: vm,
                    action: 'single',
                },
                success: function(data) {
                    formatAlertMessage(data);
                },
        });
    });

    $('#main_table').on("click", ".MassMaintenanceButton", function(e) { //since table items are dynamically generated, we will not get ordinary .click() event
        e.preventDefault(); // prevent href to go # (jump to the top of the page)
        $('#PleaseWaitDialog').modal('show');
        var sourcevm = $(this).data('source');
        var action = $(this).data('action');
        $.post({
            url: 'inc/infrastructure/KVM/VMMaintenance.php',
                data: {
                    source: sourcevm,
                    action: action,
                },
                success: function(data) {
                    if (action == 'mass_on')
                        $('.MaintenanceCheckboxChild-' + sourcevm).prop('checked', 'true');
                    else
                        $('.MaintenanceCheckboxChild-' + sourcevm).prop('checked', '');
                    $('#PleaseWaitDialog').modal('hide');
                    formatAlertMessage(data);
                },
        });
    });

    $('#main_table').on("click", ".MassSnapshotButton", function(e) { //since table items are dynamically generated, we will not get ordinary .click() event
        e.preventDefault(); // prevent href to go # (jump to the top of the page)
        $('#PleaseWaitDialog').modal('show');
        var sourcevm = $(this).data('source');
        var action = $(this).data('action');
        $.post({
            url: 'inc/infrastructure/KVM/VMSnapshot.php',
                data: {
                    vm: sourcevm,
                    action: action,
                },
                success: function(data) {
                    if (action == 'mass_on')
                        $('.SnapshotCheckboxChild-' + sourcevm).prop('checked', 'true');
                    else
                        $('.SnapshotCheckboxChild-' + sourcevm).prop('checked', '');
                    $('#PleaseWaitDialog').modal('hide');
                    formatAlertMessage(data);
                },
        });
    });

    $('#main_table').on("click", ".ParentRow", function(e) { //since table items are dynamically generated, we will not get ordinary .click() event
        if ($('#childof-'+this.id).hasClass('fa-minus')){
            $('#childof-'+this.id).removeClass('fa-minus');
            $('#childof-'+this.id).addClass('fa-plus');
            showHideTableSection(this.id,'hide');
        }
        else {
            $('#childof-'+this.id).removeClass('fa-plus');
            $('#childof-'+this.id).addClass('fa-minus');
            showHideTableSection(this.id,'show');
        }
    });

    $('.DeleteHypervisorButton').click(function() {
        $("#SubmitHypervisorsButton").removeClass('hide');
        var id = $(this).data('id');
        $('#hypervisor-'+id).prop('checked', true);
        $(".name-"+id).addClass('hypervisor-deleted');
    })

    $('#SubmitHypervisorsButton').click(function() {
        var to_delete = [];
        if (confirm('Are you sure?')){
            $(":checked").each(function() {
                if ($(this).val()!='on')
                    to_delete.push($(this).val());
                $("#row-name-"+$(this).val()).remove();
            });
            $.post({
                url : 'inc/infrastructure/KVM/UpdateHypervisors.php',
                data: {
                    type : 'delete',
                    hypervisor : to_delete,
                },
                    success:function (data) {
                        $("#SubmitHypervisorsButton").addClass('hide');
                        formatAlertMessage(data);
                }
            });
        }
    });

    $('#AddHypervisorButton').click(function() {
        if(!$('#HypervisorForm')[0].checkValidity()){
            $('#HypervisorForm').find('input[type="submit"]').click();
        }
        else{
            $("#HypervisorProgress").removeClass('hide');
            $.post({
                url : 'inc/infrastructure/KVM/UpdateHypervisors.php',
                data: {
                    type : 'new',
                    address1 : $('#address1').val(),
                    address2 : $('#address2').val(),
                    port : $('#port').val(),
                    name : $('#name').val(),
                },
                success:function (data) {
                    var msg = jQuery.parseJSON(data);
                    if ("success" in msg){
                        $("#address1").val("");
                        $("#address2").val("");
                        $("#port").val("");
                        $("#name").val("");
                        refresh_screen();
                    }
                    $("#HypervisorProgress").addClass('hide');
                    formatAlertMessage(data);
                }
            });
        }
    });

    $('#main_table').on("click", ".PopulateMachinesButton", function(e) { //since table items are dynamically generated, we will not get ordinary .click() event
        e.preventDefault(); // prevent href to go # (jump to the top of the page)
        if (confirm('All virtual machines will be powered off and their initial snapshots recreated.\nProceed?')){
            $('#PleaseWaitDialog').modal('show');
            var vm = $(this).data('vm');
            var hypervisor = $(this).data('hypervisor');
            $.post({
                url: 'inc/infrastructure/KVM/PopulateVMS.php',
                    data: {
                        vm: vm,
                        hypervisor: hypervisor,
                    },
                    success: function(data) {
                        $('#PleaseWaitDialog').modal('hide');
                        formatAlertMessage(data);
                    },
            });
        }
    });

    $('#main_table').on("click", ".PowerButton", function(e) { //since table items are dynamically generated, we will not get ordinary .click() event
        e.preventDefault(); // prevent href to go # (jump to the top of the page)
        if (confirm('Are you sure?')){
            $('#PleaseWaitDialog').modal('show');
            var vm = $(this).data('vm');
            var hypervisor = $(this).data('hypervisor');
            var state = $(this).data('state');
            var action = $(this).data('action');
            if (action == 'single')
                checkVMStatus(vm, state, 0);
            else
                checkVMStatus(vm, action, 1);
            $.post({
                url: 'inc/infrastructure/KVM/Power.php',
                    data: {
                        vm: vm,
                        hypervisor: hypervisor,
                        state: state,
                        action: action,
                    },
                    success: function(data) {
                        $('#PleaseWaitDialog').modal('hide');
                        formatAlertMessage(data);
                    },
            });
        }
    });

});
//==================================================================
<commit_msg>KVM: making screen to refresh after adding or deleting hypervisor<commit_after>function showHideTableSection(parentid,status){
    $.post({
        url : 'inc/infrastructure/KVM/TableState.php',
        data: {
            parentid: parentid,
            status: status,
        },
    });
}
//==================================================================
function updateVMLock(vmid,lock){
    $.post({
        url : 'inc/infrastructure/KVM/LockVM.php',
        data: {
            vm: vmid,
            lock: lock,
        },
        success: function(data){
            formatAlertMessage(data);
        },
    });
}
//==================================================================
function lockVM(vmid){
    if ($("#copy-disk-from-source-button-"+vmid ).hasClass( 'disabled' )){
        updateVMLock(vmid,'false');
        $("#lock-vm-button-"+vmid).html("VM locked:");
        $("#copy-disk-from-source-button-"+vmid).removeClass('disabled');
        $(".lockable-vm-buttons-"+vmid).removeClass('disabled');
        $("#PopulateMachinesButton-"+vmid).removeClass('disabled');
    }
    else{
        updateVMLock(vmid,'true');
        $("#lock-vm-button-"+vmid).html("VM locked:");
        $("#copy-disk-from-source-button-"+vmid).addClass('disabled');
        $(".lockable-vm-buttons-"+vmid).addClass('disabled');
        $("#PopulateMachinesButton-"+vmid).addClass('disabled');
    }
}
//==================================================================
function reloadKVMVmTable(){
    $( "#main_table" ).load( "inc/infrastructure/KVM/DrawTable.php" );
}
//==================================================================
function checkVMStatus(vm, state, is_parent){
    function runQuery(){
        $.post({
            url: 'inc/infrastructure/KVM/GetVMState.php',
                data: {
                    vm: vm,
                    is_parent: is_parent,
                },
                success: function(data) {
                    var required_state = '';
                    if(state == 'mass_on' || state == 'up')
                        required_state = 'running';
                    else
                        required_state = 'shut';
                    reply = jQuery.parseJSON(data);
                    if (is_parent){ // if there are multiple machines (using mass_x button from initial machine)
                        item_count = reply.length;
                        $.each(reply, function(i, obj){
                            if (obj['state'] == required_state){// if machine is in required state, update information in table
                                $("#VMStatusText-" + obj.id).html(obj.state_html);
                                $("#PowerProgressBar-" + obj.id).addClass('hide');
                                --item_count;
                            }
                            else{
                                $("#PowerProgressBar-" + obj.id).removeClass('hide');
                            }
                        });
                        if (item_count > 0){ // if there are still machines in unwanted state, re-run query
                            setTimeout(function() {runQuery()}, 4000);
                        }
                    }
                    else{// if it is a single VM power cycle
                        if (reply.state == required_state){
                            $("#VMStatusText-" + reply.id).html(reply.state_html);
                            $("#PowerProgressBar-" + reply.id).addClass('hide');
                        }
                        else{
                            $("#PowerProgressBar-" + reply.id).removeClass('hide');
                            setTimeout(function() {runQuery()}, 4000);
                        }
                    }
                },
            });
        }
    runQuery();
}
//==================================================================
$(document).ready(function(){
    $('#main_table').on("click", "a.DeleteVMButton", function() { //since table items are dynamically generated, we will not get ordinary .click() event
        var vm = $(this).attr('data-vm');
        var hypervisor = $(this).attr('data-hypervisor');
        var action = $(this).attr('data-action');
        var parent = $(this).attr('data-parent');
        $.confirm({
            title: 'Alert!',
            content: 'Are you sure?',
            animation: 'opacity',
            buttons: {
                yes: {
                    btnClass: 'btn-danger',
                    action: function(){
                        $('#PleaseWaitDialog').modal('show');
                        $.post({
                            url: 'inc/infrastructure/KVM/DeleteVM.php',
                            data: {
                                vm: vm,
                                hypervisor: hypervisor,
                                action: action,
                                parent: parent
                            },
                            success: function(data) {
                                formatAlertMessage(data)
                                refresh_screen();
                                $('#PleaseWaitDialog').modal('hide');
                            },
                        });
                    }
                },
                no: {
                    btnClass: 'btn-primary',
                }
            }
        });
    });
//==================================================================
    $('#create-vm-button-click').click(function() {
        $("#new_vm_creation_info_box").addClass('hide');
        if(!$('#new_vm')[0].checkValidity()){
            $('#new_vm').find('input[type="submit"]').click();
        }
        else{
            $("#new_vm_creation_info_box").removeClass('hide');
            $("#new_vm_creation_info_box").html("Creating VM please wait.");
            $(".create_vm_buttons").addClass('disabled');
            var machinename = $('#machinename').val();
            if ($('#machine_type').val()=='import')
                machinename = $('#source-machine').val();
                $.ajax({
                    type : 'POST',
                    url : 'inc/infrastructure/KVM/CreateVM.php',
                    data: {
                        machine_type: $('#machine_type').val(),
                        hypervisor: $('#hypervisor').val(),
                        source_volume: $('#source_volume').val(),
                        source_drivepath: $('#source_drivepath').val(),
                        source_drive_size: $('#source_drive_size').val(),
                        iso_image: $('#iso_image').val(),
                        iso_path: $('#iso_path').val(),
                        numsock: $('#numsock').val(),
                        numcore: $('#numcore').val(),
                        numram: $('#numram').val(),
                      network: $('#network').val(),
                        machinename: machinename,
                        machinecount: $('#machinecount').val(),
                        os_type: $('#os_type').val(),
                        os_version: $('#os_version').val(),
                        vmname: $('#machinename').val(),
                        source_hypervisor: $('#source-hypervisor').val(),
                    },
                    success:function (data) {
                        if ($('#machine_type').val() != 'initialmachine') // initial machine uses redirect to disk_copy.php so no json messages here
                            formatAlertMessage(data);
                        $(".create_vm_buttons").removeClass('disabled');
                        $("#new_vm_creation_info_box").addClass('hide');
                        refresh_screen();
                    }
                });
            }
        });

    $('#main_table').on("click", "a.HypervisorMaintenanceButton", function() { //since table items are dynamically generated, we will not get ordinary .click() event
        var hypervisor = $(this).data('hypervisor');
        var maintenance = $(this).data('maintenance');
        var $this = $(this); //need to move reference for ajax callback as $(this) will not work in ajax 'success:'
        $.post({
            url: 'inc/infrastructure/KVM/HypervisorMaintenance.php',
                data: {
                    maintenance: maintenance,
                    hypervisor: hypervisor,
                },
                success: function(data) {
                    if (maintenance == 1){
                        $this.data('maintenance', '0');
                        $this.removeClass('glyphicon-ok-circle');
                        $this.removeClass('btn-success');
                        $this.addClass('glyphicon-ban-circle');
                        $this.addClass('btn-default');
                        $('#hypervisor-table-' + hypervisor).addClass('hypervisor-screen-disabled');
                    }
                    else{
                        $this.data('maintenance', '1');
                        $this.removeClass('glyphicon-ban-circle btn-default');
                        $this.addClass('glyphicon-ok-circle btn-success');
                        $('#hypervisor-table-' + hypervisor).removeClass('hypervisor-screen-disabled');
                      }
                    formatAlertMessage(data);
                    refresh_screen();
                    $('#PleaseWaitDialog').modal('hide');
                },
        });
    });

    $('#main_table').on("click", "a.LockVMButton", function() { //since table items are dynamically generated, we will not get ordinary .click() event
        lockVM($(this).data('id'));
    });

    $('#main_table').on("click", ".MaintenanceCheckbox", function() { //since table items are dynamically generated, we will not get ordinary .click() event
        var vm = $(this).data('id');
        $.post({
            url: 'inc/infrastructure/KVM/VMMaintenance.php',
                data: {
                    source: vm,
                    action: 'single',
                },
                success: function(data) {
                    formatAlertMessage(data);
                },
        });
    });

    $('#main_table').on("click", ".SnapshotCheckbox", function() { //since table items are dynamically generated, we will not get ordinary .click() event
        var vm = $(this).data('id');
        $.post({
            url: 'inc/infrastructure/KVM/VMSnapshot.php',
                data: {
                    vm: vm,
                    action: 'single',
                },
                success: function(data) {
                    formatAlertMessage(data);
                },
        });
    });

    $('#main_table').on("click", ".MassMaintenanceButton", function(e) { //since table items are dynamically generated, we will not get ordinary .click() event
        e.preventDefault(); // prevent href to go # (jump to the top of the page)
        $('#PleaseWaitDialog').modal('show');
        var sourcevm = $(this).data('source');
        var action = $(this).data('action');
        $.post({
            url: 'inc/infrastructure/KVM/VMMaintenance.php',
                data: {
                    source: sourcevm,
                    action: action,
                },
                success: function(data) {
                    if (action == 'mass_on')
                        $('.MaintenanceCheckboxChild-' + sourcevm).prop('checked', 'true');
                    else
                        $('.MaintenanceCheckboxChild-' + sourcevm).prop('checked', '');
                    $('#PleaseWaitDialog').modal('hide');
                    formatAlertMessage(data);
                },
        });
    });

    $('#main_table').on("click", ".MassSnapshotButton", function(e) { //since table items are dynamically generated, we will not get ordinary .click() event
        e.preventDefault(); // prevent href to go # (jump to the top of the page)
        $('#PleaseWaitDialog').modal('show');
        var sourcevm = $(this).data('source');
        var action = $(this).data('action');
        $.post({
            url: 'inc/infrastructure/KVM/VMSnapshot.php',
                data: {
                    vm: sourcevm,
                    action: action,
                },
                success: function(data) {
                    if (action == 'mass_on')
                        $('.SnapshotCheckboxChild-' + sourcevm).prop('checked', 'true');
                    else
                        $('.SnapshotCheckboxChild-' + sourcevm).prop('checked', '');
                    $('#PleaseWaitDialog').modal('hide');
                    formatAlertMessage(data);
                },
        });
    });

    $('#main_table').on("click", ".ParentRow", function(e) { //since table items are dynamically generated, we will not get ordinary .click() event
        if ($('#childof-'+this.id).hasClass('fa-minus')){
            $('#childof-'+this.id).removeClass('fa-minus');
            $('#childof-'+this.id).addClass('fa-plus');
            showHideTableSection(this.id,'hide');
        }
        else {
            $('#childof-'+this.id).removeClass('fa-plus');
            $('#childof-'+this.id).addClass('fa-minus');
            showHideTableSection(this.id,'show');
        }
    });

    $('.DeleteHypervisorButton').click(function() {
        $("#SubmitHypervisorsButton").removeClass('hide');
        var id = $(this).data('id');
        $('#hypervisor-'+id).prop('checked', true);
        $(".name-"+id).addClass('hypervisor-deleted');
    })

    $('#SubmitHypervisorsButton').click(function() {
        var to_delete = [];
        if (confirm('Are you sure?')){
            $(":checked").each(function() {
                if ($(this).val()!='on')
                    to_delete.push($(this).val());
                $("#row-name-"+$(this).val()).remove();
            });
            $.post({
                url : 'inc/infrastructure/KVM/UpdateHypervisors.php',
                data: {
                    type : 'delete',
                    hypervisor : to_delete,
                },
                    success:function (data) {
                        $("#SubmitHypervisorsButton").addClass('hide');
                        refresh_screen();
                        formatAlertMessage(data);
                }
            });
        }
    });

    $('#AddHypervisorButton').click(function() {
        if(!$('#HypervisorForm')[0].checkValidity()){
            $('#HypervisorForm').find('input[type="submit"]').click();
        }
        else{
            $("#HypervisorProgress").removeClass('hide');
            $.post({
                url : 'inc/infrastructure/KVM/UpdateHypervisors.php',
                data: {
                    type : 'new',
                    address1 : $('#address1').val(),
                    address2 : $('#address2').val(),
                    port : $('#port').val(),
                    name : $('#name').val(),
                },
                success:function (data) {
                    var msg = jQuery.parseJSON(data);
                    if ("success" in msg){
                        $("#address1").val("");
                        $("#address2").val("");
                        $("#port").val("");
                        $("#name").val("");
                        refresh_screen();
                    }
                    $("#HypervisorProgress").addClass('hide');
                    refresh_screen();
                    formatAlertMessage(data);
                }
            });
        }
    });

    $('#main_table').on("click", ".PopulateMachinesButton", function(e) { //since table items are dynamically generated, we will not get ordinary .click() event
        e.preventDefault(); // prevent href to go # (jump to the top of the page)
        if (confirm('All virtual machines will be powered off and their initial snapshots recreated.\nProceed?')){
            $('#PleaseWaitDialog').modal('show');
            var vm = $(this).data('vm');
            var hypervisor = $(this).data('hypervisor');
            $.post({
                url: 'inc/infrastructure/KVM/PopulateVMS.php',
                    data: {
                        vm: vm,
                        hypervisor: hypervisor,
                    },
                    success: function(data) {
                        $('#PleaseWaitDialog').modal('hide');
                        formatAlertMessage(data);
                    },
            });
        }
    });

    $('#main_table').on("click", ".PowerButton", function(e) { //since table items are dynamically generated, we will not get ordinary .click() event
        e.preventDefault(); // prevent href to go # (jump to the top of the page)
        if (confirm('Are you sure?')){
            $('#PleaseWaitDialog').modal('show');
            var vm = $(this).data('vm');
            var hypervisor = $(this).data('hypervisor');
            var state = $(this).data('state');
            var action = $(this).data('action');
            if (action == 'single')
                checkVMStatus(vm, state, 0);
            else
                checkVMStatus(vm, action, 1);
            $.post({
                url: 'inc/infrastructure/KVM/Power.php',
                    data: {
                        vm: vm,
                        hypervisor: hypervisor,
                        state: state,
                        action: action,
                    },
                    success: function(data) {
                        $('#PleaseWaitDialog').modal('hide');
                        formatAlertMessage(data);
                    },
            });
        }
    });

});
//==================================================================
<|endoftext|>


<commit_before>'use strict';

import _ from 'underscore'
import sinon from 'sinon'
import Promise from 'bluebird'

import { Dispatcher, Module, ProxyMethods } from '../../'

const stubPromise = sinon.createStubInstance(Promise)

class TestApp extends Dispatcher {
  constructor() {
    super()

    this.log = sinon.spy();
    this.log.debug = sinon.spy();
    this.log.info = sinon.spy();
    this.log.error = sinon.spy();
    this.config = {};

    this.on = sinon.spy(this.on);
    this.once = sinon.spy(this.once);
    this.before = sinon.spy(this.before);
    this.after = sinon.spy(this.after);
    this.onceBefore = sinon.spy(this.onceBefore);
    this.onceAfter = sinon.spy(this.onceAfter);

    this._request = sinon.stub().returns(stubPromise)
    this._provide = sinon.stub().returns(stubPromise)
    this._replace = sinon.stub().returns(stubPromise)
    this._default = sinon.stub().returns(stubPromise)

    this._get_on = sinon.spy();
    this._get_emit = sinon.spy();
    this._get_once = sinon.spy();
    this._get_gather = sinon.stub().returnsThis();
    this._get_respond = sinon.stub().returnsThis();
    this._get_default = sinon.stub().returnsThis();
    this._get_replace = sinon.stub().returnsThis();

    let handler = function(next) {
      return function(name, h) {
        if (h == undefined) {
          throw "Handler does not exist for "+name
        }
        return next(name, h)
      }
    }
    this._get = {
      gather: this._get_gather,
      respond: this._get_respond,
      on: sinon.stub().returns(this._get_on),
      emit: sinon.stub().returns(this._get_emit),
      once: sinon.stub().returns(this._get_once),
      request: this._request,
      provide: this._replace,
      provideAfter: this._replace,
      provideBefore: this._default,
      default: this._default,
      replace: this._replace,
      use: (i) => {
        let m = new Module(this)
        let useme = _.extend(_.clone(this._get), {gather: handler(this._get_gather), respond: handler(this._get_respond)})
        return m.use.call(useme, i)
      }
    }
    this.get = sinon.stub().returns(ProxyMethods(() => {return this._get})());
    this._request.withArgs().returns(this.get())
    this._provide.withArgs().returns(this.get())
    this._default.withArgs().returns(this.get())
    this._replace.withArgs().returns(this.get())

  }

  launch() {
    return new Promise.mapSeries(['init', 'load', 'startup', 'launch'], (e) => {
      return this.emit(e)
    })
  }

}

export default TestApp;
<commit_msg>TestApp.get.emit returns actual promise<commit_after>'use strict';

import _ from 'underscore'
import sinon from 'sinon'
import Promise from 'bluebird'

import { Dispatcher, Module, ProxyMethods } from '../../'

const stubPromise = sinon.createStubInstance(Promise)

class TestApp extends Dispatcher {
  constructor() {
    super()

    this.log = sinon.spy();
    this.log.debug = sinon.spy();
    this.log.info = sinon.spy();
    this.log.error = sinon.spy();
    this.config = {};

    this.on = sinon.spy(this.on);
    this.once = sinon.spy(this.once);
    this.before = sinon.spy(this.before);
    this.after = sinon.spy(this.after);
    this.onceBefore = sinon.spy(this.onceBefore);
    this.onceAfter = sinon.spy(this.onceAfter);

    this._request = sinon.stub().returns(stubPromise)
    this._provide = sinon.stub().returns(stubPromise)
    this._replace = sinon.stub().returns(stubPromise)
    this._default = sinon.stub().returns(stubPromise)

    this._get_on = sinon.spy();
    this._get_emit = sinon.spy(function(event, ...args) {return Promise.resolve(...args)})
    this._get_once = sinon.spy();
    this._get_gather = sinon.stub().returnsThis();
    this._get_respond = sinon.stub().returnsThis();
    this._get_default = sinon.stub().returnsThis();
    this._get_replace = sinon.stub().returnsThis();

    let handler = function(next) {
      return function(name, h) {
        if (h == undefined) {
          throw "Handler does not exist for "+name
        }
        return next(name, h)
      }
    }
    this._get = {
      gather: this._get_gather,
      respond: this._get_respond,
      on: sinon.stub().returns(this._get_on),
      emit: this._get_emit,
      once: sinon.stub().returns(this._get_once),
      request: this._request,
      provide: this._replace,
      provideAfter: this._replace,
      provideBefore: this._default,
      default: this._default,
      replace: this._replace,
      use: (i) => {
        let m = new Module(this)
        let useme = _.extend(_.clone(this._get), {gather: handler(this._get_gather), respond: handler(this._get_respond)})
        return m.use.call(useme, i)
      }
    }
    this.get = sinon.stub().returns(ProxyMethods(() => {return this._get})());
    this._request.withArgs().returns(this.get())
    this._provide.withArgs().returns(this.get())
    this._default.withArgs().returns(this.get())
    this._replace.withArgs().returns(this.get())

  }

  launch() {
    return new Promise.mapSeries(['init', 'load', 'startup', 'launch'], (e) => {
      return this.emit(e)
    })
  }

}

export default TestApp;
<|endoftext|>


<commit_before>/*global describe, beforeEach, it*/
'use strict';

var path    = require('path');
var helpers = require('yeoman-generator').test;
var should  = require('should');

describe('controller sub-generator (with arg)', function(){

  var ctrlName = 'test'
    , testRoot = path.join(__dirname, 'temp');

  before(function (done) {
    this.controller = helpers.createGenerator('clutch:controller', [
      path.join(__dirname, '../controller')
    ], [ctrlName]);

    helpers.mockPrompt(this.controller, {
      'createTemplate': true
    });

    this.controller.run({}, function () {
      done();
    });
  });

  it('should have proper controller name', function(){
    this.controller.controllerName.should.equal(ctrlName);
  });

  it('should create proper controller file', function(){
    helpers.assertFile(
      path.join(testRoot, 'server/app/controllers', ctrlName + '_controller.js')
    );
  })

});<commit_msg>Finalized test for controller generator<commit_after>/*global describe, beforeEach, it*/
'use strict';

var path    = require('path')
  , fs      = require('fs')
  , helpers = require('yeoman-generator').test
  , should  = require('should');

describe('controller sub-generator (with arg, no directory prefix)', function(){

  var ctrlName = 'witharg'
    , testRoot = path.join(__dirname, 'temp');

  before(function (done) {
    this.controller = helpers.createGenerator('clutch:controller', [
      path.join(__dirname, '../controller')
    ], [ctrlName]);

    helpers.mockPrompt(this.controller, {
      'createTemplate': true
    });

    this.controller.run({}, function () {
      done();
    });
  });

  it('should have proper controller name', function(){
    this.controller.name.should.equal(ctrlName);
  });

  it('should create proper controller file', function(){
    helpers.assertFile(
      path.join(testRoot, 'server/app/controllers', ctrlName + '_controller.js')
    );
  });

  it('should have created a template file', function(){
    helpers.assertFile(
      path.join(testRoot, 'server/templates/', ctrlName, 'index.html')
    );
  })

});

describe('controller sub-generator (with arg, and directory prefix)', function(){

  var ctrlName = 'dir/witharg'
    , testRoot = path.join(__dirname, 'temp');

  before(function (done) {
    this.controller = helpers.createGenerator('clutch:controller', [
      path.join(__dirname, '../controller')
    ], [ctrlName]);

    helpers.mockPrompt(this.controller, {
      'createTemplate': true
    });

    this.controller.run({}, function () {
      done();
    });
  });

  it('should have recieved controller name', function(){
    this.controller.name.should.equal(ctrlName);
  });

  it('should create proper controller file', function(){
    helpers.assertFile(
      path.join(testRoot, 'server/app/controllers', ctrlName + '_controller.js')
    );
  });

  it('should have created a template file', function(){
    helpers.assertFile(
      path.join(testRoot, 'server/templates/', ctrlName, 'index.html')
    );
  })

});

describe('controller sub-generator (without arg, no directory prefix)', function(){

  var ctrlName = 'noarg'
    , testRoot = path.join(__dirname, 'temp');

  before(function (done) {
    this.controller = helpers.createGenerator('clutch:controller', [
      path.join(__dirname, '../controller')
    ]);

    helpers.mockPrompt(this.controller, {
      'createTemplate': true,
      'controllerName': ctrlName
    });

    this.controller.run({}, function () {
      done();
    });
  });

  it('should have recieved controller name', function(){
    this.controller.name.should.equal(ctrlName);
  });

  it('should create proper controller file', function(){
    helpers.assertFile(
      path.join(testRoot, 'server/app/controllers', ctrlName + '_controller.js')
    );
  });

  it('should have created a template file', function(){
    helpers.assertFile(
      path.join(testRoot, 'server/templates/', ctrlName, 'index.html')
    );
  })

});

describe('controller sub-generator (without arg, directory prefix)', function(){

  var ctrlName = 'dir/noarg'
    , testRoot = path.join(__dirname, 'temp');

  before(function (done) {
    this.controller = helpers.createGenerator('clutch:controller', [
      path.join(__dirname, '../controller')
    ]);

    helpers.mockPrompt(this.controller, {
      'createTemplate': true,
      'controllerName': ctrlName
    });

    this.controller.run({}, function () {
      done();
    });
  });

  it('should have recieved controller name', function(){
    this.controller.name.should.equal(ctrlName);
  });

  it('should create proper controller file', function(){
    helpers.assertFile(
      path.join(testRoot, 'server/app/controllers', ctrlName + '_controller.js')
    );
  });

  it('should have created a template file', function(){
    helpers.assertFile(
      path.join(testRoot, 'server/templates/', ctrlName, 'index.html')
    );
  })

});

describe('controller sub-generator (no template)', function(){

  var ctrlName = 'notemplate'
    , testRoot = path.join(__dirname, 'temp');

  before(function (done) {
    this.controller = helpers.createGenerator('clutch:controller', [
      path.join(__dirname, '../controller')
    ]);

    helpers.mockPrompt(this.controller, {
      'createTemplate': false,
      'controllerName': ctrlName
    });

    this.controller.run({}, function () {
      done();
    });
  });

  it('should have recieved controller name', function(){
    this.controller.name.should.equal(ctrlName);
  });

  it('should create proper controller file', function(){
    helpers.assertFile(
      path.join(testRoot, 'server/app/controllers', ctrlName + '_controller.js')
    );
  });

  it('should have NOT created a template file', function(){
    fs.existsSync(path.join(testRoot, 'server/templates/', ctrlName, 'index.html'))
      .should.not.exist;
  })

});<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var assert = require('assert');
var inherits = require('util').inherits;
var EventEmitter = require('../lib/event_emitter');

module.exports = EgressNodes;

function EgressNodes(options) {
    if (!(this instanceof EgressNodes)) {
        return new EgressNodes(options);
    }
    var self = this;

    assert(options && options.ringpop, 'ringpop required');
    assert(options && options.defaultKValue, 'defaultKValue required');

    EventEmitter.call(self);

    self.ringpop = options.ringpop;
    self.defaultKValue = options.defaultKValue;

    self.kValueForServiceName = {};

    // Surface the membership changed event (for use in particular by service
    // proxies).
    self.membershipChangedEvent = self.defineEvent('membershipChanged');
    self.ringpop.on('membershipChanged', onMembershipChanged);
    function onMembershipChanged() {
        self.membershipChangedEvent.emit(self);
    }
}

inherits(EgressNodes, EventEmitter);

EgressNodes.prototype.kValueFor = function kValueFor(serviceName) {
    var self = this;
    return self.kValueForServiceName[serviceName] ||
        self.defaultKValue;
};

EgressNodes.prototype.setDefaultKValue = function setDefaultKValue(kValue) {
    var self = this;
    assert(typeof kValue === 'number' && kValue > 0);
    self.defaultKValue = kValue;
};

EgressNodes.prototype.setKValueFor = function setKValueFor(serviceName, k) {
    var self = this;
    self.kValueForServiceName[serviceName] = k;
};

EgressNodes.prototype.exitsFor = function exitsFor(serviceName) {
    var self = this;
    var k = self.kValueFor(serviceName);
    // Object<hostPort: String, Array<lookupKey: String>>
    var exitNodes = Object.create(null);
    for (var i = 0; i < k; i++) {
        var shardKey = serviceName + '~' + i;

        // TODO ringpop will return itself if it cannot find
        // it which is probably the wrong semantics.
        var node = self.ringpop.lookup(shardKey);

        // TODO ringpop can return duplicates. do we want
        // <= k exitNodes or k exitNodes ?
        // TODO consider walking the ring instead.

        exitNodes[node] = exitNodes[node] || [];
        exitNodes[node].push(shardKey);
    }
    return exitNodes;
};

EgressNodes.prototype.isExitFor = function isExitFor(serviceName) {
    var self = this;
    var k = self.kValueFor(serviceName);
    var me = self.ringpop.whoami();
    for (var i = 0; i < k; i++) {
        var shardKey = serviceName + '~' + i;
        var node = self.ringpop.lookup(shardKey);
        if (me === node) {
            return true;
        }
    }
    return false;
};
<commit_msg>move egress nodes<commit_after><|endoftext|>


<commit_before>/**
 * This contains API endpoints in the design doc.
 */
export const API = {
    'new-job': '/jobs',
    'update-job': '/jobs',
    'get-individual-job': '/jobs',
    'get-job-listings': '/jobs/listings',
    'delete-job': '/jobs/delete',
    'expire-job': '/jobs/expire',
};
<commit_msg>Fix grammar error<commit_after>/**
 * This file contains API endpoints in the design doc.
 */
export const API = {
    'new-job': '/jobs',
    'update-job': '/jobs',
    'get-individual-job': '/jobs',
    'get-job-listings': '/jobs/listings',
    'delete-job': '/jobs/delete',
    'expire-job': '/jobs/expire',
};
<|endoftext|>


<commit_before>
/*
 *  Waltz
 * Copyright (c) David Watkins. All rights reserved.
 * The use and distribution terms for this software are covered by the
 * Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
 * which can be found in the file epl-v10.html at the root of this distribution.
 * By using this software in any fashion, you are agreeing to be bound by
 * the terms of this license.
 * You must not remove this notice, or any other, from this software.
 *
 */

import {nest} from "d3-collection";
import _ from "lodash";
import {aggregatePeopleInvolvements} from "../involvement/involvement-utils";

const CHANGE_LOG_LIMIT = 20;

function addDataTypes(extras, vm) {
    const existing = vm.dataTypes ? vm.dataTypes : [];
    vm.dataTypes = _.union(existing, extras);
    return vm.dataTypes;
}

function addOrgUnits(extras, vm) {
    const existing = vm.orgUnits ? vm.orgUnits : [];
    vm.orgUnits = _.union(existing, extras);
    vm.orgUnitsById = _.keyBy(vm.orgUnits, 'id');
    return vm.orgUnits;
}

export function loadDataFlows(dataFlowStore, id, vm) {
    return dataFlowStore
        .findByEntityReference('APPLICATION', id)
        .then(flows => vm.flows = flows);
}

export function loadChangeLog(changeLogStore, id, vm) {
    changeLogStore
        .findByEntityReference('APPLICATION', id, CHANGE_LOG_LIMIT)
        .then(log => vm.log = log);
}

export function loadSourceDataRatings(sourceDataRatingStore, vm) {
    sourceDataRatingStore
        .findAll()
        .then(sdrs => vm.sourceDataRatings = sdrs);
}

export function loadServers(serverInfoStore, appId, vm) {
    serverInfoStore
        .findByAppId(appId)
        .then(servers => vm.servers = servers);
}

export function loadSoftwareCatalog(catalogStore, appId, vm) {
    catalogStore.findByAppIds([appId])
        .then(resp => vm.softwareCatalog = resp);
}

export function loadDatabases(databaseStore, appId, vm) {
    databaseStore.findByAppId(appId)
        .then(resp => vm.databases = resp);
}

export function loadInvolvements($q, involvementStore, id, vm) {
    $q.all([
        involvementStore.findByEntityReference('APPLICATION', id),
        involvementStore.findPeopleByEntityReference('APPLICATION', id)
    ]).then(([involvements, people]) => {
        vm.peopleInvolvements = aggregatePeopleInvolvements(involvements, people);
    });
}

export function loadAuthSources(authSourceStore, orgUnitStore, appId, ouId, vm) {
    const appAuthSourcePromise = authSourceStore.findByApp(appId);
    const ouAuthSourcesPromise = authSourceStore.findByReference('ORG_UNIT', ouId);

    ouAuthSourcesPromise.then(ouas => vm.ouAuthSources = ouas);
    appAuthSourcePromise.then(aas => vm.appAuthSources = aas);

    appAuthSourcePromise.then(authSources => nest()
        .key(a => a.dataType)
        .key(a => a.rating)
        .map(authSources))
        .then(nested => vm.authSources = nested)
        .then(nested => addDataTypes(_.keys(nested), vm));

    return appAuthSourcePromise
        .then(authSources => _.chain(authSources)
            .filter(a => a.parentReference.kind === 'ORG_UNIT')
            .map(a => a.parentReference.id)
            .uniq()
            .value())
        .then(orgUnitIds => orgUnitStore.findByIds(orgUnitIds))
        .then(orgUnits => addOrgUnits(orgUnits, vm));
}

export function loadDataTypeUsages(dataTypeUsageStore, appId, vm) {
    return dataTypeUsageStore
        .findForEntity('APPLICATION', appId)
        .then(usages => vm.dataTypeUsages = usages);
}

export function loadDataFlowDecorators(store, appId, vm) {
    const selector = {
        entityReference: { id: appId, kind: 'APPLICATION'},
        scope: 'EXACT'
    };

    return store
        .findBySelectorAndKind(selector, 'DATA_TYPE')
        .then(r => vm.dataFlowDecorators = r);
}
<commit_msg>Auth source bug (nest.map -> nest.object) #1140<commit_after>
/*
 *  Waltz
 * Copyright (c) David Watkins. All rights reserved.
 * The use and distribution terms for this software are covered by the
 * Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
 * which can be found in the file epl-v10.html at the root of this distribution.
 * By using this software in any fashion, you are agreeing to be bound by
 * the terms of this license.
 * You must not remove this notice, or any other, from this software.
 *
 */

import {nest} from "d3-collection";
import _ from "lodash";
import {aggregatePeopleInvolvements} from "../involvement/involvement-utils";

const CHANGE_LOG_LIMIT = 20;

function addDataTypes(extras, vm) {
    const existing = vm.dataTypes ? vm.dataTypes : [];
    vm.dataTypes = _.union(existing, extras);
    return vm.dataTypes;
}

function addOrgUnits(extras, vm) {
    const existing = vm.orgUnits ? vm.orgUnits : [];
    vm.orgUnits = _.union(existing, extras);
    vm.orgUnitsById = _.keyBy(vm.orgUnits, 'id');
    return vm.orgUnits;
}

export function loadDataFlows(dataFlowStore, id, vm) {
    return dataFlowStore
        .findByEntityReference('APPLICATION', id)
        .then(flows => vm.flows = flows);
}

export function loadChangeLog(changeLogStore, id, vm) {
    changeLogStore
        .findByEntityReference('APPLICATION', id, CHANGE_LOG_LIMIT)
        .then(log => vm.log = log);
}

export function loadSourceDataRatings(sourceDataRatingStore, vm) {
    sourceDataRatingStore
        .findAll()
        .then(sdrs => vm.sourceDataRatings = sdrs);
}

export function loadServers(serverInfoStore, appId, vm) {
    serverInfoStore
        .findByAppId(appId)
        .then(servers => vm.servers = servers);
}

export function loadSoftwareCatalog(catalogStore, appId, vm) {
    catalogStore.findByAppIds([appId])
        .then(resp => vm.softwareCatalog = resp);
}

export function loadDatabases(databaseStore, appId, vm) {
    databaseStore.findByAppId(appId)
        .then(resp => vm.databases = resp);
}

export function loadInvolvements($q, involvementStore, id, vm) {
    $q.all([
        involvementStore.findByEntityReference('APPLICATION', id),
        involvementStore.findPeopleByEntityReference('APPLICATION', id)
    ]).then(([involvements, people]) => {
        vm.peopleInvolvements = aggregatePeopleInvolvements(involvements, people);
    });
}

export function loadAuthSources(authSourceStore, orgUnitStore, appId, ouId, vm) {
    const appAuthSourcePromise = authSourceStore.findByApp(appId);
    const ouAuthSourcesPromise = authSourceStore.findByReference('ORG_UNIT', ouId);

    ouAuthSourcesPromise.then(ouas => vm.ouAuthSources = ouas);
    appAuthSourcePromise.then(aas => vm.appAuthSources = aas);

    appAuthSourcePromise.then(authSources => nest()
        .key(a => a.dataType)
        .key(a => a.rating)
        .object(authSources))
        .then(nested => vm.authSources = nested)
        .then(nested => addDataTypes(_.keys(nested), vm));

    return appAuthSourcePromise
        .then(authSources => _.chain(authSources)
            .filter(a => a.parentReference.kind === 'ORG_UNIT')
            .map(a => a.parentReference.id)
            .uniq()
            .value())
        .then(orgUnitIds => orgUnitStore.findByIds(orgUnitIds))
        .then(orgUnits => addOrgUnits(orgUnits, vm));
}

export function loadDataTypeUsages(dataTypeUsageStore, appId, vm) {
    return dataTypeUsageStore
        .findForEntity('APPLICATION', appId)
        .then(usages => vm.dataTypeUsages = usages);
}

export function loadDataFlowDecorators(store, appId, vm) {
    const selector = {
        entityReference: { id: appId, kind: 'APPLICATION'},
        scope: 'EXACT'
    };

    return store
        .findBySelectorAndKind(selector, 'DATA_TYPE')
        .then(r => vm.dataFlowDecorators = r);
}
<|endoftext|>


<commit_before>var fs    = require('fs');
var path  = require('path');
var jsdom = require('jsdom').jsdom;

module.exports = jsdomrequire;
function jsdomrequire(html, requireOptions, callback) {
    var doc;
    var window;

    if (arguments.length === 2) {
        if (typeof html === 'string') {
            callback = requireOptions;
            requireOptions = {};
        } else {
            callback = requireOptions;
            requireOptions = html;
            html = null;
        }
    } else if (arguments.length === 1) {
        callback = html;
        html = null;
        requireOptions = {};
    }

    window = getWindow(html);

    initRequire(window, requireOptions, function(err) {
        callback(err, window);
    });

    this.amdrequire = function(deps, callback) {
        deps = Array.isArray(deps) ? deps : [ deps ];

        if (!window) {
            return callback(new Error(
                'Could not require module because load() has not been run'
            ));
        }

        window.require(deps, function(module) {
            callback(null, module);
        });
    }
}

function getWindow(html) {
    html = html || '';
    if (html.indexOf('') === -1) {
        html = '' + html + '';
    }

    var level   = null; // defaults to 3
    var options = {};

    doc = jsdom(html, level, options);
    window = doc.parentWindow;

    // Allow AMD modules to use console to log to STDOUT/ERR
    window.console = console;

    return window;
}

function initRequire(window, options, onRequireLoad) {
    // Set require.js options
    window.require = options;

    var requirePath = path.resolve(__dirname, './node_modules/requirejs/require.js');
    fs.exists(requirePath, function(exists) {
        if (!exists) {
            var err = new Error(
                'Could not load require.js at path ' + requirePath
            );
            return onRequireLoad(err);
        }

        var scriptEl = window.document.createElement('script');
        scriptEl.src = requirePath;
        scriptEl.onload = function() {
            onRequireLoad();
        }
        window.document.body.appendChild(scriptEl);
    });
}
<commit_msg>Simplify argument normalisation and internal variables<commit_after>var fs    = require('fs');
var path  = require('path');
var jsdom = require('jsdom').jsdom;

module.exports = jsdomrequire;
function jsdomrequire(html, requireOptions, callback) {
    var window;

    if (arguments.length === 2) {
        callback = requireOptions;
        if (typeof html === 'string') {
            requireOptions = {};
        } else {
            requireOptions = html;
            html = null;
        }
    } else if (arguments.length === 1) {
        callback = html;
        html = null;
        requireOptions = {};
    }

    window = getWindow(html);

    initRequire(window, requireOptions, function(err) {
        callback(err, window);
    });

    this.amdrequire = function(deps, callback) {
        deps = Array.isArray(deps) ? deps : [ deps ];

        if (!window) {
            return callback(new Error(
                'Could not require module because load() has not been run'
            ));
        }

        window.require(deps, function(module) {
            callback(null, module);
        });
    }
}

function getWindow(html) {
    html = html || '';
    if (html.indexOf('') === -1) {
        html = '' + html + '';
    }

    var level   = null; // defaults to 3
    var options = {};

    var doc = jsdom(html, level, options);
    window = doc.parentWindow;

    // Allow AMD modules to use console to log to STDOUT/ERR
    window.console = console;

    return window;
}

function initRequire(window, options, onRequireLoad) {
    // Set require.js options
    window.require = options;

    var requirePath = path.resolve(__dirname, './node_modules/requirejs/require.js');
    fs.exists(requirePath, function(exists) {
        if (!exists) {
            var err = new Error(
                'Could not load require.js at path ' + requirePath
            );
            return onRequireLoad(err);
        }

        var scriptEl = window.document.createElement('script');
        scriptEl.src = requirePath;
        scriptEl.onload = function() {
            onRequireLoad();
        }
        window.document.body.appendChild(scriptEl);
    });
}
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Fri Jun 24 2016 23:41:04 GMT+0200 (CEST)

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

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

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

    // list of files / patterns to load in the browser
    files: [
      './www/lib/ionic/js/angular/angular.js',
      './www/lib/angular-mocks/angular-mocks.js',
      './www/js/*.js',
      './www/js/**/*.js',
      './www/lib/ionic/js/ionic.js',
      './www/lib/ionic/js/ionic-angular.js',
      './www/lib/ionic/js/angular/angular-animate.js',
      './www/lib/ngCordova/dist/*.js',
      './www/lib/ionic/js/angular/angular-resource.js',
      './www/lib/ionic/js/angular/angular-sanitize.js',
      './www/lib/ionic/js/angular-ui/angular-ui-router.js',
      './tests/unit-tests/**/*.js'
    ],

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

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

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

    // web server port
    port: 9876,

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

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

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,
/*
    customLaunchers: {
      Chrome_travis_ci: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    },
    */
    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['PhantomJS'],

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

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
}
<commit_msg>delete redundant file<commit_after><|endoftext|>


<commit_before>angular.module('NutrifApp').controller("pesquisaCtrl", function ($scope, diaRefeicaoService, refeicaoRealizadaService, $cookies) {

	var TAM_MIN_BUSCA_MATRICULA = 11;
	var TAM_MIN_BUSCA_NOME = 3;

	$scope.refeicoes = [];

	$scope.limparBusca = function () {
		$scope.refeicoes = [];
		delete $scope.refeicao;
	}

	$scope.buscarRefeicoes = function (refeicao) {

		var _matricula = refeicao.aluno.matricula;
		var _nome = refeicao.aluno.nome;

		if (_matricula != undefined && _matricula.length == TAM_MIN_BUSCA_MATRICULA) {

			diaRefeicaoService.buscaRefeicaoPorMatricula(_matricula).success(function (data, status) {

				$scope.refeicoes = data;

			}).error(function (data, status) {

                if (!data) {

					alert("Ocorreu um erro na comunicação com o servidor, favor chamar o suporte.");

				} else {

					alert(data.mensagem);

				}

			});

		} else if (_nome != undefined && _nome.length >= TAM_MIN_BUSCA_NOME) {

			diaRefeicaoService.buscaRefeicaoPorNome(_nome).success(function (data, status) {

				$scope.refeicoes = data;

			}).error(function (data, status) {

				if (!data) {

					alert("Ocorreu um erro na comunicação com o servidor, favor chamar o suporte.");

				} else {

					alert(data.mensagem);

				}

			});

		}

	}

	$scope.selecionarRefeicao = function (refeicao) {
		$scope.refeicaoSelecionada = refeicao;
		$('#confirmar-refeicao').openModal();
	}

	$scope.registrarRefeicao = function (refeicaoSelecionada) {

		var _refeicaoRealizada = {};
		_refeicaoRealizada.confirmaRefeicaoDia = {};
		_refeicaoRealizada.confirmaRefeicaoDia.diaRefeicao = refeicaoSelecionada;
		_refeicaoRealizada.inspetor = {};
		_refeicaoRealizada.inspetor.id = $cookies.getObject('user').id;

		delete _refeicaoRealizada.confirmaRefeicaoDia.diaRefeicao.refeicao.horaInicio;
		delete _refeicaoRealizada.confirmaRefeicaoDia.diaRefeicao.refeicao.horaFinal;

		refeicaoRealizadaService.inserirRefeicao(_refeicaoRealizada).success(function (data, status) {

			$scope.refeicaoSelecionada = {};
			$scope.refeicoes = [];
			$scope.refeicao = {};

			Materialize.toast('Refeição realizada com sucesso', 6000);

		}).error(function (data, status){

			if (!data) {

				alert("Erro ao registrar refeição, tente novamente ou contate os administradores.");

			} else {

				alert(data.mensagem);

			}

		});

	}

});
<commit_msg>Ajustado erro na confirmação da refeição<commit_after>angular.module('NutrifApp').controller("pesquisaCtrl", function ($scope, diaRefeicaoService, refeicaoRealizadaService, $cookies) {

	var TAM_MIN_BUSCA_MATRICULA = 11;
	var TAM_MIN_BUSCA_NOME = 3;

	$scope.refeicoes = [];

	$scope.limparBusca = function () {
		$scope.refeicoes = [];
		delete $scope.refeicao;
	}

	$scope.buscarRefeicoes = function (refeicao) {

		var _matricula = refeicao.aluno.matricula;
		var _nome = refeicao.aluno.nome;

		if (_matricula != undefined && _matricula.length == TAM_MIN_BUSCA_MATRICULA) {

			diaRefeicaoService.buscaRefeicaoPorMatricula(_matricula).success(function (data, status) {

				$scope.refeicoes = data;

			}).error(function (data, status) {

                if (!data) {

					alert("Ocorreu um erro na comunicação com o servidor, favor chamar o suporte.");

				} else {

					alert(data.mensagem);

				}

			});

		} else if (_nome != undefined && _nome.length >= TAM_MIN_BUSCA_NOME) {

			diaRefeicaoService.buscaRefeicaoPorNome(_nome).success(function (data, status) {

				$scope.refeicoes = data;

			}).error(function (data, status) {

				if (!data) {

					alert("Ocorreu um erro na comunicação com o servidor, favor chamar o suporte.");

				} else {

					alert(data.mensagem);

				}

			});

		}

	}

	$scope.selecionarRefeicao = function (refeicao) {
		$scope.refeicaoSelecionada = refeicao;
		$('#confirmar-refeicao').openModal();
	}

	$scope.registrarRefeicao = function (refeicaoSelecionada) {

		var _refeicaoRealizada = {};
		_refeicaoRealizada.confirmaRefeicaoDia = {};
		_refeicaoRealizada.confirmaRefeicaoDia.diaRefeicao = refeicaoSelecionada;
		_refeicaoRealizada.inspetor = {};
		_refeicaoRealizada.inspetor.id = $cookies.getObject('user').id;

		delete _refeicaoRealizada.confirmaRefeicaoDia.diaRefeicao.refeicao.horaInicio;
		delete _refeicaoRealizada.confirmaRefeicaoDia.diaRefeicao.refeicao.horaFinal;
		delete _refeicaoRealizada.confirmaRefeicaoDia.diaRefeicao.refeicao.horaPretensao;

		refeicaoRealizadaService.inserirRefeicao(_refeicaoRealizada).success(function (data, status) {

			$scope.refeicaoSelecionada = {};
			$scope.refeicoes = [];
			$scope.refeicao = {};

			Materialize.toast('Refeição realizada com sucesso', 6000);

		}).error(function (data, status){

			if (!data) {

				alert("Erro ao registrar refeição, tente novamente ou contate os administradores.");

			} else {

				alert(data.mensagem);

			}

		});

	}

});
<|endoftext|>


<commit_before>/**
 * 技术统计模块
 * */

var Brick = require("node-lego").Brick;
var StatisticService = require("../../../../../service/statistic_service/index");
var logger = require("winston").loggers.get("app");

module.exports = Brick.create("Statistic", function (params, finish) {
    var gameId = params.gameId;

    StatisticService.loadStatistic(gameId, function (error, statistic) {
        if (error) {
            logger.error("Load Statistic error", error);
            finish(Brick.FAIL);
        } else {
            var data = {
                teams: [],
                headers: []
            };
            if (statistic && statistic.length) {
                statistic.forEach(function (row, i) {
                    //处理主客队
                    row.forEach(function (column, j) {
                        if (column.match(/主队|客队/)) {
                            data.teams.push(i);
                            data.headers.push(i + 1);
                        }
                    });
                });
                data.statistic = statistic;
            }
            finish(Brick.SUCCESS, data);
        }
    });
});
<commit_msg>statistic<commit_after>/**
 * 技术统计模块
 * */

var Brick = require("node-lego").Brick;
var StatisticService = require("../../../../../service/statistic_service/index");
var logger = require("winston").loggers.get("app");

module.exports = Brick.create("Statistic", function (params, finish) {
    var gameId = params.gameId;

    StatisticService.loadStatistic(gameId, function (error, statistic) {
        if (error) {
            logger.error("Load Statistic error", error);
            finish(Brick.FAIL);
        } else {
            var data = {
                teams: [],
                headers: []
            };
            if (statistic && statistic.length) {
                statistic.forEach(function (row, i) {
                    //处理主客队
                    row.forEach(function (column, j) {
                        if (column.match(/主队|客队/)) {
                            data.teams.push(i);
                        }
                        if(column.match(/首发|替补/)){
                            data.headers.push(i);
                        }
                    });
                });
                data.statistic = statistic;
            }
            finish(Brick.SUCCESS, data);
        }
    });
});
<|endoftext|>


<commit_before>//
// Mixin class for nodetree elements

var OCRJS = OCRJS || {};
OCRJS.Nodetree = OCRJS.Nodetree || {};

OCRJS.Nodetree.SvgHelper = OCRJS.OcrBase.extend({
    constructor: function() {
        this.base();
    },
    translatere: /translate\(([-\d\.]+)(\s*,\s*([-\d\.]+))?\)/,
    scalere: /scale\(([-\d\.]+)(\s*,\s*([-\d\.]+)\))?/,

    updateScale: function(element, scale) {
        var trans = this.getTranslate(element);
        this.updateTransform(element, trans.x, trans.y, scale);
    },

    updateTranslate: function(element, x, y) {
        this.updateTransform(element, x, y, this.getScale(element));
    },

    updateTransform: function(element, tx, ty, scale) {
        // slightly more efficent method where we can just set the
        // scale and transform outright without parsing for
        // existing values.
        // Assumes there's no rotation!
        var str = "translate(" + (tx).toFixed(2) + ","
                + (ty).toFixed(2) + ") scale("
                + (scale).toFixed(2) + "," + (scale).toFixed(2) + ")";
        $(element).attr("transform", str);

    },

    getTranslate: function(element) {
        var trans = {x: 0, y: 0},
            tattr = $(element).attr("transform"),
            tparse = tattr ? tattr.match(this.translatere) : null;
        if (tparse) {
            trans = {
                x: parseFloat(tparse[1]),
                y: tparse[3] !== undefined
                    ? parseFloat(tparse[3])
                    : parseFloat(tparse[1]),
            };
        }
        return trans;
    },

    getScale: function(element) {
        // N.B: Ignore
        var tattr = $(element).attr("transform"),
            tparse = tattr ? tattr.match(this.scalere) : null;
        if (!tparse)
            return 1;
        return parseFloat(tparse[1]);
    },

    multPoints: function(p1, p2) {
        return { x: p1.x * p2.x, y: p1.y * p2.y};
    },

    divPoints: function(p1, p2) {
        return { x: p1.x / p2.x, y: p1.y / p2.y};
    },

    mouseCoord: function(parent, event) {
        var off = $(parent).offset();
        return {
            x: event.pageX - off.left,
            y: event.pageY - off.top,
        };
    },

    centrePointOfCircle: function(e) {
        return {
            x: parseInt($(e).attr("cx")),
            y: parseInt($(e).attr("cy")),
        };
    },

    norm: function(abs, element, stop) {
        // get the position of the mouse relative to a
        // transformed element.  FIXME: This is HORRIBLY
        // inefficient and stupid.
        var parent = element.parentNode;
        var trans;
        while (parent && parent != stop && parent.nodeName == "g") {
            trans = this.getTranslate(parent);
            scale = this.getScale(parent);
            abs.x -= (trans.x * scale);
            abs.y -= (trans.y * scale);
            parent = parent.parentNode;
        }
        return abs;
    },

    denorm: function(abs, element, stop) {
        // get the position of the mouse relative to a
        // transformed element.  FIXME: This is HORRIBLY
        // inefficient and stupid.
        var parent = element.parentNode;
        var trans;
        while (parent && parent != stop && parent.nodeName == "g") {
            trans = this.getTranslate(parent);
            scale = this.getScale(parent);
            abs.x += (trans.x / scale);
            abs.y += (trans.y / scale);
            parent = parent.parentNode;
        }
        return abs;
    },

    rectFromPoints: function(p1, p2) {
        // get a normalised rect from two points
        var x, y, width, height;
        if (p1.x < p2.x) {
            x = p1.x, width = p2.x - p1.x;
        } else {
            x = p2.x, width = p1.x - p2.x;
        }
        if (p1.y < p2.y) {
            y = p1.y, height = p2.y - p1.y;
        } else {
            y = p2.y, height = p1.y - p2.y;
        }
        return { x: x, y: y, width: width, height: height};
    },

    rectsOverlap: function(r1, r2) {
        // does rect 2 overlap rect 1

        return ov =  r1.x < (r2.x + r2.width) && (r1.x + r1.width) > r2.x
            && r1.y < (r2.y + r2.height) && (r1.y + r1.height) > r2.y;
    },
});
<commit_msg>Make extra sure we use floats when setting transform<commit_after>//
// Mixin class for nodetree elements

var OCRJS = OCRJS || {};
OCRJS.Nodetree = OCRJS.Nodetree || {};

OCRJS.Nodetree.SvgHelper = OCRJS.OcrBase.extend({
    constructor: function() {
        this.base();
    },
    translatere: /translate\(([-\d\.]+)(\s*,\s*([-\d\.]+))?\)/,
    scalere: /scale\(([-\d\.]+)(\s*,\s*([-\d\.]+)\))?/,

    updateScale: function(element, scale) {
        var trans = this.getTranslate(element);
        this.updateTransform(element, trans.x, trans.y, scale);
    },

    updateTranslate: function(element, x, y) {
        this.updateTransform(element, x, y, this.getScale(element));
    },

    updateTransform: function(element, tx, ty, scale) {
        // slightly more efficent method where we can just set the
        // scale and transform outright without parsing for
        // existing values.
        // Assumes there's no rotation!
        var str = "translate(" + (parseFloat(tx)).toFixed(2) + ","
                + (parseFloat(ty)).toFixed(2) + ") scale("
                + (parseFloat(scale)).toFixed(2) + "," + (parseFloat(scale)).toFixed(2) + ")";
        $(element).attr("transform", str);

    },

    getTranslate: function(element) {
        var trans = {x: 0, y: 0},
            tattr = $(element).attr("transform"),
            tparse = tattr ? tattr.match(this.translatere) : null;
        if (tparse) {
            trans = {
                x: parseFloat(tparse[1]),
                y: tparse[3] !== undefined
                    ? parseFloat(tparse[3])
                    : parseFloat(tparse[1]),
            };
        }
        return trans;
    },

    getScale: function(element) {
        // N.B: Ignore
        var tattr = $(element).attr("transform"),
            tparse = tattr ? tattr.match(this.scalere) : null;
        if (!tparse)
            return 1;
        return parseFloat(tparse[1]);
    },

    multPoints: function(p1, p2) {
        return { x: p1.x * p2.x, y: p1.y * p2.y};
    },

    divPoints: function(p1, p2) {
        return { x: p1.x / p2.x, y: p1.y / p2.y};
    },

    mouseCoord: function(parent, event) {
        var off = $(parent).offset();
        return {
            x: event.pageX - off.left,
            y: event.pageY - off.top,
        };
    },

    centrePointOfCircle: function(e) {
        return {
            x: parseInt($(e).attr("cx")),
            y: parseInt($(e).attr("cy")),
        };
    },

    norm: function(abs, element, stop) {
        // get the position of the mouse relative to a
        // transformed element.  FIXME: This is HORRIBLY
        // inefficient and stupid.
        var parent = element.parentNode;
        var trans;
        while (parent && parent != stop && parent.nodeName == "g") {
            trans = this.getTranslate(parent);
            scale = this.getScale(parent);
            abs.x -= (trans.x * scale);
            abs.y -= (trans.y * scale);
            parent = parent.parentNode;
        }
        return abs;
    },

    denorm: function(abs, element, stop) {
        // get the position of the mouse relative to a
        // transformed element.  FIXME: This is HORRIBLY
        // inefficient and stupid.
        var parent = element.parentNode;
        var trans;
        while (parent && parent != stop && parent.nodeName == "g") {
            trans = this.getTranslate(parent);
            scale = this.getScale(parent);
            abs.x += (trans.x / scale);
            abs.y += (trans.y / scale);
            parent = parent.parentNode;
        }
        return abs;
    },

    rectFromPoints: function(p1, p2) {
        // get a normalised rect from two points
        var x, y, width, height;
        if (p1.x < p2.x) {
            x = p1.x, width = p2.x - p1.x;
        } else {
            x = p2.x, width = p1.x - p2.x;
        }
        if (p1.y < p2.y) {
            y = p1.y, height = p2.y - p1.y;
        } else {
            y = p2.y, height = p1.y - p2.y;
        }
        return { x: x, y: y, width: width, height: height};
    },

    rectsOverlap: function(r1, r2) {
        // does rect 2 overlap rect 1

        return ov =  r1.x < (r2.x + r2.width) && (r1.x + r1.width) > r2.x
            && r1.y < (r2.y + r2.height) && (r1.y + r1.height) > r2.y;
    },
});
<|endoftext|>