<commit_before>var geocoder = new google.maps.Geocoder();
var latlngCache = [],
    boundaryCache = [],
    shapeCache = [],
    representativeCache = {};
var map, marker, shape, boundary; // the displayed boundary

var boundaryTemplate = _.template('
' +
      '
' +
        '
' +
          '<a href="#" class="shape" data-url="<%= url %>"><%= name %> ' +
          '<%= boundary_set_name %> ' +
          '<a class="label" href="<%= url %>?format=apibrowser">JSON ' +
        '
' +
      '
' +
    '
'),
   representativeTemplate = _.template('
' +
      '<% if (photo_url) { %>' +
        '<img src="<%= photo_url %>" width="60">' +
      '<% } else { %>' +
        '' +
      '<% } %>' +
    '
' +
    '
' +
      '
' +
        '<% if (url) { %><a href="<%= url %>"><%= name %><% } else { %><%= name %><% } %> ' +
        '<a class="label" href="<%= related.boundary_url %>representatives/?elected_office=<%= elected_office %>&format=apibrowser">JSON ' +
      '
' +
      '
' +
        '<% if (party_name) { %><%= party_name %><% } %> ' +
        '<%= elected_office %>' +
        '<% if (typeof representative_set_name !== "undefined") { %> at <%= representative_set_name %><% } %>' +
        '<% if (email) { %>
<a href="mailto:<%= email %>"><%= email %><% } %>' +
        '<% if (personal_url) { %>
<a href="<%= personal_url %>"><%= personal_url %><% } %>' +
      '
 ' +
    '
');

/**
 * Calls the API and displays the boundaries that contain the given point.
 * @param L.LatLng latlng
 */
function processLatLng(latlng) {
  var key = latlng.toString();

  removeBoundary();

  // Center the marker and map on the point.
  marker.setLatLng(latlng);
  map.panTo(latlng);

  // Call the API.
  if (key in latlngCache) {
    processLatLngCallback(latlng);
  }
  else {
    $.getJSON('/boundaries/?contains=' + latlng.lat + ',' + latlng.lng, function (response) {
      latlngCache[key] = response;
      processLatLngCallback(latlng);
    });
  }
}

/**
 * Displays the boundaries that contain the given point.
 * @param L.LatLng latlng
 * @note expects the API to have already been called
 * @private
 */
function processLatLngCallback(latlng) {
  var key = latlng.toString();

  // Display the boundaries.
  $('#boundaries').empty();
  $.each(latlngCache[key].objects, function (i, object) {
    boundaryCache[object.url] = object;
    var $row = $(boundaryTemplate(object));
    $('#boundaries').append($row);

    // And add representative info
    if (object.url in representativeCache) {
      displayRepresentative(object.url, $row);
    }
    else {
      $.getJSON(object.url + 'representatives/?limit=0', function (response) {
        representativeCache[object.url] = response;
        displayRepresentative(object.url, $row);
      });
    }
  });

  // Try to display a boundary from the same set.
  if (boundary) {
    boundary = _.find(latlngCache[key].objects, function (object) {
      return object.boundary_set_name == boundary.boundary_set_name;
    });
  }
  // Otherwise, default to first boundary, if any.
  else if (latlngCache[key].objects.length) {
    boundary = latlngCache[key].objects[0];
  }
  if (boundary) {
    displayBoundary(boundary.url, false);
  }
}

/**
 * Appends information on representatives to a boundary DOM node.
 * @param string url the unique URL of the corresponding boundary
 * @param $row jQuery object of the boundary DOM node
 */
function displayRepresentative(url, $row) {
  _.each(representativeCache[url].objects, function (object) {
    // @todo hack for representative sets that aren't true "sets"
    if (_.include(['Élus municipaux du Québec', 'Municipal officials of Alberta', 'Municipal officials of British Columbia'], object.representative_set_name)) {
      delete object.representative_set_name;
    }
    $row.append($(representativeTemplate(object)));
  });
}

/**
 * Calls the API and displays a boundary polygon.
 * @param string url the unique URL of the boundary to display
 * @param boolean fitBounds whether to set a map view that contains the boundary
 *   with the maximum zoom level possible
 */
function displayBoundary(url, fitBounds) {
  removeBoundary();

  // Call the API.
  if (url in shapeCache) {
    displayBoundaryCallback(url, fitBounds);
  }
  else {
    $.getJSON(url + 'simple_shape', function (response) {
      shapeCache[url] = response;
      displayBoundaryCallback(url, fitBounds);
    });
  }
}

/**
 * Displays a boundary polygon.
 * @param string url the unique URL of the boundary to display
 * @param boolean fitBounds whether to set a map view that contains the boundary
 *   with the maximum zoom level possible
 * @note expects the API to have already been called
 * @private
 */
function displayBoundaryCallback(url, fitBounds) {
  // Parse the API response.
  var latlngs = [];
  var paths = [];
  $.each(shapeCache[url].coordinates, function (j, lines) {
    $.each(lines, function (k, points) {
      var path = [];
      $.each(points, function (m, point) {
        var latlng = new L.LatLng(point[1], point[0]);
        latlngs.push(latlng);
        path.push(latlng);
      });
      paths.push(path);
    });
  });

  // Opposite of removeBoundary()
  $('a[data-url="' + url + '"]').parents('.boundary').addClass('selected');
  shape = new L.Polygon(paths);
  map.addLayer(shape);

  // Only fit bounds if clicking on boundary name.
  if (fitBounds) {
    map.fitBounds(new L.LatLngBounds(latlngs));
  }

  boundary = boundaryCache[url];
}

/**
 * Removes any displayed boundary.
 * @note Doesn't reset +boundary+
 */
function removeBoundary() {
  if (shape) {
    map.removeLayer(shape);
    shape = undefined;
    $('#boundaries .selected').removeClass('selected');
  }
}

function processAddress() {
  $('#addresses').hide().empty();
  geocoder.geocode({address: $('#address').val(), region: 'ca'}, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      if (results.length > 1) {
        // Display the list of addresses.
        $.each(results, function (i, result) {
          $('#addresses').append('<option data-latitude="' + result.geometry.location.lat() + '" data-longitude="' + result.geometry.location.lng() + '">' + result.formatted_address + '</option>');
        });
        $('#addresses').show();
      }

      var lat = results[0].geometry.location.lat(),
          lng = results[0].geometry.location.lng();
      window.location.hash = lat + ' ' + lng;
      processLatLng(new L.LatLng(lat, lng));
    }
  });
}

jQuery(function ($) {
  if ($('#map').length) {
    var latlng = new L.LatLng(45.444369, -75.693832); // 24 Sussex Drive, Ottawa

    // Create the marker.
    marker = new L.Marker(latlng, {draggable: true});

    // Moving the marker calls the API.
    marker.on('dragend', function () {
      $('#addresses').hide();
      processLatLng(marker.getLatLng());
    });

    // Create the map.
    map = new L.Map('map', {
      center: latlng,
      zoom: 13,
      layers: [
        new L.TileLayer('http://{s}.tile.cloudmade.com/266d579a42a943a78166a0a732729463/51080/256/{z}/{x}/{y}.png', {
          attribution: '© 2011 CloudMade – Map data CCBYSA 2011 OpenStreetMap.org – Terms of Use'
        })
      ],
      maxZoom: 17
    });

    // Geolocation calls the API.
    map.on('locationfound', function (event) {
      $('#addresses').hide();
      processLatLng(event.latlng);
    });

    map.addLayer(marker);
    map.attributionControl.setPrefix('');

    // Perform the first geolocation.
    var address,
        index = window.location.href.indexOf('#');
    if (index == -1) {
      address = store.get('address');
    } else {
      address = window.location.href.substr(index + 1);
    }
    if (address) {
      $('#address').val(address);
      processAddress();
    }
    else {
      map.locateAndSetView(13);
    }

    // http://stackoverflow.com/questions/2996431/javascript-detect-when-a-window-is-resized
    $(window).resize(function () {
      if (this.resizeTo) {
        clearTimeout(this.resizeTo);
      };
      this.resizeTo = setTimeout(function () {
        $(this).trigger('resizeend');
      }, 500);
    });
    // Keep the marker visible on resize.
    $(window).bind('resizeend', function () {
      map.panTo(marker.getLatLng());
    });

    // Geocode an address and call the API.
    $('#submit').click(function (event) {
      store.set('address', $('#address').val());
      processAddress();
      event.preventDefault();
    });

    // Call the API if the user clicks on an address.
    $('#addresses').live('change', function (event) {
      var $this = $(this).find(':selected');
      processLatLng(new L.LatLng($this.data('latitude'), $this.data('longitude')));
      event.preventDefault();
    });

    // Display a boundary if user clicks on a boundary name.
    $('.shape').live('click', function (event) {
      var $this = $(this);
      displayBoundary($this.data('url'), true);
      event.preventDefault();
    });
  }
});
<commit_msg>unescape stored location<commit_after>var geocoder = new google.maps.Geocoder();
var latlngCache = [],
    boundaryCache = [],
    shapeCache = [],
    representativeCache = {};
var map, marker, shape, boundary; // the displayed boundary

var boundaryTemplate = _.template('
' +
      '
' +
        '
' +
          '<a href="#" class="shape" data-url="<%= url %>"><%= name %> ' +
          '<%= boundary_set_name %> ' +
          '<a class="label" href="<%= url %>?format=apibrowser">JSON ' +
        '
' +
      '
' +
    '
'),
   representativeTemplate = _.template('
' +
      '<% if (photo_url) { %>' +
        '<img src="<%= photo_url %>" width="60">' +
      '<% } else { %>' +
        '' +
      '<% } %>' +
    '
' +
    '
' +
      '
' +
        '<% if (url) { %><a href="<%= url %>"><%= name %><% } else { %><%= name %><% } %> ' +
        '<a class="label" href="<%= related.boundary_url %>representatives/?elected_office=<%= elected_office %>&format=apibrowser">JSON ' +
      '
' +
      '
' +
        '<% if (party_name) { %><%= party_name %><% } %> ' +
        '<%= elected_office %>' +
        '<% if (typeof representative_set_name !== "undefined") { %> at <%= representative_set_name %><% } %>' +
        '<% if (email) { %>
<a href="mailto:<%= email %>"><%= email %><% } %>' +
        '<% if (personal_url) { %>
<a href="<%= personal_url %>"><%= personal_url %><% } %>' +
      '
 ' +
    '
');

/**
 * Calls the API and displays the boundaries that contain the given point.
 * @param L.LatLng latlng
 */
function processLatLng(latlng) {
  var key = latlng.toString();

  removeBoundary();

  // Center the marker and map on the point.
  marker.setLatLng(latlng);
  map.panTo(latlng);

  // Call the API.
  if (key in latlngCache) {
    processLatLngCallback(latlng);
  }
  else {
    $.getJSON('/boundaries/?contains=' + latlng.lat + ',' + latlng.lng, function (response) {
      latlngCache[key] = response;
      processLatLngCallback(latlng);
    });
  }
}

/**
 * Displays the boundaries that contain the given point.
 * @param L.LatLng latlng
 * @note expects the API to have already been called
 * @private
 */
