<commit_before>change_buttons = function(check_node = 0) {
  var button, buttons, item, num_checked, text, _i, _j, _k, _l, _len, _len2, _len3, _len4, _results, _results2;
  buttons = ["#add", "#remove"];

  num_checked = 0
  table_api = $('#trait_table').DataTable();
  check_cells = table_api.column(0).nodes().to$();
  for (let i = 0; i < check_cells.length; i++) {
    if (check_cells[i].childNodes[check_node].checked){
      num_checked += 1
    }
  }

  if (num_checked === 0) {
    for (_i = 0, _len = buttons.length; _i < _len; _i++) {
      button = buttons[_i];
      $(button).prop("disabled", true);
    }
  } else {
    for (_j = 0, _len2 = buttons.length; _j < _len2; _j++) {
      button = buttons[_j];
      $(button).prop("disabled", false);
    }
  }
};

$(function() {
  var add, checked_traits, deselect_all, invert, remove, removed_traits, select_all;

  checked_traits = null;
  select_all = function() {
    table_api = $('#trait_table').DataTable();

    check_cells = table_api.column(0).nodes().to$();
    for (let i = 0; i < check_cells.length; i++) {
      check_cells[i].childNodes[0].checked = true;
    }

    check_rows = table_api.rows().nodes();
    for (let i =0; i < check_rows.length; i++) {
      check_rows[i].classList.add("selected");
    }

    change_buttons();
  };

  deselect_all = function() {
    table_api = $('#trait_table').DataTable();

    check_cells = table_api.column(0).nodes().to$();
    for (let i = 0; i < check_cells.length; i++) {
      check_cells[i].childNodes[0].checked = false;
    }

    check_rows = table_api.rows().nodes();
    for (let i =0; i < check_rows.length; i++) {
      check_rows[i].classList.remove("selected")
    }

    change_buttons();
  };

  invert = function() {
    table_api = $('#trait_table').DataTable();

    check_cells = table_api.column(0).nodes().to$();
    for (let i = 0; i < check_cells.length; i++) {
      if (check_cells[i].childNodes[0].checked){
        check_cells[i].childNodes[0].checked = false;
      } else {
        check_cells[i].childNodes[0].checked = true;
      }
    }

    check_rows = table_api.rows().nodes();
    for (let i =0; i < check_rows.length; i++) {
      if (check_rows[i].classList.contains("selected")){
        check_rows[i].classList.remove("selected")
      } else {
        check_rows[i].classList.add("selected")
      }
    }

    change_buttons();
  };

  $('#searchbox').keyup(function(){
      if ($(this).val() != ""){
        $('#filter_term').val($(this).val());
      } else {
        $('#filter_term').val("None");
      }
      $('#trait_table').DataTable().search($(this).val()).draw();
  });

  $('#select_top').keyup(function(){
      num_rows = $(this).val()
      if (num_rows = parseInt(num_rows)){
          i = 0
          $('#trait_table > tbody > tr').each(function(){
              if (i < num_rows) {
                  $(this).find('.trait_checkbox').prop("checked", true)
                  if (!$(this).closest('tr').hasClass('selected')) {
                      $(this).closest('tr').addClass('selected')
                  }
              }
              else {
                  if ($(this).closest('tr').hasClass('selected')) {
                      $(this).closest('tr').removeClass('selected')
                      $(this).find('.trait_checkbox').prop("checked", false)
                  }
              }
              i += 1
          });
      }
      else {
          $('#trait_table > tbody > tr').each(function(){
              $(this).closest('tr').removeClass('selected')
              $(this).find('.trait_checkbox').prop("checked", false)
          });
      }
      change_buttons();
  });

  add_to_collection = function() {
    var traits;
    traits = $("#trait_table input:checked").map(function() {
      return $(this).val();
    }).get();

    var traits_hash = md5(traits.toString());

    $.ajax({
          type: "POST",
          url: "/collections/store_trait_list",
          data: {
            hash: traits_hash,
            traits: traits.toString()
          }
    });

    return $.colorbox({
      href: "/collections/add?hash=" + traits_hash
    });

  };

  removed_traits = function() {
    return checked_traits.closest("tr").fadeOut();
  };

  submit_bnw = function() {
    trait_data = submit_traits_to_export_or_bnw("trait_table", "submit_bnw")
  }

  export_traits = function() {
    trait_data = submit_traits_to_export_or_bnw("trait_table", "export_csv")
  };

  submit_traits_to_export_or_bnw = function(table_name, destination) {
    trait_table = $('#'+table_name);
    table_dict = {};

    headers = [];
    trait_table.find('th').each(function () {
      if ($(this).data('export')){
        headers.push($(this).data('export'))
      }
    });
    table_dict['headers'] = headers;

    selected_rows = [];
    all_rows = []; //ZS: If no rows are checked, export all
    table_api = $('#' + table_name).DataTable();
    check_cells = table_api.column(0).nodes().to$();
    for (let i = 0; i < check_cells.length; i++) {
      this_node = check_cells[i].childNodes[0];
      all_rows.push(this_node.value)
      if (this_node.checked){
        selected_rows.push(this_node.value)
      }
    }

    if (selected_rows.length > 0){
      table_dict['rows'] = selected_rows;
    } else {
      table_dict['rows'] = all_rows;
    }

    json_table_dict = JSON.stringify(table_dict);
    $('input[name=export_data]').val(json_table_dict);

    if (destination == "export_csv"){
        $('#export_form').attr('action', '/export_traits_csv');
    } else{
        $('#export_form').attr('action', '/submit_bnw');
    }
    $('#export_form').submit();
  };

  get_traits_from_table = function(){
    traits = $("#trait_table input:checked").map(function() {
      return $(this).val();
    }).get();
    if (traits.length == 0){
      num_traits = $("#trait_table input").length
      if (num_traits <= 100){
        traits = $("#trait_table input").map(function() {
          return $(this).val();
        }).get();
      }
    }
    return traits
  }

  $("#corr_matrix").on("click", function() {
      traits = get_traits_from_table()
      $("#trait_list").val(traits)
      $("input[name=tool_used]").val("Correlation Matrix")
      $("input[name=form_url]").val($(this).data("url"))
      return submit_special("/loading")
  });
  $("#network_graph").on("click", function() {
      traits = get_traits_from_table()
      $("#trait_list").val(traits)
      $("input[name=tool_used]").val("Network Graph")
      $("input[name=form_url]").val($(this).data("url"))
      return submit_special("/loading")
  });
  $("#wgcna_setup").on("click", function() {
      traits = get_traits_from_table()
      $("#trait_list").val(traits)
      $("input[name=tool_used]").val("WGCNA Setup")
      $("input[name=form_url]").val($(this).data("url"))
      return submit_special("/loading")
  });
  $("#ctl_setup").on("click", function() {
      traits = get_traits_from_table()
      $("#trait_list").val(traits)
      $("input[name=tool_used]").val("CTL Setup")
      $("input[name=form_url]").val($(this).data("url"))
      return submit_special("/loading")
  });
  $("#heatmap").on("click", function() {
      traits = get_traits_from_table()
      $("#trait_list").val(traits)
      $("input[name=tool_used]").val("Heatmap")
      $("input[name=form_url]").val($(this).data("url"))
      return submit_special("/loading")
  });
  $("#comp_bar_chart").on("click", function() {
      traits = get_traits_from_table()
      $("#trait_list").val(traits)
      $("input[name=tool_used]").val("Comparison Bar Chart")
      $("input[name=form_url]").val($(this).data("url"))
      return submit_special("/loading")
  });

  $("#send_to_webgestalt, #send_to_bnw, #send_to_geneweaver").on("click", function() {
      traits = get_traits_from_table()
      $("#trait_list").val(traits)
      url = $(this).data("url")
      return submit_special(url)
  });

  $("#select_all").click(select_all);
  $("#deselect_all").click(deselect_all);
  $("#invert").click(invert);
  $("#add").click(add_to_collection);
  $("#submit_bnw").click(submit_bnw);
  $("#export_traits").click(export_traits);

  let naturalAsc = $.fn.dataTableExt.oSort["natural-ci-asc"]
  let naturalDesc = $.fn.dataTableExt.oSort["natural-ci-desc"]

  let na_equivalent_vals = ["N/A", "--", ""]; //ZS: Since there are multiple values that should be treated the same as N/A

  function extract_inner_text(the_string){
    var span = document.createElement('span');
    span.innerHTML = the_string;
    return span.textContent || span.innerText;
  }

  function sort_NAs(a, b, sort_function){
    if ( na_equivalent_vals.includes(a) && na_equivalent_vals.includes(b)) {
      return 0;
    }
    if (na_equivalent_vals.includes(a)){
      return 1
    }
    if (na_equivalent_vals.includes(b)) {
      return -1;
    }
    return sort_function(a, b)
  }

  $.extend( $.fn.dataTableExt.oSort, {
    "natural-minus-na-asc": function (a, b) {
      return sort_NAs(extract_inner_text(a), extract_inner_text(b), naturalAsc)
    },
    "natural-minus-na-desc": function (a, b) {
      return sort_NAs(extract_inner_text(a), extract_inner_text(b), naturalDesc)
    }
  });

  $.fn.dataTable.ext.order['dom-checkbox'] = function  ( settings, col )
  {
      return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
          return $('input', td).prop('checked') ? '1' : '0';
      } );
  };

  $.fn.dataTable.ext.order['dom-inner-text'] = function  ( settings, col )
  {
      return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
          return $(td).text();
      } );
  }

});<commit_msg>Fixed the Select Top Rows feature to use DataTables API instead of JQuery<commit_after>change_buttons = function(check_node = 0) {
  var button, buttons, item, num_checked, text, _i, _j, _k, _l, _len, _len2, _len3, _len4, _results, _results2;
  buttons = ["#add", "#remove"];

  num_checked = 0
  table_api = $('#trait_table').DataTable();
  check_cells = table_api.column(0).nodes().to$();
  for (let i = 0; i < check_cells.length; i++) {
    if (check_cells[i].childNodes[check_node].checked){
      num_checked += 1
    }
  }

  if (num_checked === 0) {
    for (_i = 0, _len = buttons.length; _i < _len; _i++) {
      button = buttons[_i];
      $(button).prop("disabled", true);
    }
  } else {
    for (_j = 0, _len2 = buttons.length; _j < _len2; _j++) {
      button = buttons[_j];
      $(button).prop("disabled", false);
    }
  }
};

