<commit_before>$(function () {
'use strict';
var website = openerp.website;
$('.columnID').css("visibility","hidden");
$('#quotation_id').css("visibility","hidden");

website.if_dom_contains('div.o_bc_website_purchase', function () {

   // Disable submit and save buttons on start
   //$('#btnSave').disabled = True;
   //$('#btnSubmit').disabled = True;

   $('.update_line.js_unitprice.input-group').on('keydown',function(event){
	console.log(event.keyCode);
	if (event.keyCode >= 48 && event.keyCode <= 57 || event.keyCode == 8 || event.keyCode == 190 || event.keyCode == 9 ||
		event.keyCode == 13 || event.keyCode == 188) {
		return true;
		}
	else {
		return false;
		}
	});

   $('.update_line.js_leadtime.input-group').on('keydown',function(event){
	if (event.keyCode >= 48 && event.keyCode <= 57 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 13) {
		return true;
		}
	else {
		return false;
		}
	});

   $('#btnCalc').hide();

   // Click on the submit button
   $('#btnSave').on('click', function (ev) {
	console.log('Clicked');
	// Reads quotation ID
	var quotation_id = parseInt($('#quotation_id').text());

	var line_ids = [];
	var line_unit_prices = [];
	var line_leadtimes = [];
	var line_update = []
	var i = 0;

	// Reads quotation lines IDs
	$('.columnID').each(function(index,element) {
		var element_column = parseInt($(element).text());
		if (!isNaN(element_column)){
			line_ids.push(parseInt($(element).text()));
			}
		});

	// Reads quotation lines unit prices
	$('.update_line.js_unitprice.input-group').each(function(index,element) {
		line_unit_prices.push(parseFloat($(element).val()));
		});

	// Reads quotation  prices
	$('.update_line.js_leadtime.input-group').each(function(index,element) {
		if ( $(element).val() != 'N/A' ) {
			line_leadtimes.push(parseInt($(element).val()));
			}
		else {
			line_leadtimes.push(0);
			}
		});

	var i = 0;
	for ( i = 0; i < line_ids.length ; i++) {
		console.log(line_ids[i]);
		console.log(line_unit_prices[i]);
		console.log(line_leadtimes[i]);
        	openerp.jsonRpc("/purchase/save", 'call', {
                	'order_id': quotation_id,
                	'line_id': line_ids,
                	'price_unit': line_unit_prices,
                	'leadtime': line_leadtimes,
	                })
        	        .then(function (data) {
				$(".update_line.js_unitprice.input-group").prop('disabled', true);
				$(".update_line.js_leadtime.input-group").prop('disabled', true);
			        location.reload();
	                });
		}

	location.reload();
        return false;

	});

   // Click on the submit button
   $('#btnSubmit').on('click', function (ev) {
	console.log('Clicked');
	// Reads quotation ID
	var quotation_id = parseInt($('#quotation_id').text());

	var line_ids = [];
	var line_unit_prices = [];
	var line_leadtimes = [];
	var line_update = []
	var i = 0;

	// Reads quotation lines IDs
	$('.columnID').each(function(index,element) {
		var element_column = parseInt($(element).text());
		if (!isNaN(element_column)){
			line_ids.push(parseInt($(element).text()));
			}
		});

	// Reads quotation lines unit prices
	$('.update_line.js_unitprice.input-group').each(function(index,element) {
		line_unit_prices.push(parseFloat($(element).val()));
		});

	// Reads quotation  prices
	$('.update_line.js_leadtime.input-group').each(function(index,element) {
		line_leadtimes.push(parseInt($(element).val()));
		});

	var i = 0;
	for ( i = 0; i < line_ids.length ; i++) {
		console.log(line_ids[i]);
		console.log(line_unit_prices[i]);
		console.log(line_leadtimes[i]);
        	openerp.jsonRpc("/purchase/update_line", 'call', {
                	'order_id': quotation_id,
                	'line_id': line_ids,
                	'price_unit': line_unit_prices,
                	'leadtime': line_leadtimes,
	                })
        	        .then(function (data) {
				$(".update_line.js_unitprice.input-group").prop('disabled', true);
				$(".update_line.js_leadtime.input-group").prop('disabled', true);
			        location.reload();
	                });
		}

	location.reload();
        return false;

	});

   // Click on the calc button
   $('.update_line.js_unitprice.input-group').on('blur',function() {
	$('#btnCalc').click();
	});

   $('#btnCalc').on('click', function (ev) {
	var subtotal = [];
	var subtotal_qty = [];
	var total_order = 0;
	var total_order_list = [];
	var i = 0;
	$('.js_product_qty').each(function(index,element) {
		subtotal_qty.push(parseInt($(element).text()));
		});
	$('.update_line.js_unitprice.input-group').each(function(index,element) {
		subtotal.push(parseInt($(element).val()));
		});
	for ( i = 0; i < subtotal.length; i ++) {
		total_order = total_order + subtotal[i] * subtotal_qty[i];
		total_order_list.push(subtotal[i] * subtotal_qty[i]);
		}
	$('.js_line_subtotal span').each(function(index,element) {
		$(element).text(total_order_list[index]);
		});
	$('.subtotal_field').children().text(total_order);

	//for (i = 0 ; i < unit_prices_fields.length ; i++) {
	//	var subtotal_field = parseInt(qty_fields[i].val()) * parseInt(unit_prices_fields[i].val());
	//	console.log(subtotal_field);
	//	}
	});

   $('a.js_update_line_json').on('click', function (ev) {
        ev.preventDefault();
        var $link = $(ev.currentTarget);
        var href = $link.attr("href");
        var order_id = href.match(/order_id=([0-9]+)/);
        var line_id = href.match(/update_line\/([0-9]+)/);
        var token = href.match(/token=(.*)/);
	console.log('Paso');
        openerp.jsonRpc("/purchase/update_line", 'call', {
                'line_id': line_id[1],
                'order_id': parseInt(order_id[1]),
                'token': token[1],
                'remove': $link.is('[href*="remove"]'),
                'unlink': $link.is('[href*="unlink"]')
                })
                .then(function (data) {
                    if(!data){
                        location.reload();
                    };
                    $link.parents('.input-group:first').find('.js_quantity').val(data[0]);
                    $('[data-id="total_amount"]>span').html(data[1]);
                });
        return false;
    }); // OK

    //$( ".update_line" ).change(function (ev) {
     //   ev.preventDefault();
    //    var $link = $(ev.currentTarget);
    //    var href = $link.attr("data");
    //    var order_id = href.match(/order_id=([0-9]+)/);
    //    var line_id = href.match(/update_line\/([0-9]+)/);
    //    var token = href.match(/token=(.*)/);
    //    var new_price_elem = $link.parents('.input-group:first').find('.js_unitprice');
    //    var new_price = new_price_elem[0].value;
    //    var new_leadtime_elem = $link.parents('.input-group:first').find('.js_leadtime');
    //    var new_leadtime = new_leadtime_elem[0].value;
    //    openerp.jsonRpc("/purchase/update_leadtime", 'call', {
    //            'line_id': line_id[1],
    //            'order_id': parseInt(order_id[1]),
    //            'token': token[1],
    //            'new_leadtime': new_leadtime
    //    }).then(function (data) {
    //            if(!data){
    //                location.reload();
    //                }
    //            $link.parents('.input-group:first').find('.js_leadtime').val(data[0]);
    //            });
    //    openerp.jsonRpc("/purchase/update_unitprice", 'call', {
    //            'line_id': line_id[1],
    //            'order_id': parseInt(order_id[1]),
    //            'token': token[1],
    //           'new_price' : new_price
    //            })
    //           .then(function (data) {
    //                if(!data){
    //                    location.reload();
    //                }
    //                $link.parents('.input-group:first').find('.js_unitprice').val(data[0]);
    //                $('*').find('.js_line_subtotal').each(function() {
    //                    var line_here = parseInt($( this).attr('data'));
    //                    if (line_here == parseInt(line_id[1])) {
    //                        $(this).children('span').html(data[1]);
    //                    }
    //                });
    //                $('[data-id="sub_total_amount"]>span').html(data[2]);
    //                $('[data-id="tax_amount"]>span').html(data[3]);
    //                $('[data-id="total_amount"]>span').html(data[4]);
    //            });
    //    return false;
    // }); //OK

    $('.js_update_line_json3').on('change', function (ev) {
        ev.preventDefault();
	alert('Paso .update_line_json3');
        var $link = $(ev.currentTarget);
        var href = $link.attr("href");
        var order_id = href.match(/order_id=([0-9]+)/);
        var line_id = href.match(/update_line\/([0-9]+)/);
        var token = href.match(/token=(.*)/);
        openerp.jsonRpc("/purchase/update_line", 'call', {
                'line_id': line_id[1],
                'order_id': parseInt(order_id[1]),
                'token': token[1],
                'remove': $link.is('[href*="remove"]'),
                'unlink': $link.is('[href*="unlink"]')
                })
                .then(function (data) {
                    if(!data){
                        location.reload();
                    }
                    $link.parents('.input-group:first').find('.js_quantity').val(data[0]);
                    $('[data-id="total_amount"]>span').html(data[1]);
                });
        return false;
    }); // OK

    $('form.js_accept_json').submit(function(ev){
        ev.preventDefault();
	alert('Paso .update_line_json3');
        var $link = $(ev.currentTarget);
        var href = $link.attr("action");
        var order_id = href.match(/accept\/([0-9]+)/);
        var token = href.match(/token=(.*)/);
        if (token) {
            token = token[1]; }
        var signer_name = $("#name").val();
        var sign = $("#signature").jSignature("getData",'image');
        var is_empty = sign?empty_sign[1]==sign[1]:false;
        $('#signer').toggleClass('has-error', ! signer_name);
        $('#drawsign').toggleClass('panel-danger', is_empty).toggleClass('panel-default', ! is_empty);
        if (is_empty || ! signer_name) {
            return false; }
        openerp.jsonRpc("/purchase/accept", 'call', {
            'order_id': parseInt(order_id[1]),
            'token': token,
            'signer': signer_name,
            'sign': sign?JSON.stringify(sign[1]):false,
        }).then(function (data) {
            $('#modelaccept').modal('hide');
            window.location.href = '/purchase/'+order_id[1]+'/'+token+'?message=3';
        });
        return false;
    }); // OK

    // automatically generate a menu from h1 and h2 tag in content
    //var $container = $('body[data-target=".navspy"]');
    //var ul = $('[data-id="quote_sidebar"]', $container);
    //var sub_li = null;
    //var sub_ul = null;
    //$("[id^=quote_header_], [id^=quote_]", $container).attr("id", "");
    //$("h1, h2", $container).each(function() {
    //    var id;
    //    switch (this.tagName.toLowerCase()) {
    //        case "h1":
    //            id = _.uniqueId('quote_header_');
    //            $(this.parentNode).attr('id',id);
    //            sub_li = $("
").html(''+$(this).text()+'').appendTo(ul);
    //            sub_ul = null;
    //            break;
    //        case "h2":
    //            id = _.uniqueId('quote_');
    //            if (sub_li) {
    //                if (!sub_ul) {
    //                    sub_ul = $("
").appendTo(sub_li);
    //                }
    //                $(this.parentNode).attr('id',id);
    //                $("
").html(''+$(this).text()+'').appendTo(sub_ul);
    //            }
    //            break;
    //        }
    //}); // OK
})

});
// }());
<commit_msg>Task #11 i Taiga<commit_after>$(function () {
'use strict';
var website = openerp.website;
$('.columnID').css("visibility","hidden");
$('#quotation_id').css("visibility","hidden");
var formChanged = false;
$('#btnSave').css('background-color','#777');
$('#btnSubmit').css('background-color','#777');