function processLatLngCallback(latlng) {
  var key = latlng.toString();

  // Display the boundaries.
  $('#boundaries').empty();
  $.each(latlngCache[key].objects, function (i, object) {
    boundaryCache[object.url] = object;
    var $row = $(boundaryTemplate(object));
    $('#boundaries').append($row);

    // And add representative info
    if (object.url in representativeCache) {
      displayRepresentative(object.url, $row);
    }
    else {
      $.getJSON(object.url + 'representatives/?limit=0', function (response) {
        representativeCache[object.url] = response;
        displayRepresentative(object.url, $row);
      });
    }
  });

  // Try to display a boundary from the same set.
  if (boundary) {
    boundary = _.find(latlngCache[key].objects, function (object) {
      return object.boundary_set_name == boundary.boundary_set_name;
    });
  }
  // Otherwise, default to first boundary, if any.
  else if (latlngCache[key].objects.length) {
    boundary = latlngCache[key].objects[0];
  }
  if (boundary) {
    displayBoundary(boundary.url, false);
  }
}

/**
 * Appends information on representatives to a boundary DOM node.
 * @param string url the unique URL of the corresponding boundary
 * @param $row jQuery object of the boundary DOM node
 */
function displayRepresentative(url, $row) {
  _.each(representativeCache[url].objects, function (object) {
    // @todo hack for representative sets that aren't true "sets"
    if (_.include(['Élus municipaux du Québec', 'Municipal officials of Alberta', 'Municipal officials of British Columbia'], object.representative_set_name)) {
      delete object.representative_set_name;
    }
    $row.append($(representativeTemplate(object)));
  });
}

/**
 * Calls the API and displays a boundary polygon.
 * @param string url the unique URL of the boundary to display
 * @param boolean fitBounds whether to set a map view that contains the boundary
 *   with the maximum zoom level possible
 */
function displayBoundary(url, fitBounds) {
  removeBoundary();

  // Call the API.
  if (url in shapeCache) {
    displayBoundaryCallback(url, fitBounds);
  }
  else {
    $.getJSON(url + 'simple_shape', function (response) {
      shapeCache[url] = response;
      displayBoundaryCallback(url, fitBounds);
    });
  }
}

/**
 * Displays a boundary polygon.
 * @param string url the unique URL of the boundary to display
 * @param boolean fitBounds whether to set a map view that contains the boundary
 *   with the maximum zoom level possible
 * @note expects the API to have already been called
 * @private
 */
function displayBoundaryCallback(url, fitBounds) {
  // Parse the API response.
  var latlngs = [];
  var paths = [];
  $.each(shapeCache[url].coordinates, function (j, lines) {
    $.each(lines, function (k, points) {
      var path = [];
      $.each(points, function (m, point) {
        var latlng = new L.LatLng(point[1], point[0]);
        latlngs.push(latlng);
        path.push(latlng);
      });
      paths.push(path);
    });
  });

  // Opposite of removeBoundary()
  $('a[data-url="' + url + '"]').parents('.boundary').addClass('selected');
  shape = new L.Polygon(paths);
  map.addLayer(shape);

  // Only fit bounds if clicking on boundary name.
  if (fitBounds) {
    map.fitBounds(new L.LatLngBounds(latlngs));
  }

  boundary = boundaryCache[url];
}

/**
 * Removes any displayed boundary.
 * @note Doesn't reset +boundary+
 */
function removeBoundary() {
  if (shape) {
    map.removeLayer(shape);
    shape = undefined;
    $('#boundaries .selected').removeClass('selected');
  }
}

function processAddress() {
  $('#addresses').hide().empty();
  geocoder.geocode({address: $('#address').val(), region: 'ca'}, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      if (results.length > 1) {
        // Display the list of addresses.
        $.each(results, function (i, result) {
          $('#addresses').append('<option data-latitude="' + result.geometry.location.lat() + '" data-longitude="' + result.geometry.location.lng() + '">' + result.formatted_address + '</option>');
        });
        $('#addresses').show();
      }

      var lat = results[0].geometry.location.lat(),
          lng = results[0].geometry.location.lng();
      window.location.hash = lat + ' ' + lng;
      processLatLng(new L.LatLng(lat, lng));
    }
  });
}

jQuery(function ($) {
  if ($('#map').length) {
    var latlng = new L.LatLng(45.444369, -75.693832); // 24 Sussex Drive, Ottawa

    // Create the marker.
    marker = new L.Marker(latlng, {draggable: true});

    // Moving the marker calls the API.
    marker.on('dragend', function () {
      $('#addresses').hide();
      processLatLng(marker.getLatLng());
    });

    // Create the map.
    map = new L.Map('map', {
      center: latlng,
      zoom: 13,
      layers: [
        new L.TileLayer('http://{s}.tile.cloudmade.com/266d579a42a943a78166a0a732729463/51080/256/{z}/{x}/{y}.png', {
          attribution: '© 2011 CloudMade – Map data CCBYSA 2011 OpenStreetMap.org – Terms of Use'
        })
      ],
      maxZoom: 17
    });

    // Geolocation calls the API.
    map.on('locationfound', function (event) {
      $('#addresses').hide();
      processLatLng(event.latlng);
    });

    map.addLayer(marker);
    map.attributionControl.setPrefix('');

    // Perform the first geolocation.
    var address,
        index = window.location.href.indexOf('#');
    if (index == -1) {
      address = store.get('address');
    } else {
      address = unescape(window.location.href.substr(index + 1));
    }
    if (address) {
      $('#address').val(address);
      processAddress();
    }
    else {
      map.locateAndSetView(13);
    }

    // http://stackoverflow.com/questions/2996431/javascript-detect-when-a-window-is-resized
    $(window).resize(function () {
      if (this.resizeTo) {
        clearTimeout(this.resizeTo);
      };
      this.resizeTo = setTimeout(function () {
        $(this).trigger('resizeend');
      }, 500);
    });
    // Keep the marker visible on resize.
    $(window).bind('resizeend', function () {
      map.panTo(marker.getLatLng());
    });

    // Geocode an address and call the API.
    $('#submit').click(function (event) {
      store.set('address', $('#address').val());
      processAddress();
      event.preventDefault();
    });

    // Call the API if the user clicks on an address.
    $('#addresses').live('change', function (event) {
      var $this = $(this).find(':selected');
      processLatLng(new L.LatLng($this.data('latitude'), $this.data('longitude')));
      event.preventDefault();
    });

    // Display a boundary if user clicks on a boundary name.
    $('.shape').live('click', function (event) {
      var $this = $(this);
      displayBoundary($this.data('url'), true);
      event.preventDefault();
    });
  }
});
<|endoftext|>


<commit_before>function FeaturedVideos(){
	var allvideos= ["https://www.youtube.com/embed/roPGuZEzeiw?list=PLSCcAGyv98icX4pV3k5uIYtzjaVw12myt",
					"https://www.youtube.com/embed/od0j4aNDGKM",
					"https://www.youtube.com/embed/kzYQxZPZtNM",
					"https://www.youtube.com/embed/3g70e2TP1YI",
					"https://www.youtube.com/embed/TwCBr0Dqlms",
					"https://www.youtube.com/embed/695PN9xaEhs",
					"https://www.youtube.com/embed/lCg_gh_fppI",
					"https://www.youtube.com/embed/9H9qdpUzu4M",
					"https://www.youtube.com/embed/F1CohjEGbPc",
					"https://www.youtube.com/embed/hAGfBjvIRFI",
					"https://www.youtube.com/embed/XKBbn5GBw0Y",
					"https://www.youtube.com/embed/yhTxFOVAZtg",
					"https://www.youtube.com/embed/j6gf8r6e3Kc",
					"https://www.youtube.com/embed/2gQuLmpK_Ok"]

	var numbervid = allvideos.length;
	var numberfeatured = 14;
	var	randomold = [];
	for (i = 0; i < numberfeatured; i++){
		var random = Math.floor(Math.random() * numbervid);
		var postvid = document.getElementById("Video" + i);
		for (r = 0; r < randomold.length; r++){
			if (random == randomold[r]){
				random = Math.floor(Math.random() * numbervid);
			}
		}
		var link = allvideos[random];
		postvid.src = link;
		randomold.push(random);
	}
}

<commit_msg>featured<commit_after>function FeaturedVideos(){
	var allvideos= ["https://www.youtube.com/embed/roPGuZEzeiw?list=PLSCcAGyv98icX4pV3k5uIYtzjaVw12myt",
					"https://www.youtube.com/embed/od0j4aNDGKM",
					"https://www.youtube.com/embed/kzYQxZPZtNM",
					"https://www.youtube.com/embed/3g70e2TP1YI",
					"https://www.youtube.com/embed/TwCBr0Dqlms",
					"https://www.youtube.com/embed/695PN9xaEhs",
					"https://www.youtube.com/embed/lCg_gh_fppI",
					"https://www.youtube.com/embed/9H9qdpUzu4M",
					"https://www.youtube.com/embed/F1CohjEGbPc",
					"https://www.youtube.com/embed/hAGfBjvIRFI",
					"https://www.youtube.com/embed/XKBbn5GBw0Y",
					"https://www.youtube.com/embed/yhTxFOVAZtg",
					"https://www.youtube.com/embed/j6gf8r6e3Kc",
					"https://www.youtube.com/embed/2gQuLmpK_Ok",
					"https://www.youtube.com/embed/PAo_JpDNQY8",
					"https://www.youtube.com/embed/3TSD9TJ5sVM",
					"https://www.youtube.com/embed/ERHEoQyBABU",
					"https://www.youtube.com/embed/vrHDaC30dqw"]

	var numbervid = allvideos.length;
	var numberfeatured = 14;
	var	randomold = [];
	for (i = 0; i < numberfeatured; i++){
		var random = Math.floor(Math.random() * numbervid);
		var postvid = document.getElementById("Video" + i);
		var done = randomold.length;
		for (r = 0; r < done; r++){
			if (random == randomold[r]){
				random = Math.floor(Math.random() * numbervid);
			}
		}
		var link = allvideos[random];
		postvid.src = link;
		randomold.push(random);
	}
}

<|endoftext|>


<commit_before>"use strict";