$(function() {
  var add, checked_traits, deselect_all, invert, remove, removed_traits, select_all;

  checked_traits = null;
  select_all = function() {
    table_api = $('#trait_table').DataTable();

    check_cells = table_api.column(0).nodes().to$();
    for (let i = 0; i < check_cells.length; i++) {
      check_cells[i].childNodes[0].checked = true;
    }

    check_rows = table_api.rows().nodes();
    for (let i =0; i < check_rows.length; i++) {
      check_rows[i].classList.add("selected");
    }

    change_buttons();
  };

  deselect_all = function() {
    table_api = $('#trait_table').DataTable();

    check_cells = table_api.column(0).nodes().to$();
    for (let i = 0; i < check_cells.length; i++) {
      check_cells[i].childNodes[0].checked = false;
    }

    check_rows = table_api.rows().nodes();
    for (let i =0; i < check_rows.length; i++) {
      check_rows[i].classList.remove("selected")
    }

    change_buttons();
  };

  invert = function() {
    table_api = $('#trait_table').DataTable();

    check_cells = table_api.column(0).nodes().to$();
    for (let i = 0; i < check_cells.length; i++) {
      if (check_cells[i].childNodes[0].checked){
        check_cells[i].childNodes[0].checked = false;
      } else {
        check_cells[i].childNodes[0].checked = true;
      }
    }

    check_rows = table_api.rows().nodes();
    for (let i =0; i < check_rows.length; i++) {
      if (check_rows[i].classList.contains("selected")){
        check_rows[i].classList.remove("selected")
      } else {
        check_rows[i].classList.add("selected")
      }
    }

    change_buttons();
  };

  $('#searchbox').keyup(function(){
      if ($(this).val() != ""){
        $('#filter_term').val($(this).val());
      } else {
        $('#filter_term').val("None");
      }
      $('#trait_table').DataTable().search($(this).val()).draw();
  });

  $('#select_top').keyup(function(){
      num_rows = $(this).val()

      if (num_rows = parseInt(num_rows)){
          table_api = $('#trait_table').DataTable();

          check_cells = table_api.column(0).nodes().to$();
          for (let i = 0; i < num_rows; i++) {
            check_cells[i].childNodes[0].checked = true;
          }

          check_rows = table_api.rows().nodes();
          for (let i=0; i < num_rows; i++) {
            if (check_rows[i].classList.contains("selected")){
              continue
            } else {
              check_rows[i].classList.add("selected")
            }
          }
          for (let i = num_rows; i < check_rows.length; i++){
            check_cells[i].childNodes[0].checked = false;
            if (check_rows[i].classList.contains("selected")){
              check_rows[i].classList.remove("selected")
            }
          }
      }
      else {
        for (let i = 0; i < check_rows.length; i++){
          check_cells[i].childNodes[0].checked = false;
          if (check_rows[i].classList.contains("selected")){
            check_rows[i].classList.remove("selected")
          }
        }
      }
      change_buttons();
  });

  add_to_collection = function() {
    var traits;
    traits = $("#trait_table input:checked").map(function() {
      return $(this).val();
    }).get();

    var traits_hash = md5(traits.toString());

    $.ajax({
          type: "POST",
          url: "/collections/store_trait_list",
          data: {
            hash: traits_hash,
            traits: traits.toString()
          }
    });

    return $.colorbox({
      href: "/collections/add?hash=" + traits_hash
    });

  };

  removed_traits = function() {
    return checked_traits.closest("tr").fadeOut();
  };

  submit_bnw = function() {
    trait_data = submit_traits_to_export_or_bnw("trait_table", "submit_bnw")
  }

  export_traits = function() {
    trait_data = submit_traits_to_export_or_bnw("trait_table", "export_csv")
  };

  submit_traits_to_export_or_bnw = function(table_name, destination) {
    trait_table = $('#'+table_name);
    table_dict = {};

    headers = [];
    trait_table.find('th').each(function () {
      if ($(this).data('export')){
        headers.push($(this).data('export'))
      }
    });
    table_dict['headers'] = headers;

    selected_rows = [];
    all_rows = []; //ZS: If no rows are checked, export all
    table_api = $('#' + table_name).DataTable();
    check_cells = table_api.column(0).nodes().to$();
    for (let i = 0; i < check_cells.length; i++) {
      this_node = check_cells[i].childNodes[0];
      all_rows.push(this_node.value)
      if (this_node.checked){
        selected_rows.push(this_node.value)
      }
    }

    if (selected_rows.length > 0){
      table_dict['rows'] = selected_rows;
    } else {
      table_dict['rows'] = all_rows;
    }

    json_table_dict = JSON.stringify(table_dict);
    $('input[name=export_data]').val(json_table_dict);

    if (destination == "export_csv"){
        $('#export_form').attr('action', '/export_traits_csv');
    } else{
        $('#export_form').attr('action', '/submit_bnw');
    }
    $('#export_form').submit();
  };

  get_traits_from_table = function(){
    traits = $("#trait_table input:checked").map(function() {
      return $(this).val();
    }).get();
    if (traits.length == 0){
      num_traits = $("#trait_table input").length
      if (num_traits <= 100){
        traits = $("#trait_table input").map(function() {
          return $(this).val();
        }).get();
      }
    }
    return traits
  }

  $("#corr_matrix").on("click", function() {
      traits = get_traits_from_table()
      $("#trait_list").val(traits)
      $("input[name=tool_used]").val("Correlation Matrix")
      $("input[name=form_url]").val($(this).data("url"))
      return submit_special("/loading")
  });
  $("#network_graph").on("click", function() {
      traits = get_traits_from_table()
      $("#trait_list").val(traits)
      $("input[name=tool_used]").val("Network Graph")
      $("input[name=form_url]").val($(this).data("url"))
      return submit_special("/loading")
  });
  $("#wgcna_setup").on("click", function() {
      traits = get_traits_from_table()
      $("#trait_list").val(traits)
      $("input[name=tool_used]").val("WGCNA Setup")
      $("input[name=form_url]").val($(this).data("url"))
      return submit_special("/loading")
  });
  $("#ctl_setup").on("click", function() {
      traits = get_traits_from_table()
      $("#trait_list").val(traits)
      $("input[name=tool_used]").val("CTL Setup")
      $("input[name=form_url]").val($(this).data("url"))
      return submit_special("/loading")
  });
  $("#heatmap").on("click", function() {
      traits = get_traits_from_table()
      $("#trait_list").val(traits)
      $("input[name=tool_used]").val("Heatmap")
      $("input[name=form_url]").val($(this).data("url"))
      return submit_special("/loading")
  });
  $("#comp_bar_chart").on("click", function() {
      traits = get_traits_from_table()
      $("#trait_list").val(traits)
      $("input[name=tool_used]").val("Comparison Bar Chart")
      $("input[name=form_url]").val($(this).data("url"))
      return submit_special("/loading")
  });

  $("#send_to_webgestalt, #send_to_bnw, #send_to_geneweaver").on("click", function() {
      traits = get_traits_from_table()
      $("#trait_list").val(traits)
      url = $(this).data("url")
      return submit_special(url)
  });

  $("#select_all").click(select_all);
  $("#deselect_all").click(deselect_all);
  $("#invert").click(invert);
  $("#add").click(add_to_collection);
  $("#submit_bnw").click(submit_bnw);
  $("#export_traits").click(export_traits);

  let naturalAsc = $.fn.dataTableExt.oSort["natural-ci-asc"]
  let naturalDesc = $.fn.dataTableExt.oSort["natural-ci-desc"]

  let na_equivalent_vals = ["N/A", "--", ""]; //ZS: Since there are multiple values that should be treated the same as N/A

  function extract_inner_text(the_string){
    var span = document.createElement('span');
    span.innerHTML = the_string;
    return span.textContent || span.innerText;
  }

  function sort_NAs(a, b, sort_function){
    if ( na_equivalent_vals.includes(a) && na_equivalent_vals.includes(b)) {
      return 0;
    }
    if (na_equivalent_vals.includes(a)){
      return 1
    }
    if (na_equivalent_vals.includes(b)) {
      return -1;
    }
    return sort_function(a, b)
  }

  $.extend( $.fn.dataTableExt.oSort, {
    "natural-minus-na-asc": function (a, b) {
      return sort_NAs(extract_inner_text(a), extract_inner_text(b), naturalAsc)
    },
    "natural-minus-na-desc": function (a, b) {
      return sort_NAs(extract_inner_text(a), extract_inner_text(b), naturalDesc)
    }
  });

  $.fn.dataTable.ext.order['dom-checkbox'] = function  ( settings, col )
  {
      return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
          return $('input', td).prop('checked') ? '1' : '0';
      } );
  };

  $.fn.dataTable.ext.order['dom-inner-text'] = function  ( settings, col )
  {
      return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
          return $(td).text();
      } );
  }

});<|endoftext|>


<commit_before>var app = angular.module('ideaBin.pullRequestControllers', []);

app.controller("PullRequestIndexController", ['$scope', '$localStorage', 'PullRequest', '$location', '$http', '$rootScope',
	function($scope, $localStorage, PullRequest, $location, $http, $rootScope) {
		$scope.$storage = $localStorage;
		$scope.pullRequests = PullRequest.query({repo_id: $localStorage.repo.id});

  	$scope.rejectPullRequest =  function(pullRequest){
			PullRequest.delete({id: pullRequest.id});
			var index = $scope.pullRequests.indexOf(pullRequest);
			$scope.pullRequests.splice(index, 1);
		}

		$scope.createNewPullRequest = function(){
			PullRequest.create();
			$location.path('/pullRequests');
		}

		$scope.showPullRequest = function(pullRequestId){
			$rootScope.$broadcast('showPullRequest', pullRequestId);
		}

		$scope.acceptPullRequest = function (pullRequestId) {
			PullRequest.update({id: pullRequestId});
			$location.path('/ideas/'+$localStorage.current_idea.id);
		}

		$scope.showNewPullRequest = function(){
			$scope.isCreatePullRequestPanelVisible = true;
		}

		$scope.$on('showMyPullRequests', function(event, userId){
			$scope.showUserPullRequests(userId);
		});

		$scope.$on('showAddPullRequest', function(event, data){
			$scope.showNewPullRequest();
		});

		$scope.$on('showAllPullRequests', function(event, data){
			$scope.pullRequests = PullRequest.query({repo_id: $localStorage.repo.id});
			$("#pullRequestIndexPanel").toggle();
		});

		$scope.$on('addPullRequestToList', function(event, data){
			$scope.pullRequests.push(data);
		});

		$scope.showUserPullRequests = function(userId){
			$http.get("/userPullRequests/" + userId+".json")
				.success(function(data){
					$scope.pullRequests = data;
				})
				.error(function(data){
					alert(data.errors);
				});
		}

		$scope.$on('hideCreatePullRequestPanel', function(event, data) {
			$scope.isCreatePullRequestPanelVisible = false;
		});
}]);

app.controller('PullRequestDetailController', ['$scope', '$localStorage', '$routeParams', 'PullRequest', '$location', '$upload', '$rootScope',
	function($scope, $localStorage, $routeParams, PullRequest, $location, $upload, $rootScope){
		$scope.$storage = $localStorage;
		$scope.pullRequest = {}

		$scope.updatePullRequest = function (pullRequestId){
			PullRequest.update($scope.pullRequest,{id: pullRequestId}, function(){

			});
		}

		$scope.hidePullRequestDetailPanel = function() {
			//$rootScope.pullRequestEditPanelVisible = false;
		}

		$scope.$on('showPullRequest', function(event, pullRequestId){
			console.log("PULL REQUEST ID :: " + pullRequestId);
			$scope.pull_request = PullRequest.show({id: pullRequestId}).$promise;
			$localStorage.pull_request = PullRequest.show({id: pullRequestId});
			$scope.pull_request.then( function onSuccess(response){
				$scope.pull_request = response;
			},
			function onFail(response) {
					alert("failed to load idea for editing");
			});
			//console.log("PULL REQUEST MESSAGE :: " + $scope.pull_request.message);
			$("#pullRequestDetailsPanel").show();
		})
	}
]);

