<commit_before>/**
 * @fileOverview ServersCtrl angular controller
 */
'use strict';

define(['./module', 'darkwallet', 'frontend/port'], function (controllers, DarkWallet, Port) {
  controllers.controller('ServersCtrl', ['$scope', function($scope) {

  $scope.newServer = {address: '', name: '', next: false};
  $scope.addServerError = '';
  $scope.connectionStatus = 'Disconnected';
  $scope.servicesStatus = {gateway: 'unknown', obelisk: 'unknown'};
  $scope.validIPPort = /^(ws[s]?:\/\/)?(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(:\d{1,5})?$/i;

  // Apply scope
  var applyScope = function() {
      if (!$scope.$$phase) {
          $scope.$apply();
      }
  };

  var identityLoaded = function(identity) {
      $scope.servers = identity.connections.servers;
      $scope.servicesStatus = DarkWallet.core.servicesStatus;
      $scope.selectedServerIdx = identity.connections.selectedServer;
      $scope.selectedServer = identity.connections.servers[$scope.selectedServerIdx];
  }

  // Track wallet status
  Port.connectNg('wallet', $scope, function(data) {
    if (data.type == 'ready') {
      var identity = DarkWallet.getIdentity();
      identityLoaded(identity);
      applyScope();

    }
  });
  var identity = DarkWallet.getIdentity();
  if (identity) {
      identityLoaded(identity);
  }

  // Track obelisk status
  Port.connectNg('obelisk', $scope, function(data) {
    if (data.type == 'connected') {
      var client = DarkWallet.getClient();
      $scope.connectionStatus = 'Connected';
      applyScope();
    } else
    if (data.type == 'connecting') {
      $scope.connectionStatus = 'Connecting';
      applyScope();
    } else
    if (data.type == 'disconnected') {
      $scope.connectionStatus = 'Disconnected';
      applyScope();
    }
  });

  // Add a server from html form
  $scope.addServer = function() {
      var newServer = $scope.newServer;
      if (!newServer.name || !newServer.address) {
          $scope.addServerError = 'Missing name or address';
          return;
      }
      var identity = DarkWallet.getIdentity();
      var address = newServer.address;
      if (address[0] != 'w') {
          address = 'wss://'+address;
      }
      identity.connections.addServer(newServer.name, address);
      $scope.newServer = {address: '', name: ''};
      $scope.addServerError = '';
  };

  // Connect the given server, triggered by select changing $scope.selectedServerIdx
  $scope.connectServer = function() {
      var identity = DarkWallet.getIdentity();
      $scope.selectedServer = identity.connections.servers[$scope.selectedServerIdx];
      identity.connections.setSelectedServer($scope.selectedServerIdx);
      // Trigger connection
      DarkWallet.core.connect();
  };

}]);

});

<commit_msg>only allow ws:// on testnet.<commit_after>/**
 * @fileOverview ServersCtrl angular controller
 */
'use strict';

define(['./module', 'darkwallet', 'frontend/port'], function (controllers, DarkWallet, Port) {
  controllers.controller('ServersCtrl', ['$scope', function($scope) {

  $scope.newServer = {address: '', name: '', next: false};
  $scope.addServerError = '';
  $scope.connectionStatus = 'Disconnected';
  $scope.servicesStatus = {gateway: 'unknown', obelisk: 'unknown'};
  $scope.validIPPort = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(:\d{1,5})?$/i;

  // Apply scope
  var applyScope = function() {
      if (!$scope.$$phase) {
          $scope.$apply();
      }
  };

  var identityLoaded = function(identity) {
      $scope.servers = identity.connections.servers;
      $scope.servicesStatus = DarkWallet.core.servicesStatus;
      $scope.selectedServerIdx = identity.connections.selectedServer;
      $scope.selectedServer = identity.connections.servers[$scope.selectedServerIdx];
      if (identity.wallet.network == 'testnet') {
          $scope.validIPPort = /^(ws[s]?:\/\/)?(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(:\d{1,5})?$/i;
      }
  }

  // Track wallet status
  Port.connectNg('wallet', $scope, function(data) {
    if (data.type == 'ready') {
      var identity = DarkWallet.getIdentity();
      identityLoaded(identity);
      applyScope();

    }
  });
  var identity = DarkWallet.getIdentity();
  if (identity) {
      identityLoaded(identity);
  }

  // Track obelisk status
  Port.connectNg('obelisk', $scope, function(data) {
    if (data.type == 'connected') {
      var client = DarkWallet.getClient();
      $scope.connectionStatus = 'Connected';
      applyScope();
    } else
    if (data.type == 'connecting') {
      $scope.connectionStatus = 'Connecting';
      applyScope();
    } else
    if (data.type == 'disconnected') {
      $scope.connectionStatus = 'Disconnected';
      applyScope();
    }
  });

  // Add a server from html form
  $scope.addServer = function() {
      var newServer = $scope.newServer;
      if (!newServer.name || !newServer.address) {
          $scope.addServerError = 'Missing name or address';
          return;
      }
      var identity = DarkWallet.getIdentity();
      var address = newServer.address;
      if (address[0] != 'w') {
          address = 'wss://'+address;
      }
      identity.connections.addServer(newServer.name, address);
      $scope.newServer = {address: '', name: ''};
      $scope.addServerError = '';
  };

  // Connect the given server, triggered by select changing $scope.selectedServerIdx
  $scope.connectServer = function() {
      var identity = DarkWallet.getIdentity();
      $scope.selectedServer = identity.connections.servers[$scope.selectedServerIdx];
      identity.connections.setSelectedServer($scope.selectedServerIdx);
      // Trigger connection
      DarkWallet.core.connect();
  };

}]);

});

<|endoftext|>


<commit_before>var service = angular.module('stoneparsingservice', ['ngResource']);

// Split given coordinate and parse it into leaflet specific format
function parseCoordinateString(raw_coordinates) {
        var coordinates = raw_coordinates.split(',');
        return L.latLng(coordinates[0], coordinates[1]);
}

service.factory('StonesService', ['$resource', '$http', function($resource, $http) {
	var promise;
	var stoneParsingService = {
		get: function() {
			if ( !promise ) {
				promise = $http.get('js/metadata.json').then(function (response) {
					var items = [];
					angular.forEach(response.data, function(el, index) {
		        		if (el.coordinate && el.origin_coordinate) {
		        			var coordinates = parseCoordinateString(el.coordinate);
      						var origin_coordinates = parseCoordinateString(el.origin_coordinate);
      						var pin = angular.merge({}, el, coordinates);
      						var pin_orig = angular.merge({}, el, origin_coordinates);
      						pin.type = "Destination";
      						pin.icon = L.MakiMarkers.icon({icon: "rocket", color: "#f00", size: "m"}).options;
      						pin_orig.type = "Source";
      						pin_orig.icon = L.MakiMarkers.icon({icon: "circle", color: "#0f0", size: "m"}).options;
		            		items.push(pin);
		            		items.push(pin_orig);
		        		}
	    			});
					return items;
				});
			}
			return promise;
		},

        /*
        Returns all the stones, grouped by location (needed for the map)
         */
        getPins: function() {
            if ( !promise ) {
                promise = $http.get('js/metadata.json').then(function (response) {
                    var pins = [],
                        groupedDataDestination,
                        groupedDataOrigins;

                    // Get pins for discovery locations
                    groupedDataDestination = _.groupBy(response.data, function(stoneItem) {
                        return stoneItem.coordinate;
                    });

                    angular.forEach(groupedDataDestination, function(element, index) {
                        var atLeastOneOriginAvailable = _.find( element, function (element) {
                            return element.origin_coordinate;
                        });

                        if (index !== 'undefined' && atLeastOneOriginAvailable) {
                            var pin = {},
                                coordinates,
                                stones;

                            coordinates = parseCoordinateString(index);
                            stones = element;

                            pin.stones = stones;
                            pin.type = "Destination";
                            pin.icon = L.MakiMarkers.icon({icon: "rocket", color: "#f00", size: "m"}).options;
                            pin = angular.merge(pin, coordinates);

                            pins.push(pin);
                        }
                    });

                    // Get pins for origin locations
                    groupedDataOrigins = _.groupBy(response.data, function(stoneItem) {
                        return stoneItem.origin_coordinate;
                    });

                    angular.forEach(groupedDataOrigins, function(element, index) {
                        var atLeastOneDestinationAvailable = _.find( element, function (element) {
                            return element.coordinate;
                        });

                        if (index !== 'undefined' && atLeastOneDestinationAvailable) {
                            var pin = {},
                                coordinates,
                                stones;

                            coordinates = parseCoordinateString(index);
                            stones = element;

                            pin.stones = stones;
                            pin.type = "Origin";
                            pin.icon = L.MakiMarkers.icon({icon: "circle", color: "#0f0", size: "m"}).options;
                            pin = angular.merge(pin, coordinates);

                            pins.push(pin);

                        }
                    });

                    return pins;
                });
            }
            return promise;
        }
	};
	return stoneParsingService;
}]);
  // return $resource('js/metadata.json',{}, {
  //    query: {method:'GET', isArray:true}
  //  });
//  }]);<commit_msg>added custom pins<commit_after>var service = angular.module('stoneparsingservice', ['ngResource']);

// Split given coordinate and parse it into leaflet specific format
function parseCoordinateString(raw_coordinates) {
        var coordinates = raw_coordinates.split(',');
        return L.latLng(coordinates[0], coordinates[1]);
}

var destinationIcon = L.icon({
        iconUrl: 'http://joshuafrazier.info/images/firefox.svg',
        iconSize: [38, 95], // size of the icon
        });

service.factory('StonesService', ['$resource', '$http', function($resource, $http) {
	var promise;
	var stoneParsingService = {
		get: function() {
			if ( !promise ) {
				promise = $http.get('js/metadata.json').then(function (response) {
					var items = [];
					angular.forEach(response.data, function(el, index) {
		        		if (el.coordinate && el.origin_coordinate) {
		        			var coordinates = parseCoordinateString(el.coordinate);
      						var origin_coordinates = parseCoordinateString(el.origin_coordinate);
      						var pin = angular.merge({}, el, coordinates);
      						var pin_orig = angular.merge({}, el, origin_coordinates);
      						pin.type = "Destination";
      						pin.icon = L.MakiMarkers.icon({icon: "rocket", color: "#f00", size: "m"}).options;
      						pin_orig.type = "Source";
      						pin_orig.icon = L.MakiMarkers.icon({icon: "circle", color: "#0f0", size: "m"}).options;
		            		items.push(pin);
		            		items.push(pin_orig);
		        		}
	    			});
					return items;
				});
			}
			return promise;
		},

        /*
        Returns all the stones, grouped by location (needed for the map)
         */
        getPins: function() {
            if ( !promise ) {
                promise = $http.get('js/metadata.json').then(function (response) {
                    var pins = [],
                        groupedDataDestination,
                        groupedDataOrigins;

                    // Get pins for discovery locations
                    groupedDataDestination = _.groupBy(response.data, function(stoneItem) {
                        return stoneItem.coordinate;
                    });

                    angular.forEach(groupedDataDestination, function(element, index) {
                        var atLeastOneOriginAvailable = _.find( element, function (element) {
                            return element.origin_coordinate;
                        });

                        if (index !== 'undefined' && atLeastOneOriginAvailable) {
                            var pin = {},
                                coordinates,
                                stones;

                            coordinates = parseCoordinateString(index);
                            stones = element;

                            pin.stones = stones;
                            pin.type = "Destination";
                            //pin.icon = L.MakiMarkers.icon({icon: "rocket", color: "#f00", size: "m"}).options;
                            var marker = L.MakiMarkers.icon({icon: "rocket", color: "#f00", size: "m"}).options;
                            marker.iconUrl = "img/assets/Pin_Gestein Fundort_ini.svg"
                            pin.icon = marker;
                            pin = angular.merge(pin, coordinates);

                            pins.push(pin);
                        }
                    });

                    // Get pins for origin locations
                    groupedDataOrigins = _.groupBy(response.data, function(stoneItem) {
                        return stoneItem.origin_coordinate;
                    });

                    angular.forEach(groupedDataOrigins, function(element, index) {
                        var atLeastOneDestinationAvailable = _.find( element, function (element) {
                            return element.coordinate;
                        });

                        if (index !== 'undefined' && atLeastOneDestinationAvailable) {
                            var pin = {},
                                coordinates,
                                stones;

                            coordinates = parseCoordinateString(index);
                            stones = element;

                            pin.stones = stones;
                            pin.type = "Origin";
                            var marker = L.MakiMarkers.icon({icon: "rocket", color: "#f00", size: "m"}).options;
                            marker.iconUrl = "img/assets/Pin_Gestein Herkunft_ini.svg"
                            pin.icon = marker;
                            pin = angular.merge(pin, coordinates);

                            pins.push(pin);

                        }
                    });

                    return pins;
                });
            }
            return promise;
        }
	};
	return stoneParsingService;
}]);
  // return $resource('js/metadata.json',{}, {
  //    query: {method:'GET', isArray:true}
  //  });
//  }]);<|endoftext|>


<commit_before>"use strict";

/*global module, require*/

var d3 = require("d3"),
    colours = require("../colour.js"),

    getShapes = function(layer) {
	return d3.selectAll("g#" + layer.name() + " path");
    },

    getShapeById = function(layer, id) {
	return d3.select("g#" + layer.name() + " path#" + id);
    };

/*
 Takes a shape layer and gives it a results-table.

 Hooks up all the events between shapes on the map, the table, and the layer's worksheet.

 Call this when a shape layer is ready for display.
 */
module.exports = function(container, zoomTo, onClickShape, onHoverShape, redraw) {
    return function(l) {
	var updateResultsTable = function() {
	    l.resultsTable.info(
		l.worksheet.headers(),
		l.worksheet.data(),
		l.worksheet.getSortProperties()
	    );
	};

	var recolour = function() {
	    if (l.worksheet.getSortProperties().properties.length > 0) {
		var colour = l.worksheet.colour(),
		    col = l.worksheet.firstSortPropertyI();

		l.resultsTable.rows().each(function(d, i) {
		    d3.select(this)
			.selectAll("td")
			.each(function(d, i) {
			    var el = d3.select(this);
			    var background = i === col ? colour(d) : null,
				font = i === col ? colours.reverse(background) : null;

			    el
				.style("background-color", background)
				.style("color", font);
			});
		});
	    } else {
		l.resultsTable.cells()
		    .style("background-color", null)
		    .style("color", null);
	    }

	    redraw();
	};

	if (!l.worksheet) {
	    throw new Error("Layer did not have a worksheet " + l.name());
	}

	if (!l.resultsTable) {
	    throw new Error("Layer did not have a results table " + l.name());
	}

	l.resultsTable.addToContainer(container);

	/*
	 When we click a header in the table, sort by that column.
	 */
	l.resultsTable.headerClicked(function(p) {
	    l.worksheet.sortProperty(p, d3.event.shiftKey);
	});

	l.resultsTable.rowClicked(function(d, i) {
	    /*
	     When we click on a row in the table, zoom to it on the map.

	     Highlight that row on the table, and hide all the others.
	     */
	    var id = d[0];
	    zoomTo(getShapeById(l, id).datum().bbox);

	    l.resultsTable.rows().
		classed("selected", function(d, i) {
		    return d[0] === id;
		});
	});

	l.resultsTable.rowHovered(function(d, i) {
	    /*
	     When we hover over a row in the table, highlight the corresponding shape in the map.
	     */
	    var id = d[0];

	    getShapes(l)
		.classed("highlight", function(d, i) {
		    return d.id === id;
		});
	});

	l.resultsTable.resetClicked(function() {
	    l.worksheet.sortProperty();
	});

	onClickShape(function(id, layer) {
	    /*
	     If we click on a shape, focus on it in the table.
	     */
	    var tbody = layer.resultsTable.tbody().node();

	    layer.resultsTable.rows().each(function(d, i) {
		var row = d3.select(this),
		    chosen = row.datum()[0] === id;

		if (chosen) {
		    tbody.scrollTop = this.offsetTop -
			/*
			 Fudge factor found by experimentation, appears to work at different zoom levels.
			 I don't know why this difference is here.
			 */
		    (2.7 * this.offsetHeight);
		}

		row.classed("selected", chosen);
	    });

	    layer.resultsTable.dialogue().show();
	});

	onHoverShape(function(id, layer) {
	    /*
	     Show the shape we're hovering the mouse cursor over as an extra layer in the table.
	     */
	    layer.resultsTable.setExtraRow(
		layer.resultsTable.rows().filter(function(d, i) {
		    return d3.select(this)
			.datum()[0] === id;
		})
	    );
	});

	l.worksheet.sortPropertyChanged(updateResultsTable);
	l.worksheet.sortPropertyChanged(recolour);
	l.worksheet.baseColourChanged(recolour);

	l.onSetOpacity(redraw);

	updateResultsTable();
    };
};
<commit_msg>Fixed problem with historical tables not getting their correct colours.<commit_after>"use strict";

/*global module, require*/

var d3 = require("d3"),
    colours = require("../colour.js"),

    getShapes = function(layer) {
	return d3.selectAll("g#" + layer.name() + " path");
    },

    getShapeById = function(layer, id) {
	return d3.select("g#" + layer.name() + " path#" + id);
    };

/*
 Takes a shape layer and gives it a results-table.

 Hooks up all the events between shapes on the map, the table, and the layer's worksheet.

 Call this when a shape layer is ready for display.
 */
module.exports = function(container, zoomTo, onClickShape, onHoverShape, redraw) {
    return function(l) {
	var updateResultsTable = function() {
	    l.resultsTable.info(
		l.worksheet.headers(),
		l.worksheet.data(),
		l.worksheet.getSortProperties()
	    );
	};

	var recolour = function() {
	    if (l.worksheet.getSortProperties().properties.length > 0) {
		var colour = l.worksheet.colour(),
		    col = l.worksheet.firstSortPropertyI();

		l.resultsTable.rows().each(function(d, i) {
		    d3.select(this)
			.selectAll("td")
			.each(function(d, i) {
			    var el = d3.select(this);
			    var background = i === col ? colour(d) : null,
				font = i === col ? colours.reverse(background) : null;

			    el
				.style("background-color", background)
				.style("color", font);
			});
		});
	    } else {
		l.resultsTable.cells()
		    .style("background-color", null)
		    .style("color", null);
	    }

	    redraw();
	};

	if (!l.worksheet) {
	    throw new Error("Layer did not have a worksheet " + l.name());
	}

	if (!l.resultsTable) {
	    throw new Error("Layer did not have a results table " + l.name());
	}

	l.resultsTable.addToContainer(container);

	/*
	 When we click a header in the table, sort by that column.
	 */
	l.resultsTable.headerClicked(function(p) {
	    l.worksheet.sortProperty(p, d3.event.shiftKey);
	});

	l.resultsTable.rowClicked(function(d, i) {
	    /*
	     When we click on a row in the table, zoom to it on the map.

	     Highlight that row on the table, and hide all the others.
	     */
	    var id = d[0];
	    zoomTo(getShapeById(l, id).datum().bbox);

	    l.resultsTable.rows().
		classed("selected", function(d, i) {
		    return d[0] === id;
		});
	});

	l.resultsTable.rowHovered(function(d, i) {
	    /*
	     When we hover over a row in the table, highlight the corresponding shape in the map.
	     */
	    var id = d[0];

	    getShapes(l)
		.classed("highlight", function(d, i) {
		    return d.id === id;
		});
	});

	l.resultsTable.resetClicked(function() {
	    l.worksheet.sortProperty();
	});

	onClickShape(function(id, layer) {
	    /*
	     If we click on a shape, focus on it in the table.
	     */
	    var tbody = layer.resultsTable.tbody().node();

	    layer.resultsTable.rows().each(function(d, i) {
		var row = d3.select(this),
		    chosen = row.datum()[0] === id;

		if (chosen) {
		    tbody.scrollTop = this.offsetTop -
			/*
			 Fudge factor found by experimentation, appears to work at different zoom levels.
			 I don't know why this difference is here.
			 */
		    (2.7 * this.offsetHeight);
		}

		row.classed("selected", chosen);
	    });

	    layer.resultsTable.dialogue().show();
	});

	onHoverShape(function(id, layer) {
	    /*
	     Show the shape we're hovering the mouse cursor over as an extra layer in the table.
	     */
	    layer.resultsTable.setExtraRow(
		layer.resultsTable.rows().filter(function(d, i) {
		    return d3.select(this)
			.datum()[0] === id;
		})
	    );
	});

	l.worksheet.sortPropertyChanged(updateResultsTable);
	l.worksheet.sortPropertyChanged(recolour);
	l.worksheet.baseColourChanged(recolour);

	l.onSetOpacity(redraw);

	updateResultsTable();
	recolour();
    };
};
<|endoftext|>


<commit_before>/*
 * testunitfmt_en_GB.js - test the unitfmt for en-GB
 *
 * Copyright © 2021 JEDLSoft
 *
 * 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.
 */

if (typeof(UnitFmt) === "undefined") {
    var UnitFmt = require("../../lib/UnitFmt.js");
}
if (typeof(Measurement) === "undefined") {
    var Measurement = require("../../lib/Measurement.js");
}

if (typeof(MeasurementFactory) === "undefined") {
    var MeasurementFactory = require("../../lib/MeasurementFactory.js");
}

if (typeof(ilib) === "undefined") {
    var ilib = require("../../lib/ilib.js");
}

if (typeof(TemperatureUnit) === "undefined") {
    var TemperatureUnit = require("../../lib/TemperatureUnit.js");
}

module.exports.testunitfmt_en_GB = {
    setUp: function(callback) {
        ilib.clearCache();
        callback();
    },
    testUnitFormatGetLocale_en_GB: function(test) {
        test.expect(2);
        var uf = new UnitFmt({
            locale: "en-GB"
        });
        test.ok(uf.getLocale());
        test.equal(uf.getLocale().getSpec(), "en-GB");
        test.done();
    },
    testGetMeasurementSystem_en_GB: function(test) {
        test.expect(1);

        test.equal(Measurement.getMeasurementSystemForLocale("en-GB"), "metric");
        test.done();
    },
    testGetTemperatureUnit_en_GB: function(test) {
        test.expect(2);

        var tu = new TemperatureUnit();
        test.ok(tu);
        var unit = tu.localize("en-GB").getUnit();

        test.equal(unit, "celsius");
        test.done();
    },
    testUnitFormatTemperature1_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "fahrenheit",
            amount: 2
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            length: "short",
            autoConvert: true,
            maxFractionDigits: 2,
            roundingMode: "down"
        });
        var str = uf.format(m1);
        test.equal(str, "-16.66°C");
        test.done();
    },
    testUnitFormatTemperature2_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "fahrenheit",
            amount: 2
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            autoConvert: true,
            autoScale: true,
            length: "long"
        });
        var str = uf.format(m1);
        test.equal(str, "-16.666666666666668 degrees Celsius");
        test.done();
    },
    testUnitFormatArea1_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "square centimeter",
            amount: 2
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            autoConvert:true,
            length:"short"
        });

        var str = uf.format(m1);
        test.equal(str, "2 cm²");
        test.done();
    },
    testUnitFormatArea2_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "square centimeter",
            amount: 2
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            autoConvert: true,
            length: "long"
        });

        var str = uf.format(m1);
        test.equal(str, "2 square centimetres");
        test.done();
    },
    testUnitFormatArea3_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "hectare",
            amount: 1000
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            autoConvert: true,
            length: "short"
        });

        var str = uf.format(m1);
        test.equal(str, "10 km²");
        test.done();
    },
    testUnitFormatArea4_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "hectare",
            amount: 1000
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            autoConvert: true,
            length: "long"
        });

        var str = uf.format(m1);
        test.equal(str, "10 square kilometres");
        test.done();
    },
    testUnitFormatFuelConsumption1_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "km/liter",
            amount: 2
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            autoConvert: true,
            length: "short"
        });
        var str = uf.format(m1);
        test.equal(str, "2 km/l");
        test.done();
    },
    testUnitFormatFuelConsumption2_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "km/liter",
            amount: 2
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            autoConvert: true,
            length: "long"
        });
        var str = uf.format(m1);
        test.equal(str, "2 kilometres per litre");
        test.done();
    },
    testUnitFormatLength1_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "mile",
            amount: 2000
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            autoConvert: true,
            length: "short"
        });
        var str = uf.format(m1);
        test.equal(str, "3.21868 Mm");
        test.done();
    },
    testUnitFormatLength2_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "mile",
            amount: 2000
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            autoConvert: true,
            length: "long"
        });
        var str = uf.format(m1);
        test.equal(str, "3.21868 megameters");
        test.done();
    },
    testUnitFormatWithUsageVehicleDistance1_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "km",
            amount: 10
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            usage: "vehicleDistance",
            length: "short",
            autoConvert: true,
        });
        var str = uf.format(m1);
        test.equal(str, "10 km");
        test.done();
    },
    testUnitFormatWithUsageVehicleDistance2_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "km",
            amount: 10
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            usage: "vehicleDistance",
            length: "long",
            autoConvert: true
        });
        var str = uf.format(m1);
        test.equal(str, "10 kilometres");
        test.done();
    },
    testUnitFormatWithUsageFuelVolume1_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "imperial gallon",
            amount: 2
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            usage: "fuelVolume",
            length: "short",
            autoConvert: true
        });

        var str = uf.format(m1);
        test.equal(str, "9.09 l");
        test.done();
    },
    testUnitFormatWithUsageFuelVolume2_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "imperial gallon",
            amount: 2
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            usage: "fuelVolume",
            length: "long",
            autoConvert: true
        });

        var str = uf.format(m1);
        test.equal(str, "9.09 litres");
        test.done();
    },
    testUnitFormatWithUsageOverrideSignificantDigits1_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "kWh",
            amount: 102.338322234
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            usage: "electricalEnergy",
            length: "short",
            significantDigits: "6",
            autoConvert: true
        });

        var str = uf.format(m1);
        test.equal(str, "102.338 kWh");
        test.done();
    },
    testUnitFormatWithUsageOverrideSignificantDigits2_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "kWh",
            amount: 102.338322234
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            usage: "electricalEnergy",
            length: "long",
            significantDigits: "6",
            autoConvert: true
        });

        var str = uf.format(m1);
        test.equal(str, "102.338 kilowatt-hours");
        test.done();
    },
    testUnitFormatWithUsagePersonWeight_Short_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "kg",
            amount: 58
        });

        var uf = new UnitFmt({
            usage: "personWeight",
            measurementSystem: "imperial",
            length: "short",
            locale: "en-GB"
        });
        var str = uf.format(m1);
        test.equal(str, "128 lb");
        test.done();
    },
    testUnitFormatWithUsagePersonWeight_Long_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "kg",
            amount: 58
        });

        var uf = new UnitFmt({
            usage: "personWeight",
            measurementSystem: "imperial",
            length: "long",
            locale: "en-GB"
        });
        var str = uf.format(m1);
        test.equal(str, "128 pounds");
        test.done();
    },
    testUnitFormatWithUsagePersonHeight_Short_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "cm",
            amount: 178
        });

        var uf = new UnitFmt({
            usage: "personHeight",
            measurementSystem: "imperial",
            length: "short",
            locale: "en-GB"
        });
        var str = uf.format(m1);
        test.equal(str, "5 ft, 10 in");
        test.done();
    },
    testUnitFormatWithUsagePersonHeight_Long_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "cm",
            amount: 178
        });

        var uf = new UnitFmt({
            usage: "personHeight",
            measurementSystem: "imperial",
            length: "long",
            locale: "en-GB"
        });
        var str = uf.format(m1);
        test.equal(str, "5 feet, 10 inches");
        test.done();
    },
    testUnitFormatWithUsageBabyHeight_Short_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "cm",
            amount: 40
        });

        var uf = new UnitFmt({
            usage: "babyHeight",
            measurementSystem: "imperial",
            length: "short",
            locale: "en-GB",
            style: "numeric"
        });
        var str = uf.format(m1);
        test.equal(str, "15.7 in");
        test.done();
    },
    testUnitFormatWithUsageBabyHeight_Long_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "cm",
            amount: 40
        });

        var uf = new UnitFmt({
            usage: "babyHeight",
            measurementSystem: "imperial",
            length: "long",
            locale: "en-GB",
            style: "numeric"
        });
        var str = uf.format(m1);
        test.equal(str, "15.7 inches");
        test.done();
    },
    testUnitFormatWithUsageBabyWeight_Short_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "kg",
            amount: 14
        });

        var uf = new UnitFmt({
            usage: "babyWeight",
            measurementSystem: "imperial",
            length: "short",
            locale: "en-GB",
            style: "numeric"
        });
        var str = uf.format(m1);
        test.equal(str, "30 lb, 14 oz");
        test.done();
    },
    testUnitFormatWithUsageBabyWeight_Long_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "kg",
            amount: 14
        });

        var uf = new UnitFmt({
            usage: "babyWeight",
            measurementSystem: "imperial",
            length: "long",
            locale: "en-GB",
            style: "numeric"
        });
        var str = uf.format(m1);
        test.equal(str, "30 pounds, 14 ounces");
        test.done();
    },
    testUnitFormatWithUsageDrinkVolume_short_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "ml",
            amount: 1234
        });

        var uf = new UnitFmt({
            usage: "drinkVolume",
            length: "short",
            measurementSystem: "imperial"
        });
        var str = uf.format(m1);
        test.equal(str, "1.09 qt(i)");
        test.done();
    },
    testUnitFormatWithUsageDrinkVolume_Long_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "ml",
            amount: 1234
        });

        var uf = new UnitFmt({
            usage: "drinkVolume",
            length: "long",
            measurementSystem: "imperial"
        });
        var str = uf.format(m1);
        test.equal(str, "1.09 imperial quarts");
        test.done();
    },
    testUnitFormatWithUsageGasVolume_short_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "liter",
            amount: 2500
        });

        var uf = new UnitFmt({
            usage: "gasVolume",
            length: "short",
            locale: "en-GB"
        });
        var str = uf.format(m1);
        test.equal(str, "2.5 m³");
        test.done();
    },
    testUnitFormatWithUsageGasVolume_long_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "liter",
            amount: 2500
        });

        var uf = new UnitFmt({
            usage: "gasVolume",
            length: "long",
            locale: "en-GB"
        });
        var str = uf.format(m1);
        test.equal(str, "2.5 cubic metres");
        test.done();
    },
}<commit_msg>Update test cases. Remove imperial value from the option. Currently, all fails<commit_after>/*
 * testunitfmt_en_GB.js - test the unitfmt for en-GB
 *
 * Copyright © 2021 JEDLSoft
 *
 * 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.
 */