website.if_dom_contains('div.o_bc_website_purchase', function () {

   $('.update_line.js_unitprice.input-group').on('keydown',function(event){
	console.log(event.keyCode);
	if (event.keyCode >= 48 && event.keyCode <= 57 || event.keyCode == 8 || event.keyCode == 190 || event.keyCode == 9 ||
		event.keyCode == 13 || event.keyCode == 188) {
		formChanged = true;
		$('#btnSave').css('background-color','#f0ad4e');
		$('#btnSubmit').css('background-color','#5cb85c');
		return true;
		}
	else {
		return false;
		}
	});

   $('.update_line.js_leadtime.input-group').on('keydown',function(event){
	if (event.keyCode >= 48 && event.keyCode <= 57 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 13) {
		formChanged = true;
		$('#btnSave').css('background-color','#f0ad4e');
		$('#btnSubmit').css('background-color','#5cb85c');
		return true;
		}
	else {
		return false;
		}
	});

   $('#btnCalc').hide();

   // Click on the submit button
   $('#btnSave').on('click', function (ev) {
	console.log('Clicked Save Button');
	if (formChanged == false) {
		return false;
		}
	// Reads quotation ID
	var quotation_id = parseInt($('#quotation_id').text());

	var line_ids = [];
	var line_unit_prices = [];
	var line_leadtimes = [];
	var line_update = []
	var i = 0;

	// Reads quotation lines IDs
	$('.columnID').each(function(index,element) {
		var element_column = parseInt($(element).text());
		if (!isNaN(element_column)){
			line_ids.push(parseInt($(element).text()));
			}
		});

	// Reads quotation lines unit prices
	$('.update_line.js_unitprice.input-group').each(function(index,element) {
		line_unit_prices.push(parseFloat($(element).val()));
		});

	// Reads quotation  prices
	$('.update_line.js_leadtime.input-group').each(function(index,element) {
		if ( $(element).val() != 'N/A' ) {
			line_leadtimes.push(parseInt($(element).val()));
			}
		else {
			line_leadtimes.push(0);
			}
		});

	var i = 0;
	for ( i = 0; i < line_ids.length ; i++) {
		console.log(line_ids[i]);
		console.log(line_unit_prices[i]);
		console.log(line_leadtimes[i]);
        	openerp.jsonRpc("/purchase/save", 'call', {
                	'order_id': quotation_id,
                	'line_id': line_ids,
                	'price_unit': line_unit_prices,
                	'leadtime': line_leadtimes,
	                })
        	        .then(function (data) {
				$(".update_line.js_unitprice.input-group").prop('disabled', true);
				$(".update_line.js_leadtime.input-group").prop('disabled', true);
			        location.reload();
	                });
		}

	location.reload();
        return false;

	});

   // Click on the submit button
   $('#btnSubmit').on('click', function (ev) {
	console.log('Clicked Submit Button');
	if (formChanged == false) {
		return false;
		}
	// Reads quotation ID
	var quotation_id = parseInt($('#quotation_id').text());

	var line_ids = [];
	var line_unit_prices = [];
	var line_leadtimes = [];
	var line_update = []
	var i = 0;

	// Reads quotation lines IDs
	$('.columnID').each(function(index,element) {
		var element_column = parseInt($(element).text());
		if (!isNaN(element_column)){
			line_ids.push(parseInt($(element).text()));
			}
		});

	// Reads quotation lines unit prices
	$('.update_line.js_unitprice.input-group').each(function(index,element) {
		line_unit_prices.push(parseFloat($(element).val()));
		});

	// Reads quotation  prices
	$('.update_line.js_leadtime.input-group').each(function(index,element) {
		line_leadtimes.push(parseInt($(element).val()));
		});

	var i = 0;
	for ( i = 0; i < line_ids.length ; i++) {
		console.log(line_ids[i]);
		console.log(line_unit_prices[i]);
		console.log(line_leadtimes[i]);
        	openerp.jsonRpc("/purchase/update_line", 'call', {
                	'order_id': quotation_id,
                	'line_id': line_ids,
                	'price_unit': line_unit_prices,
                	'leadtime': line_leadtimes,
	                })
        	        .then(function (data) {
				$(".update_line.js_unitprice.input-group").prop('disabled', true);
				$(".update_line.js_leadtime.input-group").prop('disabled', true);
			        location.reload();
	                });
		}

	location.reload();
        return false;

	});

   // Click on the calc button
   $('.update_line.js_unitprice.input-group').on('blur',function() {
	$('#btnCalc').click();
	});

   $('#btnCalc').on('click', function (ev) {
	var subtotal = [];
	var subtotal_qty = [];
	var total_order = 0;
	var total_order_list = [];
	var i = 0;
	$('.js_product_qty').each(function(index,element) {
		subtotal_qty.push(parseInt($(element).text()));
		});
	$('.update_line.js_unitprice.input-group').each(function(index,element) {
		subtotal.push(parseInt($(element).val()));
		});
	for ( i = 0; i < subtotal.length; i ++) {
		total_order = total_order + subtotal[i] * subtotal_qty[i];
		total_order_list.push(subtotal[i] * subtotal_qty[i]);
		}
	$('.js_line_subtotal span').each(function(index,element) {
		$(element).text(total_order_list[index]);
		});
	$('.subtotal_field').children().text(total_order);

	//for (i = 0 ; i < unit_prices_fields.length ; i++) {
	//	var subtotal_field = parseInt(qty_fields[i].val()) * parseInt(unit_prices_fields[i].val());
	//	console.log(subtotal_field);
	//	}
	});

   $('a.js_update_line_json').on('click', function (ev) {
        ev.preventDefault();
        var $link = $(ev.currentTarget);
        var href = $link.attr("href");
        var order_id = href.match(/order_id=([0-9]+)/);
        var line_id = href.match(/update_line\/([0-9]+)/);
        var token = href.match(/token=(.*)/);
	console.log('Paso');
        openerp.jsonRpc("/purchase/update_line", 'call', {
                'line_id': line_id[1],
                'order_id': parseInt(order_id[1]),
                'token': token[1],
                'remove': $link.is('[href*="remove"]'),
                'unlink': $link.is('[href*="unlink"]')
                })
                .then(function (data) {
                    if(!data){
                        location.reload();
                    };
                    $link.parents('.input-group:first').find('.js_quantity').val(data[0]);
                    $('[data-id="total_amount"]>span').html(data[1]);
                });
        return false;
    }); // OK

    //$( ".update_line" ).change(function (ev) {
     //   ev.preventDefault();
    //    var $link = $(ev.currentTarget);
    //    var href = $link.attr("data");
    //    var order_id = href.match(/order_id=([0-9]+)/);
    //    var line_id = href.match(/update_line\/([0-9]+)/);
    //    var token = href.match(/token=(.*)/);
    //    var new_price_elem = $link.parents('.input-group:first').find('.js_unitprice');
    //    var new_price = new_price_elem[0].value;
    //    var new_leadtime_elem = $link.parents('.input-group:first').find('.js_leadtime');
    //    var new_leadtime = new_leadtime_elem[0].value;
    //    openerp.jsonRpc("/purchase/update_leadtime", 'call', {
    //            'line_id': line_id[1],
    //            'order_id': parseInt(order_id[1]),
    //            'token': token[1],
    //            'new_leadtime': new_leadtime
    //    }).then(function (data) {
    //            if(!data){
    //                location.reload();
    //                }
    //            $link.parents('.input-group:first').find('.js_leadtime').val(data[0]);
    //            });
    //    openerp.jsonRpc("/purchase/update_unitprice", 'call', {
    //            'line_id': line_id[1],
    //            'order_id': parseInt(order_id[1]),
    //            'token': token[1],
    //           'new_price' : new_price
    //            })
    //           .then(function (data) {
    //                if(!data){
    //                    location.reload();
    //                }
    //                $link.parents('.input-group:first').find('.js_unitprice').val(data[0]);
    //                $('*').find('.js_line_subtotal').each(function() {
    //                    var line_here = parseInt($( this).attr('data'));
    //                    if (line_here == parseInt(line_id[1])) {
    //                        $(this).children('span').html(data[1]);
    //                    }
    //                });
    //                $('[data-id="sub_total_amount"]>span').html(data[2]);
    //                $('[data-id="tax_amount"]>span').html(data[3]);
    //                $('[data-id="total_amount"]>span').html(data[4]);
    //            });
    //    return false;
    // }); //OK

    $('.js_update_line_json3').on('change', function (ev) {
        ev.preventDefault();
	alert('Paso .update_line_json3');
        var $link = $(ev.currentTarget);
        var href = $link.attr("href");
        var order_id = href.match(/order_id=([0-9]+)/);
        var line_id = href.match(/update_line\/([0-9]+)/);
        var token = href.match(/token=(.*)/);
        openerp.jsonRpc("/purchase/update_line", 'call', {
                'line_id': line_id[1],
                'order_id': parseInt(order_id[1]),
                'token': token[1],
                'remove': $link.is('[href*="remove"]'),
                'unlink': $link.is('[href*="unlink"]')
                })
                .then(function (data) {
                    if(!data){
                        location.reload();
                    }
                    $link.parents('.input-group:first').find('.js_quantity').val(data[0]);
                    $('[data-id="total_amount"]>span').html(data[1]);
                });
        return false;
    }); // OK

    $('form.js_accept_json').submit(function(ev){
        ev.preventDefault();
	alert('Paso .update_line_json3');
        var $link = $(ev.currentTarget);
        var href = $link.attr("action");
        var order_id = href.match(/accept\/([0-9]+)/);
        var token = href.match(/token=(.*)/);
        if (token) {
            token = token[1]; }
        var signer_name = $("#name").val();
        var sign = $("#signature").jSignature("getData",'image');
        var is_empty = sign?empty_sign[1]==sign[1]:false;
        $('#signer').toggleClass('has-error', ! signer_name);
        $('#drawsign').toggleClass('panel-danger', is_empty).toggleClass('panel-default', ! is_empty);
        if (is_empty || ! signer_name) {
            return false; }
        openerp.jsonRpc("/purchase/accept", 'call', {
            'order_id': parseInt(order_id[1]),
            'token': token,
            'signer': signer_name,
            'sign': sign?JSON.stringify(sign[1]):false,
        }).then(function (data) {
            $('#modelaccept').modal('hide');
            window.location.href = '/purchase/'+order_id[1]+'/'+token+'?message=3';
        });
        return false;
    }); // OK

    // automatically generate a menu from h1 and h2 tag in content
    //var $container = $('body[data-target=".navspy"]');
    //var ul = $('[data-id="quote_sidebar"]', $container);
    //var sub_li = null;
    //var sub_ul = null;
    //$("[id^=quote_header_], [id^=quote_]", $container).attr("id", "");
    //$("h1, h2", $container).each(function() {
    //    var id;
    //    switch (this.tagName.toLowerCase()) {
    //        case "h1":
    //            id = _.uniqueId('quote_header_');
    //            $(this.parentNode).attr('id',id);
    //            sub_li = $("
").html(''+$(this).text()+'').appendTo(ul);
    //            sub_ul = null;
    //            break;
    //        case "h2":
    //            id = _.uniqueId('quote_');
    //            if (sub_li) {
    //                if (!sub_ul) {
    //                    sub_ul = $("
").appendTo(sub_li);
    //                }
    //                $(this.parentNode).attr('id',id);
    //                $("
").html(''+$(this).text()+'').appendTo(sub_ul);
    //            }
    //            break;
    //        }
    //}); // OK
})

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