app.controller('PullRequestCreationController', ['$scope', '$rootScope', 'PullRequest', '$location', '$upload','$localStorage',
	function($scope, $rootScope, PullRequest, $location, $upload, $localStorage ){
		//callback for ng-click 'createNewPullRequest'
		$scope.pullRequestForm = {};

		$scope.createNewPullRequest = function(){
			$scope.pullRequestForm.idea_id = $localStorage.current_idea.id;
			PullRequest.create($scope.pullRequestForm, function(){
				});
		}

		$scope.$on('showPullRequestCreatePanel', function() {
			$("#pullRequestCreatePanel").show();
		})

		$scope.hideCreatePullRequestPanel = function(){
			$("#pullRequestCreatePanel").hide();
		}
	}
]);<commit_msg>removed default loading of pull requests instead deferring to event listener for when to load requests<commit_after>var app = angular.module('ideaBin.pullRequestControllers', []);

app.controller("PullRequestIndexController", ['$scope', '$localStorage', 'PullRequest', '$location', '$http', '$rootScope',
	function($scope, $localStorage, PullRequest, $location, $http, $rootScope) {
		$scope.$storage = $localStorage;

  	$scope.rejectPullRequest =  function(pullRequest){
			PullRequest.delete({id: pullRequest.id});
			var index = $scope.pullRequests.indexOf(pullRequest);
			$scope.pullRequests.splice(index, 1);
		}

		$scope.createNewPullRequest = function(){
			PullRequest.create();
			$location.path('/pullRequests');
		}

		$scope.showPullRequest = function(pullRequestId){
			$rootScope.$broadcast('showPullRequest', pullRequestId);
		}

		$scope.acceptPullRequest = function (pullRequestId) {
			PullRequest.update({id: pullRequestId});
			$location.path('/ideas/'+$localStorage.current_idea.id);
		}

		$scope.showNewPullRequest = function(){
			$scope.isCreatePullRequestPanelVisible = true;
		}

		$scope.$on('showMyPullRequests', function(event, userId){
			$scope.showUserPullRequests(userId);
		});

		$scope.$on('showAddPullRequest', function(event, data){
			$scope.showNewPullRequest();
		});

		$scope.$on('showAllPullRequests', function(event, data){
			$scope.pullRequests = PullRequest.query({repo_id: $localStorage.repo.id});
			$("#pullRequestIndexPanel").toggle();
		});

		$scope.$on('addPullRequestToList', function(event, data){
			$scope.pullRequests.push(data);
		});

		$scope.showUserPullRequests = function(userId){
			$http.get("/userPullRequests/" + userId+".json")
				.success(function(data){
					$scope.pullRequests = data;
				})
				.error(function(data){
					alert(data.errors);
				});
		}

		$scope.$on('hideCreatePullRequestPanel', function(event, data) {
			$scope.isCreatePullRequestPanelVisible = false;
		});
}]);

app.controller('PullRequestDetailController', ['$scope', '$localStorage', '$routeParams', 'PullRequest', '$location', '$upload', '$rootScope',
	function($scope, $localStorage, $routeParams, PullRequest, $location, $upload, $rootScope){
		$scope.$storage = $localStorage;
		$scope.pullRequest = {}

		$scope.updatePullRequest = function (pullRequestId){
			PullRequest.update($scope.pullRequest,{id: pullRequestId}, function(){

			});
		}

		$scope.hidePullRequestDetailPanel = function() {
			//$rootScope.pullRequestEditPanelVisible = false;
		}

		$scope.$on('showPullRequest', function(event, pullRequestId){
			console.log("PULL REQUEST ID :: " + pullRequestId);
			$scope.pull_request = PullRequest.show({id: pullRequestId}).$promise;
			$localStorage.pull_request = PullRequest.show({id: pullRequestId});
			$scope.pull_request.then( function onSuccess(response){
				$scope.pull_request = response;
			},
			function onFail(response) {
					alert("failed to load idea for editing");
			});
			//console.log("PULL REQUEST MESSAGE :: " + $scope.pull_request.message);
			$("#pullRequestDetailsPanel").show();
		})
	}
]);

app.controller('PullRequestCreationController', ['$scope', '$rootScope', 'PullRequest', '$location', '$upload','$localStorage',
	function($scope, $rootScope, PullRequest, $location, $upload, $localStorage ){
		//callback for ng-click 'createNewPullRequest'
		$scope.pullRequestForm = {};

		$scope.createNewPullRequest = function(){
			$scope.pullRequestForm.idea_id = $localStorage.current_idea.id;
			PullRequest.create($scope.pullRequestForm, function(){
				});
		}

		$scope.$on('showPullRequestCreatePanel', function() {
			$("#pullRequestCreatePanel").show();
		})

		$scope.hideCreatePullRequestPanel = function(){
			$("#pullRequestCreatePanel").hide();
		}
	}
]);<|endoftext|>


<commit_before>
var stream = require('stream'),
    util = require('util');

function ConsoleListener() {
    stream.Writable.call(this);
}

util.inherits(ConsoleListener, stream.Writable);

ConsoleListener.prototype._write = function (data) {
    var time = new Date();
    var j = JSON.parse(data.toString());
    console.log(util.inspect(j, false, 5, true));
};

module.exports = ConsoleListener;
<commit_msg>Fixing callback on console listener<commit_after>
var stream = require('stream'),
    util = require('util');

function ConsoleListener() {
    stream.Writable.call(this);
}

util.inherits(ConsoleListener, stream.Writable);

ConsoleListener.prototype._write = function (data, encoding, callback) {
    var time = new Date();
    var j = JSON.parse(data.toString());
    console.log('[' + time + '] ' + util.inspect(j, false, 5, true));
    callback();
};

module.exports = ConsoleListener;
<|endoftext|>