if (typeof(UnitFmt) === "undefined") {
    var UnitFmt = require("../../lib/UnitFmt.js");
}
if (typeof(Measurement) === "undefined") {
    var Measurement = require("../../lib/Measurement.js");
}

if (typeof(MeasurementFactory) === "undefined") {
    var MeasurementFactory = require("../../lib/MeasurementFactory.js");
}

if (typeof(ilib) === "undefined") {
    var ilib = require("../../lib/ilib.js");
}

if (typeof(TemperatureUnit) === "undefined") {
    var TemperatureUnit = require("../../lib/TemperatureUnit.js");
}

module.exports.testunitfmt_en_GB = {
    setUp: function(callback) {
        ilib.clearCache();
        callback();
    },
    testUnitFormatGetLocale_en_GB: function(test) {
        test.expect(2);
        var uf = new UnitFmt({
            locale: "en-GB"
        });
        test.ok(uf.getLocale());
        test.equal(uf.getLocale().getSpec(), "en-GB");
        test.done();
    },
    testGetMeasurementSystem_en_GB: function(test) {
        test.expect(1);

        test.equal(Measurement.getMeasurementSystemForLocale("en-GB"), "metric");
        test.done();
    },
    testGetTemperatureUnit_en_GB: function(test) {
        test.expect(2);

        var tu = new TemperatureUnit();
        test.ok(tu);
        var unit = tu.localize("en-GB").getUnit();

        test.equal(unit, "celsius");
        test.done();
    },
    testUnitFormatTemperature1_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "fahrenheit",
            amount: 2
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            length: "short",
            autoConvert: true,
            maxFractionDigits: 2,
            roundingMode: "down"
        });
        var str = uf.format(m1);
        test.equal(str, "-16.66°C");
        test.done();
    },
    testUnitFormatTemperature2_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "fahrenheit",
            amount: 2
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            autoConvert: true,
            autoScale: true,
            length: "long"
        });
        var str = uf.format(m1);
        test.equal(str, "-16.666666666666668 degrees Celsius");
        test.done();
    },
    testUnitFormatArea1_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "square centimeter",
            amount: 2
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            autoConvert:true,
            length:"short"
        });

        var str = uf.format(m1);
        test.equal(str, "2 cm²");
        test.done();
    },
    testUnitFormatArea2_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "square centimeter",
            amount: 2
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            autoConvert: true,
            length: "long"
        });

        var str = uf.format(m1);
        test.equal(str, "2 square centimetres");
        test.done();
    },
    testUnitFormatArea3_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "hectare",
            amount: 1000
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            autoConvert: true,
            length: "short"
        });

        var str = uf.format(m1);
        test.equal(str, "10 km²");
        test.done();
    },
    testUnitFormatArea4_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "hectare",
            amount: 1000
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            autoConvert: true,
            length: "long"
        });

        var str = uf.format(m1);
        test.equal(str, "10 square kilometres");
        test.done();
    },
    testUnitFormatFuelConsumption1_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "km/liter",
            amount: 2
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            autoConvert: true,
            length: "short"
        });
        var str = uf.format(m1);
        test.equal(str, "2 km/l");
        test.done();
    },
    testUnitFormatFuelConsumption2_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "km/liter",
            amount: 2
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            autoConvert: true,
            length: "long"
        });
        var str = uf.format(m1);
        test.equal(str, "2 kilometres per litre");
        test.done();
    },
    testUnitFormatLength1_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "mile",
            amount: 2000
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            autoConvert: true,
            length: "short"
        });
        var str = uf.format(m1);
        test.equal(str, "3.21868 Mm");
        test.done();
    },
    testUnitFormatLength2_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "mile",
            amount: 2000
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            autoConvert: true,
            length: "long"
        });
        var str = uf.format(m1);
        test.equal(str, "3.21868 megameters");
        test.done();
    },
    testUnitFormatWithUsageVehicleDistance1_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "km",
            amount: 10
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            usage: "vehicleDistance",
            length: "short",
            autoConvert: true,
        });
        var str = uf.format(m1);
        test.equal(str, "10 km");
        test.done();
    },
    testUnitFormatWithUsageVehicleDistance2_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "km",
            amount: 10
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            usage: "vehicleDistance",
            length: "long",
            autoConvert: true
        });
        var str = uf.format(m1);
        test.equal(str, "10 kilometres");
        test.done();
    },
    testUnitFormatWithUsageFuelVolume1_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "imperial gallon",
            amount: 2
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            usage: "fuelVolume",
            length: "short",
            autoConvert: true
        });

        var str = uf.format(m1);
        test.equal(str, "9.09 l");
        test.done();
    },
    testUnitFormatWithUsageFuelVolume2_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "imperial gallon",
            amount: 2
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            usage: "fuelVolume",
            length: "long",
            autoConvert: true
        });

        var str = uf.format(m1);
        test.equal(str, "9.09 litres");
        test.done();
    },
    testUnitFormatWithUsageOverrideSignificantDigits1_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "kWh",
            amount: 102.338322234
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            usage: "electricalEnergy",
            length: "short",
            significantDigits: "6",
            autoConvert: true
        });

        var str = uf.format(m1);
        test.equal(str, "102.338 kWh");
        test.done();
    },
    testUnitFormatWithUsageOverrideSignificantDigits2_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "kWh",
            amount: 102.338322234
        });

        var uf = new UnitFmt({
            locale: "en-GB",
            usage: "electricalEnergy",
            length: "long",
            significantDigits: "6",
            autoConvert: true
        });

        var str = uf.format(m1);
        test.equal(str, "102.338 kilowatt-hours");
        test.done();
    },
    testUnitFormatWithUsagePersonWeight_Short_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "kg",
            amount: 58
        });

        var uf = new UnitFmt({
            usage: "personWeight",
            length: "short",
            locale: "en-GB"
        });
        var str = uf.format(m1);
        test.equal(str, "128 lb");
        test.done();
    },
    testUnitFormatWithUsagePersonWeight_Long_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "kg",
            amount: 58
        });

        var uf = new UnitFmt({
            usage: "personWeight",
            length: "long",
            locale: "en-GB"
        });
        var str = uf.format(m1);
        test.equal(str, "128 pounds");
        test.done();
    },
    testUnitFormatWithUsagePersonHeight_Short_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "cm",
            amount: 178
        });

        var uf = new UnitFmt({
            usage: "personHeight",
            length: "short",
            locale: "en-GB"
        });
        var str = uf.format(m1);
        test.equal(str, "5 ft, 10 in");
        test.done();
    },
    testUnitFormatWithUsagePersonHeight_Long_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "cm",
            amount: 178
        });

        var uf = new UnitFmt({
            usage: "personHeight",
            length: "long",
            locale: "en-GB"
        });
        var str = uf.format(m1);
        test.equal(str, "5 feet, 10 inches");
        test.done();
    },
    testUnitFormatWithUsageBabyHeight_Short_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "cm",
            amount: 40
        });

        var uf = new UnitFmt({
            usage: "babyHeight",
            length: "short",
            locale: "en-GB",
            style: "numeric"
        });
        var str = uf.format(m1);
        test.equal(str, "15.7 in");
        test.done();
    },
    testUnitFormatWithUsageBabyHeight_Long_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "cm",
            amount: 40
        });

        var uf = new UnitFmt({
            usage: "babyHeight",
            length: "long",
            locale: "en-GB",
            style: "numeric"
        });
        var str = uf.format(m1);
        test.equal(str, "15.7 inches");
        test.done();
    },
    testUnitFormatWithUsageBabyWeight_Short_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "kg",
            amount: 2.5
        });

        var uf = new UnitFmt({
            usage: "babyWeight",
            length: "short",
            locale: "en-GB",
            style: "numeric"
        });
        var str = uf.format(m1);
        test.equal(str, "5 lb, 8 oz");
        test.done();
    },
    testUnitFormatWithUsageBabyWeight_Long_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "kg",
            amount: 2.5
        });

        var uf = new UnitFmt({
            usage: "babyWeight",
            length: "long",
            locale: "en-GB",
            style: "numeric"
        });
        var str = uf.format(m1);
        test.equal(str, "5 pounds, 8 ounces");
        test.done();
    },
    testUnitFormatWithUsageDrinkVolume_short_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "ml",
            amount: 569
        });

        var uf = new UnitFmt({
            usage: "drinkVolume",
            length: "short",
        });
        var str = uf.format(m1);
        test.equal(str, "1 pt(i)");
        test.done();
    },
    testUnitFormatWithUsageDrinkVolume_Long_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "ml",
            amount: 569
        });

        var uf = new UnitFmt({
            usage: "drinkVolume",
            length: "long",
        });
        var str = uf.format(m1);
        test.equal(str, "1 imperial pint");
        test.done();
    },
    testUnitFormatWithUsageGasVolume_short_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "liter",
            amount: 2500
        });

        var uf = new UnitFmt({
            usage: "gasVolume",
            length: "short",
            locale: "en-GB"
        });
        var str = uf.format(m1);
        test.equal(str, "2.5 m³");
        test.done();
    },
    testUnitFormatWithUsageGasVolume_long_en_GB: function(test) {
        test.expect(1);
        var m1 = MeasurementFactory({
            unit: "liter",
            amount: 2500
        });

        var uf = new UnitFmt({
            usage: "gasVolume",
            length: "long",
            locale: "en-GB"
        });
        var str = uf.format(m1);
        test.equal(str, "2.5 cubic metres");
        test.done();
    },
}<|endoftext|>