<commit_before>define([
    "dojo/_base/declare",
    "dojo/dom-style",
    "dojo/dom-construct",
    "dijit/form/Button"
], function (
    declare,
    domStyle,
    domConstruct,
    Button
) {
    return declare([Button], {

        initialLabel: "",
        progressBar: null,
        isProcessing: false,
        isCancelable: false,

        postCreate: function () {
            this.inherited(arguments);

            domStyle.set(this.domNode, "position", "relative");
            this.progressBar = domConstruct.create("span", {
                style: {
                    backgroundColor: "#ddd",
                    position: "absolute",
                    left: 0,
                    width: 0,
                    height: "100%",
                    opacity: 0.3,
                    borderRadius: "4px 0 0 4px"
                }
            });
            this.progressBar.on('click', function() {
                if (!this.get("disabled")) {
                    this.onClick();
                }
            });
            domConstruct.place(this.progressBar, this.domNode, 'first');
        },

        setCancelable: function(isCancelable) {
            this.isCancelable = isCancelable;
        },

        setProgress: function(value) {
            if (!this.isProcessing) {
                this.setProcessing();
            }
            value = (value >= 0 && value < 1) ? value : 0;
            domStyle.set(this.progressBar, 'width', (value*100)+'%');
        },

        setProcessing: function() {
            this.isProcessing = true;
            this.initialLabel = this.get("label");
            this.set("label", this.initialLabel+' ');
            if (!this.isCancelable) {
                this.set("disabled", true);
            }
        },

        reset: function() {
            this.set("label", this.initialLabel);
            if (!this.isCancelable) {
                this.set("disabled", false);
            }
            this.setProgress(0);
            this.isProcessing = false;
        }
    });
});<commit_msg>fixed click handler<commit_after>define([
    "dojo/_base/declare",
    "dojo/_base/lang",
    "dojo/dom-style",
    "dojo/dom-construct",
    "dijit/form/Button"
], function (
    declare,
    lang,
    domStyle,
    domConstruct,
    Button
) {
    return declare([Button], {

        initialLabel: "",
        progressBar: null,
        isProcessing: false,
        isCancelable: false,

        postCreate: function () {
            this.inherited(arguments);

            domStyle.set(this.domNode, "position", "relative");
            this.progressBar = domConstruct.create("span", {
                style: {
                    backgroundColor: "#ddd",
                    position: "absolute",
                    left: 0,
                    width: 0,
                    height: "100%",
                    opacity: 0.3,
                    borderRadius: "4px 0 0 4px"
                },
                onclick: lang.hitch(this, function(e) {
                    if (!this.get("disabled")) {
                        this.onClick(e);
                    }
                })
            });
            domConstruct.place(this.progressBar, this.domNode, 'first');
        },

        setCancelable: function(isCancelable) {
            this.isCancelable = isCancelable;
        },

        setProgress: function(value) {
            if (!this.isProcessing) {
                this.setProcessing();
            }
            value = (value >= 0 && value < 1) ? value : 0;
            domStyle.set(this.progressBar, 'width', (value*100)+'%');
        },

        setProcessing: function() {
            this.isProcessing = true;
            this.initialLabel = this.get("label");
            this.set("label", this.initialLabel+' ');
            if (!this.isCancelable) {
                this.set("disabled", true);
            }
        },

        reset: function() {
            this.set("label", this.initialLabel);
            if (!this.isCancelable) {
                this.set("disabled", false);
            }
            this.setProgress(0);
            this.isProcessing = false;
        }
    });
});<|endoftext|>


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

    // Define object config of properties for this chart directive
    var BarChartDefaults = {
        plotWidth: 800,
        plotHeight: 200,
        transitionMillis: 500,
        lazyLoad: true,
        binType: 'temporal'
    };

    /**
     * ngInject
     */
    function barChart (CartoConfig, BarChartDefaults) {

        var PLOT_CLASS = 'mos-barchart';

        // Begin directive module definition
        var module = {};

        module.restrict = 'EA';
        module.templateUrl = 'scripts/charting/barchart-partial.html';
        module.controller = 'ChartingController';

        module.scope = {
            data: '=',              // Required
            id: '@',                // Required
            plotWidth: '@',
            selectedY: '=',
            selectLabel: '=',
            selectUnit: '=',
            plotHeight: '@',
            margin: '&',
            binType: '@',
            lazyLoad: '@',
            transitionMillis: '@'
        };

        // This is a helper function for transforming api data into percentiles based on sqft
        function binBySqFt(data, groups) {
            data = _.filter(data, function(d) { return d.sqfeet > 0; });
            _.forEach(data, function(d) {
                d.log = Math.log10(d.sqfeet);
            });
            var maxLog = _.max(data, function(d) { return d.log; }).log;
            var binnedBySqFt = {};
            var binSize = maxLog / groups;
            var getBinSize =  function(d) {
                return binSize * i < d.log && (binSize * i) + binSize >= d.log;
            };
            for (var i = 0; i < groups; i++) {
                binnedBySqFt[i] = _.filter(data, getBinSize);
            }
            var output = [];
            _.forEach(binnedBySqFt, function(d, i) {
                // Naive count
                var kCount = d.length;
                // Special counts for fair avging
                var nEnergystar = _.filter(d, function(e) { return !isNaN(e.energystar) && e.energystar > 0; }).length;
                var nEUI = _.filter(d, function(e) { return !isNaN(e.eui) && e.eui > 0; }).length;
                // The bin boundaries
                var lowBound = Math.round(Math.pow(10, (i * binSize))).toLocaleString();
                var highBound = Math.round(Math.pow(10, (i * binSize) + binSize)).toLocaleString();
                // Min and max sq ft
                var minsqft = _.min(d, function(val) { return val.sqfeet; }).sqfeet;
                var maxsqft = _.max(d, function(val) { return val.sqfeet; }).sqfeet;
                output = output.concat({
                    totalemissions: _.reduce(d, function(memo, val) { return val.emissions + memo; }, 0),
                    avgenergystar: nEnergystar > 0 ? _.reduce(d, function(memo, val) { return val.energystar + memo; }, 0) / nEnergystar : 0,
                    avgeui: nEUI > 0 ? _.reduce(d, function(memo, val) { return val.eui + memo; }, 0) / nEUI : 0,
                    minsqft: minsqft ? minsqft : 0,
                    maxsqft: maxsqft ? maxsqft : 0,
                    avgsqft: _.reduce(d, function(memo, val) { return val.sqfeet + memo; }, 0) / kCount,
                    totalsqft: _.reduce(d, function(memo, val) { return val.sqfeet + memo; }, 0),
                    totalenergy: _.reduce(d, function(memo, val) { return (val.sqfeet * val.eui) + memo; }, 0),
                    count: kCount,
                    key: lowBound + ' - ' + highBound,
                    yearRange: _.min(d, function(d) { return d.yearbuilt; }).yearbuilt +
                        '-' + _.max(d, function(d) { return d.yearbuilt; }).yearbuilt
                });
            });
            return _.rest(output, function(d) { return d.count === 0; }).reverse(); // Prune empty head
        }

        // Helper function for transforming unshaped data into data binned and aggregated over 5 year periods
        function binByYears(data) {
            var filteredData = _.filter(data, function(d) { return d.yearbuilt > 1849; });
            var dateRanges = _.zip(_.range(1849, 2015, 5), _.range(1853, 2019, 5));
            var rolledData =
                d3.nest()
                    .key(function(d) {
                        var years = _.find(dateRanges, function(range) {
                            return range[0] <= d.yearbuilt && d.yearbuilt <= range[1];
                        });
                        return years[0]+' - '+years[1];
                    })
                    .rollup(function(d) {
                        return {
                            totalsqft: d3.mean(d, function(e) { return e.sqfeet; }),
                            avgeui: d3.mean(d, function(e) { return e.eui; }),
                            totalemissions: d3.mean(d, function(e) { return e.emissions; }),
                            avgenergystar: d3.mean(d, function(e) { return e.energystar; }),
                            count: d3.sum(d, function() { return 1; }),
                            totalenergy: d3.sum(d, function(e) { return e.eui * e.sqfeet; })
                        };
                    })
                    .entries(filteredData);
            return _.chain(rolledData)
                    .sortBy(function(d) { return d.key; })
                    .map(function(d) {
                        var obj = d.values;
                        obj.key = d.key;
                        obj.avgenergystar = isNaN(obj.avgenergystar) ? 0 : obj.avgenergystar;
                        return obj;
                    })
                    .reverse()
                    .value();
        }

        module.link = function ($scope, element, attrs) {
            $scope.configure(BarChartDefaults);
            var config = $scope.config;
            config.margin.left = 0;

            // D3 margin, sizing, and spacing code
            element.addClass(PLOT_CLASS);
            var chart = d3.select('#' + attrs.id + ' .chart')
                    .attr('width', config.plotWidth);

            // Overridden ChartingController method
            $scope.plot = function(data) {
                // The dimension of choice for representation along Y
                var yAttr = $scope.selectedY;
                // Chart height
                chart.attr('height', config.plotHeight);

                // Choose appropriate binning algorithm
                if (config.binType === 'temporal') {
                    data = binByYears(data);
                } else if (config.binType === 'area') {
                    data = binBySqFt(data, 62); // 62 is the magic number for generating a
                                                // logarithmically generated set of bins which
                                                // have  32 after pruning the empty head (30 removed)
                }

                // Axes and scales
                var x = d3.scale.ordinal()
                    .domain(data.map(function(d) { return d.key; }))
                    .rangeRoundBands([config.plotWidth-config.margin.left-config.margin.right, 0], 0.05);
                var y = d3.scale.linear()
                    .domain([0, d3.max(data, function(d) { return d[yAttr]; })])
                    .range([config.plotHeight-config.margin.bottom-config.margin.top, 0]);
                var bottomAxis = d3.svg.axis()
                    .orient('bottom')
                    .scale(x)
                    .tickSize(3,1)
                    .tickValues([]);
                chart.append('g')
                    .attr('class', 'x axis')
                    .attr('transform', 'translate(' +config.margin.left + ',' + (config.plotHeight - config.margin.bottom) + ')')
                    .call(bottomAxis);

                // Axes should have custom labels to prevent cluttering; tooltips can handle detail
                var labelStart = chart.append('text')
                    .attr('class', 'x startLabel')
                    .attr('x', config.margin.left)
                    .attr('y', config.plotHeight-config.margin.top);
                var labelEnd = chart.append('text')
                    .attr('class', 'x endLabel')
                    .attr('x', config.plotWidth-config.margin.right)
                    .attr('y', config.plotHeight-config.margin.top);
                var labelMiddle = chart.append('text')
                    .attr('class', 'x centerLabel')
                    .attr('x', (config.plotWidth - config.margin.right) / 2)
                    .attr('y', config.plotHeight - config.margin.top);
                // Depending on bin type, our axis labeling should look rather different
                if (config.binType === 'temporal') {
                    labelStart.text('1850');
                    labelEnd.text('2013');
                    labelMiddle.text('Years');
                } else if (config.binType === 'area') {
                    labelStart.text(Math.round(data[data.length - 1].minsqft / 1000).toLocaleString() + 'k');
                    labelEnd.text(Math.round(data[0].maxsqft / 1000).toLocaleString() + 'k');
                    labelMiddle.text('Sq. Feet');
                }

                // Tooltips
                var tip = d3.tip()
                  .attr('class', 'd3-tip')
                  .offset([-10, 0])
                  .html(function(d) {
                    var dataLabel = d.key + (config.binType === 'area' ? ' Sq Ft' : '');
                    return '
' + dataLabel + '

' +
                           '
' + $scope.selectLabel + ':
' +
                           '
' + Math.round(d[yAttr]).toLocaleString() + ' ' + $scope.selectUnit + '
';
                  });
                chart.call(tip);

                // Bars
                chart.selectAll('bar')
                    .data(data)
                    .enter().append('rect')
                    .attr('transform', function(d) { return 'translate(' + (x(d.key) + config.margin.left).toString() + ',0)'; })
                    .attr('y', config.plotHeight - config.margin.bottom)
                    // Height of zero initially so it can be animated on load
                    .attr('height', 0)
                    .attr('width', x.rangeBand())
                    .attr('opacity', function(d, i) { return 1 - (i / data.length) * 0.3; })
                    .attr('rx', 3) // Rounding of corners
                    .attr('ry', 3)
                    .on('mouseover', tip.show)
                    .on('mouseout', tip.hide);

                // Perform the initial animation
                refreshData();

                // Animation functions
                function refreshScale() {
                    y.domain([0, d3.max(data, function(d) { return d[yAttr]; })]);
                }

                function refreshData() {
                    var transitionMillis = config.transitionMillis;
                    refreshScale();
                    chart.selectAll('rect')
                        .transition()
                        .ease('linear')
                        .duration(transitionMillis)
                        .attr('class', config.binType)
                        .attr('y', function(d) {
                            var val = isNaN(d[yAttr]) ? 0 : y(d[yAttr]);
                            return val - 10 + config.margin.top; })
                        .attr('height', function(d) {
                            var val = isNaN(d[yAttr]) ? 0 : y(d[yAttr]);
                            return config.plotHeight - val - config.margin.top - config.margin.bottom;
                        });
                }

                $scope.$watch('selectedY', function(newValue) {
                    yAttr = newValue;
                    refreshData();
                });
            };
        };

        return module;
    }

    angular.module('mos.charting')
      .constant('BarChartDefaults', BarChartDefaults)
      .directive('mosBarchart', barChart);

})();
<commit_msg>Use Math.log since Math.log10 is experimental<commit_after>(function () {
    'use strict';

    // Define object config of properties for this chart directive
    var BarChartDefaults = {
        plotWidth: 800,
        plotHeight: 200,
        transitionMillis: 500,
        lazyLoad: true,
        binType: 'temporal'
    };

    /**
     * ngInject
     */
    function barChart (CartoConfig, BarChartDefaults) {

        var PLOT_CLASS = 'mos-barchart';

        // Begin directive module definition
        var module = {};

        module.restrict = 'EA';
        module.templateUrl = 'scripts/charting/barchart-partial.html';
        module.controller = 'ChartingController';

        module.scope = {
            data: '=',              // Required
            id: '@',                // Required
            plotWidth: '@',
            selectedY: '=',
            selectLabel: '=',
            selectUnit: '=',
            plotHeight: '@',
            margin: '&',
            binType: '@',
            lazyLoad: '@',
            transitionMillis: '@'
        };

        // This is a helper function for transforming api data into percentiles based on sqft
        function binBySqFt(data, groups) {
            data = _.filter(data, function(d) { return d.sqfeet > 0; });
            _.forEach(data, function(d) {
                d.log = Math.log(d.sqfeet) / Math.log(10);
            });
            var maxLog = _.max(data, function(d) { return d.log; }).log;
            var binnedBySqFt = {};
            var binSize = maxLog / groups;
            var getBinSize =  function(d) {
                return binSize * i < d.log && (binSize * i) + binSize >= d.log;
            };
            for (var i = 0; i < groups; i++) {
                binnedBySqFt[i] = _.filter(data, getBinSize);
            }
            var output = [];
            _.forEach(binnedBySqFt, function(d, i) {
                // Naive count
                var kCount = d.length;
                // Special counts for fair avging
                var nEnergystar = _.filter(d, function(e) { return !isNaN(e.energystar) && e.energystar > 0; }).length;
                var nEUI = _.filter(d, function(e) { return !isNaN(e.eui) && e.eui > 0; }).length;
                // The bin boundaries
                var lowBound = Math.round(Math.pow(10, (i * binSize))).toLocaleString();
                var highBound = Math.round(Math.pow(10, (i * binSize) + binSize)).toLocaleString();
                // Min and max sq ft
                var minsqft = _.min(d, function(val) { return val.sqfeet; }).sqfeet;
                var maxsqft = _.max(d, function(val) { return val.sqfeet; }).sqfeet;
                output = output.concat({
                    totalemissions: _.reduce(d, function(memo, val) { return val.emissions + memo; }, 0),
                    avgenergystar: nEnergystar > 0 ? _.reduce(d, function(memo, val) { return val.energystar + memo; }, 0) / nEnergystar : 0,
                    avgeui: nEUI > 0 ? _.reduce(d, function(memo, val) { return val.eui + memo; }, 0) / nEUI : 0,
                    minsqft: minsqft ? minsqft : 0,
                    maxsqft: maxsqft ? maxsqft : 0,
                    avgsqft: _.reduce(d, function(memo, val) { return val.sqfeet + memo; }, 0) / kCount,
                    totalsqft: _.reduce(d, function(memo, val) { return val.sqfeet + memo; }, 0),
                    totalenergy: _.reduce(d, function(memo, val) { return (val.sqfeet * val.eui) + memo; }, 0),
                    count: kCount,
                    key: lowBound + ' - ' + highBound,
                    yearRange: _.min(d, function(d) { return d.yearbuilt; }).yearbuilt +
                        '-' + _.max(d, function(d) { return d.yearbuilt; }).yearbuilt
                });
            });
            return _.rest(output, function(d) { return d.count === 0; }).reverse(); // Prune empty head
        }

        // Helper function for transforming unshaped data into data binned and aggregated over 5 year periods
        function binByYears(data) {
            var filteredData = _.filter(data, function(d) { return d.yearbuilt > 1849; });
            var dateRanges = _.zip(_.range(1849, 2015, 5), _.range(1853, 2019, 5));
            var rolledData =
                d3.nest()
                    .key(function(d) {
                        var years = _.find(dateRanges, function(range) {
                            return range[0] <= d.yearbuilt && d.yearbuilt <= range[1];
                        });
                        return years[0]+' - '+years[1];
                    })
                    .rollup(function(d) {
                        return {
                            totalsqft: d3.mean(d, function(e) { return e.sqfeet; }),
                            avgeui: d3.mean(d, function(e) { return e.eui; }),
                            totalemissions: d3.mean(d, function(e) { return e.emissions; }),
                            avgenergystar: d3.mean(d, function(e) { return e.energystar; }),
                            count: d3.sum(d, function() { return 1; }),
                            totalenergy: d3.sum(d, function(e) { return e.eui * e.sqfeet; })
                        };
                    })
                    .entries(filteredData);
            return _.chain(rolledData)
                    .sortBy(function(d) { return d.key; })
                    .map(function(d) {
                        var obj = d.values;
                        obj.key = d.key;
                        obj.avgenergystar = isNaN(obj.avgenergystar) ? 0 : obj.avgenergystar;
                        return obj;
                    })
                    .reverse()
                    .value();
        }

        module.link = function ($scope, element, attrs) {
            $scope.configure(BarChartDefaults);
            var config = $scope.config;
            config.margin.left = 0;

            // D3 margin, sizing, and spacing code
            element.addClass(PLOT_CLASS);
            var chart = d3.select('#' + attrs.id + ' .chart')
                    .attr('width', config.plotWidth);

            // Overridden ChartingController method
            $scope.plot = function(data) {
                // The dimension of choice for representation along Y
                var yAttr = $scope.selectedY;
                // Chart height
                chart.attr('height', config.plotHeight);

                // Choose appropriate binning algorithm
                if (config.binType === 'temporal') {
                    data = binByYears(data);
                } else if (config.binType === 'area') {
                    data = binBySqFt(data, 62); // 62 is the magic number for generating a
                                                // logarithmically generated set of bins which
                                                // have  32 after pruning the empty head (30 removed)
                }

                // Axes and scales
                var x = d3.scale.ordinal()
                    .domain(data.map(function(d) { return d.key; }))
                    .rangeRoundBands([config.plotWidth-config.margin.left-config.margin.right, 0], 0.05);
                var y = d3.scale.linear()
                    .domain([0, d3.max(data, function(d) { return d[yAttr]; })])
                    .range([config.plotHeight-config.margin.bottom-config.margin.top, 0]);
                var bottomAxis = d3.svg.axis()
                    .orient('bottom')
                    .scale(x)
                    .tickSize(3,1)
                    .tickValues([]);
                chart.append('g')
                    .attr('class', 'x axis')
                    .attr('transform', 'translate(' +config.margin.left + ',' + (config.plotHeight - config.margin.bottom) + ')')
                    .call(bottomAxis);

                // Axes should have custom labels to prevent cluttering; tooltips can handle detail
                var labelStart = chart.append('text')
                    .attr('class', 'x startLabel')
                    .attr('x', config.margin.left)
                    .attr('y', config.plotHeight-config.margin.top);
                var labelEnd = chart.append('text')
                    .attr('class', 'x endLabel')
                    .attr('x', config.plotWidth-config.margin.right)
                    .attr('y', config.plotHeight-config.margin.top);
                var labelMiddle = chart.append('text')
                    .attr('class', 'x centerLabel')
                    .attr('x', (config.plotWidth - config.margin.right) / 2)
                    .attr('y', config.plotHeight - config.margin.top);
                // Depending on bin type, our axis labeling should look rather different
                if (config.binType === 'temporal') {
                    labelStart.text('1850');
                    labelEnd.text('2013');
                    labelMiddle.text('Years');
                } else if (config.binType === 'area') {
                    labelStart.text(Math.round(data[data.length - 1].minsqft / 1000).toLocaleString() + 'k');
                    labelEnd.text(Math.round(data[0].maxsqft / 1000).toLocaleString() + 'k');
                    labelMiddle.text('Sq. Feet');
                }

                // Tooltips
                var tip = d3.tip()
                  .attr('class', 'd3-tip')
                  .offset([-10, 0])
                  .html(function(d) {
                    var dataLabel = d.key + (config.binType === 'area' ? ' Sq Ft' : '');
                    return '
' + dataLabel + '

' +
                           '
' + $scope.selectLabel + ':
' +
                           '
' + Math.round(d[yAttr]).toLocaleString() + ' ' + $scope.selectUnit + '
';
                  });
                chart.call(tip);

                // Bars
                chart.selectAll('bar')
                    .data(data)
                    .enter().append('rect')
                    .attr('transform', function(d) { return 'translate(' + (x(d.key) + config.margin.left).toString() + ',0)'; })
                    .attr('y', config.plotHeight - config.margin.bottom)
                    // Height of zero initially so it can be animated on load
                    .attr('height', 0)
                    .attr('width', x.rangeBand())
                    .attr('opacity', function(d, i) { return 1 - (i / data.length) * 0.3; })
                    .attr('rx', 3) // Rounding of corners
                    .attr('ry', 3)
                    .on('mouseover', tip.show)
                    .on('mouseout', tip.hide);

                // Perform the initial animation
                refreshData();

                // Animation functions
                function refreshScale() {
                    y.domain([0, d3.max(data, function(d) { return d[yAttr]; })]);
                }

                function refreshData() {
                    var transitionMillis = config.transitionMillis;
                    refreshScale();
                    chart.selectAll('rect')
                        .transition()
                        .ease('linear')
                        .duration(transitionMillis)
                        .attr('class', config.binType)
                        .attr('y', function(d) {
                            var val = isNaN(d[yAttr]) ? 0 : y(d[yAttr]);
                            return val - 10 + config.margin.top; })
                        .attr('height', function(d) {
                            var val = isNaN(d[yAttr]) ? 0 : y(d[yAttr]);
                            return config.plotHeight - val - config.margin.top - config.margin.bottom;
                        });
                }

                $scope.$watch('selectedY', function(newValue) {
                    yAttr = newValue;
                    refreshData();
                });
            };
        };

        return module;
    }

    angular.module('mos.charting')
      .constant('BarChartDefaults', BarChartDefaults)
      .directive('mosBarchart', barChart);

})();
<|endoftext|>