codeCampControllers.controller("speakersController", ["$scope", "$routeParams", "$http", "$uibModal", "codeCampServiceFactory", function ($scope, $routeParams, $http, $uibModal, codeCampServiceFactory) {

    $scope.currentSpeaker = {};
    $scope.speakers = {};
    $scope.currentUserRegistration = {};
    $scope.currentSpeakerSessions = [];
    $scope.hasSpeakers = false;
    $scope.showSpeakerSubmission = false;

    var factory = codeCampServiceFactory;
    factory.init(moduleId, moduleName);

    $scope.LoadSpeakerSubmission = function () {
        if ($scope.currentSpeakerSessions != undefined) {
            $scope.showSpeakerSubmission = ($scope.currentSpeakerSessions.length == 0);
        } else {
            $scope.showSpeakerSubmission = ($scope.currentSpeaker == undefined && $scope.currentUserRegistration != undefined);
        }
    }

    $scope.LoadData = function() {
        factory.callGetService("GetCurrentUserId")
            .then(function (response) {
                var fullResult = angular.fromJson(response);
                var serviceResponse = JSON.parse(fullResult.data);

                $scope.currentUserId = serviceResponse.Content;

                $scope.getEvent();

                LogErrors(serviceResponse.Errors);
            },
            function (data) {
                console.log("Unknown error occurred calling GetCurrentUserId");
                console.log(data);
            });
    }

    $scope.updateSpeakersList = function () {
        factory.callGetService("GetSpeakers?codeCampId=" + $scope.codeCamp.CodeCampId)
            .then(function (response) {
                var fullResult = angular.fromJson(response);
                var serviceResponse = JSON.parse(fullResult.data);

                $scope.speakers = serviceResponse.Content;

                if ($scope.speakers === null) {
                    $scope.hasSpeakers = false;
                } else {
                    $scope.hasSpeakers = ($scope.speakers.length > 0);

                    $.each($scope.speakers, function (i, obj) {
                        obj.SpeakerSlug = GetSlugFromValue(obj.SpeakerName);
                    });
                }

                LogErrors(serviceResponse.Errors);
            },
            function (data) {
                console.log("Unknown error occurred calling GetSpeakers");
                console.log(data);
            });
    }

    $scope.getSpeakerSessions = function() {
        factory.callGetService("GetSessionsBySpeakerId?codeCampId=" + $scope.codeCamp.CodeCampId + "&speakerId=" + $scope.currentSpeaker.SpeakerId)
            .then(function (response) {
                var fullResult = angular.fromJson(response);
                var serviceResponse = JSON.parse(fullResult.data);

                $scope.currentSpeakerSessions = serviceResponse.Content;

                $scope.LoadSpeakerSubmission();

                LogErrors(serviceResponse.Errors);
            },
                function (data) {
                    console.log("Unknown error occurred calling GetSessionsBySpeakerId");
                    console.log(data);
                });
    }

    $scope.getSpeaker = function() {
        factory.callGetService("GetSpeakerByRegistrationId?codeCampId=" + $scope.codeCamp.CodeCampId + "&registrationId=" + $scope.currentUserRegistration.RegistrationId)
            .then(function (response) {
                var fullResult = angular.fromJson(response);
                var serviceResponse = JSON.parse(fullResult.data);

                $scope.currentSpeaker = serviceResponse.Content;

                if ($scope.currentSpeaker != null) {
                    $scope.getSpeakerSessions();
                }

                LogErrors(serviceResponse.Errors);
            },
                function (data) {
                    console.log("Unknown error occurred calling GetSpeakerByRegistrationId");
                    console.log(data);
                });
    }

    $scope.getRegistration = function() {
        factory.callGetService("GetRegistrationByUserId?userId=" + $scope.currentUserId + "&codeCampId=" + $scope.codeCamp.CodeCampId)
            .then(function (response) {
                var fullResult = angular.fromJson(response);
                var serviceResponse = JSON.parse(fullResult.data);

                $scope.currentUserRegistration = serviceResponse.Content;

                if ($scope.codeCamp != null && $scope.currentUserRegistration != null) {
                    $scope.getSpeaker();
                }

                $scope.LoadSpeakerSubmission();

                LogErrors(serviceResponse.Errors);
            },
            function (data) {
                console.log("Unknown error occurred calling GetRegistrationByUserId");
                console.log(data);
            });
    }

    $scope.getEvent = function() {
        factory.callGetService("GetEventByModuleId")
            .then(function (response) {
                var fullResult = angular.fromJson(response);
                var serviceResponse = JSON.parse(fullResult.data);

                $scope.codeCamp = serviceResponse.Content;

                if ($scope.codeCamp != null) {
                    $scope.codeCamp.BeginDate = ParseDate($scope.codeCamp.BeginDate);
                    $scope.codeCamp.EndDate = ParseDate($scope.codeCamp.EndDate);
                }

                if ($scope.codeCamp === null) {
                    $scope.hasCodeCamp = false;
                } else {
                    $scope.hasCodeCamp = true;

                    $scope.updateSpeakersList();

                    $scope.getRegistration();
                }

                LogErrors(serviceResponse.Errors);
            },
            function (data) {
                console.log("Unknown error occurred calling GetEventByModuleId");
                console.log(data);
            });
    }

    $scope.openModal = function (size) {
        var modalInstance = $uibModal.open({
            templateUrl: "AddSpeakerModal.html",
            controller: "AddSpeakerModalController",
            size: size,
            backdrop: "static",
            scope: $scope,
            resolve: {
                userId: function() {
                    return $scope.currentUserId;
                },
                currentSpeaker: function () {
                    return ($scope.currentSpeaker) ? $scope.currentSpeaker : null;
                },
                currentSessions: function () {
                    return ($scope.currentSpeakerSessions) ? $scope.currentSpeakerSessions : null;
                },
                codeCamp: function () {
                    return $scope.codeCamp;
                },
                registration: function() {
                    return $scope.currentUserRegistration;
                }
            }
        });

        modalInstance.result.then(function (savedSpeaker) {
            $scope.savedSpeaker = savedSpeaker;
            $scope.LoadData();
        }, function () {
            console.log("Modal dismissed at: " + new Date());
        });
    };

    $scope.LoadData();

}])
.directive("speakerCards", function() {
    return {
        restrict: "E",
        templateUrl: "/DesktopModules/CodeCamp/Templates/_default/speaker-cards.html",
        scope: {
            speakers: "=data"
        },
        link: function (scope, element, attrs) {
            scope.$watch("speakers", function() {
                processSpeakerCards();
            });
        }
    };
});

/*
 * Speakers Modal Controller
 */
codeCampApp.controller("AddSpeakerModalController", ["$scope", "$rootScope", "$uibModal", "$uibModalInstance", "userId", "currentSpeaker", "currentSessions", "codeCamp", "registration", "codeCampServiceFactory", function ($scope, $rootScope, $uibModal, $uibModalInstance, userId, currentSpeaker, currentSessions, codeCamp, registration, codeCampServiceFactory) {

    $scope.speaker = {};
    $scope.savedSpeaker = {};
    $scope.sessions = [];
    $scope.savedSessions = [];
    $scope.UpdateMode = false;

    var factory = codeCampServiceFactory;
    factory.init(moduleId, moduleName);

    $scope.CodeCampId = codeCamp.CodeCampId;

    if (currentSpeaker) {
        $scope.UpdateMode = true;
        $scope.speaker = currentSpeaker;
        $scope.sessions = currentSessions;
    }

    if ($scope.sessions.length == 0) {
        $scope.sessions.push({
            AudienceLevel: 0,
            Title: "",
            Description: "",
            CodeCampId: $scope.CodeCampId
        });
    }

    $scope.AddSession = function () {
        $scope.sessions.push({
            AudienceLevel: 0,
            Title: "",
            Description: "",
            CodeCampId: $scope.CodeCampId
        });
    }

    $scope.requiresConfirmation = function(session) {
        return (session.SessionId > 0 || (session.Title.length > 0 || session.Description.length > 0));
    }

    $scope.ProcessSessionRemoval = function (elem, session) {
        if ($scope.requiresConfirmation(session)) {
            $scope.ConfirmDeleteSession(session);
        } else {
            $scope.RemoveSession(session);
        }
    }

    $scope.RemoveSession = function(session) {
        var index = $scope.sessions.indexOf(session);
        $scope.sessions.splice(index, 1);
    }

    $scope.SessionIndex = function(session) {
        return $scope.sessions.indexOf(session);
    }

    $scope.ok = function () {
        $scope.speaker.RegistrationId = registration.RegistrationId;
        $scope.speaker.CodeCampId = $scope.CodeCampId;

        var speakerAction = ($scope.UpdateMode) ? "UpdateSpeaker" : "CreateSpeaker";

        // save the speaker
        factory.callPostService(speakerAction, $scope.speaker)
            .success(function (data) {
                var savedSpeaker = angular.fromJson(data);
                $scope.savedSpeaker = savedSpeaker.Content;

                // save the speaker avatar

                // save the sessions
                $.each($scope.sessions, function (index, session) {

                    var sessionAction = (session.SessionId > 0) ? "UpdateSession" : "CreateSession";
                    var sessionSpeakerAction = (session.SessionId > 0) ? "UpdateSessionSpeaker" : "CreateSessionSpeaker";

                    $scope.saveSession(sessionAction, session, sessionSpeakerAction);
                });

                LogErrors(savedSpeaker.Errors);
            })
            .error(function (data, status) {
                $scope.HasErrors = true;
                console.log("Unknown error occurred calling " + speakerAction);
                console.log(data);
            });

        $uibModalInstance.close($scope.savedSpeaker);
    };

    $scope.saveAvatar = function (file, errFiles) {
        if ($.ServicesFramework) {
            var _sf = $.ServicesFramework(moduleId);
            $uploadService.ServiceRoot = _sf.getServiceRoot(moduleName);
            $uploadService.ServicePath = $uploadService.ServiceRoot + "Event/";
            $uploadService.Headers = {
                "ModuleId": moduleId,
                "TabId": _sf.getTabId(),
                "RequestVerificationToken": _sf.getAntiForgeryValue()
            };
        }

        $scope.f = file;
        $scope.errFile = errFiles && errFiles[0];
        if (file) {
            file.upload = Upload.upload({
                method: "POST",
                headers: $uploadService.Headers,
                url: $uploadService.ServicePath + "UpdateSpeakerAvatar",
                data: { file: file }
            });

            file.upload.then(function (response) {
                console.log(response);
                $timeout(function () {
                    file.result = response.data;
                });
            }, function (response) {
                if (response.status > 0)
                    $scope.errorMsg = response.status + ": " + response.data;
            }, function (evt) {
                file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
            });
        }
    }

    $scope.saveSession = function (sessionAction, session, sessionSpeakerAction) {
        factory.callPostService(sessionAction, session)
            .success(function (data) {
                var savedSession = angular.fromJson(data);

                $scope.savedSessions.push(savedSession.Content);

                var sessionSpeaker = {
                    SessionId: savedSession.Content.SessionId,
                    SpeakerId: $scope.savedSpeaker.SpeakerId
                };

                // save the speaker session joins
                $scope.saveSpeakerSession(sessionSpeakerAction, sessionSpeaker);

                LogErrors(savedSession.Errors);
            })
            .error(function (data, status) {
                $scope.HasErrors = true;
                console.log("Unknown error occurred calling " + sessionAction);
                console.log(data);
            });
    }

    $scope.saveSpeakerSession = function(sessionSpeakerAction, sessionSpeaker) {
        factory.callPostService(sessionSpeakerAction, sessionSpeaker)
            .success(function (data) {
                var sessionSpeaker = angular.fromJson(data);

                $scope.updateSpeakersList();

                $scope.LoadData();

                LogErrors(sessionSpeaker.Errors);
            })
            .error(function (data, status) {
                $scope.HasErrors = true;
                console.log("Unknown error occurred calling CreateSessionSpeaker");
                console.log(data);
            });
    }

    $scope.cancel = function () {
        $uibModalInstance.dismiss("cancel");
    };

    $scope.ConfirmDeleteSession = function (session) {
        var modalInstance = $uibModal.open({
            templateUrl: "DeleteSessionModal.html",
            controller: "DeleteSessionModalController",
            size: "sm",
            backdrop: "static",
            scope: $scope,
            resolve: {
                session: function () {
                    return $scope.session;
                }
            }
        });

        modalInstance.result.then(function (result) {
            if (result != null) {
                $scope.RemoveSession(result);
            }
        }, function () {
            console.log("Modal dismissed at: " + new Date());
        });
    }
}]);