<commit_before>import app from '../../../app';
import { getWallet, launchWallet } from '../../../utils/modalManager';
import { openSimpleMessage } from '../../modals/SimpleMessage';
import loadTemplate from '../../../utils/loadTemplate';
import baseVw from '../../baseVw';
import { clipboard } from 'electron';
import qr from 'qr-encode';

const obDonationAddress = '3QxbMjed45NLXnkUg9yYHRgbKCeLyZa4La';
const qrCodeDataURI = qr(`bitcoin:${obDonationAddress}`, { type: 6, size: 6, level: 'Q' });
const donationCountFloor = 500;
let hiderTimer;

export default class extends baseVw {
  constructor(options = {}) {
    super({
      className: 'aboutDonations',
      ...options,
    });
  }

  events() {
    return {
      'click .js-copyAddress': 'copyDonationAddress',
      'click .js-openInWallet': 'openInWalletClick',
    };
  }

  copyDonationAddress() {
    clipboard.writeText(obDonationAddress);

    this.$copyNotification.addClass('active');
    if (!!hiderTimer) {
      clearTimeout(hiderTimer);
    }
    hiderTimer = setTimeout(
      () => this.$copyNotification.removeClass('active'), 3000);
  }

  get $copyNotification() {
    return this._$copyNotification ||
      (this._$copyNotification = this.$('.js-copyNotification'));
  }