<commit_before>'use strict';
/**
 * @ngdoc function
 * @name sbAdminApp.controller:MainCtrl
 * @description
 * # MainCtrl
 * Controller of the sbAdminApp
 */
angular.module('sbAdminApp')
  .controller('GraphCtrl', function ($scope, $resource) {

      $scope.apiUrl = "http://localhost:5000/"
      $scope.graphSigma = [];
      //get users
      var Users = $resource($scope.apiUrl + 'users');
      var users = Users.query();
      users.$promise.then(function (result) {
          $scope.users = result;
      });
      //get posts
      var Posts = $resource($scope.apiUrl + 'posts');
      var posts = Posts.query();
      posts.$promise.then(function (result) {
          $scope.posts = result;
      });
      //get comments
      var Comments = $resource($scope.apiUrl + 'comments');
      var comments = Comments.query();
      comments.$promise.then(function (result) {
          $scope.comments = result;
      });
      // get layout algo
      var Layout = $resource($scope.apiUrl + 'layoutAlgorithm');
      var layout = Layout.query();
      layout.$promise.then(function (result) {
          var layout = []
          var layoutName = ""
          angular.forEach(result, function(value, key) {
              layoutName = ""
              angular.forEach(value, function(value2, key) {
                  layoutName += value2;
              });
              layout.push(layoutName)
          });
          $scope.layout = layout;
      });

      $scope.field = "uid";
      $scope.value = "34";
      $scope.layoutChoice = "FM^3 (OGDF)";
      $scope.submit = function () {
          // // Read the complete graph from api
          if($scope.complete) {
              var drawGraph = $resource($scope.apiUrl + 'draw/complete/' + $scope.layoutChoice);
              var drawgraph = drawGraph.query();
              drawgraph.$promise.then(function (result) {
                  $scope.graphSigma = result.pop();
                  console.log("done");
              });
          }
          else {
              if($scope.field == "uid" && $scope.user)
                  $scope.value = $scope.user;
              else if($scope.field == "pid")
                  $scope.value = $scope.post;
              else if($scope.field == "cid")
                  $scope.value = $scope.comment;
              var CreateGraph = $resource($scope.apiUrl + 'createGraph/'+ $scope.field +'/'+ $scope.value);
              var creategraph = CreateGraph.query();
              creategraph.$promise.then(function (result) {
                  var graph_id = result.pop();
                  var graph_id_string = ""
                  angular.forEach(graph_id, function(value, key) {
                      graph_id_string += value;
                  });
                  console.log(graph_id_string);
                  var drawGraph = $resource($scope.apiUrl + 'draw/'+ graph_id_string +'/'+ $scope.layoutChoice);
                  var drawgraph = drawGraph.query();
                  drawgraph.$promise.then(function (result) {
                      $scope.graphSigma = result.pop();
                      console.log("done");
                  });
              });
          }
      };

      $scope.submit();
});<commit_msg>change url for server test<commit_after>'use strict';
/**
 * @ngdoc function
 * @name sbAdminApp.controller:MainCtrl
 * @description
 * # MainCtrl
 * Controller of the sbAdminApp
 */