<commit_before>// Copyright (C) 2016 The Android Open Source Project
//
// 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';

  var DiffViewMode = {
    SIDE_BY_SIDE: 'SIDE_BY_SIDE',
    UNIFIED: 'UNIFIED_DIFF',
  };

  var DiffSide = {
    LEFT: 'left',
    RIGHT: 'right',
  };

  Polymer({
    is: 'gr-diff',

    /**
     * Fired when the user selects a line.
     * @event line-selected
     */

    properties: {
      changeNum: String,
      patchRange: Object,
      path: String,
      prefs: {
        type: Object,
        observer: '_prefsObserver',
      },
      projectConfig: {
        type: Object,
        observer: '_projectConfigChanged',
      },
      project: String,
      commit: String,
      isImageDiff: {
        type: Boolean,
        computed: '_computeIsImageDiff(_diff)',
        notify: true,
      },
      filesWeblinks: {
        type: Object,
        value: function() { return {}; },
        notify: true,
      },

      _loggedIn: {
        type: Boolean,
        value: false,
      },
      viewMode: {
        type: String,
        value: DiffViewMode.SIDE_BY_SIDE,
        observer: '_viewModeObserver',
      },
      _diff: Object,
      _comments: Object,
      _baseImage: Object,
      _revisionImage: Object,
    },

    listeners: {
      'thread-discard': '_handleThreadDiscard',
      'comment-discard': '_handleCommentDiscard',
      'comment-update': '_handleCommentUpdate',
      'comment-save': '_handleCommentSave',
      'create-comment': '_handleCreateComment',
    },

    attached: function() {
      this._getLoggedIn().then(function(loggedIn) {
        this._loggedIn = loggedIn;
      }.bind(this));
    },

    reload: function() {
      this._clearDiffContent();

      var promises = [];

      promises.push(this._getDiff().then(function(diff) {
        this._diff = diff;
        return this._loadDiffAssets();
      }.bind(this)));

      promises.push(this._getDiffCommentsAndDrafts().then(function(comments) {
        this._comments = comments;
      }.bind(this)));

      return Promise.all(promises).then(function() {
        if (this.prefs) {
          this._render();
        }
      }.bind(this));
    },

    getCursorStops: function() {
      if (this.hidden) {
        return [];
      }

      return Polymer.dom(this.root).querySelectorAll('.diff-row');
    },

    addDraftAtLine: function(el) {
      this._selectLine(el);
      this._getLoggedIn().then(function(loggedIn) {
        if (!loggedIn) { return; }

        var value = el.getAttribute('data-value');
        if (value === GrDiffLine.FILE) {
          this._addDraft(el);
          return;
        }
        var lineNum = parseInt(value, 10);
        if (isNaN(lineNum)) {
          throw Error('Invalid line number: ' + value);
        }
        this._addDraft(el, lineNum);
      }.bind(this));
    },

    isRangeSelected: function() {
      return this.$.highlights.isRangeSelected();
    },

    _getCommentThreads: function() {
      return Polymer.dom(this.root).querySelectorAll('gr-diff-comment-thread');
    },

    _computeContainerClass: function(loggedIn, viewMode) {
      var classes = ['diffContainer'];
      switch (viewMode) {
        case DiffViewMode.UNIFIED:
          classes.push('unified');
          break;
        case DiffViewMode.SIDE_BY_SIDE:
          classes.push('sideBySide');
          break;
        default:
          throw Error('Invalid view mode: ', viewMode);
      }
      if (loggedIn) {
        classes.push('canComment');
      }
      return classes.join(' ');
    },

    _handleTap: function(e) {
      var el = Polymer.dom(e).rootTarget;

      if (el.classList.contains('showContext')) {
        this.$.diffBuilder.showContext(e.detail.groups, e.detail.section);
      } else if (el.classList.contains('lineNum')) {
        this.addDraftAtLine(el);
      } if (el.tagName === 'HL' ||
          el.classList.contains('content') ||
          el.classList.contains('contentText')) {
        var target = this.$.diffBuilder.getLineElByChild(el);
        if (target) { this._selectLine(target); }
      }
    },

    _selectLine: function(el) {
      this.fire('line-selected', {
        side: el.classList.contains('left') ? DiffSide.LEFT : DiffSide.RIGHT,
        number: el.getAttribute('data-value'),
      });
    },

    _handleCreateComment: function(e) {
      var range = e.detail.range;
      var diffSide = e.detail.side;
      var line = range.endLine;
      var lineEl = this.$.diffBuilder.getLineElByNumber(line, diffSide);
      var contentText = this.$.diffBuilder.getContentByLineEl(lineEl);
      var contentEl = contentText.parentElement;
      var patchNum = this._getPatchNumByLineAndContent(lineEl, contentEl);
      var side = this._getSideByLineAndContent(lineEl, contentEl);
      var threadEl = this._getOrCreateThreadAtLine(contentEl, patchNum, side);

      threadEl.addDraft(line, range);
    },

    _addDraft: function(lineEl, opt_lineNum) {
      var contentText = this.$.diffBuilder.getContentByLineEl(lineEl);
      var contentEl = contentText.parentElement;
      var patchNum = this._getPatchNumByLineAndContent(lineEl, contentEl);
      var side = this._getSideByLineAndContent(lineEl, contentEl);
      var threadEl = this._getOrCreateThreadAtLine(contentEl, patchNum, side);

      threadEl.addOrEditDraft(opt_lineNum);
    },

    _getOrCreateThreadAtLine: function(contentEl, patchNum, side) {
      var threadEl = contentEl.querySelector('gr-diff-comment-thread');

      if (!threadEl) {
        threadEl = this.$.diffBuilder.createCommentThread(
            this.changeNum, patchNum, this.path, side, this.projectConfig);
        contentEl.appendChild(threadEl);
      }

      return threadEl;
    },

    _getPatchNumByLineAndContent: function(lineEl, contentEl) {
      var patchNum = this.patchRange.patchNum;
      if ((lineEl.classList.contains(DiffSide.LEFT) ||
          contentEl.classList.contains('remove')) &&
          this.patchRange.basePatchNum !== 'PARENT') {
        patchNum = this.patchRange.basePatchNum;
      }
      return patchNum;
    },

    _getSideByLineAndContent: function(lineEl, contentEl) {
      var side = 'REVISION';
      if ((lineEl.classList.contains(DiffSide.LEFT) ||
          contentEl.classList.contains('remove')) &&
          this.patchRange.basePatchNum === 'PARENT') {
        side = 'PARENT';
      }
      return side;
    },

    _handleThreadDiscard: function(e) {
      var el = Polymer.dom(e).rootTarget;
      el.parentNode.removeChild(el);
    },

    _handleCommentDiscard: function(e) {
      var comment = e.detail.comment;
      this._removeComment(comment, e.detail.patchNum);
    },

    _removeComment: function(comment, opt_patchNum) {
      var side = this._findCommentSide(comment, opt_patchNum);
      this._removeCommentFromSide(comment, side);
    },

    _findCommentSide: function(comment, opt_patchNum) {
      if (comment.side === 'PARENT') {
        return DiffSide.LEFT;
      } else {
        return this._comments.meta.patchRange.basePatchNum === opt_patchNum ?
            DiffSide.LEFT : DiffSide.RIGHT;
      }
    },

    _handleCommentSave: function(e) {
      var comment = e.detail.comment;
      var side = this._findCommentSide(comment, e.detail.patchNum);
      var idx = this._findDraftIndex(comment, side);
      this.set(['_comments', side, idx], comment);
    },

    _handleCommentUpdate: function(e) {
      var comment = e.detail.comment;
      var side = this._findCommentSide(comment, e.detail.patchNum);
      var idx = this._findCommentIndex(comment, side);
      if (idx === -1) {
        idx = this._findDraftIndex(comment, side);
      }
      if (idx !== -1) { // Update draft or comment.
        this.set(['_comments', side, idx], comment);
      } else { // Create new draft.
        this.push(['_comments', side], comment);
      }
    },

    _removeCommentFromSide: function(comment, side) {
      var idx = this._findCommentIndex(comment, side);
      if (idx === -1) {
        idx = this._findDraftIndex(comment, side);
      }
      if (idx !== -1) {
        this.splice('_comments.' + side, idx, 1);
      }
    },

    _findCommentIndex: function(comment, side) {
      if (!comment.id || !this._comments[side]) {
        return -1;
      }
      return this._comments[side].findIndex(function(item) {
        return item.id === comment.id;
      });
    },

    _findDraftIndex: function(comment, side) {
      if (!comment.__draftID || !this._comments[side]) {
        return -1;
      }
      return this._comments[side].findIndex(function(item) {
        return item.__draftID === comment.__draftID;
      });
    },

    _prefsObserver: function(newPrefs, oldPrefs) {
      // Scan the preference objects one level deep to see if they differ.
      var differ = !oldPrefs;
      if (newPrefs && oldPrefs) {
        for (var key in newPrefs) {
          if (newPrefs[key] !== oldPrefs[key]) {
            differ = true;
          }
        }
      }

      if (differ) {
        this._prefsChanged(newPrefs);
      }
    },

    _viewModeObserver: function() {
      this._prefsChanged(this.prefs);
    },

    _prefsChanged: function(prefs) {
      if (!prefs) { return; }
      this.customStyle['--content-width'] = prefs.line_length + 'ch';
      this.updateStyles();

      if (this._diff && this._comments) {
        this._render();
      }
    },

    _render: function() {
      this.$.diffBuilder.render(this._comments, this.prefs);
    },

    _clearDiffContent: function() {
      this.$.diffTable.innerHTML = null;
    },

    _handleGetDiffError: function(response) {
      this.fire('page-error', {response: response});
    },

    _getDiff: function() {
      return this.$.restAPI.getDiff(
          this.changeNum,
          this.patchRange.basePatchNum,
          this.patchRange.patchNum,
          this.path,
          this._handleGetDiffError.bind(this)).then(function(diff) {
               this.filesWeblinks = {
                 meta_a: diff.meta_a && diff.meta_a.web_links,
                 meta_b: diff.meta_b && diff.meta_b.web_links,
               };
               return diff;
             }.bind(this));
    },

    _getDiffComments: function() {
      return this.$.restAPI.getDiffComments(
          this.changeNum,
          this.patchRange.basePatchNum,
          this.patchRange.patchNum,
          this.path);
    },

    _getDiffDrafts: function() {
      return this._getLoggedIn().then(function(loggedIn) {
        if (!loggedIn) {
          return Promise.resolve({baseComments: [], comments: []});
        }
        return this.$.restAPI.getDiffDrafts(
            this.changeNum,
            this.patchRange.basePatchNum,
            this.patchRange.patchNum,
            this.path);
      }.bind(this));
    },

    _getDiffCommentsAndDrafts: function() {
      var promises = [];
      promises.push(this._getDiffComments());
      promises.push(this._getDiffDrafts());
      return Promise.all(promises).then(function(results) {
        return Promise.resolve({
          comments: results[0],
          drafts: results[1],
        });
      }).then(this._normalizeDiffCommentsAndDrafts.bind(this));
    },

    _normalizeDiffCommentsAndDrafts: function(results) {
      function markAsDraft(d) {
        d.__draft = true;
        return d;
      }
      var baseDrafts = results.drafts.baseComments.map(markAsDraft);
      var drafts = results.drafts.comments.map(markAsDraft);
      return Promise.resolve({
        meta: {
          path: this.path,
          changeNum: this.changeNum,
          patchRange: this.patchRange,
          projectConfig: this.projectConfig,
        },
        left: results.comments.baseComments.concat(baseDrafts),
        right: results.comments.comments.concat(drafts),
      });
    },

    _getLoggedIn: function() {
      return this.$.restAPI.getLoggedIn();
    },

    _computeIsImageDiff: function() {
      if (!this._diff) { return false; }

      var isA = this._diff.meta_a &&
          this._diff.meta_a.content_type.indexOf('image/') === 0;
      var isB = this._diff.meta_b &&
          this._diff.meta_b.content_type.indexOf('image/') === 0;

      return this._diff.binary && (isA || isB);
    },

    _loadDiffAssets: function() {
      if (this.isImageDiff) {
        return this._getImages().then(function(images) {
          this._baseImage = images.baseImage;
          this._revisionImage = images.revisionImage;
        }.bind(this));
      } else {
        this._baseImage = null;
        this._revisionImage = null;
        return Promise.resolve();
      }
    },

    _getImages: function() {
      return this.$.restAPI.getImagesForDiff(this.project, this.commit,
          this.changeNum, this._diff, this.patchRange);
    },

    _projectConfigChanged: function(projectConfig) {
      var threadEls = this._getCommentThreads();
      for (var i = 0; i < threadEls.length; i++) {
        threadEls[i].projectConfig = projectConfig;
      }
    },
  });
})();
<commit_msg>Fixes an if-else chain<commit_after>// Copyright (C) 2016 The Android Open Source Project
//
// 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';

  var DiffViewMode = {
    SIDE_BY_SIDE: 'SIDE_BY_SIDE',
    UNIFIED: 'UNIFIED_DIFF',
  };

  var DiffSide = {
    LEFT: 'left',
    RIGHT: 'right',
  };

  Polymer({
    is: 'gr-diff',

    /**
     * Fired when the user selects a line.
     * @event line-selected
     */

    properties: {
      changeNum: String,
      patchRange: Object,
      path: String,
      prefs: {
        type: Object,
        observer: '_prefsObserver',
      },
      projectConfig: {
        type: Object,
        observer: '_projectConfigChanged',
      },
      project: String,
      commit: String,
      isImageDiff: {
        type: Boolean,
        computed: '_computeIsImageDiff(_diff)',
        notify: true,
      },
      filesWeblinks: {
        type: Object,
        value: function() { return {}; },
        notify: true,
      },

      _loggedIn: {
        type: Boolean,
        value: false,
      },
      viewMode: {
        type: String,
        value: DiffViewMode.SIDE_BY_SIDE,
        observer: '_viewModeObserver',
      },
      _diff: Object,
      _comments: Object,
      _baseImage: Object,
      _revisionImage: Object,
    },

    listeners: {
      'thread-discard': '_handleThreadDiscard',
      'comment-discard': '_handleCommentDiscard',
      'comment-update': '_handleCommentUpdate',
      'comment-save': '_handleCommentSave',
      'create-comment': '_handleCreateComment',
    },

    attached: function() {
      this._getLoggedIn().then(function(loggedIn) {
        this._loggedIn = loggedIn;
      }.bind(this));
    },

    reload: function() {
      this._clearDiffContent();

      var promises = [];

      promises.push(this._getDiff().then(function(diff) {
        this._diff = diff;
        return this._loadDiffAssets();
      }.bind(this)));

      promises.push(this._getDiffCommentsAndDrafts().then(function(comments) {
        this._comments = comments;
      }.bind(this)));

      return Promise.all(promises).then(function() {
        if (this.prefs) {
          this._render();
        }
      }.bind(this));
    },

    getCursorStops: function() {
      if (this.hidden) {
        return [];
      }

      return Polymer.dom(this.root).querySelectorAll('.diff-row');
    },

    addDraftAtLine: function(el) {
      this._selectLine(el);
      this._getLoggedIn().then(function(loggedIn) {
        if (!loggedIn) { return; }

        var value = el.getAttribute('data-value');
        if (value === GrDiffLine.FILE) {
          this._addDraft(el);
          return;
        }
        var lineNum = parseInt(value, 10);
        if (isNaN(lineNum)) {
          throw Error('Invalid line number: ' + value);
        }
        this._addDraft(el, lineNum);
      }.bind(this));
    },

    isRangeSelected: function() {
      return this.$.highlights.isRangeSelected();
    },

    _getCommentThreads: function() {
      return Polymer.dom(this.root).querySelectorAll('gr-diff-comment-thread');
    },

    _computeContainerClass: function(loggedIn, viewMode) {
      var classes = ['diffContainer'];
      switch (viewMode) {
        case DiffViewMode.UNIFIED:
          classes.push('unified');
          break;
        case DiffViewMode.SIDE_BY_SIDE:
          classes.push('sideBySide');
          break;
        default:
          throw Error('Invalid view mode: ', viewMode);
      }
      if (loggedIn) {
        classes.push('canComment');
      }
      return classes.join(' ');
    },

    _handleTap: function(e) {
      var el = Polymer.dom(e).rootTarget;

      if (el.classList.contains('showContext')) {
        this.$.diffBuilder.showContext(e.detail.groups, e.detail.section);
      } else if (el.classList.contains('lineNum')) {
        this.addDraftAtLine(el);
      } else if (el.tagName === 'HL' ||
          el.classList.contains('content') ||
          el.classList.contains('contentText')) {
        var target = this.$.diffBuilder.getLineElByChild(el);
        if (target) { this._selectLine(target); }
      }
    },

    _selectLine: function(el) {
      this.fire('line-selected', {
        side: el.classList.contains('left') ? DiffSide.LEFT : DiffSide.RIGHT,
        number: el.getAttribute('data-value'),
      });
    },

    _handleCreateComment: function(e) {
      var range = e.detail.range;
      var diffSide = e.detail.side;
      var line = range.endLine;
      var lineEl = this.$.diffBuilder.getLineElByNumber(line, diffSide);
      var contentText = this.$.diffBuilder.getContentByLineEl(lineEl);
      var contentEl = contentText.parentElement;
      var patchNum = this._getPatchNumByLineAndContent(lineEl, contentEl);
      var side = this._getSideByLineAndContent(lineEl, contentEl);
      var threadEl = this._getOrCreateThreadAtLine(contentEl, patchNum, side);

      threadEl.addDraft(line, range);
    },

    _addDraft: function(lineEl, opt_lineNum) {
      var contentText = this.$.diffBuilder.getContentByLineEl(lineEl);
      var contentEl = contentText.parentElement;
      var patchNum = this._getPatchNumByLineAndContent(lineEl, contentEl);
      var side = this._getSideByLineAndContent(lineEl, contentEl);
      var threadEl = this._getOrCreateThreadAtLine(contentEl, patchNum, side);

      threadEl.addOrEditDraft(opt_lineNum);
    },

    _getOrCreateThreadAtLine: function(contentEl, patchNum, side) {
      var threadEl = contentEl.querySelector('gr-diff-comment-thread');

      if (!threadEl) {
        threadEl = this.$.diffBuilder.createCommentThread(
            this.changeNum, patchNum, this.path, side, this.projectConfig);
        contentEl.appendChild(threadEl);
      }

      return threadEl;
    },

    _getPatchNumByLineAndContent: function(lineEl, contentEl) {
      var patchNum = this.patchRange.patchNum;
      if ((lineEl.classList.contains(DiffSide.LEFT) ||
          contentEl.classList.contains('remove')) &&
          this.patchRange.basePatchNum !== 'PARENT') {
        patchNum = this.patchRange.basePatchNum;
      }
      return patchNum;
    },

    _getSideByLineAndContent: function(lineEl, contentEl) {
      var side = 'REVISION';
      if ((lineEl.classList.contains(DiffSide.LEFT) ||
          contentEl.classList.contains('remove')) &&
          this.patchRange.basePatchNum === 'PARENT') {
        side = 'PARENT';
      }
      return side;
    },

    _handleThreadDiscard: function(e) {
      var el = Polymer.dom(e).rootTarget;
      el.parentNode.removeChild(el);
    },

    _handleCommentDiscard: function(e) {
      var comment = e.detail.comment;
      this._removeComment(comment, e.detail.patchNum);
    },

    _removeComment: function(comment, opt_patchNum) {
      var side = this._findCommentSide(comment, opt_patchNum);
      this._removeCommentFromSide(comment, side);
    },

    _findCommentSide: function(comment, opt_patchNum) {
      if (comment.side === 'PARENT') {
        return DiffSide.LEFT;
      } else {
        return this._comments.meta.patchRange.basePatchNum === opt_patchNum ?
            DiffSide.LEFT : DiffSide.RIGHT;
      }
    },

    _handleCommentSave: function(e) {
      var comment = e.detail.comment;
      var side = this._findCommentSide(comment, e.detail.patchNum);
      var idx = this._findDraftIndex(comment, side);
      this.set(['_comments', side, idx], comment);
    },

    _handleCommentUpdate: function(e) {
      var comment = e.detail.comment;
      var side = this._findCommentSide(comment, e.detail.patchNum);
      var idx = this._findCommentIndex(comment, side);
      if (idx === -1) {
        idx = this._findDraftIndex(comment, side);
      }
      if (idx !== -1) { // Update draft or comment.
        this.set(['_comments', side, idx], comment);
      } else { // Create new draft.
        this.push(['_comments', side], comment);
      }
    },

    _removeCommentFromSide: function(comment, side) {
      var idx = this._findCommentIndex(comment, side);
      if (idx === -1) {
        idx = this._findDraftIndex(comment, side);
      }
      if (idx !== -1) {
        this.splice('_comments.' + side, idx, 1);
      }
    },

    _findCommentIndex: function(comment, side) {
      if (!comment.id || !this._comments[side]) {
        return -1;
      }
      return this._comments[side].findIndex(function(item) {
        return item.id === comment.id;
      });
    },

    _findDraftIndex: function(comment, side) {
      if (!comment.__draftID || !this._comments[side]) {
        return -1;
      }
      return this._comments[side].findIndex(function(item) {
        return item.__draftID === comment.__draftID;
      });
    },

    _prefsObserver: function(newPrefs, oldPrefs) {
      // Scan the preference objects one level deep to see if they differ.
      var differ = !oldPrefs;
      if (newPrefs && oldPrefs) {
        for (var key in newPrefs) {
          if (newPrefs[key] !== oldPrefs[key]) {
            differ = true;
          }
        }
      }

      if (differ) {
        this._prefsChanged(newPrefs);
      }
    },

    _viewModeObserver: function() {
      this._prefsChanged(this.prefs);
    },

    _prefsChanged: function(prefs) {
      if (!prefs) { return; }
      this.customStyle['--content-width'] = prefs.line_length + 'ch';
      this.updateStyles();

      if (this._diff && this._comments) {
        this._render();
      }
    },

    _render: function() {
      this.$.diffBuilder.render(this._comments, this.prefs);
    },

    _clearDiffContent: function() {
      this.$.diffTable.innerHTML = null;
    },

    _handleGetDiffError: function(response) {
      this.fire('page-error', {response: response});
    },

    _getDiff: function() {
      return this.$.restAPI.getDiff(
          this.changeNum,
          this.patchRange.basePatchNum,
          this.patchRange.patchNum,
          this.path,
          this._handleGetDiffError.bind(this)).then(function(diff) {
               this.filesWeblinks = {
                 meta_a: diff.meta_a && diff.meta_a.web_links,
                 meta_b: diff.meta_b && diff.meta_b.web_links,
               };
               return diff;
             }.bind(this));
    },

    _getDiffComments: function() {
      return this.$.restAPI.getDiffComments(
          this.changeNum,
          this.patchRange.basePatchNum,
          this.patchRange.patchNum,
          this.path);
    },

    _getDiffDrafts: function() {
      return this._getLoggedIn().then(function(loggedIn) {
        if (!loggedIn) {
          return Promise.resolve({baseComments: [], comments: []});
        }
        return this.$.restAPI.getDiffDrafts(
            this.changeNum,
            this.patchRange.basePatchNum,
            this.patchRange.patchNum,
            this.path);
      }.bind(this));
    },

    _getDiffCommentsAndDrafts: function() {
      var promises = [];
      promises.push(this._getDiffComments());
      promises.push(this._getDiffDrafts());
      return Promise.all(promises).then(function(results) {
        return Promise.resolve({
          comments: results[0],
          drafts: results[1],
        });
      }).then(this._normalizeDiffCommentsAndDrafts.bind(this));
    },

    _normalizeDiffCommentsAndDrafts: function(results) {
      function markAsDraft(d) {
        d.__draft = true;
        return d;
      }
      var baseDrafts = results.drafts.baseComments.map(markAsDraft);
      var drafts = results.drafts.comments.map(markAsDraft);
      return Promise.resolve({
        meta: {
          path: this.path,
          changeNum: this.changeNum,
          patchRange: this.patchRange,
          projectConfig: this.projectConfig,
        },
        left: results.comments.baseComments.concat(baseDrafts),
        right: results.comments.comments.concat(drafts),
      });
    },

    _getLoggedIn: function() {
      return this.$.restAPI.getLoggedIn();
    },

    _computeIsImageDiff: function() {
      if (!this._diff) { return false; }

      var isA = this._diff.meta_a &&
          this._diff.meta_a.content_type.indexOf('image/') === 0;
      var isB = this._diff.meta_b &&
          this._diff.meta_b.content_type.indexOf('image/') === 0;

      return this._diff.binary && (isA || isB);
    },

    _loadDiffAssets: function() {
      if (this.isImageDiff) {
        return this._getImages().then(function(images) {
          this._baseImage = images.baseImage;
          this._revisionImage = images.revisionImage;
        }.bind(this));
      } else {
        this._baseImage = null;
        this._revisionImage = null;
        return Promise.resolve();
      }
    },

    _getImages: function() {
      return this.$.restAPI.getImagesForDiff(this.project, this.commit,
          this.changeNum, this._diff, this.patchRange);
    },

    _projectConfigChanged: function(projectConfig) {
      var threadEls = this._getCommentThreads();
      for (var i = 0; i < threadEls.length; i++) {
        threadEls[i].projectConfig = projectConfig;
      }
    },
  });
})();
<|endoftext|>