  openInWalletClick() {
    const wallet = getWallet();

    if (!wallet) {
      launchWallet()
        .setSendFormData({ address: obDonationAddress });
    } else {
      if (wallet.setSendFormData({ address: obDonationAddress })) {
        wallet.open(false);
      } else {
        openSimpleMessage(app.polyglot.t('about.donationsTab.unableToOpenInWallet.title'),
          app.polyglot.t('about.donationsTab.unableToOpenInWallet.body'));
      }
    }
  }

  render() {
    loadTemplate('modals/about/donations.html', (t) => {
      this.$el.html(t({
        obDonationAddress,
        donationCountFloor,
        qrCodeDataURI,
      }));
    });

    return this;
  }
}

<commit_msg>update address<commit_after>import app from '../../../app';
import { getWallet, launchWallet } from '../../../utils/modalManager';
import { openSimpleMessage } from '../../modals/SimpleMessage';
import loadTemplate from '../../../utils/loadTemplate';
import baseVw from '../../baseVw';
import { clipboard } from 'electron';
import qr from 'qr-encode';

const obDonationAddress = '3EN8kP3yW9MGvyiRMtGqKavQ9wYg4BspzR';
const qrCodeDataURI = qr(`bitcoin:${obDonationAddress}`, { type: 6, size: 6, level: 'Q' });
const donationCountFloor = 500;
let hiderTimer;

export default class extends baseVw {
  constructor(options = {}) {
    super({
      className: 'aboutDonations',
      ...options,
    });
  }

  events() {
    return {
      'click .js-copyAddress': 'copyDonationAddress',
      'click .js-openInWallet': 'openInWalletClick',
    };
  }

  copyDonationAddress() {
    clipboard.writeText(obDonationAddress);

    this.$copyNotification.addClass('active');
    if (!!hiderTimer) {
      clearTimeout(hiderTimer);
    }
    hiderTimer = setTimeout(
      () => this.$copyNotification.removeClass('active'), 3000);
  }

  get $copyNotification() {
    return this._$copyNotification ||
      (this._$copyNotification = this.$('.js-copyNotification'));
  }

  openInWalletClick() {
    const wallet = getWallet();

    if (!wallet) {
      launchWallet()
        .setSendFormData({ address: obDonationAddress });
    } else {
      if (wallet.setSendFormData({ address: obDonationAddress })) {
        wallet.open(false);
      } else {
        openSimpleMessage(app.polyglot.t('about.donationsTab.unableToOpenInWallet.title'),
          app.polyglot.t('about.donationsTab.unableToOpenInWallet.body'));
      }
    }
  }

  render() {
    loadTemplate('modals/about/donations.html', (t) => {
      this.$el.html(t({
        obDonationAddress,
        donationCountFloor,
        qrCodeDataURI,
      }));
    });

    return this;
  }
}

<|endoftext|>