angular.module('sbAdminApp')
  .controller('GraphCtrl', function ($scope, $resource) {

      $scope.apiUrl = "http://nferon.ovh:5000/"
      $scope.graphSigma = [];
      //get users
      var Users = $resource($scope.apiUrl + 'users');
      var users = Users.query();
      users.$promise.then(function (result) {
          $scope.users = result;
      });
      //get posts
      var Posts = $resource($scope.apiUrl + 'posts');
      var posts = Posts.query();
      posts.$promise.then(function (result) {
          $scope.posts = result;
      });
      //get comments
      var Comments = $resource($scope.apiUrl + 'comments');
      var comments = Comments.query();
      comments.$promise.then(function (result) {
          $scope.comments = result;
      });
      // get layout algo
      var Layout = $resource($scope.apiUrl + 'layoutAlgorithm');
      var layout = Layout.query();
      layout.$promise.then(function (result) {
          var layout = []
          var layoutName = ""
          angular.forEach(result, function(value, key) {
              layoutName = ""
              angular.forEach(value, function(value2, key) {
                  layoutName += value2;
              });
              layout.push(layoutName)
          });
          $scope.layout = layout;
      });

      $scope.field = "uid";
      $scope.value = "34";
      $scope.layoutChoice = "FM^3 (OGDF)";
      $scope.submit = function () {
          // // Read the complete graph from api
          if($scope.complete) {
              var drawGraph = $resource($scope.apiUrl + 'draw/complete/' + $scope.layoutChoice);
              var drawgraph = drawGraph.query();
              drawgraph.$promise.then(function (result) {
                  $scope.graphSigma = result.pop();
                  console.log("done");
              });
          }
          else {
              if($scope.field == "uid" && $scope.user)
                  $scope.value = $scope.user;
              else if($scope.field == "pid")
                  $scope.value = $scope.post;
              else if($scope.field == "cid")
                  $scope.value = $scope.comment;
              var CreateGraph = $resource($scope.apiUrl + 'createGraph/'+ $scope.field +'/'+ $scope.value);
              var creategraph = CreateGraph.query();
              creategraph.$promise.then(function (result) {
                  var graph_id = result.pop();
                  var graph_id_string = ""
                  angular.forEach(graph_id, function(value, key) {
                      graph_id_string += value;
                  });
                  console.log(graph_id_string);
                  var drawGraph = $resource($scope.apiUrl + 'draw/'+ graph_id_string +'/'+ $scope.layoutChoice);
                  var drawgraph = drawGraph.query();
                  drawgraph.$promise.then(function (result) {
                      $scope.graphSigma = result.pop();
                      console.log("done");
                  });
              });
          }
      };

      $scope.submit();
});<|endoftext|>


<commit_before>/**
 * @class DepthPerspectiveFilter
 * @contructor
 * @param texture {Texture} The texture used for the displacemtent map * must be power of 2 texture at the moment
 */
'use strict';
PIXI.DepthPerspectiveFilter = function(texture)
{
  PIXI.AbstractFilter.call( this );

  this.passes = [this];

  // set the uniforms
  this.uniforms = {
    displacementMap: {type: 'sampler2D', value:texture},
    scale:           {type: '1f', value:0.015},
    offset:          {type: '2f', value:{x:0, y:0}},
    mapDimensions:   {type: '2f', value:{x:1, y:5112}},
    dimensions:      {type: '4fv', value:[0,0,0,0]},
    focus:           {type: '1f', value:0.5}
  };

  if(texture.baseTexture.hasLoaded)
  {
    this.uniforms.mapDimensions.value.x = texture.width;
    this.uniforms.mapDimensions.value.y = texture.height;
  }
  else
  {
    this.boundLoadedFunction = this.onTextureLoaded.bind(this);

    texture.baseTexture.on('loaded', this.boundLoadedFunction);
  }

  this.fragmentSrc = [
'precision highp float;',
'varying vec2 vTextureCoord;',
'varying vec4 vColor;',
'uniform sampler2D displacementMap;',
'uniform sampler2D uSampler;',
'uniform vec4 dimensions;',
'uniform vec2 mapDimensions;',
'uniform float scale;',
'uniform vec2 offset;',
'uniform float focus;',
'const float maxSteps = 32.0;',
'',
'float perspective = -0.05;',
'float upscale = 1.1;',
'float steps = min(128.0, maxSteps);',
'',
'float aspect = dimensions.x / dimensions.y;',
'vec2 scale2 = vec2(scale / aspect, scale) * vec2(1, -1) * vec2(2);',
'mat2 baseVector = mat2(vec2(-focus * offset) * scale2, vec2(offset - focus * offset) * scale2);',
'',
'',
'void main(void) {',
'    vec2 pos = (vTextureCoord - vec2(0.5)) / vec2(upscale) + vec2(0.5);',
'    mat2 vector = baseVector;',
'    // perspective shift',
'    vector[1] += (vec2(2.0) * pos - vec2(1.0)) * vec2(perspective);',
'    ',
'    float dstep = 1.0 / (steps - 1.0);',
'    vec2 vstep = (vector[1] - vector[0]) / vec2((steps - 1.0));',
'    ',
'    vec4 colSum = vec4(0.0);',
'    float colCount = 0.0;',
'    float minConfidence = dstep / 2.0;',
'    ',
'    vec2 vpos = pos + vector[1];',
'    float dpos = 1.0;',
'    ',
'    #define METHOD 1',
'    #define BRANCHED 1 // its faster no to branch on shorter loops [?]',
'    #define DEBUG 0',
'    ',
'    for(float i = 1.0; i <= maxSteps; ++i) {',
'        #if BRANCHED >= 1',
'        if (dpos >= 0.0 && colCount < 0.2) {',
'        #endif',
'            float depth = 1.0 - texture2D(displacementMap, vpos * vec2(1, -1) + vec2(0, 1)).r;',
'            float confidence;',
'',
'            #if METHOD == 1',
'               confidence = step(dpos - dstep, depth);',
'//                if (depth < dpos) confidence = 0.0;',
'',
'            #elif METHOD == 2',
'                confidence = 1.0 - abs(dpos - depth);',
'                if (confidence < 1.0 - minConfidence * 2.0) confidence = 0.0;',
'',
'            #elif METHOD == 3',
'                confidence = 1.0 - abs(dpos - depth);',
'                if (confidence < 1.0 - minConfidence * 1.0) confidence = 0.0;',
'',
'            #elif METHOD == 4',
'               // 1 - (x)^2 * 100',
'                confidence = 1.0 - pow(dpos - depth, 4.0) * 1000.0;',
'',
'            #elif METHOD == 5',
'                confidence = 1.0 - abs(dpos - depth);',
'                confidence = pow(confidence, 64.0);',
'',
'            #endif',
'',
'            #if BRANCHED == 0',
'               confidence *= step(0.0, dpos);',
'               confidence *= step(colCount, 0.2);',
'            #endif',
'',
'            #if BRANCHED >= 2',
'            if (confidence > 0.0) {',
'            #endif',
'                ',
'               colSum += texture2D(uSampler, vpos) * confidence;',
'               colCount += confidence;',
'            #if BRANCHED >= 2',
'            }',
'            #endif',
'            ',
'            #if DEBUG > 0',
'               gl_FragColor = vec4(confidence, depth, dpos, 0);',
'            #endif',
'    //         return;',
'            ',
'        #if BRANCHED >= 1',
'        }',
'        #endif',
'            ',
'        dpos -= dstep;',
'        vpos -= vstep;',
'    };',
'    ',
'    #if DEBUG <= 0',
'    gl_FragColor = colSum / vec4(colCount);',
'    #endif',
'}',

];
};

PIXI.DepthPerspectiveFilter.prototype = Object.create( PIXI.AbstractFilter.prototype );
PIXI.DepthPerspectiveFilter.prototype.constructor = PIXI.DepthPerspectiveFilter;