/*
 * Delete Modal
 */
codeCampApp.controller("DeleteSessionModalController", ["$scope", "$rootScope", "$uibModalInstance", "session", function ($scope, $rootScope, $uibModalInstance, session) {

    $scope.ok = function () {
        $scope.RemoveSession(session);
        $uibModalInstance.close(session);
    };

    $scope.cancel = function () {
        $uibModalInstance.dismiss("cancel");
    };

}]);

/*
 * Additional functions
 */
function processSpeakerCards() {
    var BLUR_RADIUS = 40;
    var sourceImages = [];

    jQuery(".speaker-avatar").each(function() {
        sourceImages.push(jQuery(this).attr("src"));
    });

    var drawBlur = function(canvas, image) {
        var w = canvas.width;
        var h = canvas.height;
        var canvasContext = canvas.getContext("2d");
        canvasContext.drawImage(image, 0, 0, w, h);
        stackBlurCanvasRGBA(canvas, 0, 0, w, h, BLUR_RADIUS);
    };

    jQuery(".card canvas").each(function(index) {
        var canvas = jQuery(this)[0];

        var image = new Image();
        image.src = sourceImages[index];

        image.onload = function() {
            drawBlur(canvas, image);
        }
    });
}<commit_msg>Include ngImageUploader directive in controller<commit_after>"use strict";

codeCampControllers.controller("speakersController", ["$scope", "$routeParams", "$http", "$uibModal", "codeCampServiceFactory", function ($scope, $routeParams, $http, $uibModal, codeCampServiceFactory) {

    $scope.currentSpeaker = {};
    $scope.speakers = {};
    $scope.currentUserRegistration = {};
    $scope.currentSpeakerSessions = [];
    $scope.hasSpeakers = false;
    $scope.showSpeakerSubmission = false;

    var factory = codeCampServiceFactory;
    factory.init(moduleId, moduleName);

    $scope.LoadSpeakerSubmission = function () {
        if ($scope.currentSpeakerSessions != undefined) {
            $scope.showSpeakerSubmission = ($scope.currentSpeakerSessions.length == 0);
        } else {
            $scope.showSpeakerSubmission = ($scope.currentSpeaker == undefined && $scope.currentUserRegistration != undefined);
        }
    }

    $scope.LoadData = function() {
        factory.callGetService("GetCurrentUserId")
            .then(function (response) {
                var fullResult = angular.fromJson(response);
                var serviceResponse = JSON.parse(fullResult.data);

                $scope.currentUserId = serviceResponse.Content;

                $scope.getEvent();

                LogErrors(serviceResponse.Errors);
            },
            function (data) {
                console.log("Unknown error occurred calling GetCurrentUserId");
                console.log(data);
            });
    }

    $scope.updateSpeakersList = function () {
        factory.callGetService("GetSpeakers?codeCampId=" + $scope.codeCamp.CodeCampId)
            .then(function (response) {
                var fullResult = angular.fromJson(response);
                var serviceResponse = JSON.parse(fullResult.data);

                $scope.speakers = serviceResponse.Content;

                if ($scope.speakers === null) {
                    $scope.hasSpeakers = false;
                } else {
                    $scope.hasSpeakers = ($scope.speakers.length > 0);

                    $.each($scope.speakers, function (i, obj) {
                        obj.SpeakerSlug = GetSlugFromValue(obj.SpeakerName);
                    });
                }

                LogErrors(serviceResponse.Errors);
            },
            function (data) {
                console.log("Unknown error occurred calling GetSpeakers");
                console.log(data);
            });
    }

    $scope.getSpeakerSessions = function() {
        factory.callGetService("GetSessionsBySpeakerId?codeCampId=" + $scope.codeCamp.CodeCampId + "&speakerId=" + $scope.currentSpeaker.SpeakerId)
            .then(function (response) {
                var fullResult = angular.fromJson(response);
                var serviceResponse = JSON.parse(fullResult.data);

                $scope.currentSpeakerSessions = serviceResponse.Content;

                $scope.LoadSpeakerSubmission();

                LogErrors(serviceResponse.Errors);
            },
                function (data) {
                    console.log("Unknown error occurred calling GetSessionsBySpeakerId");
                    console.log(data);
                });
    }

    $scope.getSpeaker = function() {
        factory.callGetService("GetSpeakerByRegistrationId?codeCampId=" + $scope.codeCamp.CodeCampId + "&registrationId=" + $scope.currentUserRegistration.RegistrationId)
            .then(function (response) {
                var fullResult = angular.fromJson(response);
                var serviceResponse = JSON.parse(fullResult.data);

                $scope.currentSpeaker = serviceResponse.Content;

                if ($scope.currentSpeaker != null) {
                    $scope.getSpeakerSessions();
                }

                LogErrors(serviceResponse.Errors);
            },
                function (data) {
                    console.log("Unknown error occurred calling GetSpeakerByRegistrationId");
                    console.log(data);
                });
    }

    $scope.getRegistration = function() {
        factory.callGetService("GetRegistrationByUserId?userId=" + $scope.currentUserId + "&codeCampId=" + $scope.codeCamp.CodeCampId)
            .then(function (response) {
                var fullResult = angular.fromJson(response);
                var serviceResponse = JSON.parse(fullResult.data);

                $scope.currentUserRegistration = serviceResponse.Content;

                if ($scope.codeCamp != null && $scope.currentUserRegistration != null) {
                    $scope.getSpeaker();
                }

                $scope.LoadSpeakerSubmission();

                LogErrors(serviceResponse.Errors);
            },
            function (data) {
                console.log("Unknown error occurred calling GetRegistrationByUserId");
                console.log(data);
            });
    }

    $scope.getEvent = function() {
        factory.callGetService("GetEventByModuleId")
            .then(function (response) {
                var fullResult = angular.fromJson(response);
                var serviceResponse = JSON.parse(fullResult.data);

                $scope.codeCamp = serviceResponse.Content;

                if ($scope.codeCamp != null) {
                    $scope.codeCamp.BeginDate = ParseDate($scope.codeCamp.BeginDate);
                    $scope.codeCamp.EndDate = ParseDate($scope.codeCamp.EndDate);
                }

                if ($scope.codeCamp === null) {
                    $scope.hasCodeCamp = false;
                } else {
                    $scope.hasCodeCamp = true;

                    $scope.updateSpeakersList();

                    $scope.getRegistration();
                }

                LogErrors(serviceResponse.Errors);
            },
            function (data) {
                console.log("Unknown error occurred calling GetEventByModuleId");
                console.log(data);
            });
    }

    $scope.openModal = function (size) {
        var modalInstance = $uibModal.open({
            templateUrl: "AddSpeakerModal.html",
            controller: "AddSpeakerModalController",
            size: size,
            backdrop: "static",
            scope: $scope,
            resolve: {
                userId: function() {
                    return $scope.currentUserId;
                },
                currentSpeaker: function () {
                    return ($scope.currentSpeaker) ? $scope.currentSpeaker : null;
                },
                currentSessions: function () {
                    return ($scope.currentSpeakerSessions) ? $scope.currentSpeakerSessions : null;
                },
                codeCamp: function () {
                    return $scope.codeCamp;
                },
                registration: function() {
                    return $scope.currentUserRegistration;
                }
            }
        });

        modalInstance.result.then(function (savedSpeaker) {
            $scope.savedSpeaker = savedSpeaker;
            $scope.LoadData();
        }, function () {
            console.log("Modal dismissed at: " + new Date());
        });
    };

    $scope.LoadData();

}])
.directive("speakerCards", function() {
    return {
        restrict: "E",
        templateUrl: "/DesktopModules/CodeCamp/Templates/_default/speaker-cards.html",
        scope: {
            speakers: "=data"
        },
        link: function (scope, element, attrs) {
            scope.$watch("speakers", function() {
                processSpeakerCards();
            });
        }
    };
});

/*
 * Speakers Modal Controller
 */
codeCampApp.controller("AddSpeakerModalController", ["$scope", "$rootScope", "$uibModal", "$uibModalInstance", "Upload", "userId", "currentSpeaker", "currentSessions", "codeCamp", "registration", "codeCampServiceFactory", function ($scope, $rootScope, $uibModal, $uibModalInstance, Upload, userId, currentSpeaker, currentSessions, codeCamp, registration, codeCampServiceFactory) {

    $scope.speaker = {};
    $scope.savedSpeaker = {};
    $scope.sessions = [];
    $scope.savedSessions = [];
    $scope.UpdateMode = false;

    var factory = codeCampServiceFactory;
    factory.init(moduleId, moduleName);

    $scope.CodeCampId = codeCamp.CodeCampId;

    if (currentSpeaker) {
        $scope.UpdateMode = true;
        $scope.speaker = currentSpeaker;
        $scope.sessions = currentSessions;
    }

    if ($scope.sessions.length == 0) {
        $scope.sessions.push({
            AudienceLevel: 0,
            Title: "",
            Description: "",
            CodeCampId: $scope.CodeCampId
        });
    }

    $scope.AddSession = function () {
        $scope.sessions.push({
            AudienceLevel: 0,
            Title: "",
            Description: "",
            CodeCampId: $scope.CodeCampId
        });
    }

    $scope.requiresConfirmation = function(session) {
        return (session.SessionId > 0 || (session.Title.length > 0 || session.Description.length > 0));
    }

    $scope.ProcessSessionRemoval = function (elem, session) {
        if ($scope.requiresConfirmation(session)) {
            $scope.ConfirmDeleteSession(session);
        } else {
            $scope.RemoveSession(session);
        }
    }

    $scope.RemoveSession = function(session) {
        var index = $scope.sessions.indexOf(session);
        $scope.sessions.splice(index, 1);
    }

    $scope.SessionIndex = function(session) {
        return $scope.sessions.indexOf(session);
    }

    $scope.ok = function () {
        $scope.speaker.RegistrationId = registration.RegistrationId;
        $scope.speaker.CodeCampId = $scope.CodeCampId;

        var speakerAction = ($scope.UpdateMode) ? "UpdateSpeaker" : "CreateSpeaker";

        // save the speaker
        factory.callPostService(speakerAction, $scope.speaker)
            .success(function (data) {
                var savedSpeaker = angular.fromJson(data);
                $scope.savedSpeaker = savedSpeaker.Content;

                // save the speaker avatar

                // save the sessions
                $.each($scope.sessions, function (index, session) {

                    var sessionAction = (session.SessionId > 0) ? "UpdateSession" : "CreateSession";
                    var sessionSpeakerAction = (session.SessionId > 0) ? "UpdateSessionSpeaker" : "CreateSessionSpeaker";

                    $scope.saveSession(sessionAction, session, sessionSpeakerAction);
                });

                LogErrors(savedSpeaker.Errors);
            })
            .error(function (data, status) {
                $scope.HasErrors = true;
                console.log("Unknown error occurred calling " + speakerAction);
                console.log(data);
            });

        $uibModalInstance.close($scope.savedSpeaker);
    };

    $scope.saveAvatar = function (file, errFiles) {
        if ($.ServicesFramework) {
            var _sf = $.ServicesFramework(moduleId);
            $uploadService.ServiceRoot = _sf.getServiceRoot(moduleName);
            $uploadService.ServicePath = $uploadService.ServiceRoot + "Event/";
            $uploadService.Headers = {
                "ModuleId": moduleId,
                "TabId": _sf.getTabId(),
                "RequestVerificationToken": _sf.getAntiForgeryValue()
            };
        }

        $scope.f = file;
        $scope.errFile = errFiles && errFiles[0];
        if (file) {
            file.upload = Upload.upload({
                method: "POST",
                headers: $uploadService.Headers,
                url: $uploadService.ServicePath + "UpdateSpeakerAvatar",
                data: { file: file }
            });

            file.upload.then(function (response) {
                console.log(response);
                $timeout(function () {
                    file.result = response.data;
                });
            }, function (response) {
                if (response.status > 0)
                    $scope.errorMsg = response.status + ": " + response.data;
            }, function (evt) {
                file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
            });
        }
    }

    $scope.saveSession = function (sessionAction, session, sessionSpeakerAction) {
        factory.callPostService(sessionAction, session)
            .success(function (data) {
                var savedSession = angular.fromJson(data);

                $scope.savedSessions.push(savedSession.Content);

                var sessionSpeaker = {
                    SessionId: savedSession.Content.SessionId,
                    SpeakerId: $scope.savedSpeaker.SpeakerId
                };

                // save the speaker session joins
                $scope.saveSpeakerSession(sessionSpeakerAction, sessionSpeaker);

                LogErrors(savedSession.Errors);
            })
            .error(function (data, status) {
                $scope.HasErrors = true;
                console.log("Unknown error occurred calling " + sessionAction);
                console.log(data);
            });
    }

    $scope.saveSpeakerSession = function(sessionSpeakerAction, sessionSpeaker) {
        factory.callPostService(sessionSpeakerAction, sessionSpeaker)
            .success(function (data) {
                var sessionSpeaker = angular.fromJson(data);

                $scope.updateSpeakersList();

                $scope.LoadData();

                LogErrors(sessionSpeaker.Errors);
            })
            .error(function (data, status) {
                $scope.HasErrors = true;
                console.log("Unknown error occurred calling CreateSessionSpeaker");
                console.log(data);
            });
    }

    $scope.cancel = function () {
        $uibModalInstance.dismiss("cancel");
    };

    $scope.ConfirmDeleteSession = function (session) {
        var modalInstance = $uibModal.open({
            templateUrl: "DeleteSessionModal.html",
            controller: "DeleteSessionModalController",
            size: "sm",
            backdrop: "static",
            scope: $scope,
            resolve: {
                session: function () {
                    return $scope.session;
                }
            }
        });

        modalInstance.result.then(function (result) {
            if (result != null) {
                $scope.RemoveSession(result);
            }
        }, function () {
            console.log("Modal dismissed at: " + new Date());
        });
    }
}]);