<commit_before>/* 控制导航按钮动作 */
function nav_click(is_show) {
  if (is_show) {
    /* 显示左侧aside */
    $('.aside')
      .addClass('visible-md visible-lg')
      .removeClass('hidden-md hidden-lg')
    /* 调整右侧内容 */
    $('.aside3')
      .removeClass('col-md-13 col-lg-13')
      .addClass('col-md-13 col-lg-13');
    /* 调整文字内容格式 */
    $('.aside3-content')
      .removeClass('col-md-10 col-lg-8 col-md-offset-1 col-lg-offset-2')
      .addClass('col-md-13');
  } else {
    /* 隐藏左侧aside */
    $('.aside')
      .removeClass('visible-md visible-lg')
      .addClass('hidden-md hidden-lg');
    /* 右侧内容最大化 */
    $('.aside3')
      .removeClass('col-md-13 col-lg-13')
      .addClass('col-md-13 col-lg-13');
    /* 修改文字排版 */
    $('.aside3-content')
      .removeClass('col-md-13')
      .addClass('col-md-10 col-lg-8 col-md-offset-1 col-lg-offset-2');
  }  /*col-md-offset-1 col-lg-offset-2*/
}
/* 控制文章章节列表按钮 */
function content_click(is_show){
  if (is_show) {
    $('#content_table').show();
    $('#content_btn i').removeClass('fa-plus').addClass('fa-minus');
  } else {
    $('#content_table').hide();
    $('#content_btn i').removeClass('fa-minus').addClass('fa-plus');
  }
}