PIXI.DepthPerspectiveFilter.prototype.onTextureLoaded = function()
{
  this.uniforms.mapDimensions.value.x = this.uniforms.displacementMap.value.width;
  this.uniforms.mapDimensions.value.y = this.uniforms.displacementMap.value.height;

  this.uniforms.displacementMap.value.baseTexture.off('loaded', this.boundLoadedFunction);
};

/**
 * The texture used for the displacemtent map * must be power of 2 texture at the moment
 *
 * @property map
 * @type Texture
 */
Object.defineProperty(PIXI.DepthPerspectiveFilter.prototype, 'map', {
  get: function() {
    return this.uniforms.displacementMap.value;
  },
  set: function(value) {
    this.uniforms.displacementMap.value = value;
  }
});

/**
 * The multiplier used to scale the displacement result from the map calculation.
 *
 * @property scale
 * @type Point
 */
Object.defineProperty(PIXI.DepthPerspectiveFilter.prototype, 'scale', {
  get: function() {
    return this.uniforms.scale.value;
  },
  set: function(value) {
    this.uniforms.scale.value = value;
  }
});

/**
 * Focus point in paralax
 *
 * @property focus
 * @type float
 */
Object.defineProperty(PIXI.DepthPerspectiveFilter.prototype, 'focus', {
  get: function() {
    return this.uniforms.focus.value;
  },
  set: function(value) {
    this.uniforms.focus.value = Math.min(1,Math.max(0,value));
  }
});

/**
 * The offset used to move the displacement map.
 *
 * @property offset
 * @type Point
 */
Object.defineProperty(PIXI.DepthPerspectiveFilter.prototype, 'offset', {
  get: function() {
    return this.uniforms.offset.value;
  },
  set: function(value) {
    this.uniforms.offset.value = value;
  }
});<commit_msg>correction<commit_after>/**
 * @class DepthPerspectiveFilter
 * @contructor
 * @param texture {Texture} The texture used for the displacemtent map * must be power of 2 texture at the moment
 */
'use strict';
PIXI.DepthPerspectiveFilter = function(texture)
{
  PIXI.AbstractFilter.call( this );

  this.passes = [this];

  // set the uniforms
  this.uniforms = {
    displacementMap: {type: 'sampler2D', value:texture},
    scale:           {type: '1f', value:0.015},
    offset:          {type: '2f', value:{x:0, y:0}},
    mapDimensions:   {type: '2f', value:{x:1, y:5112}},
    dimensions:      {type: '4fv', value:[0,0,0,0]},
    focus:           {type: '1f', value:0.5}
  };

  if(texture.baseTexture.hasLoaded)
  {
    this.uniforms.mapDimensions.value.x = texture.width;
    this.uniforms.mapDimensions.value.y = texture.height;
  }
  else
  {
    this.boundLoadedFunction = this.onTextureLoaded.bind(this);

    texture.baseTexture.on('loaded', this.boundLoadedFunction);
  }

  this.fragmentSrc = [

'precision highp float;',
'',
'varying vec2 vTextureCoord;',
'varying vec4 vColor;',
'uniform sampler2D displacementMap;',
'uniform sampler2D uSampler;',
'uniform vec4 dimensions;',
'uniform vec2 mapDimensions;',
'uniform float scale;',
'uniform vec2 offset;',
'uniform float focus;',
'',
'#define METHOD 1',
'#define BRANCHED 1 // its faster no to branch on shorter loops [?]',
'#define DEBUG 0',
'#define CORRECT',
'',
'const float maxSteps = 16.0;',
'',
'const float perspective = -0.05;',
'const float upscale = 1.1;',
'// float steps = clamp( ceil( max(abs(offset.x), abs(offset.y)) * maxSteps ), 1.0, maxSteps);',
'float steps = maxSteps;',
'',
'float maskPower = steps * 2.0;// 32.0;',
'float correctPower = max(1.0, steps / 4.0);',
'',
'float aspect = dimensions.x / dimensions.y;',
'vec2 scale2 = vec2(scale / aspect, scale) * vec2(1, -1) * vec2(2);',
'mat2 baseVector = mat2(vec2(-focus * offset) * scale2, vec2(offset - focus * offset) * scale2);',
'',
'',
'void main(void) {',
'    vec2 pos = (vTextureCoord - vec2(0.5)) / vec2(upscale) + vec2(0.5);',
'    mat2 vector = baseVector;',
'    // perspective shift',
'    vector[1] += (vec2(2.0) * pos - vec2(1.0)) * vec2(perspective);',
'    ',
'    float dstep = 1.0 / (steps - 1.0);',
'    vec2 vstep = (vector[1] - vector[0]) / vec2((steps - 1.0));',
'    ',
'    vec4 colSum = vec4(0.0);',
'    float colCount = 0.0;',
'    float minConfidence = dstep / 2.0;',
'    ',
'    vec2 vpos = pos + vector[1];',
'    float dpos = 1.0;',
'    ',
'    ',
'    for(float i = 1.0; i <= maxSteps; ++i) {',
'        #if BRANCHED >= 1',
'        if (dpos >= 0.0 && colCount < 0.2) {',
'        #endif',
'            float depth = 1.0 - texture2D(displacementMap, vpos * vec2(1, -1) + vec2(0, 1)).r;',
'            float confidence;',
'',
'            #if METHOD == 1',
'               confidence = step(dpos - dstep, depth);',
'//                if (depth < dpos) confidence = 0.0;',
'',
'            #elif METHOD == 2',
'                confidence = 1.0 - abs(dpos - depth);',
'                if (confidence < 1.0 - minConfidence * 2.0) confidence = 0.0;',
'',
'            #elif METHOD == 3',
'                confidence = 1.0 - abs(dpos - depth);',
'                if (confidence < 1.0 - minConfidence * 1.0) confidence = 0.0;',
'',
'            #elif METHOD == 4',
'               // 1 - (x)^2 * 100',
'                confidence = 1.0 - pow(dpos - depth, 4.0) * 1000.0;',
'',
'            #elif METHOD == 5',
'                confidence = 1.0 - abs(dpos - depth);',
'                confidence = pow(confidence, maskPower);',
'',
'            #endif',
'',
'            #if BRANCHED == 0',
'               confidence *= step(0.0, dpos);',
'               confidence *= step(colCount, 0.2);',
'            #endif',
'',
'            #if BRANCHED >= 2',
'            if (confidence > 0.0) {',
'            #endif',
'                ',
'            #ifdef CORRECT',
'              colSum += texture2D(uSampler, vpos ',
'                          + ( vec2((depth - dpos) / (dstep * correctPower)) * vstep )',
'                        ) * confidence;',
'            #else',
'              colSum += texture2D(uSampler, vpos) * confidence;',
'            #endif',
'            colCount += confidence;',
'                ',
'            #if BRANCHED >= 2',
'            }',
'            #endif',
'            ',
'            #if DEBUG > 0',
'               gl_FragColor = vec4(confidence, depth, dpos, 0);',
'            #endif',
'    //         return;',
'            ',
'        #if BRANCHED >= 1',
'        }',
'        #endif',
'            ',
'        dpos -= dstep;',
'        vpos -= vstep;',
'    };',
'    ',
'    #if DEBUG <= 0',
'    gl_FragColor = colSum / vec4(colCount);',
'    #endif',
'}',

];
};

PIXI.DepthPerspectiveFilter.prototype = Object.create( PIXI.AbstractFilter.prototype );
PIXI.DepthPerspectiveFilter.prototype.constructor = PIXI.DepthPerspectiveFilter;

PIXI.DepthPerspectiveFilter.prototype.onTextureLoaded = function()
{
  this.uniforms.mapDimensions.value.x = this.uniforms.displacementMap.value.width;
  this.uniforms.mapDimensions.value.y = this.uniforms.displacementMap.value.height;

  this.uniforms.displacementMap.value.baseTexture.off('loaded', this.boundLoadedFunction);
};

/**
 * The texture used for the displacemtent map * must be power of 2 texture at the moment
 *
 * @property map
 * @type Texture
 */
Object.defineProperty(PIXI.DepthPerspectiveFilter.prototype, 'map', {
  get: function() {
    return this.uniforms.displacementMap.value;
  },
  set: function(value) {
    this.uniforms.displacementMap.value = value;
  }
});

/**
 * The multiplier used to scale the displacement result from the map calculation.
 *
 * @property scale
 * @type Point
 */
Object.defineProperty(PIXI.DepthPerspectiveFilter.prototype, 'scale', {
  get: function() {
    return this.uniforms.scale.value;
  },
  set: function(value) {
    this.uniforms.scale.value = value;
  }
});

/**
 * Focus point in paralax
 *
 * @property focus
 * @type float
 */
Object.defineProperty(PIXI.DepthPerspectiveFilter.prototype, 'focus', {
  get: function() {
    return this.uniforms.focus.value;
  },
  set: function(value) {
    this.uniforms.focus.value = Math.min(1,Math.max(0,value));
  }
});

/**
 * The offset used to move the displacement map.
 *
 * @property offset
 * @type Point
 */
Object.defineProperty(PIXI.DepthPerspectiveFilter.prototype, 'offset', {
  get: function() {
    return this.uniforms.offset.value;
  },
  set: function(value) {
    this.uniforms.offset.value = value;
  }
});<|endoftext|>


<commit_before>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Foreground page
"use strict";

var files = [];

var newFileIndex = 0;

// Returns the indices of the selected files.
function selectedFiles() {
  var selected = [];
  var trs = document.querySelectorAll('#file_table tbody tr');
  for (var i = 0; i < trs.length; i++) {
    var tr = trs[i];
    if (tr.querySelector('input[type = "checkbox"]').checked) {
      var fileBox = tr.querySelector('input[type = "text"]');
      selected.push(i);
    }
  }
  return selected;
}

function selectionChanged() {
  var selected = selectedFiles();

  var deleteButton = document.getElementById('delete_files');
  if (selected.length > 0)
    deleteButton.removeAttribute('disabled');
  else
    deleteButton.setAttribute('disabled', '');

  var contents_textfield = document.getElementById('contents_textfield');
  if (selected.length == 1) {
    // Display a preview of the file's contents.
    contents_textfield.value = files[selected[0]].contents;
    contents_textfield.style.display = 'block';
  } else {
    contents_textfield.style.display = 'none';
  }
}

function generateTableRows() {
  var table = document.getElementById('file_table');
  var tbody = table.querySelector('tbody');
  while (tbody.firstChild)
    tbody.removeChild(tbody.firstChild);

  for (var i = 0; i < files.length; i++) {
    var file = files[i];
    var tr = document.createElement('tr');

    var td1 = document.createElement('td');
    td1.setAttribute('class', 'mdl-data-table__cell--non-numeric');
    var textField = document.createElement('div');
    textField.setAttribute(
        'class', 'mdl-textfield mdl-js-textfield compact-mdl-textfield');
    var textFieldInput = document.createElement('input');
    textFieldInput.setAttribute('class', 'mdl-textfield__input');
    textFieldInput.setAttribute('type', 'text');
    textFieldInput.value = file.name;
    textFieldInput.ballistaIndex = i;
    textField.appendChild(textFieldInput);
    componentHandler.upgradeElement(textField);
    td1.appendChild(textField);
    tr.appendChild(td1);

    var td2 = document.createElement('td');
    td2.setAttribute('class', 'mdl-data-table__cell--non-numeric');
    var button = document.createElement('button');
    button.setAttribute('class', 'mdl-button mdl-js-button mdl-button--raised mdl-button--colored mdl-js-ripple-effect edit-button');
    button.appendChild(document.createTextNode('Open'));
    componentHandler.upgradeElement(button);
    td2.appendChild(button);
    tr.appendChild(td2);

    tbody.appendChild(tr);

    textFieldInput.addEventListener('change', onFilenameChanged);
  }
  reUpgradeTable(table, selectionChanged);
}