/*
 * Delete Modal
 */
codeCampApp.controller("DeleteSessionModalController", ["$scope", "$rootScope", "$uibModalInstance", "session", function ($scope, $rootScope, $uibModalInstance, session) {

    $scope.ok = function () {
        $scope.RemoveSession(session);
        $uibModalInstance.close(session);
    };

    $scope.cancel = function () {
        $uibModalInstance.dismiss("cancel");
    };

}]);

/*
 * Additional functions
 */
function processSpeakerCards() {
    var BLUR_RADIUS = 40;
    var sourceImages = [];

    jQuery(".speaker-avatar").each(function() {
        sourceImages.push(jQuery(this).attr("src"));
    });

    var drawBlur = function(canvas, image) {
        var w = canvas.width;
        var h = canvas.height;
        var canvasContext = canvas.getContext("2d");
        canvasContext.drawImage(image, 0, 0, w, h);
        stackBlurCanvasRGBA(canvas, 0, 0, w, h, BLUR_RADIUS);
    };

    jQuery(".card canvas").each(function(index) {
        var canvas = jQuery(this)[0];

        var image = new Image();
        image.src = sourceImages[index];

        image.onload = function() {
            drawBlur(canvas, image);
        }
    });
}
<|endoftext|>


<commit_before>var sqlite3 = require("sqlite3").verbose(),
    assert = require("assert"),
    dbFile = "./database/test.db",
    db = new sqlite3.Database(dbFile),
    Location = require('./location');
/*
A mail object looks like:

var customerprice = {
    origin: 1,
    destination: 2,
    weightcost: 50,
    volumecost: 20,
    priority: "Land"
};

The id is the primary key and is autoincremented. So when updating or inserting
a customerprice object you do not need to supply the id.

The following are the database function implemented by customerprice.js file:
    1.getAllPrices ==> returns array of customerprice objects
    2.getpriceById ==>
    2 getPriceByOrigin ==> returns array of customerprice object that have origin = Origin parameter
    3 getPriceByOriginAndDestination ==> returns array of customerprice object that have origin = Origin parameter AND destination = Destination parameter
    4 insertPrice ==> inserts new customerprice object to database
    5 deletePrice ==> deletes customerprice by id
    6 updatePrice ==> update customerprice by id

*/

//returns list of all customerprice objects
exports.getAllPrices = function(callback){
    var stmt = "SELECT priceid, ORIGIN.name AS origin, DEST.name AS destination, weightcost, volumecost, priority "
    			 + "FROM customerprice "
    			 + "LEFT JOIN locations AS ORIGIN ON customerprice.origin = ORIGIN.locationid "
    			 + "LEFT JOIN locations AS DEST ON customerprice.destination = DEST.locationid";

    db.all(stmt, function(err, rows){
        if (err){
            console.log("Error loading customerprices: " + err);
            callback([]);
        } else if (callback){
            callback(rows);
        }
    });
}

//returns customerprice objects where origin == origin parameter.
//The paramter: origin must be location id.
exports.getPriceByOrigin = function(originid, callback){
    var stmt = "SELECT priceid, ORIGIN.name AS origin, DEST.name AS destination, weightcost, volumecost, priority "
    			 + "FROM customerprice "
    			 + "LEFT JOIN locations AS ORIGIN ON customerprice.origin = ORIGIN.locationid "
    			 + "LEFT JOIN locations AS DEST ON customerprice.destination = DEST.locationid "
    			 + "WHERE customerprice.origin = $originid";

    db.all(stmt, {$originid: originid}, function(err, rows){
        if(err){
            console.log("Error loading customerprice: " + err);
            callback([]);
        } else if (callback){
            callback(rows);
        }
    });
}

//returns customerprice objects where origin == origin parameter AND destination == destination parameter.
//The paramters: origin and destination must be location id.
exports.getPriceByOriginAndDestination = function(originid, destinationid, callback){
    var stmt = "SELECT priceid, ORIGIN.name AS origin, DEST.name AS destination, weightcost, volumecost, priority "
    			 + "FROM customerprice "
    			 + "LEFT JOIN locations AS ORIGIN ON customerprice.origin = ORIGIN.locationid "
    			 + "LEFT JOIN locations AS DEST ON customerprice.destination = DEST.locationid "
    			 + "WHERE customerprice.origin = $originid AND customerprice.destination = $destinationid";

    db.all(stmt, {$originid: originid, $destinationid: destinationid}, function(err, rows){
        if(err){
            console.log("Error loading customerprice: " + err);
            callback([]);
        } else if (callback){
            callback(rows);
        }
    });
}

//returns customerprices object by id
exports.getPriceById = function(priceid, callback){
	var stmt = "SELECT priceid, ORIGIN.name AS origin, DEST.name AS destination, weightcost, volumecost, priority "
    			 + "FROM customerprice "
    			 + "LEFT JOIN locations AS ORIGIN ON customerprice.origin = ORIGIN.locationid "
    			 + "LEFT JOIN locations AS DEST ON customerprice.origin = DEST.locationid "
    			 + "WHERE priceid = $priceid";
    db.get(stmt, {$priceid: priceid}, function(err, customerprice){
        if(err){
            console.log("Error loading customerprice: " + err)
            callback();
        } else if (callback){
            callback(customerprice);
        }
    });
}

//Adds a new customerprice row to the customerprice table
//The customerprice object must be similar to:
/* var customerprice = {
    origin: 1,
    destination: 2,
    weightcost: 50,
    volumecost: 20,
    priority: "Land"
	};*/
//Origin and destination are foreign keys so they must be integers
//PostCondition: if return value > 0 ==> customerprice inserted sucessfully
exports.insertCustomerPrice = function(customerprice, callback){
	var stmt = db.prepare("INSERT INTO customerprice (origin, destination, weightcost, volumecost, priority) VALUES (?, ?, ?, ?, ?) ");

	stmt.run([
        customerprice.origin,
        customerprice.destination,
        customerprice.weightcost,
        customerprice.volumecost,
        customerprice.priority
    ], function(err){
        if(err){
            callback(0)}
        else{
            console.log(this);
            callback(this.changes);
        }
    });
}

//removes a customerprice from table by its id
//The number of rows removed is returned
//PostCondition: if return > 0 ==> {return} rows deleted successfully
exports.deleteCustomerPrice = function(priceid, callback){
    db.run("DELETE FROM customerprice WHERE priceid = $id", {$id: priceid}, function(err){
        if(err){
            console.log("Error removing customerprice with id: " + priceid);
            callback(0);
        }else{
            console.log(this);
            if(callback){
                callback(this.changes);
            }
        }
    });

}

//updates a customerprice row specified by the id
//the newCustomerPrice object must be similar to customerprice object of insertCustomerPrice paramter
//Returns the number of rows changed
exports.updateCustomerPrice = function(priceid, newCustomerPrice, callback){
    db.run("UPDATE customerprice SET origin = $origin, destination=$destination, weightcost=$weightcost, volumecost=$volumecost, priority=$priority WHERE priceid = $id", {
		$id: priceid,
		$origin: newCustomerPrice.origin,
      $destination : newCustomerPrice.destination,
      $weightcost: newCustomerPrice.weightcost,
      $volumecost: newCustomerPrice.volumecost,
      $priority: newCustomerPrice.priority
    	}, function(err){
        if(err){
            console.log("Error updating customerprice with id: " + priceid);
        }else{
            console.log(this);
            callback(this.changes);
        }
    });
}
<commit_msg>Fixed: customerprice returning origin instead of destination<commit_after>var sqlite3 = require("sqlite3").verbose(),
    assert = require("assert"),
    dbFile = "./database/test.db",
    db = new sqlite3.Database(dbFile),
    Location = require('./location');
/*
A mail object looks like:

var customerprice = {
    origin: 1,
    destination: 2,
    weightcost: 50,
    volumecost: 20,
    priority: "Land"
};

The id is the primary key and is autoincremented. So when updating or inserting
a customerprice object you do not need to supply the id.

The following are the database function implemented by customerprice.js file:
    1.getAllPrices ==> returns array of customerprice objects
    2.getpriceById ==>
    2 getPriceByOrigin ==> returns array of customerprice object that have origin = Origin parameter
    3 getPriceByOriginAndDestination ==> returns array of customerprice object that have origin = Origin parameter AND destination = Destination parameter
    4 insertPrice ==> inserts new customerprice object to database
    5 deletePrice ==> deletes customerprice by id
    6 updatePrice ==> update customerprice by id

*/