<commit_before>function Recipe(attributes) {
  this.name = attributes.name;
  this.content = attributes.content;
  this.id = attributes.id;
  this.ingredients = attributes.ingredients;
}

Recipe.templateSource = $('#recipe-template').html()
Recipe.template = Handlebars.compile(Recipe.templateSource);

Recipe.prototype.renderDisplay = function() {

}

$(function () {
  $('form#new_recipe').submit(function(event) {
    event.preventDefault();
    var $form = $(this);
    var action = $form.attr("action");
    var params = $form.serialize();
    var posting = $.post(action, params);

      posting.success(function(data) {
        var recipe = new Recipe(data);
        var recipeDisplay = recipe.renderDisplay()

        var recipe = data["recipe"];
        $("#recipeName").text(recipe["name"]);
        $("#recipeContent").text(recipe["content"])
      }) .error(function(response) {
          console.log("Error!", response)
      })
    });
  });
<commit_msg>move handlebars recipe template variables to doument cready<commit_after>function Recipe(attributes) {
  this.name = attributes.name;
  this.content = attributes.content;
  this.id = attributes.id;
  this.ingredients = attributes.ingredients;
}

$(function() {
  Recipe.templateSource = $('#recipe-template').html()
  Recipe.template = Handlebars.compile(Recipe.templateSource);
})

Recipe.prototype.renderDisplay = function() {

}

$(function () {
  $('form#new_recipe').submit(function(event) {
    event.preventDefault();
    var $form = $(this);
    var action = $form.attr("action");
    var params = $form.serialize();
    var posting = $.post(action, params);

      posting.success(function(data) {
        var recipe = new Recipe(data);
        var recipeDisplay = recipe.renderDisplay()

        var recipe = data["recipe"];
        $("#recipeName").text(recipe["name"]);
        $("#recipeContent").text(recipe["content"])
      }) .error(function(response) {
          console.log("Error!", response)
      })
    });
  });
<|endoftext|>


<commit_before>'use strict';

const url2Domain = require('./ext/url2domain');
const credibleSources = require('./data/credible');
const notCredibleSources = require('./data/notCredible');

module.exports.check = (event, context, callback) => {
	const origin = (event.queryStringParameters) ? event.queryStringParameters.__amp_source_origin : '*';
	const articleUrl = (event.queryStringParameters) ? event.queryStringParameters.url : '';
	const domain = url2Domain(articleUrl);

	const response = {
		statusCode: 200,
		headers: {
			'Access-Control-Allow-Credentials': true,
			'Access-Control-Allow-Origin': origin,
			'AMP-Access-Control-Allow-Source-Origin': origin,
			'Access-Control-Expose-Headers': 'AMP-Access-Control-Allow-Source-Origin'
		},
		body: JSON.stringify({
			url: articleUrl,
			score: '¯\\_(ツ)_/¯',
			meta: {
				opensources: {
					redFlag: (notCredibleSources[domain]) ? notCredibleSources[domain] : false,
					credible: credibleSources.some(source => source.url === domain)
				}
			}
		})
	};

	callback(null, response);
};
<commit_msg>Update response to match swagger spec<commit_after>'use strict';