function createNewFile() {
  var filename = `New File ${++newFileIndex}.txt`;
  files.push({name: filename, contents: ''});
  generateTableRows();
}

function deleteSelectedFiles() {
  var selected = selectedFiles();
  selected.reverse();
  selected.forEach(i => files.splice(i, 1));
  generateTableRows();
}

function onFilenameChanged(e) {
  var index = e.target.ballistaIndex;
  var file = files[index];
  file.name = e.target.value;
}

// Updates |contents_textfield| with the contents of |file|, asynchronously.
function updateTextFromFile(file) {
  var contents_textfield = document.getElementById('contents_textfield');
  return readBlobAsText(file)
      .then(text => {
        contents_textfield.value = text;
      });
}

function editButtonClick() {
  var contents_textfield = document.getElementById('contents_textfield');
  var contents = contents_textfield.value;
  var filename = document.getElementById('filename_textfield').value;
  var file = new File([contents], filename, {type: "text/plain"});

  var channel = new MessageChannel();
  channel.port1.onmessage = event => {
    var data = event.data;
    var type = data.type;

    if (type == 'update') {
      if (data.file !== undefined)
        updateTextFromFile(data.file);
    }
  }
  navigator.serviceWorker.controller.postMessage(
      {type: 'open', file: file, port: channel.port2}, [channel.port2]);
}

function onLoad() {
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/sw.js').then(registration => {
      // Registration was successful
      console.log('ServiceWorker registration successful with scope: ',
                  registration.scope);
    }).catch(err => {
      // registration failed :(
      console.log('ServiceWorker registration failed: ', err);
    });
  }

  document.getElementById('delete_files')
      .addEventListener('click', deleteSelectedFiles);

  document.getElementById('new_file')
      .addEventListener('click', createNewFile);

  generateTableRows();
}

window.addEventListener('load', onLoad, false);
<commit_msg>requester: Open button works again.<commit_after>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Foreground page
"use strict";

var files = [];

var newFileIndex = 0;

// Returns the indices of the selected files.
function selectedFiles() {
  var selected = [];
  var trs = document.querySelectorAll('#file_table tbody tr');
  for (var i = 0; i < trs.length; i++) {
    var tr = trs[i];
    if (tr.querySelector('input[type = "checkbox"]').checked) {
      var fileBox = tr.querySelector('input[type = "text"]');
      selected.push(i);
    }
  }
  return selected;
}

function selectionChanged() {
  var selected = selectedFiles();

  var deleteButton = document.getElementById('delete_files');
  if (selected.length > 0)
    deleteButton.removeAttribute('disabled');
  else
    deleteButton.setAttribute('disabled', '');

  var contents_textfield = document.getElementById('contents_textfield');
  if (selected.length == 1) {
    // Display a preview of the file's contents.
    contents_textfield.value = files[selected[0]].contents;
    contents_textfield.style.display = 'block';
  } else {
    contents_textfield.style.display = 'none';
  }
}

function generateTableRows() {
  var table = document.getElementById('file_table');
  var tbody = table.querySelector('tbody');
  while (tbody.firstChild)
    tbody.removeChild(tbody.firstChild);

  for (var i = 0; i < files.length; i++) {
    var file = files[i];
    var tr = document.createElement('tr');

    var td1 = document.createElement('td');
    td1.setAttribute('class', 'mdl-data-table__cell--non-numeric');
    var textField = document.createElement('div');
    textField.setAttribute(
        'class', 'mdl-textfield mdl-js-textfield compact-mdl-textfield');
    var textFieldInput = document.createElement('input');
    textFieldInput.setAttribute('class', 'mdl-textfield__input');
    textFieldInput.setAttribute('type', 'text');
    textFieldInput.value = file.name;
    textFieldInput.ballistaIndex = i;
    textField.appendChild(textFieldInput);
    componentHandler.upgradeElement(textField);
    td1.appendChild(textField);
    tr.appendChild(td1);

    var td2 = document.createElement('td');
    td2.setAttribute('class', 'mdl-data-table__cell--non-numeric');
    var button = document.createElement('button');
    button.setAttribute('class', 'mdl-button mdl-js-button mdl-button--raised mdl-button--colored mdl-js-ripple-effect edit-button');
    button.appendChild(document.createTextNode('Open'));
    componentHandler.upgradeElement(button);
    td2.appendChild(button);
    tr.appendChild(td2);

    tbody.appendChild(tr);

    textFieldInput.addEventListener('change', onFilenameChanged);
    button.addEventListener('click', editButtonClick.bind(undefined, i));
  }
  reUpgradeTable(table, selectionChanged);
}

function createNewFile() {
  var filename = `New File ${++newFileIndex}.txt`;
  files.push({name: filename, contents: ''});
  generateTableRows();
}

function deleteSelectedFiles() {
  var selected = selectedFiles();
  selected.reverse();
  selected.forEach(i => files.splice(i, 1));
  generateTableRows();
}

function onFilenameChanged(e) {
  var index = e.target.ballistaIndex;
  var file = files[index];
  file.name = e.target.value;
}

// Updates |contents_textfield| with the contents of |file|, asynchronously.
function updateTextFromFile(file) {
  var contents_textfield = document.getElementById('contents_textfield');
  return readBlobAsText(file)
      .then(text => {
        contents_textfield.value = text;
      });
}

function editButtonClick(index) {
  var file = files[index];
  var blob = new File([file.contents], file.name, {type: "text/plain"});

  var channel = new MessageChannel();
  channel.port1.onmessage = event => {
    var data = event.data;
    var type = data.type;

    if (type == 'update') {
      if (data.file !== undefined)
        updateTextFromFile(data.file);
    }
  }
  navigator.serviceWorker.controller.postMessage(
      {type: 'open', file: blob, port: channel.port2}, [channel.port2]);
}

function onLoad() {
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/sw.js').then(registration => {
      // Registration was successful
      console.log('ServiceWorker registration successful with scope: ',
                  registration.scope);
    }).catch(err => {
      // registration failed :(
      console.log('ServiceWorker registration failed: ', err);
    });
  }

  document.getElementById('delete_files')
      .addEventListener('click', deleteSelectedFiles);

  document.getElementById('new_file')
      .addEventListener('click', createNewFile);

  generateTableRows();
}

window.addEventListener('load', onLoad, false);
<|endoftext|>


<commit_before>// jscs:disable
(function(){

  /**
   * Base service class for services with pagination
   *   getList
   *   $get
   *   $delete
   *   $create
   *   operation
   */

  angular.module('ncsaas')
    .service('baseServiceClass', [
      '$q', 'currentStateService', '$resource', 'ENV', '$rootScope', 'listCache', baseServiceClass]);
  function baseServiceClass($q, currentStateService, $resource, ENV, $rootScope, listCache) {
    // pageSize, page, pages - default variables, you can change this in your init method or call this._super() in init
    var BaseServiceClass = Class.extend({
      ALL_CACHE_KEYS: 'ALL_CACHE_KEYS',
      pageSize:null,
      page:null,
      pages:null,
      resultCount:null,
      currentStateService:null,
      endpoint:null,
      filterByCustomer: true,
      customerUuid:null,
      cacheTime: 0,
      cacheReset: false,
      endpointPostfix: '',

      init:function() {
        this.pageSize = ENV.pageSize;
        this.page = 1;
        this.pages = null;
        this.defaultFilter = {};
        this.currentStateService = currentStateService;
        this.pageChangingReset();
        this.cacheTime = 0;
      },

      getList:function(filter, endpointUrl) {
        var vm = this;
        var deferred = $q.defer();
        filter = filter || {};
        for (var key in this.defaultFilter) {
          filter[key] = this.defaultFilter[key];
        }
        var queryList = function() {
          filter.page = filter.page || vm.page;
          /*jshint camelcase: false */
          filter.page_size = vm.pageSize;
          var cacheKey = vm.endpoint + JSON.stringify(filter);
          var cache = vm.getCache(cacheKey);

          if (!vm.cacheReset && vm.cacheTime > 0 && cache && cache.time > new Date().getTime()) {
            vm.setPagesCount(cache.count);
            deferred.resolve(cache.data);
          } else {
            vm.cacheReset = false;
            listCache.put(cacheKey, {data: null, time: 0});
            vm.getFactory(true, null, endpointUrl).query(filter, function(response, responseHeaders) {
              var header = responseHeaders();
              var resultCount = !header['x-result-count'] ? null : header['x-result-count'];
              vm.setPagesCount(resultCount);
              if (vm.cacheTime > 0) {
                vm.setCache(vm.cacheTime, response, cacheKey, vm.endpoint);
              }
              deferred.resolve(response);
            }, function(err) {
              if (err.status === 401) {
                $rootScope.$broadcast('authService:signout');
              }
              deferred.reject(err);
            });
          }

        };

        if (vm.currentStateService == null || !vm.filterByCustomer) {
          queryList();
        } else {
          vm.currentStateService.getCustomer().then(function (response) {
            /*jshint camelcase: false */
            filter.customer = (this.customerUuid) ? this.customerUuid() : response.uuid;
            queryList();
          }, function (err) {
            deferred.reject(err);
          });
        }

        return deferred.promise;
      },
      getAll: function(filter, endpointUrl) {
        var vm = this;
        return vm.getList(filter, endpointUrl).then(function(response) {
          if (vm.pages > 1) {
            var pages = {0: response};
            var promises = [];
            for (var i = 0; i < vm.pages; i++) {
              (function(i) {
                var page = i + 1;
                var query = angular.extend({}, filter, {page: page});
                var promise = vm.getList(query, endpointUrl).then(function(response) {
                  pages[page] = response;
                });
                promises.push(promise);
              })(i);
            }
            return $q.all(promises).then(function() {
              var result = [];
              for (var i = 0; i < vm.pages; i++) {
                var page = pages[i];
                for (var j = 0; j < page.length; j++) {
                  result.push(page[j]);
                }
              }
              return result;
            });
          }
          return response;
        })
      },
      setCache: function(time, response, cacheKey, endpoint) {
        var allCacheKeys = listCache.get(this.ALL_CACHE_KEYS) ? listCache.get(this.ALL_CACHE_KEYS) : {};
        var keysForCurrentEndpoint = allCacheKeys[endpoint] ? allCacheKeys[endpoint] : [];
        if (keysForCurrentEndpoint.indexOf(cacheKey) == -1) {
          keysForCurrentEndpoint.push(cacheKey);
          allCacheKeys[endpoint] = keysForCurrentEndpoint;
          listCache.put(this.ALL_CACHE_KEYS, allCacheKeys);
        }
        var cacheTime = new Date().getTime() + (time * 1000);
        listCache.put(cacheKey, {data: response, time: cacheTime, count: this.resultCount});
      },
      getCache: function(cacheKey) {
        return listCache.get(cacheKey);
      },
      setPagesCount: function(count) {
        if (count) {
          this.resultCount = count;
          this.pages = Math.ceil(this.resultCount/this.pageSize);
          this.sliceStart = (this.page - 1) * this.pageSize + 1;
          this.sliceEnd = Math.min(this.resultCount, this.page * this.pageSize)
        }
      },
      clearAllCacheForCurrentEndpoint: function() {
        var allKeys = listCache.get(this.ALL_CACHE_KEYS);
        var currentKeys = allKeys[this.endpoint];
        if (currentKeys) {
          for (var i = 0; i < currentKeys.length; i++) {
            listCache.remove(currentKeys[i]);
          }
        }
      },
      $create:function(endpointUrl) {
        var Instance = this.getFactory(false, null, endpointUrl);
        return new Instance();
      },

      $delete:function(uuid) {
        var deferred = $q.defer();
        this.getFactory(false).remove({}, {uuid: uuid}).$promise.then(function(response) {
          deferred.resolve(response);
        }, function(err) {
          deferred.reject(err);
        });
        return deferred.promise;
      },

      /**
       * Use this function if you need to remove some entity by full endPoint url
       *
       * @param url     string   endPoint url
       * @return promise
       */
      $deleteByUrl: function(url) {
        return this.getFactory(false, null, url).delete().$promise;
      },

      operation: function(operation, url) {
        var factory = this.getFactory(false, null, url);
        return factory.operation({'operation': operation}).$promise;
      },

      getFactory: function(isList, endpoint, endpointUrl) {
        endpoint = endpoint || this.getEndpoint(isList);
        endpointUrl = endpointUrl || ENV.apiEndpoint + 'api' + endpoint;
        /*jshint camelcase: false */
        return $resource(endpointUrl + ':UUID/:operation/', {UUID:'@uuid',
            page_size: '@page_size', page: '@page', 'DONTBLOCK': '@DONTBLOCK', operation: '@operation'},
          {
            operation: {
              method: 'POST',
              url: endpointUrl + ':UUID/:operation/',
              params: {UUID:'@uuid', operation:'@operation'}
            },
            update: {
              method: 'PUT'
            },
            options: {
              method: 'OPTIONS'
            }
          }
        );
      },

      $update: function(uuid, url, fields) {
        var modelObject = JSON.parse(JSON.stringify(fields));
        if (url) {
          delete modelObject.uuid;
        } else {
          modelObject.uuid = uuid;
        }
        return this.getFactory(false, null, url).update({}, modelObject).$promise;
      },

      $get: function(uuid, url) {
        return this.getFactory(false, null, url).get({}, {uuid: uuid}).$promise;
      },

      getEndpoint:function(isList) {
        return this.endpoint + this.endpointPostfix;
      },

      // helper, that adds functions to promise
      chainFunctionsToPromise:function(promise, functions) {
        var deferred = $q.defer();
        promise.then(
          function(response) {
            for (var i=0; i < functions.length; i++) {
              var f = functions[i];
              f(response);
              deferred.resolve(response);
            }
          },
          function(error) {
            deferred.reject(error);
          }
        );
        return deferred.promise;
      },
      pageChangingReset: function() {
        var vm = this;
        $rootScope.$on('$stateChangeSuccess', function() {
          vm.defaultFilter = {};
          vm.page = 1;
        });
      },
      getOption: function(endpointUrl) {
        return this.getFactory(false, null, endpointUrl).options().$promise;
      },
      cleanAllCache: function() {
        listCache.removeAll();
      }
    });

    return BaseServiceClass;
  }
})();