//returns list of all customerprice objects
exports.getAllPrices = function(callback){
    var stmt = "SELECT priceid, ORIGIN.name AS origin, DEST.name AS destination, weightcost, volumecost, priority "
    			 + "FROM customerprice "
    			 + "LEFT JOIN locations AS ORIGIN ON customerprice.origin = ORIGIN.locationid "
    			 + "LEFT JOIN locations AS DEST ON customerprice.destination = DEST.locationid";

    db.all(stmt, function(err, rows){
        if (err){
            console.log("Error loading customerprices: " + err);
            callback([]);
        } else if (callback){
            callback(rows);
        }
    });
}

//returns customerprice objects where origin == origin parameter.
//The paramter: origin must be location id.
exports.getPriceByOrigin = function(originid, callback){
    var stmt = "SELECT priceid, ORIGIN.name AS origin, DEST.name AS destination, weightcost, volumecost, priority "
    			 + "FROM customerprice "
    			 + "LEFT JOIN locations AS ORIGIN ON customerprice.origin = ORIGIN.locationid "
    			 + "LEFT JOIN locations AS DEST ON customerprice.destination = DEST.locationid "
    			 + "WHERE customerprice.origin = $originid";

    db.all(stmt, {$originid: originid}, function(err, rows){
        if(err){
            console.log("Error loading customerprice: " + err);
            callback([]);
        } else if (callback){
            callback(rows);
        }
    });
}

//returns customerprice objects where origin == origin parameter AND destination == destination parameter.
//The paramters: origin and destination must be location id.
exports.getPriceByOriginAndDestination = function(originid, destinationid, callback){
    var stmt = "SELECT priceid, ORIGIN.name AS origin, DEST.name AS destination, weightcost, volumecost, priority "
    			 + "FROM customerprice "
    			 + "LEFT JOIN locations AS ORIGIN ON customerprice.origin = ORIGIN.locationid "
    			 + "LEFT JOIN locations AS DEST ON customerprice.destination = DEST.locationid "
    			 + "WHERE customerprice.origin = $originid AND customerprice.destination = $destinationid";

    db.all(stmt, {$originid: originid, $destinationid: destinationid}, function(err, rows){
        if(err){
            console.log("Error loading customerprice: " + err);
            callback([]);
        } else if (callback){
            callback(rows);
        }
    });
}

//returns customerprices object by id
exports.getPriceById = function(priceid, callback){
	var stmt = "SELECT priceid, ORIGIN.name AS origin, DEST.name AS destination, weightcost, volumecost, priority "
    			 + "FROM customerprice "
    			 + "LEFT JOIN locations AS ORIGIN ON customerprice.origin = ORIGIN.locationid "
    			 + "LEFT JOIN locations AS DEST ON customerprice.destination = DEST.locationid "
    			 + "WHERE priceid = $priceid";
    db.get(stmt, {$priceid: priceid}, function(err, customerprice){
        if(err){
            console.log("Error loading customerprice: " + err)
            callback();
        } else if (callback){
            callback(customerprice);
        }
    });
}

//Adds a new customerprice row to the customerprice table
//The customerprice object must be similar to:
/* var customerprice = {
    origin: 1,
    destination: 2,
    weightcost: 50,
    volumecost: 20,
    priority: "Land"
	};*/
//Origin and destination are foreign keys so they must be integers
//PostCondition: if return value > 0 ==> customerprice inserted sucessfully
exports.insertCustomerPrice = function(customerprice, callback){
	var stmt = db.prepare("INSERT INTO customerprice (origin, destination, weightcost, volumecost, priority) VALUES (?, ?, ?, ?, ?) ");

	stmt.run([
        customerprice.origin,
        customerprice.destination,
        customerprice.weightcost,
        customerprice.volumecost,
        customerprice.priority
    ], function(err){
        if(err){
            callback(0)}
        else{
            console.log(this);
            callback(this.changes);
        }
    });
};

//removes a customerprice from table by its id
//The number of rows removed is returned
//PostCondition: if return > 0 ==> {return} rows deleted successfully
exports.deleteCustomerPrice = function(priceid, callback){
    db.run("DELETE FROM customerprice WHERE priceid = $id", {$id: priceid}, function(err){
        if(err){
            console.log("Error removing customerprice with id: " + priceid);
            callback(0);
        }else{
            console.log(this);
            if(callback){
                callback(this.changes);
            }
        }
    });

}

//updates a customerprice row specified by the id
//the newCustomerPrice object must be similar to customerprice object of insertCustomerPrice paramter
//Returns the number of rows changed
exports.updateCustomerPrice = function(priceid, newCustomerPrice, callback){
    db.run("UPDATE customerprice SET origin = $origin, destination=$destination, weightcost=$weightcost, volumecost=$volumecost, priority=$priority WHERE priceid = $id", {
		$id: priceid,
		$origin: newCustomerPrice.origin,
      $destination : newCustomerPrice.destination,
      $weightcost: newCustomerPrice.weightcost,
      $volumecost: newCustomerPrice.volumecost,
      $priority: newCustomerPrice.priority
    	}, function(err){
        if(err){
            console.log("Error updating customerprice with id: " + priceid);
        }else{
            console.log(this);
            callback(this.changes);
        }
    });
}
<|endoftext|>


<commit_before>/*globals define, WebGMEGlobal*/
/*jshint browser: true*/

/**
 * Generated by VisualizerGenerator 0.1.0 from webgme on Wed Apr 06 2016 14:15:27 GMT-0500 (CDT).
 */