const url2Domain = require('./ext/url2domain');
const credibleSources = require('./data/credible');
const notCredibleSources = require('./data/notCredible');

module.exports.check = (event, context, callback) => {
	const origin = (event.queryStringParameters) ? event.queryStringParameters.__amp_source_origin : '*';
	const articleUrl = (event.queryStringParameters) ? event.queryStringParameters.url : '';
	const domain = url2Domain(articleUrl);

	const response = {
		statusCode: 200,
		headers: {
			'Access-Control-Allow-Credentials': true,
			'Access-Control-Allow-Origin': origin,
			'AMP-Access-Control-Allow-Source-Origin': origin,
			'Access-Control-Expose-Headers': 'AMP-Access-Control-Allow-Source-Origin'
		},
		body: JSON.stringify({
			url: articleUrl,
			score: '¯\\_(ツ)_/¯', // TODO: implement score
			criteria: {
				opensources: {
					flag: (notCredibleSources[domain]) ? true : false,
					type: (notCredibleSources[domain]) ? notCredibleSources[domain].type : null,
					credible: credibleSources.some(source => source.url === domain)
				}
			}
		})
	};

	callback(null, response);
};
<|endoftext|>


<commit_before>export default function visitYieldTag ( generator, block, state ) {
	block.builders.mount.addLine(
		`${block.component}._yield && ${block.component}._yield.mount( ${state.parentNode || block.target}, null );`
	);

	block.builders.destroy.addLine(
		`${block.component}._yield && ${block.component}._yield.destroy( detach );`
	);
}<commit_msg>mount yield blocks immediately, if yield has a parent node (fixes #561)<commit_after>export default function visitYieldTag ( generator, block, state ) {
	const parentNode = state.parentNode || block.target;

	( state.parentNode ? block.builders.create : block.builders.mount ).addLine(
		`if ( ${block.component}._yield ) ${block.component}._yield.mount( ${parentNode}, null );`
	);

	block.builders.destroy.addLine(
		`if ( ${block.component}._yield ) ${block.component}._yield.destroy( detach );`
	);
}<|endoftext|>


<commit_before>
var launches = new Firebase("https://gonzo1234.firebaseio.com/launches");

var model = {

    rests : {
        "0": { "lat": 32.108880, "lng": 34.839711, "name": "פלאפל רצון", "pic_url": "https://s3-eu-west-1.amazonaws.com/uploads-eu.hipchat.com/20405/1377403/De0pKwdsXiYnQug/1249731-5.jpg"},
        "1": { "lat": 32.109246, "lng": 34.840262, "name": "כלביה", "pic_url": "https://s3-eu-west-1.amazonaws.com/uploads-eu.hipchat.com/20405/1377403/Njh1PyTa13R65sC/images.jpeg"},
        "2": { "lat": 32.107515, "lng": 34.837325, "name": "חתוליה", "pic_url": "https://s3-eu-west-1.amazonaws.com/uploads-eu.hipchat.com/20405/1377403/DP617N3jaeTA9VT/2_wa.jpg"},
        "3": { "lat": 32.106909, "lng": 34.836031, "name": "המסעדה של צחי", "pic_url": "https://s3-eu-west-1.amazonaws.com/uploads-eu.hipchat.com/20405/1377403/QUkmSwI27A0AbZC/tsachi.jpg"}
    },

    drivers : {
        "0":  { "driver_name":"ISIS",         "driver_id":"1", "pic_url":"https://s3-eu-west-1.amazonaws.com/uploads-eu.hipchat.com/20405/1377403/FRDFYXChw8u3HKZ/Screen%20Shot%202016-01-20%20at%2015.47.49.png"},
        "1":  { "driver_name":"AlexeyLO",     "driver_id":"2", "pic_url":"https://s3-eu-west-1.amazonaws.com/uploads-eu.hipchat.com/20405/1377403/5k2JqyXETopEdIf/upload.jpg"},
        "2":  { "driver_name":"Ohad DDOS",    "driver_id":"3", "pic_url":"https://s3-eu-west-1.amazonaws.com/uploads-eu.hipchat.com/20405/1377403/5743zvmn9PoQUoF/ohad.jpg"},
        "3":  { "driver_name":"Prison Break", "driver_id":"4", "pic_url":"https://s3-eu-west-1.amazonaws.com/uploads-eu.hipchat.com/20405/1377403/v94BUIvb5CaPe1h/Screen%20Shot%202016-01-20%20at%2016.08.44.png"},
        "4":  { "driver_name":"Rambo",        "driver_id":"5", "pic_url":"https://s3-eu-west-1.amazonaws.com/uploads-eu.hipchat.com/20405/1377403/Mk1tGd5JDCKx5qv/Screen%20Shot%202016-01-20%20at%2016.00.03.png"}
    },

    addLaunch: function (rest_id, time){
        launches.push({
            "rest_id": rest_id,
            'time': time,
        })
    },

    onLaunchChange: function(cb) {
        launches.child("/").on("value", cb);
        console.log("event registered")
    },

    joinLaunch: function(lunch_id, driver_id) {

        var obj = {};
        obj[driver_id] = "I'll join";

        debugger
        launches.child("/" + lunch_id).push(obj);
    }

};

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