$(document).ready(function() {
  /* 控制左侧 aside 的动作 */
  $("#nav_btn").on('click', function() {
    isClicked = $(this).data('clicked');

    nav_click(isClicked);

    $(this).data('clicked', !isClicked);
  });

  $("#content_btn").on('click', function(){
    isClicked = $(this).data('clicked');

    content_click(!isClicked);

    $(this).data('clicked',!isClicked);

  });

  $(document).pjax('.pjaxlink', '#pjax', { fragment: "#pjax", timeout: 10000 });
  $(document).on("pjax:end", function() {
    if($("body").find('.container').width() < 992)
      $('#nav_btn').click();
    $('.aside3').scrollTop(0);
    contentEffects();
  });
  $('body').on('click', '.show-commend', function(){
    var ds_loaded = false;
    window.disqus_shortname = $('.show-commend').attr('name');
    $.ajax({
      type: "GET",
      url: "http://" + disqus_shortname + ".disqus.com/embed.js",
      dataType: "script",
      cache: true
    });
  });
  contentEffects();
});
function contentEffects(){
  //remove the asidebar
  $('.row-offcanvas').removeClass('active');
  if($("#nav").length > 0){
    $("#content > h2,#content > h3,#content > h4,#content > h5,#content > h6").each(function(i) {
        var current = $(this);
        current.attr("id", "title" + i);
        tag = current.prop('tagName').substr(-1);
        $("#nav").append("
" + current.html() + "
");
    });
    $("pre").addClass("prettyprint");
    prettyPrint();
    $('#content img').addClass('img-thumbnail').parent('p').addClass('center');
    $('#content_btn').show();
  }else{
    $('#content_btn').hide();
  }
}<commit_msg>添加h1的目录<commit_after>/* 控制导航按钮动作 */
function nav_click(is_show) {
  if (is_show) {
    /* 显示左侧aside */
    $('.aside')
      .addClass('visible-md visible-lg')
      .removeClass('hidden-md hidden-lg')
    /* 调整右侧内容 */
    $('.aside3')
      .removeClass('col-md-13 col-lg-13')
      .addClass('col-md-13 col-lg-13');
    /* 调整文字内容格式 */
    $('.aside3-content')
      .removeClass('col-md-10 col-lg-8 col-md-offset-1 col-lg-offset-2')
      .addClass('col-md-13');
  } else {
    /* 隐藏左侧aside */
    $('.aside')
      .removeClass('visible-md visible-lg')
      .addClass('hidden-md hidden-lg');
    /* 右侧内容最大化 */
    $('.aside3')
      .removeClass('col-md-13 col-lg-13')
      .addClass('col-md-13 col-lg-13');
    /* 修改文字排版 */
    $('.aside3-content')
      .removeClass('col-md-13')
      .addClass('col-md-10 col-lg-8 col-md-offset-1 col-lg-offset-2');
  }  /*col-md-offset-1 col-lg-offset-2*/
}
/* 控制文章章节列表按钮 */
function content_click(is_show){
  if (is_show) {
    $('#content_table').show();
    $('#content_btn i').removeClass('fa-plus').addClass('fa-minus');
  } else {
    $('#content_table').hide();
    $('#content_btn i').removeClass('fa-minus').addClass('fa-plus');
  }
}

$(document).ready(function() {
  /* 控制左侧 aside 的动作 */
  $("#nav_btn").on('click', function() {
    isClicked = $(this).data('clicked');

    nav_click(isClicked);

    $(this).data('clicked', !isClicked);
  });

  $("#content_btn").on('click', function(){
    isClicked = $(this).data('clicked');

    content_click(!isClicked);

    $(this).data('clicked',!isClicked);

  });

  $(document).pjax('.pjaxlink', '#pjax', { fragment: "#pjax", timeout: 10000 });
  $(document).on("pjax:end", function() {
    if($("body").find('.container').width() < 992)
      $('#nav_btn').click();
    $('.aside3').scrollTop(0);
    contentEffects();
  });
  $('body').on('click', '.show-commend', function(){
    var ds_loaded = false;
    window.disqus_shortname = $('.show-commend').attr('name');
    $.ajax({
      type: "GET",
      url: "http://" + disqus_shortname + ".disqus.com/embed.js",
      dataType: "script",
      cache: true
    });
  });
  contentEffects();
});
function contentEffects(){
  //remove the asidebar
  $('.row-offcanvas').removeClass('active');
  if($("#nav").length > 0){
    $("#content > h1,#content > h2,#content > h3,#content > h4,#content > h5,#content > h6").each(function(i) {
        var current = $(this);
        current.attr("id", "title" + i);
        tag = current.prop('tagName').substr(-1);
        $("#nav").append("
" + current.html() + "
");
    });
    $("pre").addClass("prettyprint");
    prettyPrint();
    $('#content img').addClass('img-thumbnail').parent('p').addClass('center');
    $('#content_btn').show();
  }else{
    $('#content_btn').hide();
  }
}<|endoftext|>


<commit_before>
function clearChat(){
   $("wrapper").html("");
}

function showChat(){

   clearChat();

   var chatUid = activeEntity.uid;
   var entityType = activeEntity.entity;

   //show Header
   DB.child(entityType+"/"+chatUid).once("value", function(dataSnapshot){
      var entityTypeLocal = entityTypeToHebrew(entityType);
      renderTemplate("#chatsHeader-tmpl",{entityType:entityTypeLocal, title:dataSnapshot.val().title },"#headerTitle");

      DB.child("chats/"+chatUid).update({title: "("+entityTypeLocal+") "+ dataSnapshot.val().title})

   });

   //show footer
   renderTemplate("#chatInput-tmpl",{},"footer");

   //listen to enter from input
   $("#chatInputTxt").keypress(function (e) {
      if (e.keyCode == 13) {
         e.preventDefault();

         addChatMessagePre(chatUid,entityType);
      }
   });

   //get chat messages

   var chatCallback = function(chats){
      if(chats.exists()){
         var text = chats.val().text;
         var time =  parseDate(chats.val().dateAdded);
         var author = chats.val().userName;

         var context = {text:text, time: time, author:author};
         appendTemplate("#chatMessage-tmpl", context, "wrapper");

         $('wrapper').scrollTop($('wrapper')[0].scrollHeight);
      }

      if (userUpdatesSet) {
         $("#globalNotificationsSub").css("color", activeColor);
      } else {
         $("#globalNotificationsSub").css("color", inactiveColor);
      }
   };

   DB.child("chats/"+chatUid).orderByChild("dateAdded").limitToLast(20).on("child_added", chatCallback);

   setActiveEntity("chats", chatUid, "child_added", chatCallback);

   //Notifications

   userUpdates = DB.child("users/"+userUuid+"/entityNotifications/"+activeEntity.entity+"/"+activeEntity.uid);

   userUpdates.once('value', function(data) {

      userUpdatesSet = data.child("/globalNotifications").exists();

      if(userUpdatesSet)
         DB.child("users/"+userUuid+"/chatInboxes/"+chatUid).set(0);

   });
}

function addChatMessage(chatUid, userUid, text, entityType){

   if (text != "") {

      //get user name
      DB.child("users/"+userUid).once("value", function(user) {
         var userName = user.val().name;

         DB.child("chats/"+chatUid).push({dateAdded: firebase.database.ServerValue.TIMESTAMP, user: userUid, userName:userName, text: text, chatUid: chatUid,entityType: entityType });

      })
   }
}

function addChatMessagePre(chatUid, entityType){

   if (chatUid == null || chatUid == undefined){
      chatUid = activeEntity.uid;
      entityType = activeEntity.entity;
   }

   var inputValue=$("#chatInputTxt").val();
   addChatMessage(chatUid, userUuid, inputValue, entityType);
   $("#chatInputTxt").val("");
}

<commit_msg>bug 2<commit_after>
function clearChat(){
   $("wrapper").html("");
}

function showChat(){

   clearChat();

   var chatUid = activeEntity.uid;
   var entityType = activeEntity.entity;

   //show Header
   DB.child(entityType+"/"+chatUid).once("value", function(dataSnapshot){
      var entityTypeLocal = entityTypeToHebrew(entityType);
      renderTemplate("#chatsHeader-tmpl",{entityType:entityTypeLocal, title:dataSnapshot.val().title },"#headerTitle");

      DB.child("chats/"+chatUid).update({title: "("+entityTypeLocal+") "+ dataSnapshot.val().title})

   });

   //show footer
   renderTemplate("#chatInput-tmpl",{},"footer");

   //listen to enter from input
   $("#chatInputTxt").keypress(function (e) {
      if (e.keyCode == 13) {
         e.preventDefault();

         addChatMessagePre(chatUid,entityType);
      }
   });

   //get chat messages

   var chatCallback = function(chats){
      if(chats.exists()){
         var text = chats.val().text;
         var time =  parseDate(chats.val().dateAdded);
         var author = chats.val().userName;

         var context = {text:text, time: time, author:author};
         appendTemplate("#chatMessage-tmpl", context, "wrapper");

         $('wrapper').scrollTop($('wrapper')[0].scrollHeight);
      }

//      if (userUpdatesSet) {
//         $("#globalNotificationsSub").css("color", activeColor);
//      } else {
//         $("#globalNotificationsSub").css("color", inactiveColor);
//      }
   };

   DB.child("chats/"+chatUid).orderByChild("dateAdded").limitToLast(20).on("child_added", chatCallback);

   setActiveEntity("chats", chatUid, "child_added", chatCallback);

   //Notifications

   userUpdates = DB.child("users/"+userUuid+"/entityNotifications/"+activeEntity.entity+"/"+activeEntity.uid);

   userUpdates.once('value', function(data) {

      userUpdatesSet = data.child("/globalNotifications").exists();

      if(userUpdatesSet)
         DB.child("users/"+userUuid+"/chatInboxes/"+chatUid).set(0);

   });
}

function addChatMessage(chatUid, userUid, text, entityType){

   if (text != "") {

      //get user name
      DB.child("users/"+userUid).once("value", function(user) {
         var userName = user.val().name;

         DB.child("chats/"+chatUid).push({dateAdded: firebase.database.ServerValue.TIMESTAMP, user: userUid, userName:userName, text: text, chatUid: chatUid,entityType: entityType });

      })
   }
}

function addChatMessagePre(chatUid, entityType){

   if (chatUid == null || chatUid == undefined){
      chatUid = activeEntity.uid;
      entityType = activeEntity.entity;
   }

   var inputValue=$("#chatInputTxt").val();
   addChatMessage(chatUid, userUuid, inputValue, entityType);
   $("#chatInputTxt").val("");
}

<|endoftext|>


<commit_before>// public/core.js
var fatCatsFeeding = angular.module('fatCatsFeeding', []);

fatCatsFeeding.controller('Controller', ['$scope', '$http', '$interval', function($scope, $http, $interval) {
  $scope.formData = {};
  $scope.quantity = 5;
  $scope.feedDate = '';
  $scope.amounts = [{"id": "1/2"}, {"id":"1/3"}, {"id":"1"}];
  $scope.refresh = function() {
    /**
     * Set $scope.feedings to feedings API get results.
     */
    $http.get('/api/feedings')
      .success(function(data) {
        $scope.feedings = data;
      })
      .error(function(data) {
        console.log('ERR: '+data);
      });

    /**
     * Set $scope.catfoods to catfoods API get results.
     */
    $http.get('/api/catfoods')
      .success(function(data) {
        $scope.catfoods = data;
      })
      .error(function(data) {
        console.log('ERR: '+data);
      });
  };
  $scope.refresh();

  /**
   * POST form results to /api/feedings
   */
  $scope.createFeeding = function() {
    $http.post('/api/feedings', $scope.formData)
      .success(function(data){
        $scope.formData = {};
        $scope.feedings = data;
      })
      .error(function(data){
        console.log('ERR: '+data);
      });
  };
  /**
   * DELETE by ID
   */
  $scope.deleteFeeding = function(id) {
    $http.delete('/api/feedings/'+id)
      .success(function(data) {
        $scope.refresh();
      })
      .error(function(data) {
          console.log('ERR: '+data);
      });
  };
  /**
   * Remove with undo
   */
   var deferId; //interval id
   $scope.showUndo = false; // Hide undo warning
   $scope.removeFeeding = function(id, date) {
     $scope.feedDate = new Date(date);
     $scope.showUndo = true; // Show undo warning
     $scope.feedings = _.filter($scope.feedings, function(feeding) {
       return feeding._id !== id;
     });
     deferId = $interval(function () {
          $scope.showUndo = false;
          $scope.deleteFeeding(id);
          $interval.cancel(deferId);
      }, 15000);
   };

 /**
  * Undo Remove
  */
  $scope.undoRemove = function() {
      $interval.cancel(deferId);
      $scope.showUndo = false;
      $scope.refresh();
  };

 /**
  * PUT by ID
  */
  $scope.update = function(feeding, food, foodAmount) {
    console.log(feeding);
    console.log(food);
    console.log(foodAmount);
    $http.put('/api/feedings/'+feeding, {food: food, amount: foodAmount})
      .success(function(data) {
        $scope.refresh();
      })
      .error(function(data) {
          console.log('ERR: '+data);
      });
  };

}]);

fatCatsFeeding.directive('myElapsed', ['$interval', function($interval) {
  function link(scope, element, attr) {
    var timeoutId;

    function updateTime() {
      element.text(getElapsed(scope.feedings[0].datetime));
    }

    scope.$watch(attr.myCurrentTime, function(value) {
      updateTime();
    });

    element.on('$destroy', function() {
      $interval.cancel(timeoutId);
    });

    timeoutId = $interval(function() {
      updateTime();
    }, 1000);
  }
  return {
    link : link
  };
}]);

/**
 * Return formatted string containing "elapsed time" since input
 */
function getElapsed(date){
    if (!date) return;
    var time = Date.parse(date),
        timeNow = new Date().getTime(),
        difference = timeNow - time,
        seconds = Math.floor(difference / 1000),
        minutes = Math.floor(seconds / 60),
        hours = Math.floor(minutes / 60),
        days = Math.floor(hours / 24);
    if (days > 1) {
        return days + " days ago";
    } else if (days == 1) {
        return "1 day ago";
    } else if (hours > 1) {
        return hours + " hours ago";
    } else if (hours == 1) {
        return "an hour ago";
    } else if (minutes > 1) {
        return minutes + " minutes ago";
    } else if (minutes == 1){
        return "a minute ago";
    } else {
        return "a few seconds ago";
    }
}
<commit_msg>Added modal popup controls. Updated .post to accept modal inputs. Cleaned up error with myElapsed directive. Other stuff I should have noted or commited long ago.<commit_after>// public/core.js
var fatCatsFeeding = angular.module('fatCatsFeeding', []);

fatCatsFeeding.controller('Controller', ['$scope', '$http', '$interval', function($scope, $http, $interval) {
  $scope.quantity = 5;
  $scope.feedDate = '';
  $scope.amounts = [{"id":"1/6"}, {"id": "1/4"}, {"id":"1/3"}, {"id":"1"}];
  $scope.modalSelection = {};
  $scope.forms = {};
  $scope.newFeeding = {
    datetime : getDatetime(),
    food : '5726b06124bf08692832fefd',
    amount : '1/4'
  };
  $scope.showUndo = false; // Hide undo warning
  var deferId; //interval id
  var prisFeeding = angular.copy($scope.newFeeding);

  $scope.refresh = function() {
    /**
     * Set $scope.feedings to feedings API get results.
     */
    $http.get('/api/feedings')
      .success(function(data) {
        $scope.feedings = data;
      })
      .error(function(data) {
        console.log('ERR: '+data);
      });

    /**
     * Set $scope.catfoods to catfoods API get results.
     */
    $http.get('/api/catfoods')
      .success(function(data) {
        $scope.catfoods = data;
      })
      .error(function(data) {
        console.log('ERR: '+data);
      });
  };
  $scope.refresh();

  /**
   * POST form results to /api/feedings
   */
  $scope.createFeeding = function() {
    $scope.newFeeding.datetime = setToGMT($scope.newFeeding.datetime);
    $http.post('/api/feedings', $scope.newFeeding)
      .success(function(data){
        $scope.newFeeding = angular.copy(prisFeeding);
        $scope.refresh();
      })
      .error(function(data){
        console.log('ERR: '+data);
      });
  };
  /**
   * DELETE by ID
   */
  $scope.deleteFeeding = function(id) {
    $http.delete('/api/feedings/'+id)
      .success(function(data) {
        $scope.refresh();
      })
      .error(function(data) {
          console.log('ERR: '+data);
      });
  };
  /**
   * Remove with undo
   */
   $scope.removeFeeding = function(id, date) {
     $scope.feedDate = new Date(date);
     $scope.showUndo = true; // Show undo warning
     $scope.feedings = _.filter($scope.feedings, function(feeding) {
       return feeding._id !== id;
     });
     deferId = $interval(function () {
          $scope.showUndo = false;
          $scope.deleteFeeding(id);
          $interval.cancel(deferId);
      }, 15000);
   };

 /**
  * Undo Remove
  */
  $scope.undoRemove = function() {
      $interval.cancel(deferId);
      $scope.showUndo = false;
      $scope.refresh();
  };

 /**
  * PUT by ID
  */
  $scope.update = function(feeding, food, foodAmount) {
    $http.put('/api/feedings/'+feeding, {food: food, amount: foodAmount})
      .success(function(data) {
        $scope.refresh();
      })
      .error(function(data) {
          console.log('ERR: '+data);
      });
  };

  $scope.resetModalForm = function() {
    $scope.newFeeding = angular.copy(prisFeeding);
    $scope.forms.modalFeedingForm.$setPristine();
  };

  $scope.toModalSelection = function(obj, prop) {
      var c = _.find($scope[obj], function(thisObj) {
          return thisObj._id === $scope.newFeeding.food;
      });
      $scope.modalSelection[obj] = { [prop] : c[prop] };
  };
}]);

fatCatsFeeding.directive('myElapsed', ['$interval', function($interval) {
  function link(scope, element, attr) {
    var timeoutId;

    function updateTime() {
      if (scope.feedings) {
        element.text(getElapsed(scope.feedings[0].datetime));
      }
    }

    scope.$watch(attr.myCurrentTime, function(value) {
      updateTime();
    });

    element.on('$destroy', function() {
      $interval.cancel(timeoutId);
    });

    timeoutId = $interval(function() {
      updateTime();
    }, 1000);
  }
  return {
    link : link
  };
}]);

/**
 * Return formatted string containing "elapsed time" since input
 */
function getElapsed(date){
    if (!date) return;
    var time = Date.parse(date),
        timeNow = new Date().getTime(),
        difference = timeNow - time,
        seconds = Math.floor(difference / 1000),
        minutes = Math.floor(seconds / 60),
        hours = Math.floor(minutes / 60),
        days = Math.floor(hours / 24);
    if (days > 1) {
        return days + " days ago";
    } else if (days == 1) {
        return "1 day ago";
    } else if (hours > 1) {
        return hours + " hours ago";
    } else if (hours == 1) {
        return "an hour ago";
    } else if (minutes > 1) {
        return minutes + " minutes ago";
    } else if (minutes == 1){
        return "a minute ago";
    } else {
        return "a few seconds ago";
    }
}

function getDatetime() {
  var nowDatetime = new Date();
  nowDatetime = new Date(nowDatetime.setSeconds(0,0));
  var tzOffset = nowDatetime.getTimezoneOffset() * 60 * 1000;
  var localDatetime = new Date(nowDatetime.getTime() - tzOffset);
  return localDatetime;
}

function setToGMT(datetime) {
  var tzOffset = datetime.getTimezoneOffset() * 60 * 1000;
  var gmtDatetime = new Date(datetime.getTime() + tzOffset);
  return gmtDatetime;
}
<|endoftext|>


<commit_before>var viz = viz || {};

// Data manipulation logic
viz.data = (function() {
  var API_BASE_URL = 'https://api.github.com';
  var API_USER = '/users/';
  var API_PUBLIC_EVENTS = '/events/public';
  var API_ORG = '/orgs/';
  var API_EVENTS = '/events';
  var API_PAGE_2_PARAM = '?page=2';

  var _commits = {};

  var _commitsByDate = {};

  var module = {};

  var _outStandingFeteches = {};

  var _filterPushEvents = function(event) {
    return event.type === 'PushEvent';
  };

  module.getOrgEvent = function(org, cb) {
    var url = API_BASE_URL + API_ORG + org + API_EVENTS;
    d3.json(url)
      .header('Authorization', 'Basic cGFyYWRpdGU6YTFhY2MzM2FlZDU2ZGE5OTg4YzY1NGJkMjQxNzdiZTY1NjFkZTllZQ==')
      .get(function(err, data) {
        if (err) {
          console.log(err);
        } else {
          console.log(data.filter(_filterPushEvents));
          // _updateCommitsFromPushes(user, data.filter(_filterPushEvents));
          // _fetchCommitDetails(user, cb);
        }
      });
  };

  module.getPubEvent = function(user, cb) {
    var url = API_BASE_URL + API_USER + user.username + API_PUBLIC_EVENTS;
    var userDetailUrl = API_BASE_URL + API_USER + user.username;

    async.parallel([
      function(callback) {
        d3.json(_useBackend(url))
          .header('Authorization', 'Basic cGFyYWRpdGU6YTFhY2MzM2FlZDU2ZGE5OTg4YzY1NGJkMjQxNzdiZTY1NjFkZTllZQ==')
          .get(callback);
      },
      function(callback) {
        d3.json(_useBackend(url + API_PAGE_2_PARAM))
          .header('Authorization', 'Basic cGFyYWRpdGU6YTFhY2MzM2FlZDU2ZGE5OTg4YzY1NGJkMjQxNzdiZTY1NjFkZTllZQ==')
          .get(callback);
      },
      function(callback) {
        d3.json(_useBackend(userDetailUrl))
          .header('Authorization', 'Basic cGFyYWRpdGU6YTFhY2MzM2FlZDU2ZGE5OTg4YzY1NGJkMjQxNzdiZTY1NjFkZTllZQ==')
          .get(callback);
      }
    ],
    function(err, results) {
      if (err) {
        console.log(err);
        cb('GitHub API error', null, null);
        return;
      }

      var data1 = results[0];
      var data = data1.concat(results[1]);
      var userdata = results[2];

      if (userdata.email && user.email === null) {
        user.email = userdata.email;
      }
      if (userdata.email === null && user.email === null) {
        cb('There is no GitHub public email for ' + user.username + ', please enter mannually', null, null);
        return;
      }
      if (userdata.name != null) {
        user.name = userdata.name;
      } else {
        user.name = null;
      }
      _updateCommitsFromPushes(user, data.filter(_filterPushEvents));
      _fetchCommitDetails(user, cb);
    });
  };

  var _updateCommitsFromPushes = function(user, data) {
    _commits[user.username] = [];
    data.forEach(function(event) {
      if (event['payload']['commits']) {
        event['payload']['commits'].forEach(function(commit) {
          if (isCommitValid(user, commit)) {
            // add the repo attr
            if (event['repo']['name']) {
              commit['repo'] = event['repo']['name'];
            } else {
              commit['repo'] = null;
            }
            _commits[user.username].push(commit);
          } else {
            // console.log("commit from others");
            // console.log(commit["author"]["email"]);
          }
        });
      }
      // _commits[user] = _commits[user].concat(event["payload"]["commits"]);
    });
  };

  var isCommitValid = function(user, commit) {
    if (user.email === (commit['author']['email'])) {
      return true;
    } else {
      return false;
    }
  };

  var _fetchCommitDetails = function(user, cb) {
    if (_commits[user.username].length === 0) {
      console.log('user does not exist or empty commits');
      cb('User does not exist or have empty commits', null, null);
      return;
    }

    _commitsByDate[user.username] = [];

    _commits[user.username].forEach(function(d) {
      _fetchCommitDetail(user, cb, d);
    });
  };

  var _useBackend = function(url) {
    return url.replace(API_BASE_URL, '');
  };

  var _fetchCommitDetail = function(user, cb, d) {
    if (!_outStandingFeteches[user.username]) {
      _outStandingFeteches[user.username] = 0;
    }
    _outStandingFeteches[user.username]++;

    // use both browser and backend to send request to overcome the 6 connections limit
    // backend is slower than browser
    var finalURL = d.url;
    if (Date.now() % 6 === 0) {
      finalURL = _useBackend(d.url);
    }
    d3.json(finalURL)
    // d3.json(d.url)
      .header('Authorization', 'Basic cGFyYWRpdGU6YTFhY2MzM2FlZDU2ZGE5OTg4YzY1NGJkMjQxNzdiZTY1NjFkZTllZQ==')
      .get(function(err, res) {
        _handleCommitDetail(user, cb, err, res, d.repo);
      });
  };

  var _handleCommitDetail = function(user, cb, err, res, repo) {
    if (err) {
      console.log(err);
    } else {
      var commitDate = viz.util.parseDate(res['commit']['author']['date']);
      // Expose date at outer level
      res['date'] = commitDate;
      // add repo attr
      res['repo'] = repo;
      var dateOnly = viz.util.formatDateOnly(commitDate);
      if (!isCommitTooEarly(commitDate)) {
        addCommitByDate(user, dateOnly, res);
      }
    }
    _outStandingFeteches[user.username]--;
    if (_outStandingFeteches[user.username] === 0) {
      cb(null, user, getCommitByDate(user));
    }
  };

  var addCommitByDate = function(user, date, commit) {
    // Check if the date is already present
    for (var i = 0; i < _commitsByDate[user.username].length; i++) {
      if (_commitsByDate[user.username][i]['dateStr'] === date) {
        _commitsByDate[user.username][i]['commits'].push(commit);
        return;
      }
    }

    // Date not added yet
    _commitsByDate[user.username].push({
      dateStr: date,
      date: viz.util.formatDateOnly.parse(date),
      commits: [commit],
      name: commit['commit']['author']['name'],
      username: commit['author']['login']
    });
  };

  var getCommitByDate = function(user) {
    return _commitsByDate[user.username];
  };

  // var _sortTime = function(d1, d2) {
  //   if (d1.date < d2.date) {
  //     return -1;
  //   } else if (d1.date === d2.date) {
  //     return 0;
  //   } else {
  //     return 1;
  //   }
  // };

  var _date = new Date();
  var _ValidDateEarliest = _date.setDate(_date.getDate() - 15); // Last month

  var isCommitTooEarly = function(date) {
    return date < _ValidDateEarliest;
  };

  module.getDomain = function(accessor) {
    var domains = [];
    for (var userkey in _commitsByDate) {
      if (_commitsByDate.hasOwnProperty(userkey)) {
        var userCommits = _commitsByDate[userkey];
        domains = domains.concat(d3.extent(userCommits, accessor));
      }
    }
    var dates = d3.extent(domains);
    // Round to next day for last date
    return [dates[0], d3.time.day.offset(dates[1], 1)];
  };

  module.MAX_COMMITS = 5;

  module.getPrimaryTooltipData = function(d) {
    return d.username + '(' + d.name + ') ' + viz.util.formatDateNice(d.date);
  };

  module.getAdditionalTooltipData = function(d) {
    return '... and ' + (d.commits.length - module.MAX_COMMITS) + ' more commits';
  };

  module.getSecondaryTooltipDataByIndex = function(d, i) {
    return _getCommitTime(d.commits[i]) + ' ' + _getCommitRepo(d.commits[i]) + ' ' +
      _getStatsContent(d.commits[i]) + ' ' + _getCommitMessage(d.commits[i]);
  };

  function _getCommitRepo(commit) {
    return commit.repo;
  }

  function _getCommitTime(commit) {
    return viz.util.formatTime(commit.date);
  }

  function _getCommitMessage(commit) {
    return commit['commit']['message'];
  }

  function _getStatsContent(commit) {
    return '+' + commit.stats.additions + ' -' + commit.stats.deletions + '';
  }

  module.sizeAccessor = function(d) {
    if (d.commits && Array.isArray(d.commits)) {
      return d.commits.length;
    } else {
      return 0;
    }
  };

  module.dateAccessor = function(d) {
    if (d.date) {
      return d.date;
    } else {
      return null;
    }
    // console.log(d.date);
  };

  module.existsOutStandingFetches = function() {
    for (var username in _outStandingFeteches) {
      if (_outStandingFeteches.hasOwnProperty(username) && _outStandingFeteches[username] > 0) {
        return true;
      }
    }
    return false;
  };

  return module;
})();
<commit_msg>use backend entirely as speed issue is local to NUS network<commit_after>var viz = viz || {};

// Data manipulation logic
viz.data = (function() {
  var API_BASE_URL = 'https://api.github.com';
  var API_USER = '/users/';
  var API_PUBLIC_EVENTS = '/events/public';
  var API_ORG = '/orgs/';
  var API_EVENTS = '/events';
  var API_PAGE_2_PARAM = '?page=2';

  var _commits = {};

  var _commitsByDate = {};

  var module = {};

  var _outStandingFeteches = {};

  var _filterPushEvents = function(event) {
    return event.type === 'PushEvent';
  };

  module.getOrgEvent = function(org, cb) {
    var url = API_BASE_URL + API_ORG + org + API_EVENTS;
    d3.json(url)
      .header('Authorization', 'Basic cGFyYWRpdGU6YTFhY2MzM2FlZDU2ZGE5OTg4YzY1NGJkMjQxNzdiZTY1NjFkZTllZQ==')
      .get(function(err, data) {
        if (err) {
          console.log(err);
        } else {
          console.log(data.filter(_filterPushEvents));
          // _updateCommitsFromPushes(user, data.filter(_filterPushEvents));
          // _fetchCommitDetails(user, cb);
        }
      });
  };

  module.getPubEvent = function(user, cb) {
    var url = API_BASE_URL + API_USER + user.username + API_PUBLIC_EVENTS;
    var userDetailUrl = API_BASE_URL + API_USER + user.username;

    async.parallel([
      function(callback) {
        d3.json(_useBackend(url))
          .header('Authorization', 'Basic cGFyYWRpdGU6YTFhY2MzM2FlZDU2ZGE5OTg4YzY1NGJkMjQxNzdiZTY1NjFkZTllZQ==')
          .get(callback);
      },
      function(callback) {
        d3.json(_useBackend(url + API_PAGE_2_PARAM))
          .header('Authorization', 'Basic cGFyYWRpdGU6YTFhY2MzM2FlZDU2ZGE5OTg4YzY1NGJkMjQxNzdiZTY1NjFkZTllZQ==')
          .get(callback);
      },
      function(callback) {
        d3.json(_useBackend(userDetailUrl))
          .header('Authorization', 'Basic cGFyYWRpdGU6YTFhY2MzM2FlZDU2ZGE5OTg4YzY1NGJkMjQxNzdiZTY1NjFkZTllZQ==')
          .get(callback);
      }
    ],
    function(err, results) {
      if (err) {
        console.log(err);
        cb('GitHub API error', null, null);
        return;
      }

      var data1 = results[0];
      var data = data1.concat(results[1]);
      var userdata = results[2];

      if (userdata.email && user.email === null) {
        user.email = userdata.email;
      }
      if (userdata.email === null && user.email === null) {
        cb('There is no GitHub public email for ' + user.username + ', please enter mannually', null, null);
        return;
      }
      if (userdata.name != null) {
        user.name = userdata.name;
      } else {
        user.name = null;
      }
      _updateCommitsFromPushes(user, data.filter(_filterPushEvents));
      _fetchCommitDetails(user, cb);
    });
  };

  var _updateCommitsFromPushes = function(user, data) {
    _commits[user.username] = [];
    data.forEach(function(event) {
      if (event['payload']['commits']) {
        event['payload']['commits'].forEach(function(commit) {
          if (isCommitValid(user, commit)) {
            // add the repo attr
            if (event['repo']['name']) {
              commit['repo'] = event['repo']['name'];
            } else {
              commit['repo'] = null;
            }
            _commits[user.username].push(commit);
          } else {
            // console.log("commit from others");
            // console.log(commit["author"]["email"]);
          }
        });
      }
      // _commits[user] = _commits[user].concat(event["payload"]["commits"]);
    });
  };

  var isCommitValid = function(user, commit) {
    if (user.email === (commit['author']['email'])) {
      return true;
    } else {
      return false;
    }
  };

  var _fetchCommitDetails = function(user, cb) {
    if (_commits[user.username].length === 0) {
      console.log('user does not exist or empty commits');
      cb('User does not exist or have empty commits', null, null);
      return;
    }

    _commitsByDate[user.username] = [];

    _commits[user.username].forEach(function(d) {
      _fetchCommitDetail(user, cb, d);
    });
  };

  var _useBackend = function(url) {
    return url.replace(API_BASE_URL, '');
  };

  var _fetchCommitDetail = function(user, cb, d) {
    if (!_outStandingFeteches[user.username]) {
      _outStandingFeteches[user.username] = 0;
    }
    _outStandingFeteches[user.username]++;

    // use both browser and backend to send request to overcome the 6 connections limit
    // backend is slower than browser in NUS, but faster than browser on heroku
    var finalURL = _useBackend(d.url);
    // if (Date.now() % 6 === 0) {
    //   finalURL = _useBackend(d.url);
    // }
    d3.json(finalURL)
    // d3.json(d.url)
      .header('Authorization', 'Basic cGFyYWRpdGU6YTFhY2MzM2FlZDU2ZGE5OTg4YzY1NGJkMjQxNzdiZTY1NjFkZTllZQ==')
      .get(function(err, res) {
        _handleCommitDetail(user, cb, err, res, d.repo);
      });
  };

  var _handleCommitDetail = function(user, cb, err, res, repo) {
    if (err) {
      console.log(err);
    } else {
      var commitDate = viz.util.parseDate(res['commit']['author']['date']);
      // Expose date at outer level
      res['date'] = commitDate;
      // add repo attr
      res['repo'] = repo;
      var dateOnly = viz.util.formatDateOnly(commitDate);
      if (!isCommitTooEarly(commitDate)) {
        addCommitByDate(user, dateOnly, res);
      }
    }
    _outStandingFeteches[user.username]--;
    if (_outStandingFeteches[user.username] === 0) {
      cb(null, user, getCommitByDate(user));
    }
  };

  var addCommitByDate = function(user, date, commit) {
    // Check if the date is already present
    for (var i = 0; i < _commitsByDate[user.username].length; i++) {
      if (_commitsByDate[user.username][i]['dateStr'] === date) {
        _commitsByDate[user.username][i]['commits'].push(commit);
        return;
      }
    }

    // Date not added yet
    _commitsByDate[user.username].push({
      dateStr: date,
      date: viz.util.formatDateOnly.parse(date),
      commits: [commit],
      name: commit['commit']['author']['name'],
      username: commit['author']['login']
    });
  };

  var getCommitByDate = function(user) {
    return _commitsByDate[user.username];
  };

  // var _sortTime = function(d1, d2) {
  //   if (d1.date < d2.date) {
  //     return -1;
  //   } else if (d1.date === d2.date) {
  //     return 0;
  //   } else {
  //     return 1;
  //   }
  // };

  var _date = new Date();
  var _ValidDateEarliest = _date.setDate(_date.getDate() - 15); // Last month

  var isCommitTooEarly = function(date) {
    return date < _ValidDateEarliest;
  };

  module.getDomain = function(accessor) {
    var domains = [];
    for (var userkey in _commitsByDate) {
      if (_commitsByDate.hasOwnProperty(userkey)) {
        var userCommits = _commitsByDate[userkey];
        domains = domains.concat(d3.extent(userCommits, accessor));
      }
    }
    var dates = d3.extent(domains);
    // Round to next day for last date
    return [dates[0], d3.time.day.offset(dates[1], 1)];
  };

  module.MAX_COMMITS = 5;

  module.getPrimaryTooltipData = function(d) {
    return d.username + '(' + d.name + ') ' + viz.util.formatDateNice(d.date);
  };

  module.getAdditionalTooltipData = function(d) {
    return '... and ' + (d.commits.length - module.MAX_COMMITS) + ' more commits';
  };

  module.getSecondaryTooltipDataByIndex = function(d, i) {
    return _getCommitTime(d.commits[i]) + ' ' + _getCommitRepo(d.commits[i]) + ' ' +
      _getStatsContent(d.commits[i]) + ' ' + _getCommitMessage(d.commits[i]);
  };

  function _getCommitRepo(commit) {
    return commit.repo;
  }

  function _getCommitTime(commit) {
    return viz.util.formatTime(commit.date);
  }

  function _getCommitMessage(commit) {
    return commit['commit']['message'];
  }

  function _getStatsContent(commit) {
    return '+' + commit.stats.additions + ' -' + commit.stats.deletions + '';
  }

  module.sizeAccessor = function(d) {
    if (d.commits && Array.isArray(d.commits)) {
      return d.commits.length;
    } else {
      return 0;
    }
  };

  module.dateAccessor = function(d) {
    if (d.date) {
      return d.date;
    } else {
      return null;
    }
    // console.log(d.date);
  };

  module.existsOutStandingFetches = function() {
    for (var username in _outStandingFeteches) {
      if (_outStandingFeteches.hasOwnProperty(username) && _outStandingFeteches[username] > 0) {
        return true;
      }
    }
    return false;
  };

  return module;
})();
<|endoftext|>


<commit_before>(function () {
var questionCount = 0;

function incrementSessionQuestionCount() {
  if (questionCount < 13) {
    questionCount += 1;
  }
}

var answerArray = questions.map(function(questionObject) {
  questionObject.answer = false;
  return questionObject;
})

function updateAnswers(answer, questionNo) {
  answerArray[questionNo - 1].answer = answer;
}

function updateDoughnut(questionNo) {
  var currentTopic = questions[questionNo - 1].topic;
  // find all the answer objects that match this topic
  var currentTopicAnswers = answerArray.filter(function(answerObject) {
    return answerObject.topic === currentTopic;
  });
  // length of array of current topic answers
  var currentTopicAllLength = currentTopicAnswers.length;
  // length of array of current topic true answers
  var currentTopicTrueLength = currentTopicAnswers.filter(function(answerObject) {
    return answerObject.answer === true;
  }).length;
  // fraction of current topic answered true
  var proportionTrueAnswers = currentTopicTrueLength / currentTopicAllLength;
  // percentage of doughnut it should take up
  var percentageOfDoughnut = proportionTrueAnswers * 100 / topics.length;
  if (questions[questionNo - 1].topic !== questions[questionNo].topic) {
    config.data.datasets[0].data.push(percentageOfDoughnut);
    config.data.datasets[0].backgroundColor.push();
    window.myDoughnut.update();
  }
}

function changeTopic(questionNo) {
  if (questions[questionNo - 1].topic !== questions[questionNo].topic) {
    $('h3.question-section-title').text(questions[questionNo - 1].topic);
    $('div.question-form').switchClass(questions[questionNo - 1].class, questions[questionNo].class, 600);
  }
  if (questions[questionNo - 1].topic === 'Case Studies') {
    $('.question-section-title').css('visibility', 'hidden');
    $('.question-section-hr').css('visibility', 'hidden');
    $('.question-button').hide();
  }
}

function changeQuestion() {
  $.each($('.question-title'), function(index, question){
    if ($(question).is(':visible')) {
      $(question).toggle('slide', { direction: 'up' }, 600, function () {
        $(question).next().toggle('slide', { direction: 'down' }, 600);
      });
    }
  });
}

function showDesiredContent() {
  var trueAnswers = answerArray.filter(function(answerObject) {
    return answerObject.answer === true;
  }).map(function(object) {
    return object.question;
  });
  $.each($('.content'), function(index, content){
    var relatedQuestion = contentData.filter(function(contentObject) {
      return contentObject.title === content.id;
    }).map(function(object) {
      return object.question;
    })[0];
    if (trueAnswers.indexOf(relatedQuestion) >= 0) {
      content.setAttribute('style', 'display: block');
    }
  });
}

function enableButtons() {
  $.each($('.question-button'), function(index, button) {
    $(button).removeAttr("disabled");
  });
}

function disableButtons() {
  $.each($('.question-button'), function(index, button) {
    $(button).attr("disabled", true);
    if (questionCount < 13) {
      setTimeout(function(){
        enableButtons();
      }, 1000);
    }
  });
}

$('.question-button').click(function(event) {
  event.preventDefault();
  disableButtons();
  incrementSessionQuestionCount();
  var answer = event.target.id === 'question-button-yes'? true : false;
  updateAnswers(answer, questionCount);
  updateDoughnut(questionCount);
  changeTopic(questionCount);
  changeQuestion();
  showDesiredContent();
});
})();
<commit_msg>have icon disappear at end of form<commit_after>(function () {
var questionCount = 0;

function incrementSessionQuestionCount() {
  if (questionCount < 13) {
    questionCount += 1;
  }
}

var answerArray = questions.map(function(questionObject) {
  questionObject.answer = false;
  return questionObject;
})

function updateAnswers(answer, questionNo) {
  answerArray[questionNo - 1].answer = answer;
}

function updateDoughnut(questionNo) {
  var currentTopic = questions[questionNo - 1].topic;
  // find all the answer objects that match this topic
  var currentTopicAnswers = answerArray.filter(function(answerObject) {
    return answerObject.topic === currentTopic;
  });
  // length of array of current topic answers
  var currentTopicAllLength = currentTopicAnswers.length;
  // length of array of current topic true answers
  var currentTopicTrueLength = currentTopicAnswers.filter(function(answerObject) {
    return answerObject.answer === true;
  }).length;
  // fraction of current topic answered true
  var proportionTrueAnswers = currentTopicTrueLength / currentTopicAllLength;
  // percentage of doughnut it should take up
  var percentageOfDoughnut = proportionTrueAnswers * 100 / topics.length;
  if (questions[questionNo - 1].topic !== questions[questionNo].topic) {
    config.data.datasets[0].data.push(percentageOfDoughnut);
    config.data.datasets[0].backgroundColor.push();
    window.myDoughnut.update();
  }
}

function changeTopic(questionNo) {
  if (questions[questionNo - 1].topic !== questions[questionNo].topic) {
    $('h3.question-section-title').text(questions[questionNo - 1].topic);
    $('div.question-form').switchClass(questions[questionNo - 1].class, questions[questionNo].class, 600);
  }
  if (questions[questionNo - 1].topic === 'Case Studies') {
    $('.question-section-wrapper').css('visibility', 'hidden');
    $('.question-button').hide();
  }
}

function changeQuestion() {
  $.each($('.question-title'), function(index, question){
    if ($(question).is(':visible')) {
      $(question).toggle('slide', { direction: 'up' }, 600, function () {
        $(question).next().toggle('slide', { direction: 'down' }, 600);
      });
    }
  });
}

function showDesiredContent() {
  var trueAnswers = answerArray.filter(function(answerObject) {
    return answerObject.answer === true;
  }).map(function(object) {
    return object.question;
  });
  $.each($('.content'), function(index, content){
    var relatedQuestion = contentData.filter(function(contentObject) {
      return contentObject.title === content.id;
    }).map(function(object) {
      return object.question;
    })[0];
    if (trueAnswers.indexOf(relatedQuestion) >= 0) {
      content.setAttribute('style', 'display: block');
    }
  });
}

function enableButtons() {
  $.each($('.question-button'), function(index, button) {
    $(button).removeAttr("disabled");
  });
}

function disableButtons() {
  $.each($('.question-button'), function(index, button) {
    $(button).attr("disabled", true);
    if (questionCount < 13) {
      setTimeout(function(){
        enableButtons();
      }, 1000);
    }
  });
}

$('.question-button').click(function(event) {
  event.preventDefault();
  disableButtons();
  incrementSessionQuestionCount();
  var answer = event.target.id === 'question-button-yes'? true : false;
  updateAnswers(answer, questionCount);
  updateDoughnut(questionCount);
  changeTopic(questionCount);
  changeQuestion();
  showDesiredContent();
});
})();
<|endoftext|>