define([
    'rosmod/Libs/flot/jquery.flot',
    'css!./styles/ResultsVizWidget.css'
], function () {
    'use strict';

    var ResultsVizWidget,
        WIDGET_CLASS = 'results-viz';

    ResultsVizWidget = function (logger, container) {
        this._logger = logger.fork('Widget');

        this._el = container;

        this.nodes = {};
        this._initialize();

        this._logger.debug('ctor finished');
    };

    ResultsVizWidget.prototype._initialize = function () {
        var width = this._el.width(),
            height = this._el.height(),
            self = this;

        // set widget class
        this._el.addClass(WIDGET_CLASS);

        // Create a dummy header
        //this._el.append('
ResultsViz Events:
');

        // Registering to events can be done with jQuery (as normal)
        this._el.on('dblclick', function (event) {
            event.stopPropagation();
            event.preventDefault();
            self.onBackgroundDblClick();
        });
    };

    ResultsVizWidget.prototype.onWidgetContainerResize = function (width, height) {
        console.log('Widget is resizing...');
    };

    // Adding/Removing/Updating items
    ResultsVizWidget.prototype.addNode = function (desc) {
        if (desc) {
            // Add node to a table of nodes
            var node = document.createElement('div'),
                label = 'children';

            if (desc.childrenIds.length === 1) {
                label = 'child';
            }

	    for (var a in desc.attributes) {
		var tmp1 = document.createElement('h3');
		tmp1.innerHTML = a;
		//var tmp = document.createElement('div');
		//tmp.innerHTML = desc.attributes[a];
		//this._el.append(tmp);
		var p = document.createElement('div');
		p.id = "log_plot_" + a;
		p.style = 'width:1300px;height:500px';
		var re = /ROSMOD::(\w+)::([\d]*)::([\w]+ ?)*::Alias=(\w+); (?:(?:[\w=;, ]*Enqueue Time)|(?:Completion Time)) sec=(\d*), nsec=(\d*)/gi;
		var result = re.exec(desc.attributes[a]);
		var log_data = {};
		while(result != null) {
		    var alias = result[4];
		    if (!log_data[alias]) {
			log_data[alias] = {
			    data : []
			};
		    }
		    if (result[3] == "ENQUEUE") {
			var enqueue_time = parseInt(result[5]) + result[6]/1000000000.0;
			log_data[alias].enqueue_time = enqueue_time;
		    }
		    else if (result[3] == "COMPLETED") {
			var completion_time = parseInt(result[5]) + result[6]/1000000000.0;
			log_data[alias].completion_time = completion_time;
		    }
		    if ( log_data[alias].completion_time && log_data[alias].enqueue_time ) {
			var exec_time = log_data[alias].completion_time -
			    log_data[alias].enqueue_time;
			log_data[alias].data.push([log_data[alias].enqueue_time, 0]);
			log_data[alias].data.push([log_data[alias].enqueue_time, exec_time]);
			log_data[alias].data.push([log_data[alias].completion_time, exec_time]);
			log_data[alias].data.push([log_data[alias].completion_time, 0]);
			log_data[alias].enqueue_time = undefined;
			log_data[alias].completion_time = undefined;
		    }
		    result = re.exec(desc.attributes[a]);
		}
		var d1 = [];
		/*
		for (var i = 0; i < 14; i += 0.5) {
		    d1.push([i, Math.sin(i)]);
		}
		*/
		var aliases = Object.keys(log_data);
		aliases.map(function(alias) {
		    d1.push(log_data[alias].data);
		});
		if (aliases.length > 0) {
		    this._el.append(tmp1);
		    this._el.append(p);
		    $.plot($("#log_plot_"+a), d1);
		}
	    }

            this.nodes[desc.id] = desc;
            node.innerHTML += 'Adding node "' + desc.name + '" (click to view). It has ' +
                desc.childrenIds.length + ' ' + label + '.';

            this._el.append(node);
            node.onclick = this.onNodeClick.bind(this, desc.id);
        }
    };

    ResultsVizWidget.prototype.removeNode = function (gmeId) {
        var desc = this.nodes[gmeId];
        this._el.append('
Removing node "'+desc.name+'"
');
        delete this.nodes[gmeId];
    };

    ResultsVizWidget.prototype.updateNode = function (desc) {
        if (desc) {
            console.log('Updating node:', desc);
            this._el.append('
Updating node "'+desc.name+'"
');
        }
    };

    /* * * * * * * * Visualizer event handlers * * * * * * * */

    ResultsVizWidget.prototype.onNodeClick = function (id) {
        // This currently changes the active node to the given id and
        // this is overridden in the controller.
    };

    ResultsVizWidget.prototype.onBackgroundDblClick = function () {
        this._el.append('
Background was double-clicked!!
');
    };

    /* * * * * * * * Visualizer life cycle callbacks * * * * * * * */
    ResultsVizWidget.prototype.destroy = function () {
    };

    ResultsVizWidget.prototype.onActivate = function () {
        console.log('ResultsVizWidget has been activated');
    };

    ResultsVizWidget.prototype.onDeactivate = function () {
        console.log('ResultsVizWidget has been deactivated');
    };

    return ResultsVizWidget;
});
<commit_msg>minor update.<commit_after>/*globals define, WebGMEGlobal*/
/*jshint browser: true*/

/**
 * Generated by VisualizerGenerator 0.1.0 from webgme on Wed Apr 06 2016 14:15:27 GMT-0500 (CDT).
 */

define([
    'rosmod/Libs/flot/jquery.flot',
    'css!./styles/ResultsVizWidget.css'
], function () {
    'use strict';

    var ResultsVizWidget,
        WIDGET_CLASS = 'results-viz';

    ResultsVizWidget = function (logger, container) {
        this._logger = logger.fork('Widget');

        this._el = container;

        this.nodes = {};
        this._initialize();

        this._logger.debug('ctor finished');
    };

    ResultsVizWidget.prototype._initialize = function () {
        var width = this._el.width(),
            height = this._el.height(),
            self = this;

        // set widget class
        this._el.addClass(WIDGET_CLASS);

        // Create a dummy header
        //this._el.append('
ResultsViz Events:
');

        // Registering to events can be done with jQuery (as normal)
        this._el.on('dblclick', function (event) {
            event.stopPropagation();
            event.preventDefault();
            self.onBackgroundDblClick();
        });
    };

    ResultsVizWidget.prototype.onWidgetContainerResize = function (width, height) {
        console.log('Widget is resizing...');
    };

    // Adding/Removing/Updating items
    ResultsVizWidget.prototype.addNode = function (desc) {
        if (desc) {
            // Add node to a table of nodes
            var node = document.createElement('div'),
                label = 'children';

            if (desc.childrenIds.length === 1) {
                label = 'child';
            }

	    for (var a in desc.attributes) {
		var tmp1 = document.createElement('h3');
		tmp1.innerHTML = a;
		//var tmp = document.createElement('div');
		//tmp.innerHTML = desc.attributes[a];
		//this._el.append(tmp);
		var p = document.createElement('div');
		p.id = "log_plot_" + a;
		p.style = 'width:1300px;height:300px';
		var re = /ROSMOD::(\w+)::([\d]*)::([\w]+ ?)*::Alias=(\w+); (?:(?:[\w=;, ]*Enqueue Time)|(?:Completion Time)) sec=(\d*), nsec=(\d*)/gi;
		var result = re.exec(desc.attributes[a]);
		var log_data = {};
		while(result != null) {
		    var alias = result[4];
		    if (!log_data[alias]) {
			log_data[alias] = {
			    data : []
			};
		    }
		    if (result[3] == "ENQUEUE") {
			var enqueue_time = parseInt(result[5]) + result[6]/1000000000.0;
			log_data[alias].enqueue_time = enqueue_time;
		    }
		    else if (result[3] == "COMPLETED") {
			var completion_time = parseInt(result[5]) + result[6]/1000000000.0;
			log_data[alias].completion_time = completion_time;
		    }
		    if ( log_data[alias].completion_time && log_data[alias].enqueue_time ) {
			var exec_time = log_data[alias].completion_time -
			    log_data[alias].enqueue_time;
			log_data[alias].data.push([log_data[alias].enqueue_time, 0]);
			log_data[alias].data.push([log_data[alias].enqueue_time, exec_time]);
			log_data[alias].data.push([log_data[alias].completion_time, exec_time]);
			log_data[alias].data.push([log_data[alias].completion_time, 0]);
			log_data[alias].enqueue_time = undefined;
			log_data[alias].completion_time = undefined;
		    }
		    result = re.exec(desc.attributes[a]);
		}
		var d1 = [];
		var aliases = Object.keys(log_data);
		aliases.map(function(alias) {
		    d1.push(log_data[alias].data);
		});
		if (aliases.length > 0) {
		    this._el.append(tmp1);
		    this._el.append(p);
		    $.plot($("#log_plot_"+a), d1);
		}
	    }

            this.nodes[desc.id] = desc;
            node.innerHTML += 'Adding node "' + desc.name + '" (click to view). It has ' +
                desc.childrenIds.length + ' ' + label + '.';

            this._el.append(node);
            node.onclick = this.onNodeClick.bind(this, desc.id);
        }
    };

    ResultsVizWidget.prototype.removeNode = function (gmeId) {
        var desc = this.nodes[gmeId];
        this._el.append('
Removing node "'+desc.name+'"
');
        delete this.nodes[gmeId];
    };

    ResultsVizWidget.prototype.updateNode = function (desc) {
        if (desc) {
            console.log('Updating node:', desc);
            this._el.append('
Updating node "'+desc.name+'"
');
        }
    };

    /* * * * * * * * Visualizer event handlers * * * * * * * */

    ResultsVizWidget.prototype.onNodeClick = function (id) {
        // This currently changes the active node to the given id and
        // this is overridden in the controller.
    };

    ResultsVizWidget.prototype.onBackgroundDblClick = function () {
        this._el.append('
Background was double-clicked!!
');
    };

    /* * * * * * * * Visualizer life cycle callbacks * * * * * * * */
    ResultsVizWidget.prototype.destroy = function () {
    };

    ResultsVizWidget.prototype.onActivate = function () {
        console.log('ResultsVizWidget has been activated');
    };

    ResultsVizWidget.prototype.onDeactivate = function () {
        console.log('ResultsVizWidget has been deactivated');
    };

    return ResultsVizWidget;
});
<|endoftext|>


<commit_before>import React from 'react';
import T from 'prop-types';
import { Card, CardTitle, CardText, ListItem } from 'material-ui';
import CloseIcon from 'material-ui/svg-icons/navigation/close';

const styles = {
  narrow: {
    default: {
      flex: 1,
      width: '100%',
      overflow: 'hidden',
      transition: 'all 0.2s ease-in',
      opacity: 1,
    },
    collapsed: {
      flex: 0,
      transition: 'all 0.2s ease-out',
      opacity: 0,
    },
    expanded: {
      flex: 2,
      transition: 'all 0.2s ease-out',
      opacity: 1,
    },
  },
  wide: {
    collapsed: {
      margin: 0,
      transition: 'all 0.2s ease-out',
      width: '100%',
    },
    expanded: {
      margin: '50px 0',
      width: 'calc(100% + 40px)',
      transition: 'all 0.2s ease-in',
    },
  },
  title: {
    padding: 0,
  },
  content: {
    default: {
      overflow: 'hidden',
    },
    collapsed: {
      transition: 'all 0.2s ease-in',
      padding: 0,
      maxHeight: 0,
      opacity: 0,
    },
    expanded: {
      transition: 'all 0.2s ease-out',
      maxHeight: '100vh',
      opacity: 1,
    },
  },
};

const AccordionItem = ({ wide, expanded, collapsed, onExpand, onCollapse, title, children }) => (
  <Card
    style={{
      ...styles[wide ? 'wide' : 'narrow'].default,
      ...styles[wide ? 'wide' : 'narrow'][expanded ? 'expanded' : 'default'],
      ...styles[wide ? 'wide' : 'narrow'][collapsed ? 'collapsed' : 'default'],
    }}
  >
    <CardTitle style={styles.title}>
      <ListItem
        primaryText={title}
        onTouchTap={onExpand}
        leftIcon={expanded ? <CloseIcon onTouchTap={onCollapse} /> : null}
      />
    </CardTitle>
    <CardText style={{ ...styles.content.default, ...styles.content[expanded ? 'expanded' : 'collapsed'] }}>
      {children}
    </CardText>
  </Card>
);

AccordionItem.propTypes = {
  wide: T.bool.isRequired,
  expanded: T.bool.isRequired,
  collapsed: T.bool.isRequired,
  onExpand: T.func.isRequired,
  onCollapse: T.func.isRequired,
  title: T.string,
  children: T.node,
};

AccordionItem.defaultProps = {
  title: undefined,
  children: undefined,
};

export default AccordionItem;
<commit_msg>fix(AccordionItem): close icon only in narrow<commit_after>import React from 'react';
import T from 'prop-types';
import { Card, CardTitle, CardText, ListItem } from 'material-ui';
import CloseIcon from 'material-ui/svg-icons/navigation/close';

const styles = {
  narrow: {
    default: {
      flex: 1,
      width: '100%',
      overflow: 'hidden',
      transition: 'all 0.2s ease-in',
      opacity: 1,
    },
    collapsed: {
      flex: 0,
      transition: 'all 0.2s ease-out',
      opacity: 0,
    },
    expanded: {
      flex: 2,
      transition: 'all 0.2s ease-out',
      opacity: 1,
    },
  },
  wide: {
    collapsed: {
      margin: 0,
      transition: 'all 0.2s ease-out',
      width: '100%',
    },
    expanded: {
      margin: '50px 0',
      width: 'calc(100% + 40px)',
      transition: 'all 0.2s ease-in',
    },
  },
  title: {
    padding: 0,
  },
  content: {
    default: {
      overflow: 'hidden',
    },
    collapsed: {
      transition: 'all 0.2s ease-in',
      padding: 0,
      maxHeight: 0,
      opacity: 0,
    },
    expanded: {
      transition: 'all 0.2s ease-out',
      maxHeight: '100vh',
      opacity: 1,
    },
  },
};

const AccordionItem = ({ wide, expanded, collapsed, onExpand, onCollapse, title, children }) => (
  <Card
    style={{
      ...styles[wide ? 'wide' : 'narrow'].default,
      ...styles[wide ? 'wide' : 'narrow'][expanded ? 'expanded' : 'default'],
      ...styles[wide ? 'wide' : 'narrow'][collapsed ? 'collapsed' : 'default'],
    }}
  >
    <CardTitle style={styles.title}>
      <ListItem
        primaryText={title}
        onTouchTap={wide && expanded ? onCollapse : onExpand}
        leftIcon={!wide && expanded ? <CloseIcon onTouchTap={onCollapse} /> : null}
      />
    </CardTitle>
    <CardText style={{ ...styles.content.default, ...styles.content[expanded ? 'expanded' : 'collapsed'] }}>
      {children}
    </CardText>
  </Card>
);

AccordionItem.propTypes = {
  wide: T.bool.isRequired,
  expanded: T.bool.isRequired,
  collapsed: T.bool.isRequired,
  onExpand: T.func.isRequired,
  onCollapse: T.func.isRequired,
  title: T.string,
  children: T.node,
};

AccordionItem.defaultProps = {
  title: undefined,
  children: undefined,
};

export default AccordionItem;
<|endoftext|>


<commit_before>module.exports = {
	rootDir: '../../',
	...require( '@wordpress/scripts/config/jest-unit.config' ),
	transform: {
		'^.+\\.[jt]sx?$': '<rootDir>/node_modules/@wordpress/scripts/config/babel-transform',
	},
	setupFiles: [
		'<rootDir>/tests/unit/setup-globals',
	],
	testPathIgnorePatterns: [
		'<rootDir>/.git',
		'<rootDir>/node_modules',
		'<rootDir>/build',
		'.*/e2e/.*',
	],
	coverageReporters: [ 'lcov' ],
	coverageDirectory: '<rootDir>/build/logs',
};
<commit_msg>Tweak coveragePathIgnorePatterns<commit_after>module.exports = {
	rootDir: '../../',
	...require( '@wordpress/scripts/config/jest-unit.config' ),
	transform: {
		'^.+\\.[jt]sx?$': '<rootDir>/node_modules/@wordpress/scripts/config/babel-transform',
	},
	setupFiles: [
		'<rootDir>/tests/unit/setup-globals',
	],
	testPathIgnorePatterns: [
		'<rootDir>/.git',
		'<rootDir>/node_modules',
		'<rootDir>/build',
		'.*/e2e/.*',
	],
	coveragePathIgnorePatterns: [ '/node_modules/', '<rootDir>/build/', '<rootDir>/assets/src/test/helpers/' ],
	coverageReporters: [ 'lcov' ],
	coverageDirectory: '<rootDir>/build/logs',
};
<|endoftext|>


<commit_before>var      express = require('express');
var  compression = require('compression');

var app = express();

app.use(compression({filter: function (req, res) {
  if (req.headers['x-no-compression']) {
    return false;
  }

  return compression.filter(req, res);
}}));

app.get('/hello.action', function (req, res) {
  res.send('Hello World!');
});

app.get('/events', function (req, res) {
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');

  var timer = setInterval(function () {
    res.write('data: ping\n\n');

    res.flush();
  }, 2000);

  res.on('close', function () {
    clearInterval(timer);
  });
});

app.use(express.static('../html'));

app.listen(8080, function () {
  console.log('Server started on port 8080!');
});
<commit_msg>Update node index.js<commit_after>var      express = require('express');
var  compression = require('compression');

var app = express();

app.use(compression({filter: function (req, res) {
  if (req.headers['x-no-compression']) {
    return false;
  }

  return compression.filter(req, res);
}}));

app.get('/hello', function (req, res) {
  res.type('json');
  res.status(200).json({
    p1: 'Hello',
    p2: new Date(),
    p3: 5,
    p4: ['heihei']
  });
});

app.get('/events', function (req, res) {
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');

  var timer = setInterval(function () {
    res.write('data: ping\n\n');

    res.flush();
  }, 2000);

  res.on('close', function () {
    clearInterval(timer);
  });
});

app.use(express.static('../html'));

app.listen(8080, function () {
  console.log('Server started on port 8080!');
});
<|endoftext|>


<commit_before>describe('IdeaController', function(){
  var scope;

  // load the controller's module
  beforeEach(module('dateworthy.idea'));

  beforeEach(module('dateworthy.services'));

  beforeEach(module(function ($provide) {
    $provide.value('$cordovaGeolocation', {
        someVariable: 1
    });
  }));

  beforeEach(module(function ($provide) {
    $provide.value('$ionicPopup', {
        someVariable: 1
    });
  }));

  beforeEach(inject(function($injector, $rootScope, $controller) {
    scope = $rootScope.$new();
    cordovaGeolocation = "foo";
    ionicPopup = "bar";
    var state = {};
    state.go = function(){};
    ionicHistory = "Buzz"
    ionicLoading = "flip"
    stateParams = "flop"
    $controller('IdeaCtrl', {$scope: scope, $state: state, $stateParams: stateParams, $ionicLoading: ionicLoading, $ionicHistory: ionicHistory, $cordovaGeolocation: cordovaGeolocation, $ionicPopup: ionicPopup});
  }));

  // tests start here
  it('should have current idea equal to 0', function(){
    expect(scope.currentIdea).toEqual(0)
  });

  it('should have a function clearData that resets the ideas and currentIdea variables', function(){
    scope.ideas = [{idea: 'testFirst'}, {idea: 'testSecond'}, {idea: 'testLast'}];
    scope.currentIdea = 1;
    scope.clearData();
    expect(scope.ideas).toEqual([]);
    expect(scope.currentIdea).toEqual(0)
  });

  it('should have a function like that sets the `liked` property to `1` on the idea object when the user clicks Like', function() {
    scope.ideas = [{idea: 'testFirst'}, {idea: 'testSecond'}, {idea: 'testLast'}];
    scope.currentIdea = 1;
    scope.like();
    expect(scope.ideas[scope.currentIdea].liked).toEqual(1);
    expect(scope.ideas[scope.currentIdea].disliked).toEqual(0);
  });

  it('should have a function like that sets the `disliked` property to `1` on the idea object when the user clicks Dislike', function() {
    scope.ideas = [{idea: 'testFirst'}, {idea: 'testSecond'}, {idea: 'testLast'}];
    scope.currentIdea = 1;
    scope.dislike();
    expect(scope.ideas[scope.currentIdea].disliked).toEqual(1);
    expect(scope.ideas[scope.currentIdea].liked).toEqual(0);
  });

  it('should set item\'s disliked property to `1` if the item has been liked then disliked', function() {
    scope.ideas = [{idea: 'testFirst'}, {idea: 'testSecond'}, {idea: 'testLast'}];
    scope.currentIdea = 1;
    scope.like();
    scope.dislike();
    expect(scope.ideas[scope.currentIdea].disliked).toEqual(1);
    expect(scope.ideas[scope.currentIdea].liked).toEqual(0);
  });

});

describe('FindADateCtrl', function(){
  var scope;
  var stateParams;
  var location;

  // load the controller's module
  beforeEach(module('dateworthy.findadate'));

  beforeEach(module('dateworthy.services'));

  beforeEach(module(function ($provide) {
    $provide.value('$cordovaGeolocation', {
        someVariable: 1
    });
  }));

  beforeEach(inject(function($injector, $rootScope, $controller, _$location_) {
    scope = $rootScope.$new();
    stateParams = { questionId: 0 };
    ionicHistory = "foo";
    ionicPlatform = "bar";
    state = {};
    state.go = function(){}
    location = _$location_;
    $controller('FindADateCtrl', {$scope: scope, $state: state, $stateParams: stateParams, $cordovaGeolocation: cordovaGeolocation, $ionicHistory: ionicHistory, $ionicPlatform: ionicPlatform, $location: location});

  }));

  it('should have obj currentQuestion equal to the current question', function(){
    expect(scope.currentQuestion.question).toBeDefined();
  });

  // it('should update the URL when someone clicks "Next" in the findadate survey', function() {
  //   location.path('/findadate/0');
  //   scope.nextQuestion();
  //   expect(location.path()).toEqual('/findadate/1');
  // });

  it('should have a function createQuestionObject that formats an object for the factory based off of survey data', function(){
    var question1 = {question: "testSecond", type: "logistics", field: "length", possibilities: ["30 mins", "1 hr", "2 hrs"]};
    var question2 = {question: "testLast", type: "tag", field: "noiseLevel", possibilities: ["Loud", "Quiet"]};
    question1.chosenOption = question1.possibilities[0];
    question2.chosenOption = question2.possibilities[0];
    var obj1 = scope.createQuestionObject(question1);
    var obj2 = scope.createQuestionObject(question2);
    console.log("obj1 is", obj1);
    expect(obj1["length"]).toEqual("30 mins");
    expect(obj2["noiseLevel"]).toEqual("Loud");
  });

});

<commit_msg>itest<commit_after>describe('IdeaController', function(){
  var scope;

  // load the controller's module
  beforeEach(module('dateworthy.idea'));

  beforeEach(module('dateworthy.services'));

  beforeEach(module(function ($provide) {
    $provide.value('$cordovaGeolocation', {
        someVariable: 1
    });
  }));

  beforeEach(module(function ($provide) {
    $provide.value('$ionicPopup', {
        someVariable: 1
    });
  }));

  beforeEach(inject(function($injector, $rootScope, $controller) {
    scope = $rootScope.$new();
    cordovaGeolocation = "foo";
    ionicPopup = "bar";
    var state = {};
    state.go = function(){};
    ionicHistory = "Buzz"
    ionicLoading = "flip"
    stateParams = "flop"
    $controller('IdeaCtrl', {$scope: scope, $state: state, $stateParams: stateParams, $ionicLoading: ionicLoading, $ionicHistory: ionicHistory, $cordovaGeolocation: cordovaGeolocation, $ionicPopup: ionicPopup});
  }));

  // tests start here
  it('should have current idea equal to 0', function(){
    expect(scope.currentIdea).toEqual(0)
  });

  it('should have a function clearData that resets the ideas and currentIdea variables', function(){
    scope.ideas = [{idea: 'testFirst'}, {idea: 'testSecond'}, {idea: 'testLast'}];
    scope.currentIdea = 1;
    scope.clearData();
    expect(scope.ideas).toEqual([]);
    expect(scope.currentIdea).toEqual(0)
  });

  it('should have a function like that sets the `liked` property to `1` on the idea object when the user clicks Like', function() {
    scope.ideas = [{idea: 'testFirst'}, {idea: 'testSecond'}, {idea: 'testLast'}];
    scope.currentIdea = 1;
    scope.like();
    expect(scope.ideas[scope.currentIdea].liked).toEqual(1);
    expect(scope.ideas[scope.currentIdea].disliked).toEqual(0);
  });

  it('should have a function like that sets the `disliked` property to `1` on the idea object when the user clicks Dislike', function() {
    scope.ideas = [{idea: 'testFirst'}, {idea: 'testSecond'}, {idea: 'testLast'}];
    scope.currentIdea = 1;
    scope.dislike();
    expect(scope.ideas[scope.currentIdea].disliked).toEqual(1);
    expect(scope.ideas[scope.currentIdea].liked).toEqual(0);
  });

  it('should set item\'s disliked property to `1` if the item has been liked then disliked', function() {
    scope.ideas = [{idea: 'testFirst'}, {idea: 'testSecond'}, {idea: 'testLast'}];
    scope.currentIdea = 1;
    scope.like();
    scope.dislike();
    expect(scope.ideas[scope.currentIdea].disliked).toEqual(1);
    expect(scope.ideas[scope.currentIdea].liked).toEqual(0);
  });

});

describe('FindADateCtrl', function(){
  var scope;
  var stateParams;
  var location;

  // load the controller's module
  beforeEach(module('dateworthy.findadate'));

  beforeEach(module('dateworthy.services'));

  beforeEach(module(function ($provide) {
    $provide.value('$cordovaGeolocation', {
        someVariable: 1
    });
  }));

  beforeEach(inject(function($injector, $rootScope, $controller, _$location_) {
    scope = $rootScope.$new();
    stateParams = { questionId: 0 };
    ionicHistory = "foo";
    ionicPlatform = "bar";
    state = {};
    state.go = function(){}
    location = _$location_;
    $controller('FindADateCtrl', {$scope: scope, $state: state, $stateParams: stateParams, $cordovaGeolocation: cordovaGeolocation, $ionicHistory: ionicHistory, $ionicPlatform: ionicPlatform, $location: location});

  }));

  it('should have obj currentQuestion equal to the current question', function(){
    expect(scope.currentQuestion.question).toBeDefined();
  });

  it('should update the URL when someone clicks "Next" in the findadate survey', function() {
    location.path('/findadate/0');
    scope.nextQuestion();
    expect(location.path()).toEqual('/findadate/1');
  });

  it('should have a function createQuestionObject that formats an object for the factory based off of survey data', function(){
    var question1 = {question: "testSecond", type: "logistics", field: "length", possibilities: ["30 mins", "1 hr", "2 hrs"]};
    var question2 = {question: "testLast", type: "tag", field: "noiseLevel", possibilities: ["Loud", "Quiet"]};
    question1.chosenOption = question1.possibilities[0];
    question2.chosenOption = question2.possibilities[0];
    var obj1 = scope.createQuestionObject(question1);
    var obj2 = scope.createQuestionObject(question2);
    console.log("obj1 is", obj1);
    expect(obj1["length"]).toEqual("30 mins");
    expect(obj2["noiseLevel"]).toEqual("Loud");
  });

});

<|endoftext|>