<commit_before>window.onload = function initialize() {

    var starting_categories = { '': 'Select a starting category', breeding_programs: 'breeding_programs', genotyping_protocols : 'genotyping_protocols', locations : 'locations', traits : 'traits', trials :'trials', years : 'years'};
    var start = format_options(starting_categories);

    jQuery('#select1').html(start);

    jQuery('select').mouseenter(function() {this.tooltip});

    if (!isLoggedIn()) {

       create_list_start('Login to start from a list');

       jQuery('#c1_to_list_menu').html('
Login to use lists
');
       jQuery('#c2_to_list_menu').html('
Login to use lists
');
       jQuery('#c3_to_list_menu').html('
Login to use lists
');
       jQuery('#c4_to_list_menu').html('
Login to use lists
');

    } else {

      create_list_start('Start from a list');

      addToListMenu('c1_to_list_menu', 'c1_data', {
        selectText: true,
        typeSourceDiv: 'select1',
      });
      addToListMenu('c2_to_list_menu', 'c2_data', {
        selectText: true,
        typeSourceDiv: 'select2',
      });
      addToListMenu('c3_to_list_menu', 'c3_data', {
        selectText: true,
        Typesourcediv: 'select3',
       });
      addToListMenu('c4_to_list_menu', 'c4_data', {
        selectText: true,
        typeSourceDiv: 'select4',
       });
    }

    jQuery('#select1').change( // reset start from list if select1 changes
	function() {
	    var startlist = jQuery('#c1_data_list_select').val();
	    if (startlist) {
		create_list_start('Start from a list');
	    }
	});

    jQuery('#select1, #select2, #select3, #select4').change(  // retrieve new data once new category is selected
    	function() {
	    var this_section = jQuery(this).attr('name');
	    reset_downstream_sections(this_section);
	    update_select_categories(this_section);
	    var category = jQuery(this).val();

	    if (!category) { // return empty if no category defined
		console.log(" no category defined");
		var data_element = "c"+this_section+"_data";
		jQuery("#"+data_element).html('');
	return;
	    }
	    var categories = get_selected_categories(this_section);
	    var data = ''
	    if (this_section !== "1") data = get_selected_data(this_section);

	    retrieve_and_display_set(categories, data, this_section);
	});

    jQuery('#c1_data, #c2_data, #c3_data, #c4_data').change( // update wizard panels and categories when data selections change
    	function() {
	    var this_section = jQuery(this).attr('name');
	    update_download_options(this_section);

	    var data_id = jQuery(this).attr('id');
	    var data = jQuery('#'+data_id).val() || [];;
	    var count_id = "c"+this_section+"_data_count";

	    reset_downstream_sections(this_section);
	    update_select_categories(this_section);
	    show_list_counts(count_id, jQuery('#'+data_id).text().split("\n").length-1, data.length);
	});

    jQuery('#c1_select_all, #c2_select_all, #c3_select_all, #c4_select_all').click( // select all data in a wizard panel
    	function() {
	    var this_section = jQuery(this).attr('name');
	    var data_id = "c"+this_section+"_data";
	    selectAllOptions(document.getElementById(data_id));

	    var data = jQuery("#"+data_id).val() || [];;
	    var count_id = "c"+this_section+"_data_count";

	    show_list_counts(count_id, jQuery('#'+data_id).text().split("\n").length-1, data.length);
	    update_select_categories(this_section);

	    console.log("showing message modal . . .");
	    jQuery('#message_modal').modal("show");
	});

      jQuery('select').dblclick(function() { // open detail page in new window or tab on double-click
	  var this_section = jQuery(this).attr('name');
	  var categories = get_selected_categories(this_section);
	  var category = categories.pop();
	  switch (category)
	  {
	  case "accessions":
	  case "plots":
	      window.open("../../stock/"+this.value+"/view");
	      break;
	  case "trials":
	      window.open("../../breeders_toolbox/trial/"+this.value);
	      break;
	  case "breeding_programs":
	      window.open("../../breeders/manage_programs");
	      break;
	  case "locations":
	      window.open("../../breeders/locations");
	      break;
	  case "traits":
	      window.open("../../chado/cvterm?action=view&cvterm_id="+this.value);
	      break;
	  default:
	      if (window.console) console.log("no link for this category");
	  }
      });

    jQuery('#download_button_excel').on('click', function () {
        var selected = get_selected_trials();
        if (selected.length !== 0) {
	  window.open('/breeders/trials/phenotype/download/'+selected.join(","));
        }
        else { alert("No trials selected for download."); }

    });

    jQuery('#download_button_csv').on('click', function () {
        var selected = get_selected_trials();
        if (selected.length !== 0) {
	  window.open('/breeders/trials/phenotype/download/'+selected.join(",")+'?format=csv');
        }
        else { alert("No trials selected for download."); }

    });
}

function retrieve_and_display_set(categories, data, this_section) {
    if (window.console) console.log("categories = "+categories);
    if (window.console) console.log("data = "+JSON.stringify(data));
    //if (window.console) console.log("querytypes="+get_querytypes(this_section));
    jQuery.ajax( {
	url: '/ajax/breeder/search',
	timeout: 60000,
	method: 'POST',
	data: {'categories': categories, 'data': data, 'querytypes': get_querytypes(this_section)},
	    beforeSend: function(){
		disable_ui();
            },
            complete : function(){
		enable_ui();
            },
	    success: function(response) {
		if (response.error) {
		    var error_html = '
'+response.error+'
';
		    var selectall_id = "c"+this_section+"_select_all";
		    jQuery('#'+selectall_id).before(error_html);
		}
		else {
                    var list = response.list || [];
		    data_html = format_options_list(list);
		    var data_id = "c"+this_section+"_data";
		    var count_id = "c"+this_section+"_data_count";
		    var listmenu_id = "c"+this_section+"_to_list_menu";
		    var select_id = "select"+this_section;

		    jQuery('#'+data_id).html(data_html);
		    show_list_counts(count_id, list.length);

		    if (isLoggedIn()) {
			addToListMenu(listmenu_id, data_id, {
			    selectText: true,
			    typeSourceDiv: select_id });
		    }
		}
	    }

	});
}

function get_selected_data(this_section) {
    var selected_data = [];

    for (i=1; i <= this_section; i++) {
	var element_id = "c"+i+"_data";
	var data = jQuery("#"+element_id).val();
	selected_data.push(data);
    }

    //if (window.console) console.log("selected data= "+JSON.stringify(selected_data));
    if (selected_data.length > 0) {
    return selected_data;
    }
}

function get_selected_categories(this_section) {

    var selected_categories = [];
    var select1 = jQuery('#select1').val();
    if (select1 === '') { // if starting category is undefined
	var list_id = jQuery('#c1_data_list_select').val();
	if (list_id) { // check to see if paste from list was used, if so get list type
	    var list_id = jQuery('#c1_data_list_select').val();
	    var lo = new CXGN.List();
	    var list_data = lo.getListData(list_id);
	    select1 = list_data.type_name;
	}
    }
    selected_categories.push(select1);
    for (i=2; i <= this_section; i++) {
	var element_id = "select"+i;
	var category = jQuery("#"+element_id).val();
	selected_categories.push(category);
    }
    var next_section = this_section +1;
    var next_select_id = "select"+next_section;
    jQuery("#"+next_select_id).val('please select');
    //if (window.console) console.log("selected categories= "+JSON.stringify(selected_categories));
    return selected_categories;
}

function get_selected_trials () {
    var max_section = 4;
    var selected_trials;
    var categories = get_selected_categories(max_section);
    var data = get_selected_data(max_section);
    for (i=0; i < categories.length; i++) {
	if (categories[i] === 'trials' && data[i]) {
	    selected_trials = data[i];
	} else {
	}
    }
    if (selected_trials.length > 0) {
	return selected_trials;
    } else {
	alert("No trials selected");
    }
}

function update_select_categories(this_section) {
    var selected_categories = get_selected_categories(this_section);

    var categories = { '': 'please select', accessions : 'accessions', breeding_programs: 'breeding_programs', genotyping_protocols : 'genotyping_protocols', locations : 'locations', plots : 'plots', traits : 'traits', trials :'trials', years : 'years'};
    var all_categories = copy_hash(categories);

    for (i=0; i < this_section; i++) {
	delete all_categories[selected_categories[i]];
    }
    var remaining_categories = format_options(all_categories);
    var next_section = ++this_section;
    var next_select_id = "select"+next_section;

    jQuery('#'+next_select_id).html(remaining_categories);
}

function update_download_options(this_section) {
    var categories = get_selected_categories(this_section);
    var data = get_selected_data(this_section);
    var trials_selected = 0;
    for (i=0; i < categories.length; i++) {
	//if (categories[i]) {console.log("category ="+categories[i]);}
	//if (data !== undefined) {console.log("data ="+data[i]);}
	if (categories[i] === 'trials' && data[i]) {
	    trials_selected = 1;
	    jQuery('#download_button_excel').removeAttr('disabled');
	    jQuery('#download_button_csv').removeAttr('disabled');
	}
    }
    if (trials_selected !== 1) {
	jQuery('#download_button_excel').attr('disabled', 'disabled');
	jQuery('#download_button_csv').attr('disabled', 'disabled');
    }
}

function reset_downstream_sections(this_section) {  // clear downstream selects, data_panels, data_counts
    jQuery('#response_error').remove();
    for (i = 4; i > this_section; i--) {
	var select_id = "select"+i;
	var data_id = "c"+i+"_data";
	var count_id = "c"+i+"_data_count";
	var querytype_id = "c"+i+"_querytype";
	jQuery('#'+select_id).html('');
	jQuery('#'+data_id).html('');
	jQuery('#'+count_id).html('');
	jQuery('#'+querytype_id).bootstrapToggle('off');
    }
}

function create_list_start(message) {
    var lo = new CXGN.List();
    var listhtml = lo.listSelect('c1_data', '', message);
    jQuery('#paste_list').html(listhtml);
    jQuery('#paste_list').change(
    function() { // if 'select a list', reinitialize, otherwise

		   pasteList('c1_data');
    });
}

function format_options(items) {
    var html = '';
    for (var key in items) {
	html = html + '<option value="'+key+'" title="'+items[key]+'">'+items[key]+'\n';
    }
    return html;
}

function retrieve_sublist(list, sublist_index) {
    var new_list = new Array();
    for(var i=0; i<list.length; i++) {
	new_list.push(list[i][sublist_index]);
    }
    return new_list;
}

function format_options_list(items) {
    var html = '';
    if (items) {
	for(var i=0; i<items.length; i++) {
	    html = html + '<option value="'+items[i][0]+'" title="'+items[i][1]+'">'+items[i][1]+'\n';
	}
	return html;
    }
    return "no data";
}

function copy_hash(hash) {
    var new_hash = new Array();

    for (var key in hash) {
	new_hash[key] = hash[key];
    }
     return new_hash;
}

function disable_ui() {
    jQuery('#working_modal').modal("show");
}

function enable_ui() {
     jQuery('#working_modal').modal("hide");
}

function show_list_counts(count_div, total_count, selected) {
    var html = 'Items: '+total_count+'
';
    if (selected) {
	html += 'Selected: '+selected;
    }
    jQuery('#'+count_div).html(html);
}

function selectAllOptions(obj) {
    if (!obj || obj.options.length ==0) { return; }
    for (var i=0; i<obj.options.length; i++) {
      obj.options[i].selected = true;
    }
}

function get_querytypes(this_section) {
    var querytypes = [];

    for (i=2; i <= this_section; i++) {
	var element_id = "c"+i+"_querytype";
	if (jQuery('#'+element_id).is(":checked")) {
	    var type = 1;
	} else {
	    var type = 0;
	}
	if (window.console) console.log("type="+type);
	querytypes.push(type);
    }
    if (querytypes.length > 0) {
    return querytypes;
    }
}<commit_msg> add function to check categories, and fix trial dwnld title<commit_after>window.onload = function initialize() {

    var starting_categories = { '': 'Select a starting category', breeding_programs: 'breeding_programs', genotyping_protocols : 'genotyping_protocols', locations : 'locations', traits : 'traits', trials :'trials', years : 'years'};
    var start = format_options(starting_categories);

    jQuery('#select1').html(start);

    jQuery('select').mouseenter(function() {this.tooltip});

    if (!isLoggedIn()) {

       create_list_start('Login to start from a list');

       jQuery('#c1_to_list_menu').html('
Login to use lists
');
       jQuery('#c2_to_list_menu').html('
Login to use lists
');
       jQuery('#c3_to_list_menu').html('
Login to use lists
');
       jQuery('#c4_to_list_menu').html('
Login to use lists
');

    } else {

      create_list_start('Start from a list');

      addToListMenu('c1_to_list_menu', 'c1_data', {
        selectText: true,
        typeSourceDiv: 'select1',
      });
      addToListMenu('c2_to_list_menu', 'c2_data', {
        selectText: true,
        typeSourceDiv: 'select2',
      });
      addToListMenu('c3_to_list_menu', 'c3_data', {
        selectText: true,
        Typesourcediv: 'select3',
       });
      addToListMenu('c4_to_list_menu', 'c4_data', {
        selectText: true,
        typeSourceDiv: 'select4',
       });
    }

    jQuery('#select1').change( // reset start from list if select1 changes
	function() {
	    var startlist = jQuery('#c1_data_list_select').val();
	    if (startlist) {
		create_list_start('Start from a list');
	    }
	});

    jQuery('#select1, #select2, #select3, #select4').change(  // retrieve new data once new category is selected
    	function() {
	    var this_section = jQuery(this).attr('name');
	    reset_downstream_sections(this_section);
	    update_select_categories(this_section);
	    var category = jQuery(this).val();

	    if (!category) { // reset by returning empty if no category was defined
		var data_element = "c"+this_section+"_data";
		jQuery("#"+data_element).html('');
		return;
	    }
	    var categories = get_selected_categories(this_section);
	    var data = ''
	    if (this_section !== "1") data = get_selected_data(this_section);
	    var error = check_missing_criteria(categories, data, this_section); // make sure criteria selected in each panel
	    if (error) return;
	    if (data.length >= categories.length) data.pop(); //remove extra data array if exists

	    retrieve_and_display_set(categories, data, this_section);
	});

    jQuery('#c1_data, #c2_data, #c3_data, #c4_data').change( // update wizard panels and categories when data selections change
    	function() {
	    var this_section = jQuery(this).attr('name');
	    update_download_options(this_section);

	    var data_id = jQuery(this).attr('id');
	    var data = jQuery('#'+data_id).val() || [];;
	    var count_id = "c"+this_section+"_data_count";

	    reset_downstream_sections(this_section);
	    update_select_categories(this_section);
	    show_list_counts(count_id, jQuery('#'+data_id).text().split("\n").length-1, data.length);
	});

    jQuery('#c1_select_all, #c2_select_all, #c3_select_all, #c4_select_all').click( // select all data in a wizard panel
    	function() {
	    var this_section = jQuery(this).attr('name');
	    var data_id = "c"+this_section+"_data";
	    selectAllOptions(document.getElementById(data_id));

	    var data = jQuery("#"+data_id).val() || [];;
	    var count_id = "c"+this_section+"_data_count";

	    show_list_counts(count_id, jQuery('#'+data_id).text().split("\n").length-1, data.length);
	    update_select_categories(this_section);

	    console.log("showing message modal . . .");
	    jQuery('#message_modal').modal("show");
	});

      jQuery('select').dblclick(function() { // open detail page in new window or tab on double-click
	  var this_section = jQuery(this).attr('name');
	  var categories = get_selected_categories(this_section);
	  var category = categories.pop();
	  switch (category)
	  {
	  case "accessions":
	  case "plots":
	      window.open("../../stock/"+this.value+"/view");
	      break;
	  case "trials":
	      window.open("../../breeders_toolbox/trial/"+this.value);
	      break;
	  case "breeding_programs":
	      window.open("../../breeders/manage_programs");
	      break;
	  case "locations":
	      window.open("../../breeders/locations");
	      break;
	  case "traits":
	      window.open("../../chado/cvterm?action=view&cvterm_id="+this.value);
	      break;
	  default:
	      if (window.console) console.log("no link for this category");
	  }
      });

    jQuery('#download_button_excel').on('click', function () {
        var selected = get_selected_trials();
        if (selected.length !== 0) {
	  window.open('/breeders/trials/phenotype/download/'+selected.join(","));
        }
        else { alert("No trials selected for download."); }

    });

    jQuery('#download_button_csv').on('click', function () {
        var selected = get_selected_trials();
        if (selected.length !== 0) {
	  window.open('/breeders/trials/phenotype/download/'+selected.join(",")+'?format=csv');
        }
        else { alert("No trials selected for download."); }

    });
}

function retrieve_and_display_set(categories, data, this_section) {
    if (window.console) console.log("categories = "+categories);
    if (window.console) console.log("data = "+JSON.stringify(data));
    //if (window.console) console.log("querytypes="+get_querytypes(this_section));
    jQuery.ajax( {
	url: '/ajax/breeder/search',
	timeout: 60000,
	method: 'POST',
	data: {'categories': categories, 'data': data, 'querytypes': get_querytypes(this_section)},
	    beforeSend: function(){
		disable_ui();
            },
            complete : function(){
		enable_ui();
            },
	    success: function(response) {
		if (response.error) {
		    var error_html = '
'+response.error+'
';
		    var selectall_id = "c"+this_section+"_select_all";
		    jQuery('#'+selectall_id).before(error_html);
		}
		else {
                    var list = response.list || [];
		    data_html = format_options_list(list);
		    var data_id = "c"+this_section+"_data";
		    var count_id = "c"+this_section+"_data_count";
		    var listmenu_id = "c"+this_section+"_to_list_menu";
		    var select_id = "select"+this_section;

		    jQuery('#'+data_id).html(data_html);
		    show_list_counts(count_id, list.length);

		    if (isLoggedIn()) {
			addToListMenu(listmenu_id, data_id, {
			    selectText: true,
			    typeSourceDiv: select_id });
		    }
		}
	    }

	});
}

function get_selected_data(this_section) {
    var selected_data = [];

    for (i=1; i <= this_section; i++) {
	var element_id = "c"+i+"_data";
	var data = jQuery("#"+element_id).val();
	if (data) selected_data.push(data);
    }
    //if (window.console) console.log("selected data= "+JSON.stringify(selected_data));
    return selected_data;
}

function get_selected_categories(this_section) {

    var selected_categories = [];
    var select1 = jQuery('#select1').val();
    if (select1 === '') { // if starting category is undefined
	var list_id = jQuery('#c1_data_list_select').val();
	if (list_id) { // check to see if paste from list was used, if so get list type
	    var list_id = jQuery('#c1_data_list_select').val();
	    var lo = new CXGN.List();
	    var list_data = lo.getListData(list_id);
	    select1 = list_data.type_name;
	}
    }
    selected_categories.push(select1);
    for (i=2; i <= this_section; i++) {
	var element_id = "select"+i;
	var category = jQuery("#"+element_id).val();
	selected_categories.push(category);
    }
    var next_section = this_section +1;
    var next_select_id = "select"+next_section;
    jQuery("#"+next_select_id).val('please select');
    //if (window.console) console.log("selected categories= "+JSON.stringify(selected_categories));
    return selected_categories;
}

function get_selected_trials () {
    var max_section = 4;
    var selected_trials;
    var categories = get_selected_categories(max_section);
    var data = get_selected_data(max_section);
    for (i=0; i < categories.length; i++) {
	if (categories[i] === 'trials' && data[i]) {
	    selected_trials = data[i];
	} else {
	}
    }
    if (selected_trials.length > 0) {
	return selected_trials;
    } else {
	alert("No trials selected");
    }
}

function update_select_categories(this_section) {
    var selected_categories = get_selected_categories(this_section);

    var categories = { '': 'please select', accessions : 'accessions', breeding_programs: 'breeding_programs', genotyping_protocols : 'genotyping_protocols', locations : 'locations', plots : 'plots', traits : 'traits', trials :'trials', years : 'years'};
    var all_categories = copy_hash(categories);

    for (i=0; i < this_section; i++) {
	delete all_categories[selected_categories[i]];
    }
    var remaining_categories = format_options(all_categories);
    var next_section = ++this_section;
    var next_select_id = "select"+next_section;

    jQuery('#'+next_select_id).html(remaining_categories);
}

function update_download_options(this_section) {
    var categories = get_selected_categories(this_section);
    var data = get_selected_data(this_section);
    var trials_selected = 0;
    for (i=0; i < categories.length; i++) {
	//if (categories[i]) {console.log("category ="+categories[i]);}
	//if (data !== undefined) {console.log("data ="+data[i]);}
	if (categories[i] === 'trials' && data[i]) {
	    trials_selected = 1;
	    jQuery('#download_button_excel').prop( 'title', 'Click to Download Trial Phenotypes');
	    jQuery('#download_button_csv').prop('title', 'Click to Download Trial Phenotypes');
	    jQuery('#download_button_excel').removeAttr('disabled');
	    jQuery('#download_button_csv').removeAttr('disabled');
	}
    }
    if (trials_selected !== 1) {
	jQuery('#download_button_excel').prop('title','First Select a Trial to Download');
	jQuery('#download_button_csv').prop('title', 'First Select a Trial to Download');
	jQuery('#download_button_excel').attr('disabled', 'disabled');
	jQuery('#download_button_csv').attr('disabled', 'disabled');
    }
}

function reset_downstream_sections(this_section) {  // clear downstream selects, data_panels, data_counts
    jQuery('#response_error').remove();
    for (i = 4; i > this_section; i--) {
	var select_id = "select"+i;
	var data_id = "c"+i+"_data";
	var count_id = "c"+i+"_data_count";
	var querytype_id = "c"+i+"_querytype";
	jQuery('#'+select_id).html('');
	jQuery('#'+data_id).html('');
	jQuery('#'+count_id).html('');
	jQuery('#'+querytype_id).bootstrapToggle('off');
    }
}

function create_list_start(message) {
    var lo = new CXGN.List();
    var listhtml = lo.listSelect('c1_data', '', message);
    jQuery('#paste_list').html(listhtml);
    jQuery('#paste_list').change(
    function() { // if 'select a list', reinitialize, otherwise

		   pasteList('c1_data');
    });
}

function format_options(items) {
    var html = '';
    for (var key in items) {
	html = html + '<option value="'+key+'" title="'+items[key]+'">'+items[key]+'\n';
    }
    return html;
}

function retrieve_sublist(list, sublist_index) {
    var new_list = new Array();
    for(var i=0; i<list.length; i++) {
	new_list.push(list[i][sublist_index]);
    }
    return new_list;
}

function format_options_list(items) {
    var html = '';
    if (items) {
	for(var i=0; i<items.length; i++) {
	    html = html + '<option value="'+items[i][0]+'" title="'+items[i][1]+'">'+items[i][1]+'\n';
	}
	return html;
    }
    return "no data";
}

function copy_hash(hash) {
    var new_hash = new Array();

    for (var key in hash) {
	new_hash[key] = hash[key];
    }
     return new_hash;
}

function disable_ui() {
    jQuery('#working_modal').modal("show");
}

function enable_ui() {
     jQuery('#working_modal').modal("hide");
}

function show_list_counts(count_div, total_count, selected) {
    var html = 'Items: '+total_count+'
';
    if (selected) {
	html += 'Selected: '+selected;
    }
    jQuery('#'+count_div).html(html);
}

function selectAllOptions(obj) {
    if (!obj || obj.options.length ==0) { return; }
    for (var i=0; i<obj.options.length; i++) {
      obj.options[i].selected = true;
    }
}

function check_missing_criteria(categories, data, this_section) {
    var test = data.length + 1;
    if (categories.length > test) {
	var error_html = '
Error: Select at least one option from each preceding panel
';
	var selectall_id = "c"+this_section+"_select_all";
	jQuery('#'+selectall_id).before(error_html);
	return 1;
    } else {
	return 0;
    }
}

function get_querytypes(this_section) {
    var querytypes = [];

    for (i=2; i <= this_section; i++) {
	var element_id = "c"+i+"_querytype";
	if (jQuery('#'+element_id).is(":checked")) {
	    var type = 1;
	} else {
	    var type = 0;
	}
	if (window.console) console.log("type="+type);
	querytypes.push(type);
    }
    if (querytypes.length > 0) {
    return querytypes;
    }
}<|endoftext|>


<commit_before>/*<ON_DEPLOY_REMOVE>*/
/* global WSE */
/*
    Copyright (c) 2012 - 2014 The WebStory Engine Contributors
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

    * Neither the name WebStory Engine nor the names of its contributors
      may be used to endorse or promote products derived from this software
      without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*</ON_DEPLOY_REMOVE>*/
(function (out)
{
    "use strict";

    out.commands.while = function (command, interpreter)
    {
        interpreter.index -= 1;
        interpreter.currentElement -= 1;
        interpreter.pushToCallStack();
        interpreter.currentCommands = command.childNodes;
        interpreter.scenePath.push(interpreter.index+1);
        interpreter.index = -1;
        interpreter.currentElement = -1;

        return {
            doNext: true
        };
    };
}(WSE));
<commit_msg>oh, damn those reserved words<commit_after>/*<ON_DEPLOY_REMOVE>*/
/* global WSE */
/*
    Copyright (c) 2012 - 2014 The WebStory Engine Contributors
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

    * Neither the name WebStory Engine nor the names of its contributors
      may be used to endorse or promote products derived from this software
      without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*</ON_DEPLOY_REMOVE>*/
(function (out)
{
    "use strict";

    out.commands["while"] = function (command, interpreter)
    {
        interpreter.index -= 1;
        interpreter.currentElement -= 1;
        interpreter.pushToCallStack();
        interpreter.currentCommands = command.childNodes;
        interpreter.scenePath.push(interpreter.index+1);
        interpreter.index = -1;
        interpreter.currentElement = -1;

        return {
            doNext: true
        };
    };
}(WSE));
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

const React = require('react')
const Button = require('../components/button')

require('../../less/button.less')
require('../../less/window.less')
// TODO: rename certerror.less to interstitial.less or something
require('../../less/about/certerror.less')

class SafebrowsingPage extends React.Component {
  constructor () {
    super()
    this.state = {
      advanced: false
    }
  }

  onAdvancedToggle () {
    this.setState({advanced: !this.state.advanced})
  }

  render () {
    return

      <svg width='75' height='75' className='errorLogo' viewBox='0 0 100 100' xmlns='http://www.w3.org/2000/svg'>
        <path className='errorLogoInner' d='M11.4743662,97.2253545 C1.98936285,97.2253571 -1.69987039,86.6466353 1.98936288,81.2764443 C2.36018089,80.2888073 37.5445854,9.4248374 37.6406733,9.21698534 C41.524789,0.483122973 56.8650161,0.0416071437 60.7924391,9.21698534 C60.7572519,9.19524917 98.2991929,81.8687547 97.9337883,81.2642177 C101.323931,86.2404407 96.9260512,97.2253571 88.8978453,97.2253545 C88.8978453,97.2253545 11.4756386,97.2879401 11.4743662,97.2253545 Z M50.5378687,73.3388569 C47.2443918,73.3388569 44.2703808,76.046195 44.2703808,79.5061732 C44.2703808,82.9729198 47.1388056,85.6802579 50.5378687,85.6802579 C53.9369317,85.6802579 56.8040029,82.9729198 56.8040029,79.5061732 C56.8053565,76.046195 53.8313455,73.3388569 50.5378687,73.3388569 Z M50.3063913,28.5 C46.5729719,28.5 42.719076,30.2990258 43.0805057,32.9143334 L45.8826007,65.934287 L54.7315355,65.934287 L57.5322768,32.9143334 C57.8937065,30.2990258 54.0398106,28.5 50.3063913,28.5 Z'/>
      </svg>

        {this.state.advanced
          ?

            <Button l10nId='safebrowsingErrorHideAdvanced' className='subtleButton' onClick={this.onAdvancedToggle.bind(this)}/>

          : <Button l10nId='safebrowsingErrorAdvanced' className='subtleButton' onClick={this.onAdvancedToggle.bind(this)}/>}

  }
}

module.exports = <SafebrowsingPage/>
<commit_msg>Fix safebrowsing page height<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

const React = require('react')
const Button = require('../components/button')

require('../../less/button.less')
require('../../less/window.less')
// TODO: rename certerror.less to interstitial.less or something
require('../../less/about/certerror.less')

class SafebrowsingPage extends React.Component {
  constructor () {
    super()
    this.state = {
      advanced: false
    }
  }

  onAdvancedToggle () {
    this.setState({advanced: !this.state.advanced})
  }

  render () {
    return

      <svg width='75' height='75' className='errorLogo' viewBox='0 0 100 100' xmlns='http://www.w3.org/2000/svg'>
        <path className='errorLogoInner' d='M11.4743662,97.2253545 C1.98936285,97.2253571 -1.69987039,86.6466353 1.98936288,81.2764443 C2.36018089,80.2888073 37.5445854,9.4248374 37.6406733,9.21698534 C41.524789,0.483122973 56.8650161,0.0416071437 60.7924391,9.21698534 C60.7572519,9.19524917 98.2991929,81.8687547 97.9337883,81.2642177 C101.323931,86.2404407 96.9260512,97.2253571 88.8978453,97.2253545 C88.8978453,97.2253545 11.4756386,97.2879401 11.4743662,97.2253545 Z M50.5378687,73.3388569 C47.2443918,73.3388569 44.2703808,76.046195 44.2703808,79.5061732 C44.2703808,82.9729198 47.1388056,85.6802579 50.5378687,85.6802579 C53.9369317,85.6802579 56.8040029,82.9729198 56.8040029,79.5061732 C56.8053565,76.046195 53.8313455,73.3388569 50.5378687,73.3388569 Z M50.3063913,28.5 C46.5729719,28.5 42.719076,30.2990258 43.0805057,32.9143334 L45.8826007,65.934287 L54.7315355,65.934287 L57.5322768,32.9143334 C57.8937065,30.2990258 54.0398106,28.5 50.3063913,28.5 Z'/>
      </svg>

        {this.state.advanced
          ?

            <Button l10nId='safebrowsingErrorHideAdvanced' className='subtleButton' onClick={this.onAdvancedToggle.bind(this)}/>

          : <Button l10nId='safebrowsingErrorAdvanced' className='subtleButton' onClick={this.onAdvancedToggle.bind(this)}/>}

  }
}

module.exports = <SafebrowsingPage/>
<|endoftext|>


<commit_before>/* =============================================================
 * bootstrap-collapse.js v2.2.3
 * http://twitter.github.com/bootstrap/javascript.html#collapse
 * =============================================================
 * Copyright 2012 Twitter, Inc.
 *
 * 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.
 * ============================================================ */

!function ($) {

  "use strict"; // jshint ;_;

 /* COLLAPSE PUBLIC CLASS DEFINITION
  * ================================ */

  var Collapse = function (element, options) {
    this.$element = $(element)
    this.options = $.extend({}, $.fn.collapse.defaults, options)

    if (this.options.parent) {
      this.$parent = $(this.options.parent)
    }

    this.options.toggle && this.toggle()
  }

  Collapse.prototype = {

    constructor: Collapse

  , dimension: function () {
      var hasWidth = this.$element.hasClass('width')
      return hasWidth ? 'width' : 'height'
    }

  , show: function () {
      var dimension
        , scroll
        , actives
        , hasData

      if (this.transitioning) return

      dimension = this.dimension()
      scroll = $.camelCase(['scroll', dimension].join('-'))
      actives = this.$parent && this.$parent.find('> .accordion-group > .in')

      if (actives && actives.length) {
        hasData = actives.data('collapse')
        if (hasData && hasData.transitioning) return
        actives.collapse('hide')
        hasData || actives.data('collapse', null)
      }

      this.$element[dimension](0)
      this.transition('addClass', $.Event('show'), 'shown')
      $.support.transition && this.$element[dimension](this.$element[0][scroll])
    }

  , hide: function () {
      var dimension
      if (this.transitioning) return
      dimension = this.dimension()
      this.reset(this.$element[dimension]())
      this.transition('removeClass', $.Event('hide'), 'hidden')
      this.$element[dimension](0)
    }

  , reset: function (size) {
      var dimension = this.dimension()

      this.$element
        .removeClass('collapse')
        [dimension](size || 'auto')
        [0].offsetWidth

      this.$element[size !== null ? 'addClass' : 'removeClass']('collapse')

      return this
    }

  , transition: function (method, startEvent, completeEvent) {
      var that = this
        , complete = function () {
            if (startEvent.type == 'show') that.reset()
            that.transitioning = 0
            that.$element.trigger(completeEvent)
          }

      this.$element.trigger(startEvent)

      if (startEvent.isDefaultPrevented()) return

      this.transitioning = 1

      this.$element[method]('in')

      $.support.transition && this.$element.hasClass('collapse') ?
        this.$element.one($.support.transition.end, complete) :
        complete()
    }

  , toggle: function () {
      this[this.$element.hasClass('in') ? 'hide' : 'show']()
    }

  }

 /* COLLAPSE PLUGIN DEFINITION
  * ========================== */

  var old = $.fn.collapse

  $.fn.collapse = function (option) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('collapse')
        , options = typeof option == 'object' && option
      if (!data) $this.data('collapse', (data = new Collapse(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.collapse.defaults = {
    toggle: true
  }

  $.fn.collapse.Constructor = Collapse

 /* COLLAPSE NO CONFLICT
  * ==================== */

  $.fn.collapse.noConflict = function () {
    $.fn.collapse = old
    return this
  }

 /* COLLAPSE DATA-API
  * ================= */

  $(document).on('click.collapse.data-api', '[data-toggle=collapse]', function (e) {
    var $this = $(this), href
      , target = $this.attr('data-target')
        || e.preventDefault()
        || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7
      , option = $(target).data('collapse') ? 'toggle' : $this.data()
    $this[$(target).hasClass('in') ? 'addClass' : 'removeClass']('collapsed')
    $(target).collapse(option)
  })

}(window.jQuery);<commit_msg>if carousel element already open, don't reopen it duh bruh bruh<commit_after>/* =============================================================
 * bootstrap-collapse.js v2.2.3
 * http://twitter.github.com/bootstrap/javascript.html#collapse
 * =============================================================
 * Copyright 2012 Twitter, Inc.
 *
 * 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.
 * ============================================================ */

!function ($) {

  "use strict"; // jshint ;_;

 /* COLLAPSE PUBLIC CLASS DEFINITION
  * ================================ */

  var Collapse = function (element, options) {
    this.$element = $(element)
    this.options = $.extend({}, $.fn.collapse.defaults, options)

    if (this.options.parent) {
      this.$parent = $(this.options.parent)
    }

    this.options.toggle && this.toggle()
  }

  Collapse.prototype = {

    constructor: Collapse

  , dimension: function () {
      var hasWidth = this.$element.hasClass('width')
      return hasWidth ? 'width' : 'height'
    }

  , show: function () {
      var dimension
        , scroll
        , actives
        , hasData

      if (this.transitioning || this.$element.hasClass('in')) return

      dimension = this.dimension()
      scroll = $.camelCase(['scroll', dimension].join('-'))
      actives = this.$parent && this.$parent.find('> .accordion-group > .in')

      if (actives && actives.length) {
        hasData = actives.data('collapse')
        if (hasData && hasData.transitioning) return
        actives.collapse('hide')
        hasData || actives.data('collapse', null)
      }

      this.$element[dimension](0)
      this.transition('addClass', $.Event('show'), 'shown')
      $.support.transition && this.$element[dimension](this.$element[0][scroll])
    }

  , hide: function () {
      var dimension
      if (this.transitioning) return
      dimension = this.dimension()
      this.reset(this.$element[dimension]())
      this.transition('removeClass', $.Event('hide'), 'hidden')
      this.$element[dimension](0)
    }

  , reset: function (size) {
      var dimension = this.dimension()

      this.$element
        .removeClass('collapse')
        [dimension](size || 'auto')
        [0].offsetWidth

      this.$element[size !== null ? 'addClass' : 'removeClass']('collapse')

      return this
    }

  , transition: function (method, startEvent, completeEvent) {
      var that = this
        , complete = function () {
            if (startEvent.type == 'show') that.reset()
            that.transitioning = 0
            that.$element.trigger(completeEvent)
          }

      this.$element.trigger(startEvent)

      if (startEvent.isDefaultPrevented()) return

      this.transitioning = 1

      this.$element[method]('in')

      $.support.transition && this.$element.hasClass('collapse') ?
        this.$element.one($.support.transition.end, complete) :
        complete()
    }

  , toggle: function () {
      this[this.$element.hasClass('in') ? 'hide' : 'show']()
    }

  }

 /* COLLAPSE PLUGIN DEFINITION
  * ========================== */

  var old = $.fn.collapse

  $.fn.collapse = function (option) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('collapse')
        , options = typeof option == 'object' && option
      if (!data) $this.data('collapse', (data = new Collapse(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.collapse.defaults = {
    toggle: true
  }

  $.fn.collapse.Constructor = Collapse

 /* COLLAPSE NO CONFLICT
  * ==================== */

  $.fn.collapse.noConflict = function () {
    $.fn.collapse = old
    return this
  }

 /* COLLAPSE DATA-API
  * ================= */

  $(document).on('click.collapse.data-api', '[data-toggle=collapse]', function (e) {
    var $this = $(this), href
      , target = $this.attr('data-target')
        || e.preventDefault()
        || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7
      , option = $(target).data('collapse') ? 'toggle' : $this.data()
    $this[$(target).hasClass('in') ? 'addClass' : 'removeClass']('collapsed')
    $(target).collapse(option)
  })

}(window.jQuery);<|endoftext|>


<commit_before>app.controller('HomeCtrl', function ($scope, $http) {
$scope.stats = {};
$scope.stats.completedSurveysPercent = "...";
$scope.stats.startedSurveys = "...";

$scope.options = {
            chart: {
                type: 'pieChart',
                height: 350,
                donut: false,
                color: ['#ffa500', '#939393'],
                x: function(d){return d.key;},
                y: function(d){return d.y;},
                showLabels: true,
                showLegend: false,
                pie: {
                    startAngle: function(d) { return d.startAngle -Math.PI },
                    endAngle: function(d) { return d.endAngle -Math.PI }
                }
            }
        };

// Simple GET request example:
$http({
  method: 'GET',
  url: '/completedSurveysCount'
}).then(function successCallback(response) {
    console.log(response.data)
       $scope.data = [
            {
                key: "Completed",
                y: response.data.completed
            },
            {
                key: "Incomplete",
                y: response.data.incomplete
            }
        ];

    $scope.stats.startedSurveys = response.data.totalSurveysStarted;
    $scope.stats.completedSurveysPercent = Math.round(response.data.totalSurveysStarted / response.data.completed) * 100;

}, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
});

});<commit_msg>dfasd<commit_after>app.controller('HomeCtrl', function ($scope, $http) {
$scope.stats = {};
$scope.stats.completedSurveysPercent = "...";
$scope.stats.startedSurveys = "...";

$scope.options = {
            chart: {
                type: 'pieChart',
                height: 350,
                donut: false,
                color: ['#ffa500', '#939393'],
                x: function(d){return d.key;},
                y: function(d){return d.y;},
                showLabels: true,
                showLegend: false,
                pie: {
                    startAngle: function(d) { return d.startAngle -Math.PI },
                    endAngle: function(d) { return d.endAngle -Math.PI }
                }
            }
        };

$http({
  method: 'GET',
  url: '/completedSurveysCount'
}).then(function successCallback(response) {
    console.log(response.data)
       $scope.data = [
            {
                key: "Completed",
                y: response.data.completed
            },
            {
                key: "Incomplete",
                y: response.data.incomplete
            }
        ];

    $scope.stats.startedSurveys = response.data.totalSurveysStarted;
    $scope.stats.completedSurveysPercent = Math.round(response.data.completed / response.data.totalSurveysStarted) * 100;

}, function errorCallback(response) {
    console.log(response);
});

});<|endoftext|>


<commit_before>// Copyright 2014-2018, University of Colorado Boulder

/**
 * Constants that are global to this sim.
 *
 * @author Andrea Lin
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( require => {
  'use strict';

  // modules
  const Bounds2 = require( 'DOT/Bounds2' );
  const GQColors = require( 'GRAPHING_QUADRATICS/common/GQColors' );
  const graphingQuadratics = require( 'GRAPHING_QUADRATICS/graphingQuadratics' );
  const Range = require( 'DOT/Range' );

  // constants
  const PANEL_CORNER_RADIUS = 5; // corner radius for all panel-like containers

  const GQConstants = {

    SCREEN_VIEW_LAYOUT_BOUNDS: new Bounds2( 0, 0, 1100, 700 ),
    SCREEN_VIEW_X_MARGIN: 20,
    SCREEN_VIEW_Y_MARGIN: 16,

    // range of the graph
    X_AXIS_RANGE: new Range( -10, 10 ),
    Y_AXIS_RANGE: new Range( -10, 10 ),

    // options applied to all AccordionBoxes
    ACCORDION_BOX_OPTIONS: {
      resize: false,
      fill: GQColors.CONTROL_PANEL_BACKGROUND,
      cornerRadius: PANEL_CORNER_RADIUS,
      titleYMargin: 10,
      buttonLength: 25,
      buttonXMargin: 10,
      buttonYMargin: 10,
      contentXMargin: 20,
      contentYMargin: 15
    },

    // options applied to all Panels
    PANEL_OPTIONS: {
      fill: GQColors.CONTROL_PANEL_BACKGROUND,
      cornerRadius: PANEL_CORNER_RADIUS,
      xMargin: 20,
      yMargin: 15
    },

    // horizontal space between checkbox text and icon
    CHECKBOX_ICON_SPACING: 8,

    // maxWidth for all checkboxes, determined empirically
    CHECKBOX_TEXT_MAX_WIDTH: 180,

    // vertical space between checkboxes
    CHECKBOXES_Y_SPACING: 15,

    PICKER_TOUCH_AREA_X_DILATION: 30,

    // radius of manipulators, in model coordinates
    MANIPULATOR_RADIUS: 0.425,

    // radius of non-interactive points, in model coordinates
    POINT_RADIUS: 0.25,

    // font sizes
    TITLE_FONT_SIZE: 20,
    INTERACTIVE_EQUATION_FONT_SIZE: 26,
    SLIDER_TICK_LABEL_FONT_SIZE: 16,
    CHECKBOX_LABEL_FONT_SIZE: 20,
    CHECKBOX_EQUATION_FONT_SIZE: 22,
    GRAPH_EQUATION_FONT_SIZE: 18,

    // line widths
    INTERACTIVE_QUADRATIC_LINE_WIDTH: 4,
    SAVED_QUADRATIC_LINE_WIDTH: 3,
    QUADRATIC_TERMS_LINE_WIDTH: 2, // y = ax^2, y = bx, y = c
    AXIS_OF_SYMMETRY_LINE_WIDTH: 3,
    DIRECTRIX_LINE_WIDTH: 3,
    POINT_ON_PARABOLA_LINE_WIDTH: 3, // lines that connect point to focus and directrix

    // line dashes
    AXIS_OF_SYMMETRY_LINE_DASH: [ 5, 5 ],
    DIRECTRIX_LINE_DASH: [ 5, 5 ],
    POINT_ON_PARABOLA_LINE_DASH: [ 5, 5 ], // lines that connect point to focus and directrix

    // decimal places
    AXIS_OF_SYMMETRY_DECIMALS: 2,
    DIRECTRIX_DECIMALS: 2,
    FOCUS_DECIMALS: 2,
    POINT_ON_PARABOLA_DECIMALS: 2,
    POINT_TOOL_DECIMALS: 1,
    ROOTS_DECIMALS: 2,
    VERTEX_DECIMALS: 2,
    EXPLORE_DECIMALS_A: 2,
    EXPLORE_DECIMALS_B: 1,
    EXPLORE_DECIMALS_C: 1,
    FOCUS_AND_DIRECTRIX_DECIMALS_A: 3,
    FOCUS_AND_DIRECTRIX_DECIMALS_P: 1,
    FOCUS_AND_DIRECTRIX_DECIMALS_H: 1,
    FOCUS_AND_DIRECTRIX_DECIMALS_K: 1,

    // slider intervals
    EXPLORE_INTERVAL_A: 0.01,
    EXPLORE_INTERVAL_B: 0.1,
    EXPLORE_INTERVAL_C: 0.1,
    FOCUS_AND_DIRECTRIX_INTERVAL_P: 0.1,
    FOCUS_AND_DIRECTRIX_INTERVAL_H: 0.1,
    FOCUS_AND_DIRECTRIX_INTERVAL_K: 0.1,

    // enums
    EQUATION_FORMS: [ 'standard', 'vertex' ], // form of equations on curves
    PROBE_SIDES: [ 'right', 'left' ], // which side the point tool's probe is on

    // margins between equations and edges of graph
    // Caution! Changing these may cause an equation to go off the graph. Test thoroughly!
    EQUATION_X_MARGIN: 1.5, // distance between equation and left/right edges of graph, in model coordinate frame
    EQUATION_Y_MARGIN: 0.5, // distance between equation and top/bottom edges of graph, in model coordinate frame

    // space between equation and the curve that it labels, in view coordinate frame
    EQUATION_SPACING: 5,

    // maxWidth for all coordinates displays (CoordinateNode instances)
    COORDINATES_MAX_WIDTH: 100
  };

  return graphingQuadratics.register( 'GQConstants', GQConstants );
} );
<commit_msg>doc<commit_after>// Copyright 2014-2018, University of Colorado Boulder

/**
 * Constants that are global to this sim.
 *
 * @author Andrea Lin
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( require => {
  'use strict';

  // modules
  const Bounds2 = require( 'DOT/Bounds2' );
  const GQColors = require( 'GRAPHING_QUADRATICS/common/GQColors' );
  const graphingQuadratics = require( 'GRAPHING_QUADRATICS/graphingQuadratics' );
  const Range = require( 'DOT/Range' );

  // constants
  const PANEL_CORNER_RADIUS = 5; // corner radius for all panel-like containers

  const GQConstants = {

    SCREEN_VIEW_LAYOUT_BOUNDS: new Bounds2( 0, 0, 1100, 700 ),
    SCREEN_VIEW_X_MARGIN: 20,
    SCREEN_VIEW_Y_MARGIN: 16,

    // range of the graph's axes
    X_AXIS_RANGE: new Range( -10, 10 ),
    Y_AXIS_RANGE: new Range( -10, 10 ),

    // options applied to all AccordionBoxes
    ACCORDION_BOX_OPTIONS: {
      resize: false,
      fill: GQColors.CONTROL_PANEL_BACKGROUND,
      cornerRadius: PANEL_CORNER_RADIUS,
      titleYMargin: 10,
      buttonLength: 25,
      buttonXMargin: 10,
      buttonYMargin: 10,
      contentXMargin: 20,
      contentYMargin: 15
    },

    // options applied to all Panels
    PANEL_OPTIONS: {
      fill: GQColors.CONTROL_PANEL_BACKGROUND,
      cornerRadius: PANEL_CORNER_RADIUS,
      xMargin: 20,
      yMargin: 15
    },

    // horizontal space between checkbox text and icon
    CHECKBOX_ICON_SPACING: 8,

    // maxWidth for all checkboxes, determined empirically
    CHECKBOX_TEXT_MAX_WIDTH: 180,

    // vertical space between checkboxes
    CHECKBOXES_Y_SPACING: 15,

    PICKER_TOUCH_AREA_X_DILATION: 30,

    // radius of manipulators, in model coordinates
    MANIPULATOR_RADIUS: 0.425,

    // radius of non-interactive points, in model coordinates
    POINT_RADIUS: 0.25,

    // font sizes
    TITLE_FONT_SIZE: 20,
    INTERACTIVE_EQUATION_FONT_SIZE: 26,
    SLIDER_TICK_LABEL_FONT_SIZE: 16,
    CHECKBOX_LABEL_FONT_SIZE: 20,
    CHECKBOX_EQUATION_FONT_SIZE: 22,
    GRAPH_EQUATION_FONT_SIZE: 18,

    // line widths
    INTERACTIVE_QUADRATIC_LINE_WIDTH: 4,
    SAVED_QUADRATIC_LINE_WIDTH: 3,
    QUADRATIC_TERMS_LINE_WIDTH: 2, // y = ax^2, y = bx, y = c
    AXIS_OF_SYMMETRY_LINE_WIDTH: 3,
    DIRECTRIX_LINE_WIDTH: 3,
    POINT_ON_PARABOLA_LINE_WIDTH: 3, // lines that connect point to focus and directrix

    // line dashes
    AXIS_OF_SYMMETRY_LINE_DASH: [ 5, 5 ],
    DIRECTRIX_LINE_DASH: [ 5, 5 ],
    POINT_ON_PARABOLA_LINE_DASH: [ 5, 5 ], // lines that connect point to focus and directrix

    // decimal places
    AXIS_OF_SYMMETRY_DECIMALS: 2,
    DIRECTRIX_DECIMALS: 2,
    FOCUS_DECIMALS: 2,
    POINT_ON_PARABOLA_DECIMALS: 2,
    POINT_TOOL_DECIMALS: 1,
    ROOTS_DECIMALS: 2,
    VERTEX_DECIMALS: 2,
    EXPLORE_DECIMALS_A: 2,
    EXPLORE_DECIMALS_B: 1,
    EXPLORE_DECIMALS_C: 1,
    FOCUS_AND_DIRECTRIX_DECIMALS_A: 3,
    FOCUS_AND_DIRECTRIX_DECIMALS_P: 1,
    FOCUS_AND_DIRECTRIX_DECIMALS_H: 1,
    FOCUS_AND_DIRECTRIX_DECIMALS_K: 1,

    // slider intervals
    EXPLORE_INTERVAL_A: 0.01,
    EXPLORE_INTERVAL_B: 0.1,
    EXPLORE_INTERVAL_C: 0.1,
    FOCUS_AND_DIRECTRIX_INTERVAL_P: 0.1,
    FOCUS_AND_DIRECTRIX_INTERVAL_H: 0.1,
    FOCUS_AND_DIRECTRIX_INTERVAL_K: 0.1,

    // enums
    EQUATION_FORMS: [ 'standard', 'vertex' ], // form of equations on curves
    PROBE_SIDES: [ 'right', 'left' ], // which side the point tool's probe is on

    // margins between equations and edges of graph
    // Caution! Changing these may cause an equation to go off the graph. Test thoroughly!
    EQUATION_X_MARGIN: 1.5, // distance between equation and left/right edges of graph, in model coordinate frame
    EQUATION_Y_MARGIN: 0.5, // distance between equation and top/bottom edges of graph, in model coordinate frame

    // space between equation and the curve that it labels, in view coordinate frame
    EQUATION_SPACING: 5,

    // maxWidth for all coordinates displays (CoordinateNode instances)
    COORDINATES_MAX_WIDTH: 100
  };

  return graphingQuadratics.register( 'GQConstants', GQConstants );
} );
<|endoftext|>


<commit_before>import React from 'react';
import { connect } from 'react-redux';
import Label from '../components/Label';
import Input from '../components/Input';
import Select from '../components/Select';
import Button from '../components/Button';
import { addItem } from '../actions';

const AddForm = connect(({ add }) => add)(
	({ dispatch, data }) => (

							<Input stateKey="title" />

							<Input stateKey="fromHH" /> : <Input stateKey="fromMM" />

							<Input stateKey="toHH" /> : <Input stateKey="toMM" />

								<input type="checkbox" />
								Run All Day

							<Select
								multiple={true}
								title="Please select [Type]"
								data={['All', 'Deposits', 'Withdrawals']}
							/>

							<Select
								multiple={true}
								title="Please select [Day]"
								data={['All', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']}
							/>

							<Input />

							<Input />

							<Select
								multiple={true}
								title="[Platforms]"
								data={['All', 'MT4', 'MT5', 'Tradologic']}
							/>

							<Select
								multiple={true}
								title="[Servers]"
								data={['All', 'Live20', 'Live21']}
							/>

							<Select
								multiple={true}
								title="[Groups]"
								data={['All', 'usd-11', 'usd-risk']}
							/>

				<Button text="Cancel" />
				<Button text="Add" onClick={() => dispatch(addItem(data))} />

	)
);

export default AddForm;
<commit_msg>Add min/max amount change<commit_after>import React from 'react';
import { connect } from 'react-redux';
import Label from '../components/Label';
import Input from '../components/Input';
import Select from '../components/Select';
import Button from '../components/Button';
import { addItem } from '../actions';

const AddForm = connect(({ add }) => add)(
	({ dispatch, data }) => (

							<Input stateKey="title" />

							<Input stateKey="fromHH" /> : <Input stateKey="fromMM" />

							<Input stateKey="toHH" /> : <Input stateKey="toMM" />

								<input type="checkbox" />
								Run All Day

							<Select
								multiple={true}
								title="Please select [Type]"
								data={['All', 'Deposits', 'Withdrawals']}
							/>

							<Select
								multiple={true}
								title="Please select [Day]"
								data={['All', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']}
							/>

							<Input stateKey="minAmount" />

							<Input stateKey="maxAmount" />

							<Select
								multiple={true}
								title="[Platforms]"
								data={['All', 'MT4', 'MT5', 'Tradologic']}
							/>

							<Select
								multiple={true}
								title="[Servers]"
								data={['All', 'Live20', 'Live21']}
							/>

							<Select
								multiple={true}
								title="[Groups]"
								data={['All', 'usd-11', 'usd-risk']}
							/>

				<Button text="Cancel" />
				<Button text="Add" onClick={() => dispatch(addItem(data))} />

	)
);

export default AddForm;
<|endoftext|>


<commit_before>/**
 * @constructor
 */
function WindowController(editor, settings) {
  this.editor_ = editor;
  this.settings_ = settings;
  this.currentTab_ = null;
  $('#window-close').click(this.close_.bind(this));
  $('#window-maximize').click(this.maximize_.bind(this));
  $('#toggle-sidebar').click(this.toggleSidebar_.bind(this));
  $('#sidebar-resizer').mousedown(this.resizeStart_.bind(this));
  $(document).bind('switchtab', this.onChangeTab_.bind(this));
  $(document).bind('tabrenamed', this.onChangeTab_.bind(this));
  $(document).bind('tabchange', this.onTabChange_.bind(this));
  $(document).bind('tabsave', this.onTabChange_.bind(this));

  if (this.settings_.isReady()) {
    this.initSidebar_();
  } else {
    $(document).bind('settingsready', this.initSidebar_.bind(this));
  }
}

WindowController.prototype.initSidebar_ = function() {
  if (this.settings_.get('sidebaropen')) {
    $('#sidebar').css('width', this.settings_.get('sidebarwidth') + 'px');
    $('#toggle-sidebar').attr('title', 'Close sidebar');
  } else {
    $('#sidebar').css('width', '0');
    $('#toggle-sidebar').attr('title', 'Open sidebar');
  }
};

WindowController.prototype.windowControlsVisible = function(show) {
  if (show) {
    $('header').removeClass('hide-controls');
  } else {
    $('header').addClass('hide-controls');
  }
};

/**
 * @param {string} theme
 */
WindowController.prototype.setTheme = function(theme) {
  $('body').attr('theme', theme);
};

WindowController.prototype.close_ = function() {
  window.close();
};

WindowController.prototype.maximize_ = function() {
  var maximized = window.outerHeight == window.screen.availHeight &&
                  window.outerWidth == window.screen.availWidth;

  if (maximized) {
    window.chrome.app.window.current().restore();
    $('#window-maximize').attr('title', 'Maximize');
  } else {
    window.chrome.app.window.current().maximize();
    $('#window-maximize').attr('title', 'Restore');
  }
};

WindowController.prototype.toggleSidebar_ = function() {
  if (this.settings_.get('sidebaropen')) {
    this.settings_.set('sidebaropen', false);
    $('#sidebar').css('width', '0');
    $('#toggle-sidebar').attr('title', 'Open sidebar');
  } else {
    this.settings_.set('sidebaropen', true);
    $('#sidebar').css('width', this.settings_.get('sidebarwidth') + 'px');
    $('#toggle-sidebar').attr('title', 'Close sidebar');
  }
  this.editor_.focus();
  setTimeout(function() {$.event.trigger('resize');}, 200);
};

WindowController.prototype.onChangeTab_ = function(e, tab) {
  this.currentTab_ = tab;
  $('#title-filename').text(tab.getName());
  this.onTabChange_();
};

WindowController.prototype.onTabChange_ = function(e, tab) {
  if (this.currentTab_.isSaved()) {
    $('#title-filename').removeClass('unsaved');
  } else {
    $('#title-filename').addClass('unsaved');
  }
};

WindowController.prototype.resizeStart_ = function(e) {
  this.resizeMouseStartX_ = e.clientX;
  this.resizeStartWidth_ = parseInt($('#sidebar').css('width'), 10);
  $(document).on('mousemove.sidebar', this.resizeOnMouseMove_.bind(this));
  $(document).on('mouseup.sidebar', this.resizeFinish_.bind(this));
  $(document).css('cursor', 'e-resize !important');
  $('#sidebar').css('-webkit-transition', 'none');
};

WindowController.prototype.resizeOnMouseMove_ = function(e) {
  var change = e.clientX - this.resizeMouseStartX_;
  var sidebarWidth = this.resizeStartWidth_ + change;
  if (sidebarWidth < 20)
    sidebarWidth = 20;
  $('#sidebar').css('width', sidebarWidth + 'px');
  return sidebarWidth;
};

WindowController.prototype.resizeFinish_ = function(e) {
  sidebarWidth = this.resizeOnMouseMove_(e);
  this.settings_.set('sidebarwidth', sidebarWidth);
  $(document).off('mousemove.sidebar');
  $(document).off('mouseup.sidebar');
  $(document).css('cursor', 'default');
  $('#sidebar').css('-webkit-transition', 'width 0.2s ease-in-out');
};
<commit_msg>Fix syntax error causing bug with sidebar resizing.<commit_after>/**
 * @constructor
 */
function WindowController(editor, settings) {
  this.editor_ = editor;
  this.settings_ = settings;
  this.currentTab_ = null;
  $('#window-close').click(this.close_.bind(this));
  $('#window-maximize').click(this.maximize_.bind(this));
  $('#toggle-sidebar').click(this.toggleSidebar_.bind(this));
  $('#sidebar-resizer').mousedown(this.resizeStart_.bind(this));
  $(document).bind('switchtab', this.onChangeTab_.bind(this));
  $(document).bind('tabrenamed', this.onChangeTab_.bind(this));
  $(document).bind('tabchange', this.onTabChange_.bind(this));
  $(document).bind('tabsave', this.onTabChange_.bind(this));

  if (this.settings_.isReady()) {
    this.initSidebar_();
  } else {
    $(document).bind('settingsready', this.initSidebar_.bind(this));
  }
}

WindowController.prototype.initSidebar_ = function() {
  if (this.settings_.get('sidebaropen')) {
    $('#sidebar').css('width', this.settings_.get('sidebarwidth') + 'px');
    $('#toggle-sidebar').attr('title', 'Close sidebar');
  } else {
    $('#sidebar').css('width', '0');
    $('#toggle-sidebar').attr('title', 'Open sidebar');
  }
};

WindowController.prototype.windowControlsVisible = function(show) {
  if (show) {
    $('header').removeClass('hide-controls');
  } else {
    $('header').addClass('hide-controls');
  }
};

/**
 * @param {string} theme
 */
WindowController.prototype.setTheme = function(theme) {
  $('body').attr('theme', theme);
};

WindowController.prototype.close_ = function() {
  window.close();
};

WindowController.prototype.maximize_ = function() {
  var maximized = window.outerHeight == window.screen.availHeight &&
                  window.outerWidth == window.screen.availWidth;

  if (maximized) {
    window.chrome.app.window.current().restore();
    $('#window-maximize').attr('title', 'Maximize');
  } else {
    window.chrome.app.window.current().maximize();
    $('#window-maximize').attr('title', 'Restore');
  }
};

WindowController.prototype.toggleSidebar_ = function() {
  if (this.settings_.get('sidebaropen')) {
    this.settings_.set('sidebaropen', false);
    $('#sidebar').css('width', '0');
    $('#toggle-sidebar').attr('title', 'Open sidebar');
  } else {
    this.settings_.set('sidebaropen', true);
    $('#sidebar').css('width', this.settings_.get('sidebarwidth') + 'px');
    $('#toggle-sidebar').attr('title', 'Close sidebar');
  }
  this.editor_.focus();
  setTimeout(function() {$.event.trigger('resize');}, 200);
};

WindowController.prototype.onChangeTab_ = function(e, tab) {
  this.currentTab_ = tab;
  $('#title-filename').text(tab.getName());
  this.onTabChange_();
};

WindowController.prototype.onTabChange_ = function(e, tab) {
  if (this.currentTab_.isSaved()) {
    $('#title-filename').removeClass('unsaved');
  } else {
    $('#title-filename').addClass('unsaved');
  }
};

WindowController.prototype.resizeStart_ = function(e) {
  this.resizeMouseStartX_ = e.clientX;
  this.resizeStartWidth_ = parseInt($('#sidebar').css('width'), 10);
  $(document).on('mousemove.sidebar', this.resizeOnMouseMove_.bind(this));
  $(document).on('mouseup.sidebar', this.resizeFinish_.bind(this));
  $(document).css('cursor', 'e-resize !important');
  $('#sidebar').css('-webkit-transition', 'none');
};

WindowController.prototype.resizeOnMouseMove_ = function(e) {
  var change = e.clientX - this.resizeMouseStartX_;
  var sidebarWidth = this.resizeStartWidth_ + change;
  if (sidebarWidth < 20)
    sidebarWidth = 20;
  $('#sidebar').css('width', sidebarWidth + 'px');
  return sidebarWidth;
};

WindowController.prototype.resizeFinish_ = function(e) {
  var sidebarWidth = this.resizeOnMouseMove_(e);
  this.settings_.set('sidebarwidth', sidebarWidth);
  $(document).off('mousemove.sidebar');
  $(document).off('mouseup.sidebar');
  $(document).css('cursor', 'default');
  $('#sidebar').css('-webkit-transition', 'width 0.2s ease-in-out');
};
<|endoftext|>


<commit_before>socket.on('connected', function(connected) {
      /*
       * NULL: not connected to the node server
       * 1: connected
       */
      console.log(connected);
      var connected = connected;
      if(connected == 1){
       $('#login').html("
<button class='small button' onclick='return false;''>Login</button>      Hi ! Welcome to nodeChat, please login to post a message.
");
      }else{}
  });

socket.on('BadName', function(c){
  /*
   * If this socket returns 1, it's because the name is too long
   */
   if(c == 1){
   console.log('The value of c is 1, the name is too long.')
   $('#login').html("
<button class='small button' onclick='return false;''>Login</button>      Hi ! Welcome to nodeChat, please login to post a message.
");
   //Clearing user form
   $('#user-name').html('');
   $('#user-form').html('');
   $('#user').html('Guest')
   }
})
  socket.on('disconnect', function () {
    document.getElementById('tchat').innerHTML += '
bot : You have been disconnected, possibly because this server was restarted.
';
    $('#user-form').remove();
    $('#user-name').remove();
    $('#login').remove();
    $('#disconnected').html('You have been disconnected, possibly because this server was restarted.');
  });
<commit_msg>Add login stuffs<commit_after>function clearForm(){
   $('#login').html("
<button id='Loginbtn' class='small button' onclick='return false;''>Login</button>   <button id='Registerbtn' class='small button' onclick='return false;''>Register</button>      Hi ! Welcome to nodeChat, please login to post a message.
");
   //Clearing user form
   $('#user-name').html('');
   $('#user-form').html('');
   $('#user').html('Guest');
}
socket.on('connected', function(connected) {
      /*
       * NULL: not connected to the node server
       * 1: connected
       */
      console.log(connected);
      var connected = connected;
      if(connected == 1){
       $('#login').html("
<button id='Loginbtn' class='small button' onclick='return false;''>Login</button>   <button id='Registerbtn' class='small button' onclick='return false;''>Register</button>      Hi ! Welcome to nodeChat, please login to post a message.
");
      }else{}
  });

socket.on('BadName', function(c){
  /*
   * If this socket returns 1, it's because the name is too long
   */
   if(c == 1){
   console.log('The value of c is 1, the name is too long.')
   clearForm();
   }
});

socket.on('isLogged', function(c){
    /*
     * -1: User doesn't exist
     *  0: Wrong id/password combinaison
     *  1: Connected
     */
     switch(c){
      case '-1':
      clearForm();
      break;
      case '0':
      clearForm();
      break;
      case '1':
      //OK
      break;
      default:
      alert('woops, there is a problem... :/');
     }
});

  socket.on('disconnect', function () {
    document.getElementById('tchat').innerHTML += '
bot : You have been disconnected, possibly because this server was restarted.
';
    $('#user-form').remove();
    $('#user-name').remove();
    $('#login').remove();
    $('#disconnected').html('You have been disconnected, possibly because this server was restarted.');
  });
<|endoftext|>


<commit_before>var LightboxCanvas = (function () {
    var events = {
        documentMouseup: [],
        windowResize: [],
    };

    window.onload = function () {
        document.body.addEventListener("mouseup", function (e) {
            events.documentMouseup = events.documentMouseup.filter(function (event) {
                // go through automatic cleanup when running events.
                if (!document.body.contains(event.canvas)) {
                    return false;
                }

                event.callback.call(this, e);
                return true;
            });
        });

        window.addEventListener("resize", function (e) {
            events.windowResize = events.windowResize.filter(function (event) {
                if (!document.body.contains(event.canvas)) {
                    return false;
                }

                event.callback.call(this, e);

                return true;
            }.bind(this));
        });
    };

    var funcs = {
        setZoom: function (meta, zoom) {
            // make sure the zoom is above 1 and below the maxZoom.
            meta.zoom = Math.min(Math.max(zoom, 1), meta.maxZoom);
        },

        // this is a function given a canvas that attaches all of the events
        // required to pan and zoom.
        attachEvents: function (canvas, context, meta) {
            var mousedown = false;

            // wheelEvent.deltaMode is a value that describes what the unit is
            // for the `deltaX`, `deltaY`, and `deltaZ` properties.
            var DELTA_MODE = {
                PIXEL: 0,
                LINE: 1,
                PAGE: 2,
            };

            // give object structure in `mousedown`, because its props are only
            // ever set once `mousedown` + `mousemove` is triggered.
            var lastPosition = {};

            // in browsers such as Safari, the `e.movementX` and `e.movementY`
            // props don't exist, so we need to create them as a difference of
            // where the last `layerX` and `layerY` movements since the last
            // `mousemove` event in this `mousedown` event were registered.
            var polyfillMouseMovement = function (e) {
                e.movementX = (e.layerX - lastPosition.x) || 0;
                e.movementY = (e.layerY - lastPosition.y) || 0;

                lastPosition = {
                    x: e.layerX,
                    y: e.layerY,
                };
            };

            // use the wheel event rather than scroll because this isn't
            // actually an element that can scroll. The wheel event will
            // detect the *gesture* of scrolling over an element, without actually
            // worrying about scrollable content.
            canvas.addEventListener("wheel", function (e) {
                e.preventDefault();

                // this is to reverese scrolling directions for the image.
                var delta = meta.direction * e.deltaY;

                if (e.deltaMode === DELTA_MODE.LINE) {
                    // the vertical height in pixels of an approximate line.
                    delta *= 15;
                }

                if (e.deltaMode === DELTA_MODE.PAGE) {
                    // the vertical height in pixels of an approximate page.
                    delta *= 300;
                }

                // this is calculated as the user defined speed times the normalizer
                // (which just is what it takes to take the raw delta and transform
                // it to a normal speed), multiply it against the current zoom.
                // Example:
                // delta = 8
                // normalizedDelta = delta * (1 / 20) * 1 = 0.4
                // zoom = zoom * (0.4 / 100) + 1
                var zoom = meta.zoom * (
                    (meta.speed * meta.internalSpeedMultiplier * delta / 100) + 1
                );

                funcs.setZoom(meta, zoom);
                funcs.displayImage(canvas, context, meta);

                return false;
            });

            // the only valid mousedown events should originate inside of the
            // canvas.
            canvas.addEventListener("mousedown", function () {
                mousedown = true;
            });

            // on mousemove, actually run the pan events.
            canvas.addEventListener("mousemove", function (e) {
                // to pan, there must be mousedown and mousemove, check if valid.
                if (mousedown === true) {
                    polyfillMouseMovement(e);
                    // find the percent of movement relative to the canvas width
                    // since e.movementX, e.movementY are in px.
                    var percentMovement = {
                        x: (e.movementX / canvas.width),
                        y: (e.movementY / canvas.height),
                    };

                    // add the percentMovement to the meta coordinates but divide
                    // out by the zoom ratio because when zoomed in 10x for example
                    // moving the photo by 1% will appear like 10% on the <canvas>.
                    meta.coords.x += percentMovement.x * 2 / meta.zoom;
                    meta.coords.y += percentMovement.y * 2 / meta.zoom;

                    // redraw the image.
                    funcs.displayImage(canvas, context, meta);
                }
            });

            // make sure that when the mousedown is lifted on <canvas>to prevent
            // panning events.
            canvas.addEventListener("mouseup", function () {
                mousedown = false;
                // reset this to be empty so that the values will `NaN` on first
                // mousemove and default to a change of (0, 0).
                lastPosition = {};
            });

            // do so on the document.body as well, though depending on the infra,
            // these are less reliable as preventDefault may prevent these events
            // from propagating all the way to the <body>.
            events.documentMouseup.push({
                canvas: canvas,
                meta: meta,
                callback: function () {
                    mousedown = false;
                },
            });

            events.windowResize.push({
                canvas: canvas,
                meta: meta,
                callback: function () {
                    funcs.sizeCanvas(canvas, meta);
                    funcs.displayImage(canvas, context, meta);
                },
            });
        },

        imageRatio: function (image) {
            return image.naturalWidth / image.naturalHeight;
        },

        displayImage: function (canvas, context, meta) {
            meta.coords.x = Math.max(1 / (meta.zoom * 2), meta.coords.x);
            meta.coords.x = Math.min(1 - (1 / (meta.zoom * 2)), meta.coords.x);

            meta.coords.y = Math.max(1 / (meta.zoom * 2), meta.coords.y);
            meta.coords.y = Math.min(1 - (1 / (meta.zoom * 2)), meta.coords.y);

            var c = {
                x: meta.coords.x - 1,
                y: meta.coords.y - 1,
            };

            var x = (meta.zoom * c.x * canvas.width) + canvas.width / 2;
            var y = (meta.zoom * c.y * canvas.height) + canvas.height / 2;
            var w = canvas.width * meta.zoom;
            var h = canvas.height * meta.zoom;

            canvas.width = canvas.width;
            context.imageSmoothingEnabled = false;

            context.drawImage(meta.image, x, y, w, h);
        },

        // the `sizeCanvas` method figures out the appropriate bounding box for
        // the canvas given a parent that has constraints.
        // for example, if a photo has a ration of 1.5:1 (w:h), and the parent
        // box is 1:1 respectively, we want to stretch the photo to be as large
        // as we can, which means that we check if having the photo width = 100%
        // means that the height is less than 100% of the parent height. If so,
        // then we size the photo as w = 100%, h = 100% / 1.5.
        sizeCanvas: function (canvas, meta) {
            if (typeof meta.onresize === "function") {
                meta.onresize(canvas);
            }

            var parent = {
                width: canvas.parentNode.clientWidth,
                height: canvas.parentNode.clientHeight,
            };

            if (parent.height * meta.ratio > parent.width) {
                canvas.width = parent.width * 2;
                canvas.style.width = parent.width + "px";

                canvas.height = (parent.width / meta.ratio) * 2;
                canvas.style.height = parent.width / meta.ratio + "px";
            } else {
                canvas.height = parent.height * 2;
                canvas.style.height = parent.height + "px";

                canvas.width = parent.height * meta.ratio * 2;
                canvas.style.width = parent.height * meta.ratio + "px";
            }

            blueslip.warn("Please specify a 'data-width' or 'data-height' argument for canvas.");
        },
    };

    // a class w/ prototype to create a new `LightboxCanvas` instance.
    var __LightboxCanvas = function (el) {
        var self = this;

        this.meta = {
            direction: -1,
            zoom: 1,
            image: null,
            coords: {
                x: 0.5,
                y: 0.5,
            },
            speed: 1,
            // this is to normalize the speed to what I would consider to be
            // "standard" zoom speed.
            internalSpeedMultiplier: 0.05,
            maxZoom: 10,
        };

        if (el instanceof Node) {
            this.canvas = el;
        } else if (typeof el === "string") {
            this.canvas = document.querySelector(el);
        } else {
            blueslip.warn("Error. 'LightboxCanvas' accepts either string selector or node.");
            return;
        }

        this.context = this.canvas.getContext("2d");

        this.meta.image = new Image();
        this.meta.image.src = this.canvas.getAttribute("data-src");
        this.meta.image.onload = function () {
            self.meta.ratio = funcs.imageRatio(this);

            funcs.sizeCanvas(self.canvas, self.meta);
            funcs.displayImage(self.canvas, self.context, self.meta);
        };

        this.canvas.image = this.meta.image;

        funcs.attachEvents(this.canvas, this.context, self.meta);
    };

    __LightboxCanvas.prototype = {
        // set the speed at which scrolling zooms in on a photo.
        speed: function (speed) {
            this.meta.speed = speed;
        },

        // set the max zoom of the `LightboxCanvas` canvas as a mult of the total width.
        maxZoom: function (maxZoom) {
            this.meta.maxZoom = maxZoom;
        },

        reverseScrollDirection: function () {
            this.meta.direction = 1;
        },

        setZoom: function (zoom) {
            funcs.setZoom(this.meta, zoom);
            funcs.displayImage(this.canvas, this.context, this.meta);
        },

        resize: function (callback) {
            this.meta.onresize = callback;
        },
    };

    return __LightboxCanvas;
}());

if (typeof module !== 'undefined') {
    module.exports = LightboxCanvas;
}
<commit_msg>hotkeys: Add shortcuts for pan and zoom in lightbox view<commit_after>var LightboxCanvas = (function () {
    var events = {
        documentMouseup: [],
        windowResize: [],
    };

    window.onload = function () {
        document.body.addEventListener("mouseup", function (e) {
            events.documentMouseup = events.documentMouseup.filter(function (event) {
                // go through automatic cleanup when running events.
                if (!document.body.contains(event.canvas)) {
                    return false;
                }

                event.callback.call(this, e);
                return true;
            });
        });

        window.addEventListener("resize", function (e) {
            events.windowResize = events.windowResize.filter(function (event) {
                if (!document.body.contains(event.canvas)) {
                    return false;
                }

                event.callback.call(this, e);

                return true;
            }.bind(this));
        });
    };

    var funcs = {
        setZoom: function (meta, zoom) {
            // condition to handle zooming event by zoom hotkeys
            if (zoom === '+') {
                zoom = meta.zoom * 1.2;
            } else if (zoom === '-') {
                zoom = meta.zoom / 1.2;
            }
            // make sure the zoom is above 1 and below the maxZoom.
            meta.zoom = Math.min(Math.max(zoom, 1), meta.maxZoom);
        },

        // this is a function given a canvas that attaches all of the events
        // required to pan and zoom.
        attachEvents: function (canvas, context, meta) {
            var mousedown = false;

            // wheelEvent.deltaMode is a value that describes what the unit is
            // for the `deltaX`, `deltaY`, and `deltaZ` properties.
            var DELTA_MODE = {
                PIXEL: 0,
                LINE: 1,
                PAGE: 2,
            };

            // give object structure in `mousedown`, because its props are only
            // ever set once `mousedown` + `mousemove` is triggered.
            var lastPosition = {};

            // in browsers such as Safari, the `e.movementX` and `e.movementY`
            // props don't exist, so we need to create them as a difference of
            // where the last `layerX` and `layerY` movements since the last
            // `mousemove` event in this `mousedown` event were registered.
            var polyfillMouseMovement = function (e) {
                e.movementX = (e.layerX - lastPosition.x) || 0;
                e.movementY = (e.layerY - lastPosition.y) || 0;

                lastPosition = {
                    x: e.layerX,
                    y: e.layerY,
                };
            };

            // use the wheel event rather than scroll because this isn't
            // actually an element that can scroll. The wheel event will
            // detect the *gesture* of scrolling over an element, without actually
            // worrying about scrollable content.
            canvas.addEventListener("wheel", function (e) {
                e.preventDefault();

                // this is to reverese scrolling directions for the image.
                var delta = meta.direction * e.deltaY;

                if (e.deltaMode === DELTA_MODE.LINE) {
                    // the vertical height in pixels of an approximate line.
                    delta *= 15;
                }

                if (e.deltaMode === DELTA_MODE.PAGE) {
                    // the vertical height in pixels of an approximate page.
                    delta *= 300;
                }

                // this is calculated as the user defined speed times the normalizer
                // (which just is what it takes to take the raw delta and transform
                // it to a normal speed), multiply it against the current zoom.
                // Example:
                // delta = 8
                // normalizedDelta = delta * (1 / 20) * 1 = 0.4
                // zoom = zoom * (0.4 / 100) + 1
                var zoom = meta.zoom * (
                    (meta.speed * meta.internalSpeedMultiplier * delta / 100) + 1
                );

                funcs.setZoom(meta, zoom);
                funcs.displayImage(canvas, context, meta);

                return false;
            });

            // the only valid mousedown events should originate inside of the
            // canvas.
            canvas.addEventListener("mousedown", function () {
                mousedown = true;
            });

            // on mousemove, actually run the pan events.
            canvas.addEventListener("mousemove", function (e) {
                // to pan, there must be mousedown and mousemove, check if valid.
                if (mousedown === true) {
                    polyfillMouseMovement(e);
                    // find the percent of movement relative to the canvas width
                    // since e.movementX, e.movementY are in px.
                    var percentMovement = {
                        x: (e.movementX / canvas.width),
                        y: (e.movementY / canvas.height),
                    };

                    // add the percentMovement to the meta coordinates but divide
                    // out by the zoom ratio because when zoomed in 10x for example
                    // moving the photo by 1% will appear like 10% on the <canvas>.
                    meta.coords.x += percentMovement.x * 2 / meta.zoom;
                    meta.coords.y += percentMovement.y * 2 / meta.zoom;

                    // redraw the image.
                    funcs.displayImage(canvas, context, meta);
                }
            });

            // event listener to handle zoom in and out from using keyboard keys z/Z and +/-
            // in the canvas
            // these hotkeys are not implemented in static/js/hotkey.js as the code in
            // static/js/lightbox_canvas.js and static/js/lightbox.js isn't written a way
            // that the LightboxCanvas instance created in lightbox.js can be
            // accessed from hotkey.js. Major code refactoring is required in lightbox.js
            // to implement these keyboard shortcuts in hotkey.js
            document.addEventListener('keydown', function (e) {
                if (!overlays.lightbox_open()) {
                    return;
                }
                if (e.key === "Z" || e.key === '+') {
                    funcs.setZoom(meta, '+');
                    funcs.displayImage(canvas, context, meta);
                } else if (e.key === "z" || e.key === '-') {
                    funcs.setZoom(meta, '-');
                    funcs.displayImage(canvas, context, meta);
                }
                e.preventDefault();
                e.stopPropagation();
            });

            // make sure that when the mousedown is lifted on <canvas>to prevent
            // panning events.
            canvas.addEventListener("mouseup", function () {
                mousedown = false;
                // reset this to be empty so that the values will `NaN` on first
                // mousemove and default to a change of (0, 0).
                lastPosition = {};
            });

            // do so on the document.body as well, though depending on the infra,
            // these are less reliable as preventDefault may prevent these events
            // from propagating all the way to the <body>.
            events.documentMouseup.push({
                canvas: canvas,
                meta: meta,
                callback: function () {
                    mousedown = false;
                },
            });

            events.windowResize.push({
                canvas: canvas,
                meta: meta,
                callback: function () {
                    funcs.sizeCanvas(canvas, meta);
                    funcs.displayImage(canvas, context, meta);
                },
            });
        },

        imageRatio: function (image) {
            return image.naturalWidth / image.naturalHeight;
        },

        displayImage: function (canvas, context, meta) {
            meta.coords.x = Math.max(1 / (meta.zoom * 2), meta.coords.x);
            meta.coords.x = Math.min(1 - (1 / (meta.zoom * 2)), meta.coords.x);

            meta.coords.y = Math.max(1 / (meta.zoom * 2), meta.coords.y);
            meta.coords.y = Math.min(1 - (1 / (meta.zoom * 2)), meta.coords.y);

            var c = {
                x: meta.coords.x - 1,
                y: meta.coords.y - 1,
            };

            var x = (meta.zoom * c.x * canvas.width) + canvas.width / 2;
            var y = (meta.zoom * c.y * canvas.height) + canvas.height / 2;
            var w = canvas.width * meta.zoom;
            var h = canvas.height * meta.zoom;

            canvas.width = canvas.width;
            context.imageSmoothingEnabled = false;

            context.drawImage(meta.image, x, y, w, h);
        },

        // the `sizeCanvas` method figures out the appropriate bounding box for
        // the canvas given a parent that has constraints.
        // for example, if a photo has a ration of 1.5:1 (w:h), and the parent
        // box is 1:1 respectively, we want to stretch the photo to be as large
        // as we can, which means that we check if having the photo width = 100%
        // means that the height is less than 100% of the parent height. If so,
        // then we size the photo as w = 100%, h = 100% / 1.5.
        sizeCanvas: function (canvas, meta) {
            if (typeof meta.onresize === "function") {
                meta.onresize(canvas);
            }

            var parent = {
                width: canvas.parentNode.clientWidth,
                height: canvas.parentNode.clientHeight,
            };

            if (parent.height * meta.ratio > parent.width) {
                canvas.width = parent.width * 2;
                canvas.style.width = parent.width + "px";

                canvas.height = (parent.width / meta.ratio) * 2;
                canvas.style.height = parent.width / meta.ratio + "px";
            } else {
                canvas.height = parent.height * 2;
                canvas.style.height = parent.height + "px";

                canvas.width = parent.height * meta.ratio * 2;
                canvas.style.width = parent.height * meta.ratio + "px";
            }

            blueslip.warn("Please specify a 'data-width' or 'data-height' argument for canvas.");
        },
    };

    // a class w/ prototype to create a new `LightboxCanvas` instance.
    var __LightboxCanvas = function (el) {
        var self = this;

        this.meta = {
            direction: -1,
            zoom: 1,
            image: null,
            coords: {
                x: 0.5,
                y: 0.5,
            },
            speed: 1,
            // this is to normalize the speed to what I would consider to be
            // "standard" zoom speed.
            internalSpeedMultiplier: 0.05,
            maxZoom: 10,
        };

        if (el instanceof Node) {
            this.canvas = el;
        } else if (typeof el === "string") {
            this.canvas = document.querySelector(el);
        } else {
            blueslip.warn("Error. 'LightboxCanvas' accepts either string selector or node.");
            return;
        }

        this.context = this.canvas.getContext("2d");

        this.meta.image = new Image();
        this.meta.image.src = this.canvas.getAttribute("data-src");
        this.meta.image.onload = function () {
            self.meta.ratio = funcs.imageRatio(this);

            funcs.sizeCanvas(self.canvas, self.meta);
            funcs.displayImage(self.canvas, self.context, self.meta);
        };

        this.canvas.image = this.meta.image;

        funcs.attachEvents(this.canvas, this.context, self.meta);
    };

    __LightboxCanvas.prototype = {
        // set the speed at which scrolling zooms in on a photo.
        speed: function (speed) {
            this.meta.speed = speed;
        },

        // set the max zoom of the `LightboxCanvas` canvas as a mult of the total width.
        maxZoom: function (maxZoom) {
            this.meta.maxZoom = maxZoom;
        },

        reverseScrollDirection: function () {
            this.meta.direction = 1;
        },

        setZoom: function (zoom) {
            funcs.setZoom(this.meta, zoom);
            funcs.displayImage(this.canvas, this.context, this.meta);
        },

        resize: function (callback) {
            this.meta.onresize = callback;
        },
    };

    return __LightboxCanvas;
}());

if (typeof module !== 'undefined') {
    module.exports = LightboxCanvas;
}
<|endoftext|>


<commit_before>//Create a module and create a controller for angular
console.log('in controller 1');

var myangularapp = angular.module("myangularapp", []);
myangularapp.controller("myangularController", function($scope, $http, $window) {
    console.log('in controller 2');
    $scope.register = function() {
        alert('In Register');
        $http.post("/register", {
                password: $scope.newUser.password,
                email: $scope.newUser.email,
                username: $scope.newUser.username
        }).then(function(response) {
            console.log('success', success);
            alert('Thanks for registering');
            $window.location = '/index.html';
        });
    };

    $scope.login = function() {

        $scope.username1;
        $scope.password1;

        $http.post('/login', {
            username: $scope.username1,
            password: $scope.password1,
        }).then(function(response) {
            alert('hi i am working');
            //alert(JSON.stringify(response));
            alert(response.data[0].status);
            if (response.data[0].status == 1) {
                //window.location.href = 'http://joelwebsites.com';
                console.log("Login Successful");
                $window.location = '/index.html';
            }

        }, function errorCallback(response) {
            alert('Password Incorrect or User not found.');
            // called asynchronously if an error occurs
            // or server returns response with an error status.
        });
    }

});
<commit_msg>fixing error<commit_after>//Create a module and create a controller for angular
console.log('in controller 1');

var myangularapp = angular.module("myangularapp", []);
myangularapp.controller("myangularController", function($scope, $http, $window) {
    console.log('in controller 2');
    $scope.register = function() {
        alert('In Register');
        $http.post("/register", {
                password: $scope.newUser.password,
                email: $scope.newUser.email,
                username: $scope.newUser.username
        }).then(function(response) {
            alert('Thanks for registering');
            $window.location = '/index.html';
        });
    };

    $scope.login = function() {

        $scope.username1;
        $scope.password1;

        $http.post('/login', {
            username: $scope.username1,
            password: $scope.password1,
        }).then(function(response) {
            alert('hi i am working');
            //alert(JSON.stringify(response));
            alert(response.data[0].status);
            if (response.data[0].status == 1) {
                //window.location.href = 'http://joelwebsites.com';
                console.log("Login Successful");
                $window.location = '/index.html';
            }

        }, function errorCallback(response) {
            alert('Password Incorrect or User not found.');
            // called asynchronously if an error occurs
            // or server returns response with an error status.
        });
    }

});
<|endoftext|>