(function() {
  angular.module('ncsaas')
    .factory('listCache', ['$cacheFactory', function($cacheFactory) {
      return $cacheFactory('list-cache');
    }]);
})();
<commit_msg>Fix merge of pages (SAAS-975)<commit_after>// jscs:disable
(function(){

  /**
   * Base service class for services with pagination
   *   getList
   *   $get
   *   $delete
   *   $create
   *   operation
   */

  angular.module('ncsaas')
    .service('baseServiceClass', [
      '$q', 'currentStateService', '$resource', 'ENV', '$rootScope', 'listCache', baseServiceClass]);
  function baseServiceClass($q, currentStateService, $resource, ENV, $rootScope, listCache) {
    // pageSize, page, pages - default variables, you can change this in your init method or call this._super() in init
    var BaseServiceClass = Class.extend({
      ALL_CACHE_KEYS: 'ALL_CACHE_KEYS',
      pageSize:null,
      page:null,
      pages:null,
      resultCount:null,
      currentStateService:null,
      endpoint:null,
      filterByCustomer: true,
      customerUuid:null,
      cacheTime: 0,
      cacheReset: false,
      endpointPostfix: '',

      init:function() {
        this.pageSize = ENV.pageSize;
        this.page = 1;
        this.pages = null;
        this.defaultFilter = {};
        this.currentStateService = currentStateService;
        this.pageChangingReset();
        this.cacheTime = 0;
      },

      getList:function(filter, endpointUrl) {
        var vm = this;
        var deferred = $q.defer();
        filter = filter || {};
        for (var key in this.defaultFilter) {
          filter[key] = this.defaultFilter[key];
        }
        var queryList = function() {
          filter.page = filter.page || vm.page;
          /*jshint camelcase: false */
          filter.page_size = vm.pageSize;
          var cacheKey = vm.endpoint + JSON.stringify(filter);
          var cache = vm.getCache(cacheKey);

          if (!vm.cacheReset && vm.cacheTime > 0 && cache && cache.time > new Date().getTime()) {
            vm.setPagesCount(cache.count);
            deferred.resolve(cache.data);
          } else {
            vm.cacheReset = false;
            listCache.put(cacheKey, {data: null, time: 0});
            vm.getFactory(true, null, endpointUrl).query(filter, function(response, responseHeaders) {
              var header = responseHeaders();
              var resultCount = !header['x-result-count'] ? null : header['x-result-count'];
              vm.setPagesCount(resultCount);
              if (vm.cacheTime > 0) {
                vm.setCache(vm.cacheTime, response, cacheKey, vm.endpoint);
              }
              deferred.resolve(response);
            }, function(err) {
              if (err.status === 401) {
                $rootScope.$broadcast('authService:signout');
              }
              deferred.reject(err);
            });
          }

        };

        if (vm.currentStateService == null || !vm.filterByCustomer) {
          queryList();
        } else {
          vm.currentStateService.getCustomer().then(function (response) {
            /*jshint camelcase: false */
            filter.customer = (this.customerUuid) ? this.customerUuid() : response.uuid;
            queryList();
          }, function (err) {
            deferred.reject(err);
          });
        }

        return deferred.promise;
      },
      getAll: function(filter, endpointUrl) {
        var vm = this;
        return vm.getList(filter, endpointUrl).then(function(response) {
          if (vm.pages > 1) {
            var pages = {1: response};
            var promises = [];
            for (var page = 2; page < vm.pages + 1; page++) {
              (function(page) {
                var query = angular.extend({}, filter, {page: page});
                var promise = vm.getList(query, endpointUrl).then(function(response) {
                  pages[page] = response;
                });
                promises.push(promise);
              })(page);
            }
            return $q.all(promises).then(function() {
              var result = [];
              for (var i = 1; i < vm.pages + 1; i++) {
                var page = pages[i];
                for (var j = 0; j < page.length; j++) {
                  result.push(page[j]);
                }
              }
              return result;
            });
          }
          return response;
        })
      },
      setCache: function(time, response, cacheKey, endpoint) {
        var allCacheKeys = listCache.get(this.ALL_CACHE_KEYS) ? listCache.get(this.ALL_CACHE_KEYS) : {};
        var keysForCurrentEndpoint = allCacheKeys[endpoint] ? allCacheKeys[endpoint] : [];
        if (keysForCurrentEndpoint.indexOf(cacheKey) == -1) {
          keysForCurrentEndpoint.push(cacheKey);
          allCacheKeys[endpoint] = keysForCurrentEndpoint;
          listCache.put(this.ALL_CACHE_KEYS, allCacheKeys);
        }
        var cacheTime = new Date().getTime() + (time * 1000);
        listCache.put(cacheKey, {data: response, time: cacheTime, count: this.resultCount});
      },
      getCache: function(cacheKey) {
        return listCache.get(cacheKey);
      },
      setPagesCount: function(count) {
        if (count) {
          this.resultCount = count;
          this.pages = Math.ceil(this.resultCount/this.pageSize);
          this.sliceStart = (this.page - 1) * this.pageSize + 1;
          this.sliceEnd = Math.min(this.resultCount, this.page * this.pageSize)
        }
      },
      clearAllCacheForCurrentEndpoint: function() {
        var allKeys = listCache.get(this.ALL_CACHE_KEYS);
        var currentKeys = allKeys[this.endpoint];
        if (currentKeys) {
          for (var i = 0; i < currentKeys.length; i++) {
            listCache.remove(currentKeys[i]);
          }
        }
      },
      $create:function(endpointUrl) {
        var Instance = this.getFactory(false, null, endpointUrl);
        return new Instance();
      },

      $delete:function(uuid) {
        var deferred = $q.defer();
        this.getFactory(false).remove({}, {uuid: uuid}).$promise.then(function(response) {
          deferred.resolve(response);
        }, function(err) {
          deferred.reject(err);
        });
        return deferred.promise;
      },

      /**
       * Use this function if you need to remove some entity by full endPoint url
       *
       * @param url     string   endPoint url
       * @return promise
       */
      $deleteByUrl: function(url) {
        return this.getFactory(false, null, url).delete().$promise;
      },

      operation: function(operation, url) {
        var factory = this.getFactory(false, null, url);
        return factory.operation({'operation': operation}).$promise;
      },

      getFactory: function(isList, endpoint, endpointUrl) {
        endpoint = endpoint || this.getEndpoint(isList);
        endpointUrl = endpointUrl || ENV.apiEndpoint + 'api' + endpoint;
        /*jshint camelcase: false */
        return $resource(endpointUrl + ':UUID/:operation/', {UUID:'@uuid',
            page_size: '@page_size', page: '@page', 'DONTBLOCK': '@DONTBLOCK', operation: '@operation'},
          {
            operation: {
              method: 'POST',
              url: endpointUrl + ':UUID/:operation/',
              params: {UUID:'@uuid', operation:'@operation'}
            },
            update: {
              method: 'PUT'
            },
            options: {
              method: 'OPTIONS'
            }
          }
        );
      },

      $update: function(uuid, url, fields) {
        var modelObject = JSON.parse(JSON.stringify(fields));
        if (url) {
          delete modelObject.uuid;
        } else {
          modelObject.uuid = uuid;
        }
        return this.getFactory(false, null, url).update({}, modelObject).$promise;
      },

      $get: function(uuid, url) {
        return this.getFactory(false, null, url).get({}, {uuid: uuid}).$promise;
      },

      getEndpoint:function(isList) {
        return this.endpoint + this.endpointPostfix;
      },

      // helper, that adds functions to promise
      chainFunctionsToPromise:function(promise, functions) {
        var deferred = $q.defer();
        promise.then(
          function(response) {
            for (var i=0; i < functions.length; i++) {
              var f = functions[i];
              f(response);
              deferred.resolve(response);
            }
          },
          function(error) {
            deferred.reject(error);
          }
        );
        return deferred.promise;
      },
      pageChangingReset: function() {
        var vm = this;
        $rootScope.$on('$stateChangeSuccess', function() {
          vm.defaultFilter = {};
          vm.page = 1;
        });
      },
      getOption: function(endpointUrl) {
        return this.getFactory(false, null, endpointUrl).options().$promise;
      },
      cleanAllCache: function() {
        listCache.removeAll();
      }
    });

    return BaseServiceClass;
  }
})();

(function() {
  angular.module('ncsaas')
    .factory('listCache', ['$cacheFactory', function($cacheFactory) {
      return $cacheFactory('list-cache');
    }]);
})();
<|endoftext|>