model.onLaunchChange(function(snapshot){
    console.log("event triggered");
    var lunches = snapshot.val();

    var container = $(".lunches");
    container.text("");
    $.each(lunches, function(id, data) {
        var participants = [];
        $.each(data, function(id, text){
            participants.push(id);
        });
        console.log(participants);
        container.append("
" + id + " - " + participants + "
");
        container.append("
");
    });

});

<commit_msg>השיפוד החלוד<commit_after>
var launches = new Firebase("https://gonzo1234.firebaseio.com/launches");

var model = {

    rests : {
        "0": { "lat": 32.108880, "lng": 34.839711, "name": "חתוליה", "pic_url": "https://s3-eu-west-1.amazonaws.com/uploads-eu.hipchat.com/20405/1377403/De0pKwdsXiYnQug/1249731-5.jpg"},
        "1": { "lat": 32.109246, "lng": 34.840262, "name": "כלביה", "pic_url": "https://s3-eu-west-1.amazonaws.com/uploads-eu.hipchat.com/20405/1377403/Njh1PyTa13R65sC/images.jpeg"},
        "2": { "lat": 32.107515, "lng": 34.837325, "name": "השיפוד החלוד", "pic_url": "https://s3-eu-west-1.amazonaws.com/uploads-eu.hipchat.com/20405/1377403/DP617N3jaeTA9VT/2_wa.jpg"},
        "3": { "lat": 32.106909, "lng": 34.836031, "name": "המסעדה של צחי", "pic_url": "https://s3-eu-west-1.amazonaws.com/uploads-eu.hipchat.com/20405/1377403/QUkmSwI27A0AbZC/tsachi.jpg"}
    },

    drivers : {
        "0":  { "driver_name":"ISIS",         "driver_id":"1", "pic_url":"https://s3-eu-west-1.amazonaws.com/uploads-eu.hipchat.com/20405/1377403/FRDFYXChw8u3HKZ/Screen%20Shot%202016-01-20%20at%2015.47.49.png"},
        "1":  { "driver_name":"AlexeyLO",     "driver_id":"2", "pic_url":"https://s3-eu-west-1.amazonaws.com/uploads-eu.hipchat.com/20405/1377403/5k2JqyXETopEdIf/upload.jpg"},
        "2":  { "driver_name":"Ohad DDOS",    "driver_id":"3", "pic_url":"https://s3-eu-west-1.amazonaws.com/uploads-eu.hipchat.com/20405/1377403/5743zvmn9PoQUoF/ohad.jpg"},
        "3":  { "driver_name":"Prison Break", "driver_id":"4", "pic_url":"https://s3-eu-west-1.amazonaws.com/uploads-eu.hipchat.com/20405/1377403/v94BUIvb5CaPe1h/Screen%20Shot%202016-01-20%20at%2016.08.44.png"},
        "4":  { "driver_name":"Rambo",        "driver_id":"5", "pic_url":"https://s3-eu-west-1.amazonaws.com/uploads-eu.hipchat.com/20405/1377403/Mk1tGd5JDCKx5qv/Screen%20Shot%202016-01-20%20at%2016.00.03.png"}
    },

    addLaunch: function (rest_id, time){
        launches.push({
            "rest_id": rest_id,
            'time': time,
        })
    },

    onLaunchChange: function(cb) {
        launches.child("/").on("value", cb);
        console.log("event registered")
    },

    joinLaunch: function(lunch_id, driver_id) {

        var obj = {};
        obj[driver_id] = "I'll join";

        debugger
        launches.child("/" + lunch_id).push(obj);
    }

};

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

model.onLaunchChange(function(snapshot){
    console.log("event triggered");
    var lunches = snapshot.val();

    var container = $(".lunches");
    container.text("");
    $.each(lunches, function(id, data) {
        var participants = [];
        $.each(data, function(id, text){
            participants.push(id);
        });
        console.log(participants);
        container.append("
" + id + " - " + participants + "
");
        container.append("
");
    });

});

<|endoftext|>


<commit_before>import React, { Component } from "react";

export default class TextContentEditor extends Component {
  static propTypes = {
    isEditing: React.PropTypes.bool,
    placeholderText: React.PropTypes.string,
    contentClass: React.PropTypes.string,
    editorClass: React.PropTypes.string,
    lineClass: React.PropTypes.string,
    componentProps: React.PropTypes.object,
    style: React.PropTypes.object,
    content: React.PropTypes.string
  }

  render() {
    const {
      editorClass,
      lineClass,
      componentProps,
      isEditing,
      contentClass,
      placeholderText,
      style,
      content
    } = this.props;

    return isEditing ?
      (
 {this.editable = component;}}
        {...componentProps}
        className={`${contentClass} ${editorClass}`}
        style={{ ...style, ...{ whiteSpace: "pre-wrap" } }}
      >
        {content !== null ?
          content
          :
          placeholderText
        }

)
      :
      (

        {content !== null ?
          content.split("\n").map((line, i) => (

              {line}

)
          )
          :
          placeholderText
        }

);
  }
}

<commit_msg>remove nesting spread operator<commit_after>import React, { Component } from "react";

export default class TextContentEditor extends Component {
  static propTypes = {
    isEditing: React.PropTypes.bool,
    placeholderText: React.PropTypes.string,
    contentClass: React.PropTypes.string,
    editorClass: React.PropTypes.string,
    lineClass: React.PropTypes.string,
    componentProps: React.PropTypes.object,
    style: React.PropTypes.object,
    content: React.PropTypes.string
  }

  render() {
    const {
      editorClass,
      lineClass,
      componentProps,
      isEditing,
      contentClass,
      placeholderText,
      style,
      content
    } = this.props;

    return isEditing ?
      (
 {this.editable = component;}}
        {...componentProps}
        className={`${contentClass} ${editorClass}`}
        style={{ ...style, whiteSpace: "pre-wrap" }}
      >
        {content !== null ?
          content
          :
          placeholderText
        }

)
      :
      (

        {content !== null ?
          content.split("\n").map((line, i) => (

              {line}

)
          )
          :
          placeholderText
        }

);
  }
}

<|endoftext|>


<commit_before>import React from 'react';
import {Route} from 'react-router';
import configure from './configure';
import warning from './utils/warning';
import requireModuleDefault from './utils/requireModuleDefault';
import CatalogContext from './components/CatalogContext';
import PageContent from './components/Page/PageContent';

const fetchText = (url) =>
  fetch(url, {credentials: 'same-origin'})
    .then((response) => response.text());

const pageComponent = (page) => {
  if (page.content) {
    return (props) => <PageContent {...props} contentPromiseFn={page.content} />;
  }
  if (page.src) {
    return (props) => <PageContent {...props} contentPromiseFn={() => fetchText(page.src)} />;
  }
  if (page.component) {
    return (props) => <PageContent {...props} contentPromiseFn={() => Promise.resolve(requireModuleDefault(page.component))} />;
  }

  return () => (

      pageComponent: Wrong page configuration: neither content, src, nor component was specified.

  );
};

const pageToRoute = (page) => ({
  component: pageComponent(page),
  path: page.path
});

const pageToJSXRoute = (page) =>
  <Route key={page.path} path={page.path} component={pageComponent(page)} />; // eslint-disable-line react/prop-types

const autoConfigure = (config) => {
  warning(
    !config.__catalogConfig,
    'The `configure` function is deprecated; use `configureRoutes` or `configureJSXRoutes` directly.'
  );

  return config.__catalogConfig ? config : configure(config);
};

export default (config) => {
  const finalConfig = autoConfigure(config);
  return {
    component: CatalogContext(finalConfig),
    childRoutes: finalConfig.pages.map(pageToRoute)
  };
};

export const configureJSXRoutes = (config) => {
  const finalConfig = autoConfigure(config);
  return (
    <Route component={CatalogContext(finalConfig)}>
      {finalConfig.pages.map(pageToJSXRoute)}
    </Route>
  );
};
<commit_msg>Use the new content constructors to handle legacy src/component page types<commit_after>import React from 'react';
import {Route} from 'react-router';
import configure from './configure';
import warning from './utils/warning';
import requireModuleDefault from './utils/requireModuleDefault';
import CatalogContext from './components/CatalogContext';
import PageContent from './components/Page/PageContent';
import {fetchMarkdown, reactComponent} from './content';

const pageComponent = (page) => {
  if (page.content) {
    return (props) => <PageContent {...props} contentPromiseFn={page.content} />;
  }
  if (page.src) {
    return (props) => <PageContent {...props} contentPromiseFn={fetchMarkdown(page.src)} />;
  }
  if (page.component) {
    return (props) => <PageContent {...props} contentPromiseFn={reactComponent(requireModuleDefault(page.component))} />;
  }

  return () => (

      pageComponent: Wrong page configuration: neither content, src, nor component was specified.

  );
};

const pageToRoute = (page) => ({
  component: pageComponent(page),
  path: page.path
});

const pageToJSXRoute = (page) =>
  <Route key={page.path} path={page.path} component={pageComponent(page)} />; // eslint-disable-line react/prop-types

const autoConfigure = (config) => {
  warning(
    !config.__catalogConfig,
    'The `configure` function is deprecated; use `configureRoutes` or `configureJSXRoutes` directly.'
  );

  return config.__catalogConfig ? config : configure(config);
};

export default (config) => {
  const finalConfig = autoConfigure(config);
  return {
    component: CatalogContext(finalConfig),
    childRoutes: finalConfig.pages.map(pageToRoute)
  };
};

export const configureJSXRoutes = (config) => {
  const finalConfig = autoConfigure(config);
  return (
    <Route component={CatalogContext(finalConfig)}>
      {finalConfig.pages.map(pageToJSXRoute)}
    </Route>
  );
};
<|endoftext|>


<commit_before>var colors = [
	['#D0E78F', '#F6B759','#EC432E', '#9AD2E2', '#584050', '#2D4C7A'],
	['#C9E8EB', '#54DCE8', '#2792D6', '#E0D2D2', '#254540', '#F3EBE8'],
	['#EEE0C6', '#F0A48A', '#6A917C', '#A4C9A7', '#CCE6CB', '#3E3634'],
	['#E9E7EC', '#F8DEDD', '#FACC74', '#FD8C6A', '#D14747', '#B6D4A2'],
	['#FDC680', '#D9654C', '#6195A0', '#C9C9C9', '#422F21', '#68275D']
];

function randomFrom(min, max) {
	return Math.floor(Math.random() * (max - min + 1) + min);
}

function randomizeColor() {
	var randomColors = colors[randomFrom(0, colors.length - 1)];

	$('.color-space').each(function(i) {
		var delay = 900;
		$(this).css('background-color', randomColors[i]).delay('slow').fadeIn(delay * i);
	});
}

Template.colors.rendered = function () {
	randomizeColor();
};
<commit_msg>tweaked fade-in<commit_after>var colors = [
	['#D0E78F', '#F6B759','#EC432E', '#9AD2E2', '#584050', '#2D4C7A'],
	['#C9E8EB', '#54DCE8', '#2792D6', '#E0D2D2', '#254540', '#F3EBE8'],
	['#EEE0C6', '#F0A48A', '#6A917C', '#A4C9A7', '#CCE6CB', '#3E3634'],
	['#E9E7EC', '#F8DEDD', '#FACC74', '#FD8C6A', '#D14747', '#B6D4A2'],
	['#FDC680', '#D9654C', '#6195A0', '#C9C9C9', '#422F21', '#68275D']
];

function randomFrom(min, max) {
	return Math.floor(Math.random() * (max - min + 1) + min);
}

function randomizeColor() {
	var randomColors = colors[randomFrom(0, colors.length - 1)];

	$('.color-space').each(function(i) {
		var delay = 500;
		$(this).css('background-color', randomColors[i]).delay(delay * i).fadeIn('slow');
	});
}

Template.colors.rendered = function () {
	randomizeColor();
};
<|endoftext|>


<commit_before>$(document).on('page:change', function() {

  $.ajax({
    url: '/filters?by_type_of=Rental',
    type: 'GET',
    dataType: 'JSON'
  })
  .done(function(data) {

    function initialize() {
      var options = {
        center: new google.maps.LatLng(40.650002, -73.949997),
        zoom: 12,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };

      var map = new google.maps.Map(document.getElementById("map-canvas"), options);

      var marker, i;

      for (var i = 0; i < data.length; i++) {
        marker = new google.maps.Marker({
          position: new google.maps.LatLng(data[i].latitude, data[i].longitude),
          map: map
        });
        marker.setMap(map);
      }
    }

    google.maps.event.addDomListener(window, 'load', initialize);

    var source = $("#listing_preview_template").html();
    var templatingFunction = Handlebars.compile(source);
    var context = {};
    context.match = data;

    if (data.length === 0) {
      $(".matches-wrapper").text("No matches found. Consider expanding your search restrictions.");
    } else {
      $(".matches-wrapper").text("");
      $(".matches-wrapper").append(templatingFunction(context));
    };

  });

});

// Helper method for handlebars conditional
Handlebars.registerHelper('if_all', function() {
    var args = [].slice.apply(arguments);
    var opts = args.pop();

    var fn = opts.fn;
    for(var i = 0; i < args.length; ++i) {
        if(args[i])
            continue;
        fn = opts.inverse;
        break;
    }
    return fn(this);
});<commit_msg>Attempt to pin markers to map<commit_after>$(document).on('page:change', function() {

  $.ajax({
    url: '/filters?by_type_of=Rental',
    type: 'GET',
    dataType: 'JSON'
  })
  .done(function(data) {

    var source = $("#listing_preview_template").html();
    var templatingFunction = Handlebars.compile(source);
    var context = {};
    context.match = data;

    if (data.length === 0) {
      $(".matches-wrapper").text("No matches found. Consider expanding your search restrictions.");
    } else {
      $(".matches-wrapper").text("");
      $(".matches-wrapper").append(templatingFunction(context));
    };

  })

  var $listingIds = []
  var $listingArr = $('.matches-wrapper').children().children()

  for (var i = 0; i < $listingArr.length; i++) {
    $listingId = $listingArr[i].attr("data-listing-id");
    $listingIds.push($listingId);
  }

  function initialize() {
    var options = {
      center: new google.maps.LatLng(40.650002, -73.949997),
      zoom: 12,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(document.getElementById("map-canvas"), options);

    var marker, i;

    for (var i = 0; i < $listingIds.length; i++) {
      marker = new google.maps.Marker({
        position: new google.maps.LatLng($listingIds[i].latitude, $listingIds[i].longitude),
        map: map
      });
      marker.setMap(map);
    }
  }

  google.maps.event.addDomListener(window, 'load', initialize);

});

// Helper method for handlebars conditional
Handlebars.registerHelper('if_all', function() {
    var args = [].slice.apply(arguments);
    var opts = args.pop();

    var fn = opts.fn;
    for(var i = 0; i < args.length; ++i) {
        if(args[i])
            continue;
        fn = opts.inverse;
        break;
    }
    return fn(this);
});<|endoftext|>


<commit_before>'use strict';

const AWS = require('aws-sdk');
const uuidv4 = require('uuid/v4');
const crypto = require('crypto');
const fh = new AWS.Firehose();
const kms = new AWS.KMS();

module.exports.tracker = (event, context, callback) => {
	console.info("Event", event);
	let response = {
		statusCode: 200,
		headers: {
			'Content-Type': 'image/gif',
			'Cache-Control' : 'no-cache'
		},
		body: "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",
		isBase64Encoded: true
	};
	let requestData = {
		ip: event.requestContext.identity.sourceIp,
		path: event.requestContext.path,
		referer: event.headers['Referer'],
		agent: event.headers['User-Agent'],
		accept: event.headers['Accept'],
		language: event.headers['Accept-Language'],
		encoding: event.headers['Accept-Encoding'],
		country: event.headers['CloudFront-Viewer-Country'],
		params: event.queryStringParameters,
		cookies: {}
	};
	if (event.headers['CloudFront-Is-Desktop-Viewer']) {
		requestData['device'] = 'desktop'
	} else if (event.headers['CloudFront-Is-Mobile-Viewer']) {
		requestData['device'] = 'mobile'
	} else {
		requestData['device'] = 'other'
	}
	// split cookie header
	if (event.headers['Cookie']) {
		requestData.cookies = event.headers['Cookie'].split(';').map((x) => {
			return x.trim().split(/(=)/);
		}).reduce(
			(a, b) => { a[b[0]] = b.slice(2).join('').replace(/^"(.*)"$/, '$1'); return a; }, {}
			)

	}
	// optional processing of tracking cookie
	if (process.env.COOKIE_NAME && process.env.SIGNATURE) {
		var promise = kms.decrypt({
  			CiphertextBlob: Buffer(process.env.SIGNATURE, 'base64')
		}).promise();
	} else {
		var promise = Promise.resolve({});
	}

	promise.then(res => {
		console.info("Res", res)
		if (res.Plaintext) {
			const secret = String(res.Plaintext)
			let tracking = requestData.cookies[process.env.COOKIE_NAME];
			let splitted = tracking ? tracking.split('/') : undefined;
			// function to determine if the cookie exists and is valid
			function verify(segments, secret) {
				return segments.length === 2 && (crypto.createHmac('sha256', secret).update(segments[0]).digest('hex')===segments[1]);
			}
			// verify the cookie
			if (!(splitted && verify(splitted,secret))) {
				// add a tracking cookie
				let uuid  = uuidv4();
				let sign = crypto.createHmac('sha256', secret).update(uuid).digest('hex');
				response.headers['Set-Cookie']=process.env.COOKIE_NAME + "=" + uuid + "/" + sign +"; path=/; HttpOnly; Secure; Max-Age=31536000";
				requestData['uuid'] = uuid;
			} else {
				requestData['uuid'] = splitted[0];
			}
			delete requestData.cookies[process.env.COOKIE_NAME];
		}
	}).catch(error => {
		console.error("KMS error", error);
	}).then(() => {
		requestData['@timestamp'] = new Date().toISOString();
		console.info("Firehose data", requestData);
		fh.putRecord({
			DeliveryStreamName: process.env.STREAM_NAME,
			Record: { Data: JSON.stringify(requestData) }
		}).promise().then(data => {
			console.info("Firehose response", data);
			if (data.RecordId) {
				response.headers['RecordId'] = data.RecordId;
			}
		}).catch(error => {
			console.error("Firehose error", error);
		}).then(() => callback(null, response));
	})
};
<commit_msg>Better expression of the oonditonal promise<commit_after>'use strict';

const AWS = require('aws-sdk');
const uuidv4 = require('uuid/v4');
const crypto = require('crypto');
const fh = new AWS.Firehose();
const kms = new AWS.KMS();

module.exports.tracker = (event, context, callback) => {
	console.info("Event", event);
	let response = {
		statusCode: 200,
		headers: {
			'Content-Type': 'image/gif',
			'Cache-Control' : 'no-cache'
		},
		body: "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",
		isBase64Encoded: true
	};
	let requestData = {
		ip: event.requestContext.identity.sourceIp,
		path: event.requestContext.path,
		referer: event.headers['Referer'],
		agent: event.headers['User-Agent'],
		accept: event.headers['Accept'],
		language: event.headers['Accept-Language'],
		encoding: event.headers['Accept-Encoding'],
		country: event.headers['CloudFront-Viewer-Country'],
		params: event.queryStringParameters,
		cookies: {}
	};
	if (event.headers['CloudFront-Is-Desktop-Viewer']) {
		requestData['device'] = 'desktop'
	} else if (event.headers['CloudFront-Is-Mobile-Viewer']) {
		requestData['device'] = 'mobile'
	} else {
		requestData['device'] = 'other'
	}
	// split cookie header
	if (event.headers['Cookie']) {
		requestData.cookies = event.headers['Cookie'].split(';').map((x) => {
			return x.trim().split(/(=)/);
		}).reduce(
			(a, b) => { a[b[0]] = b.slice(2).join('').replace(/^"(.*)"$/, '$1'); return a; }, {}
			)

	}

	function maybeDecrypt() {
		if (process.env.COOKIE_NAME && process.env.SIGNATURE) {
			return  kms.decrypt({
  				CiphertextBlob: Buffer(process.env.SIGNATURE, 'base64')
			}).promise()
		} else {
			return Promise.resolve();
		}
	}

	// optional processing of tracking cookie
	var promise = maybeDecrypt();

	promise.then(res => {
		console.info("Res", res)
		if (res && res.Plaintext) {
			const secret = String(res.Plaintext)
			let tracking = requestData.cookies[process.env.COOKIE_NAME];
			let splitted = tracking ? tracking.split('/') : undefined;
			// function to determine if the cookie exists and is valid
			function verify(segments, secret) {
				return segments.length === 2 && (crypto.createHmac('sha256', secret).update(segments[0]).digest('hex')===segments[1]);
			}
			// verify the cookie
			if (!(splitted && verify(splitted,secret))) {
				// add a tracking cookie
				let uuid  = uuidv4();
				let sign = crypto.createHmac('sha256', secret).update(uuid).digest('hex');
				response.headers['Set-Cookie']=process.env.COOKIE_NAME + "=" + uuid + "/" + sign +"; path=/; HttpOnly; Secure; Max-Age=31536000";
				requestData['uuid'] = uuid;
			} else {
				requestData['uuid'] = splitted[0];
			}
			delete requestData.cookies[process.env.COOKIE_NAME];
		}
	}).catch(error => {
		console.error("KMS error", error);
	}).then(() => {
		requestData['@timestamp'] = new Date().toISOString();
		console.info("Firehose data", requestData);
		fh.putRecord({
			DeliveryStreamName: process.env.STREAM_NAME,
			Record: { Data: JSON.stringify(requestData) }
		}).promise().then(data => {
			console.info("Firehose response", data);
			if (data.RecordId) {
				response.headers['RecordId'] = data.RecordId;
			}
		}).catch(error => {
			console.error("Firehose error", error);
		}).then(() => callback(null, response));
	})
};
<|endoftext|>


<commit_before>$(document).on("click", "a[data-confirm]", function(ev) {
    var href = $(this).attr('href');
    if (!$('#dataConfirmModal').length) {
        $('body').append('

<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
Please Confirm

<button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>OK

');
    }
    $('#dataConfirmModal').find('.modal-body').text($(this).attr('data-confirm'));
    $('#dataConfirmOK').attr('data-permission-id', $(this).attr('data-permission-id')).addClass('deletepermission');
    $('#dataConfirmModal').modal({show:true});
    return false;
});
$(document).on("click", ".deletepermission", function(e){
    $("#dataConfirmModal").modal('hide');
    e.preventDefault();
    var permissionid = $(this).attr('data-permission-id');

    delete_permissiondata = {
        'permisison_id': permissionid
    }
    $.post('deletepermission/', delete_permissiondata, function(resultdata) {
        if (resultdata['success']) {
            $("#permission"+permissionid).addClass('error').fadeOut();
        } else {
            alert("Couldn't delete that permission.");
        }
    });
});
$("#addpermissionbtn").click(function(e){
    e.preventDefault();
    var name = $("#name option:selected").val();
    var method = $("#method option:selected").val();
    var value = $("#value").val();
    permissiondata = {
        'permission_name': name,
        'permission_method': method,
        'permission_value': value
    }
    $.post('addpermission/', permissiondata, function(resultdata) {
        permission_id=resultdata.id;
        if (!(resultdata['error'])) {
            $("#permissions tbody").append('
<input type="hidden" name="permission" value="' + permission_id + '" /><input type="hidden" name="name' + permission_id + '" value="' + name + '" />' + name + '	<input type="hidden" name="method' + permission_id + '" value="' + method + '" />' + method + '	' + value + '	<input type="hidden" name="value' + permission_id + '" value="' + value + '" />
');
            $("#addPermission").modal('hide');
        } else {
            alert("Couldn't add that permission. Maybe you're not authorised, or maybe that permission already exists?");
        }
    });
});
<commit_msg>Add some JS for adding permissions sets<commit_after>$(document).on("click", "a[data-confirm]", function(ev) {
    var href = $(this).attr('href');
    if (!$('#dataConfirmModal').length) {
        $('body').append('

<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
Please Confirm

<button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>OK

');
    }
    $('#dataConfirmModal').find('.modal-body').text($(this).attr('data-confirm'));
    $('#dataConfirmOK').attr('data-permission-id', $(this).attr('data-permission-id')).addClass('deletepermission');
    $('#dataConfirmModal').modal({show:true});
    return false;
});
$(document).on("click", ".deletepermission", function(e){
    $("#dataConfirmModal").modal('hide');
    e.preventDefault();
    var permissionid = $(this).attr('data-permission-id');

    delete_permissiondata = {
        'permisison_id': permissionid
    }
    $.post('deletepermission/', delete_permissiondata, function(resultdata) {
        if (resultdata['success']) {
            $("#permission"+permissionid).addClass('error').fadeOut();
        } else {
            alert("Couldn't delete that permission.");
        }
    });
});
$("#addpermissionbtn").click(function(e){
    e.preventDefault();
    var name = $("#name option:selected").val();
    var method = $("#method option:selected").val();
    var value = $("#value").val();
    permissiondata = {
        'permission_name': name,
        'permission_method': method,
        'permission_value': value
    }
    $.post('addpermission/', permissiondata, function(resultdata) {
        permission_id=resultdata.id;
        if (!(resultdata['error'])) {
            $("#permissions tbody").append('
<input type="hidden" name="permission" value="' + permission_id + '" /><input type="hidden" name="name' + permission_id + '" value="' + name + '" />' + name + '	<input type="hidden" name="method' + permission_id + '" value="' + method + '" />' + method + '	' + value + '	<input type="hidden" name="value' + permission_id + '" value="' + value + '" />
');
            $("#addPermission").modal('hide');
        } else {
            alert("Couldn't add that permission. Maybe you're not authorised, or maybe that permission already exists?");
        }
    });
});
$("#addpermissionSetbtn").click(function(e){
    e.preventDefault();
    var name = $("#setname option:selected").val();
    var value = $("#setvalue option:selected").val();
    var permissions = {};
    permissions['csocomments'] = [
            {'permission_name': 'survey_cso',
             'permission_method': 'view',
             'permission_value': value},
            {'permission_name': 'cso',
             'permission_method': 'role',
             'permission_value': value},
            {'permission_name': 'organisation',
             'permission_method': 'view',
             'permission_value': value},
            {'permission_name': 'survey_pwyfreview',
             'permission_method': 'view',
             'permission_value': value},
            {'permission_name': 'survey_donorcomments',
             'permission_method': 'view',
             'permission_value': value},
            {'permission_name': 'survey_pwyffinal',
             'permission_method': 'view',
             'permission_value': value},
            {'permission_name': 'survey_finalised',
             'permission_method': 'view',
             'permission_value': value},
            {'permission_name': 'survey_cso',
             'permission_method': 'edit',
             'permission_value': value}]
    permissions['csoresearcher'] = permissions['csocomments']
    permissions['csoresearcher'].push({
             'permission_name': 'survey_researcher',
             'permission_method': 'view',
             'permission_value': value},
            {'permission_name': 'survey_researcher',
             'permission_method': 'edit',
             'permission_value': value})
    permissions['donor'] = [{'permission_name': 'organisation',
             'permission_method': 'view',
             'permission_value': value},
            {'permission_name': 'survey_donorreview',
             'permission_method': 'view',
             'permission_value': value},
            {'permission_name': 'survey_donorcomments',
             'permission_method': 'view',
             'permission_value': value},
            {'permission_name': 'survey_finalised',
             'permission_method': 'view',
             'permission_value': value},
            {'permission_name': 'organisation',
             'permission_method': 'edit',
             'permission_value': value},
            {'permission_name': 'survey_donorreview',
             'permission_method': 'edit',
             'permission_value': value},
            {'permission_name': 'survey_donorcomments',
             'permission_method': 'edit',
             'permission_value': value},
            {'permission_name': 'organisation_feedback',
             'permission_method': 'create',
             'permission_value': value}]

    var permission = {}
    var successcount = 0;
    $(permissions[name]).each(function(i, permissiondata) {
        $.post('addpermission/', permissiondata, function(resultdata) {
            permission_id=resultdata.id;
            if (!(resultdata['error'])) {
                successcount++;
                $("#permissions tbody").append('
<input type="hidden" name="permission" value="' + permission_id + '" /><input type="hidden" name="name' + permission_id + '" value="' + permissiondata['permission_name'] + '" />' + permissiondata['permission_name'] + '	<input type="hidden" name="method' + permission_id + '" value="' + permissiondata['permission_method'] + '" />' + permissiondata['permission_method'] + '	' + permissiondata['permission_value'] + '	<input type="hidden" name="value' + permission_id + '" value="' + permissiondata['permission_value'] + '" />
');
            }
        });
    }).promise()
      .done( function() {
        $("#addPermissionsSet").modal('hide');
    });
});
<|endoftext|>