<commit_before>/**
 * @ngdoc overview
 * @name ngmReportHubApp
 * @description
 * # ngmReportHubApp
 *
 * Main module of the application.
 */
angular
	.module('ngmReportHub', [
		// vendor
		'ngAnimate',
		'ngCookies',
		'ngResource',
		'ngRoute',
		'ngSanitize',
		'ngTouch',
		'ngTable',
		'ngCsv',
		'ngDropzone',
		'ngCountTo',
		'highcharts-ng',
		'leaflet-directive',
		'xeditable',
		// ngm
		'ngm',
		'ngm.widget.form.authentication',
		'ngm.widget.project.details',
		'ngm.widget.project.financials',
		// 'ngm.widget.project.reports.list',
		'ngm.widget.project.report',
		'ngm.widget.organization.stocks.list',
		'ngm.widget.organization.stock',
		// modules
		'ngmCluster',
		'ngmEthiopia',
		'ngmDews',
		'ngmDrr',
    'ngmEpr',
    'ngmSbp',
		'ngmWatchkeeper',
		// utils
		'angularUtils.directives.dirPagination',
		// widgets
		'ngm.widget.calHeatmap',
		'ngm.widget.dropzone',
		'ngm.widget.highchart',
		'ngm.widget.html',
		'ngm.widget.leaflet',
		'ngm.widget.list',
		'ngm.widget.modal',
		'ngm.widget.stats',
		'ngm.widget.table'
	])
	.config([ '$routeProvider', '$locationProvider', '$compileProvider', function ( $routeProvider, $locationProvider, $compileProvider ) {

		// from http://mysite.com/#/notes/1 to http://mysite.com/notes/1
		// $locationProvider.html5Mode(true);

		// extend localstorage to set an object
		Storage.prototype.setObject = function( key, value ) {
			this.setItem( key, JSON.stringify( value ) );
		}

		// extend localstorage to get an object
		Storage.prototype.getObject = function( key ) {
			var value = this.getItem( key );
			return value && JSON.parse( value );
		}

		// https://medium.com/swlh/improving-angular-performance-with-1-line-of-code-a1fb814a6476#.ufea9sjt1
		$compileProvider.debugInfoEnabled( false );

		// all routes prescribed within specific module app.js files
		$routeProvider

			// LOGIN
			.when( '/login', {
				templateUrl: '/views/app/dashboard.html',
				controller: 'DashboardLoginCtrl',
				resolve: {
					access: [ 'ngmAuth', function(ngmAuth) {
						return ngmAuth.isAnonymous();
					}],
				}
			})
			// FORBIDDEN
			.when( '/forbidden', {
				templateUrl: '/views/app/dashboard.html',
				controller: 'DashboardForbiddenCtrl',
				resolve: {
					access: [ 'ngmAuth', function(ngmAuth) {
						return !ngmAuth.isAuthenticated();
					}],
				}
			})
			// PROFILE
			.when( '/profile', {
				templateUrl: '/views/app/dashboard.html',
				controller: 'DashboardProfileCtrl',
				resolve: {
					access: [ 'ngmAuth', function(ngmAuth) {
						return ngmAuth.isAuthenticated();
					}],
				}
			})

			// achievements
			.when( '/reporthub', {
				redirectTo: '/reporthub/2016'
			})
			.when( '/reporthub/login', {
				redirectTo: '/reporthub/2016'
			})
			// achievements
			.when( '/reporthub/:year', {
				templateUrl: '/views/app/dashboard.html',
				controller: 'DashboardReportHubCtrl',
				resolve: {
					access: [ 'ngmAuth', function( ngmAuth ) {
						return ngmAuth.grantPublicAccess();
					}],
				}
			})
			// DEFAULT
			.otherwise({
				redirectTo: '/cluster/projects'
			});
	}])
	.run([ '$rootScope', '$window', '$location', 'ngmAuth', 'ngmUser', function( $rootScope, $window, $location, ngmAuth, ngmUser ) {

		// check session by last login
		ngmAuth.setSessionTimeout( ngmUser.get() );

		// new guest page visit
		if ( ngmUser.get() && ngmUser.get().guest ) {
			ngmUser.unset();
		}

		// check URL
		if ( $location.$$host.search('dev') > -1 ) {
			// add DEV message if necissary
			$('#print').append('
TEST VERSION
');
		}

		// IE checks!!!!!!
		if (/MSIE 10/i.test($window.navigator.userAgent)) {
		   // This is internet explorer 10
		   openIeModal();
		}
		if (/MSIE 9/i.test($window.navigator.userAgent) || /rv:11.0/i.test($window.navigator.userAgent)) {
		    // This is internet explorer 9 or 11
		    openIeModal();
		}
		if (/Edge\/\d./i.test($window.navigator.userAgent)){
		   // This is Microsoft Edge
		   openIeModal();
		}
		// open modal
		function openIeModal() {
			$('#ngm-ie-modal').openModal({dismissible: false});
		}

		// when error on route update redirect
		$rootScope.$on( '$routeChangeError', function( event, current, previous, rejection ) {

			// get app
			var app = current.$$route.originalPath.split('/')[1];
			if ( rejection === ngmAuth.UNAUTHORIZED ) {
				$location.path( '/' + app + '/login' );
			} else if ( rejection === ngmAuth.FORBIDDEN ) {
				$location.path( '/' + app + '/forbidden' );
			}

		});

	}])
	.controller('ngmReportHubCrtl', ['$scope', '$route', '$location', '$http', '$timeout', 'ngmAuth', 'ngmUser', function ($scope, $route, $location, $http, $timeout, ngmAuth, ngmUser) {

		// ngm object
		$scope.ngm = {

			// app name
			title: 'Welcome',

			// current route
			route: $route,

			// active dashboard placeholder
			dashboard: {
				model: {}
			},

			// top navigation page menu
			navigationMenu: false,

			// left menu
			menu: {
				search: true,
				focused: false,
				query: []
			},

			// page height
			height: $( window ).height(),

			// dashboard footer
			footer: false,

			// paint application
			setApplication: function( app ) {

				// set app colors based on
				switch( app ){
          case 'reporthub':
            // set style obj
            $scope.ngm.style = {
              logo: 'logo.png',
              home: '#/reporthub',
              darkPrimaryColor: '#1976D2',
              defaultPrimaryColor: '#2196F3',
              lightPrimaryColor: '#BBDEFB'
            }
            break;
					case 'immap':
						// set style obj
						$scope.ngm.style = {
							logo: 'logo-immap.png',
							home: '#/immap',
							darkPrimaryColor: '#DE696E',
							defaultPrimaryColor: '#EE6E73',
							lightPrimaryColor: '#EF9A9A'
						}
						break;
					case 'who':
						// set style obj
						if ( $location.$$path.split('/')[2] === 'ethiopia' ) {
							$scope.ngm.style = {
								logo: 'logo-health.png',
								home: '#/who/ethiopia',
								darkPrimaryColor: '#1976D2',
								defaultPrimaryColor: '#2196F3',
								lightPrimaryColor: '#BBDEFB'
							}
						} else {
							$scope.ngm.style = {
								logo: 'logo-who.png',
								home: '#/who',
								darkPrimaryColor: '#1976D2',
								defaultPrimaryColor: '#2196F3',
								lightPrimaryColor: '#BBDEFB'
							}
						}
						break;
          case 'epr':
            // set style obj
            $scope.ngm.style = {
              logo: 'logo-health.png',
              home: '#/epr',
              darkPrimaryColor: '#1976D2',
              defaultPrimaryColor: '#2196F3',
              lightPrimaryColor: '#BBDEFB'
            }
            break;
					default:

						// logo
						var logo = 'logo.png';
						if ( ngmUser.get() && ngmUser.get().cluster_id ) {
							logo = 'logo-' + ngmUser.get().cluster_id + '.png';
						}

						// if WHO Ethiopia user!
						if ( ngmUser.get() && ngmUser.get().organization_tag === 'who'
								&& ngmUser.get().admin0pcode === 'ET' ) {
							$scope.ngm.style = {
								logo: 'logo-health.png',
								home: '#/who/ethiopia',
								darkPrimaryColor: '#1976D2',
								defaultPrimaryColor: '#2196F3',
								lightPrimaryColor: '#BBDEFB'
							}
						} else {
							// default
							$scope.ngm.style = {
								logo: logo,
								home: '#/cluster',
								darkPrimaryColor: '#1976D2',
								defaultPrimaryColor: '#2196F3',
								lightPrimaryColor: '#BBDEFB'
							}
						}
				}

				// body footer
				$scope.ngm.footer = '
'
														+	'

'
														+	'
'
															+	'
Supported by iMMAP
'
															+ '
perm_contact_calendarContact
'
															+ '
' +moment().format('DD MMM, YYYY @ h:mm a') + '
'
														+	'
'
													+	'
';

			},

			// user
			getUser: function() {
				// ngmUser
				return ngmUser.get();
			},

			// username
			getUserName: function() {
				// ngmUser
				if ( ngmUser.get() ) {
					return ngmUser.get().username;
				} else {
					return 'welcome';
				}
			},

			// app functions
			logout: function() {
				ngmAuth.logout();
			},

			// open contact modal
			contact: function() {
				// open modal
				$( '#ngm-contact-modal' ).openModal({ dismissible: false });
			},

			// Detect touch screen and enable scrollbar if necessary
			isTouchDevice: function () {
				try {
					document.createEvent( 'TouchEvent' );
					return true;
				} catch (e) {
					return false;
				}
			},

			// toggle search active
			toggleSearch: function(selector) {
				// toggle search input
				$( '#nav-' + selector ).slideToggle();
			},

			//
			toggleNavigationMenu: function() {
				// rotate icon
				$( '.ngm-profile-icon' ).toggleClass( 'rotate' );
				// set class
	    	$( '.ngm-profile' ).toggleClass( 'active' );
	    	$( '.ngm-profile-menu-content' ).toggleClass( 'active' );
	    	// toggle menu dropdown
				$( '.ngm-profile-menu-content' ).slideToggle();
			}

		};

		// nav menu
		if ( $scope.ngm.isTouchDevice() ) {
			$( '#nav-mobile' ).css({ overflow: 'auto'});
		}

		// profile menu dropdown click
		$( '.ngm-profile-icon' ).click( function(){
				// on app load, toggle menu on click
				$scope.ngm.toggleNavigationMenu();
		});

		// paint application
		$scope.$on( '$routeChangeStart', function( next, current ) {

			// get application
			var app = $location.$$path.split('/')[1];
			// set application
			$scope.ngm.setApplication( app );

		});

		// annoying loading artifacts of left menu
    angular.element(document).ready(function () {
      // give a few seconds to render
      $timeout(function() {
				$( '.ngm-navigation-menu' ).css({ 'display': 'block' });
			}, 1000 );
    });

	}]);
<commit_msg>updated DEV text<commit_after>/**
 * @ngdoc overview
 * @name ngmReportHubApp
 * @description
 * # ngmReportHubApp
 *
 * Main module of the application.
 */
angular
	.module('ngmReportHub', [
		// vendor
		'ngAnimate',
		'ngCookies',
		'ngResource',
		'ngRoute',
		'ngSanitize',
		'ngTouch',
		'ngTable',
		'ngCsv',
		'ngDropzone',
		'ngCountTo',
		'highcharts-ng',
		'leaflet-directive',
		'xeditable',
		// ngm
		'ngm',
		'ngm.widget.form.authentication',
		'ngm.widget.project.details',
		'ngm.widget.project.financials',
		// 'ngm.widget.project.reports.list',
		'ngm.widget.project.report',
		'ngm.widget.organization.stocks.list',
		'ngm.widget.organization.stock',
		// modules
		'ngmCluster',
		'ngmEthiopia',
		'ngmDews',
		'ngmDrr',
    'ngmEpr',
    'ngmSbp',
		'ngmWatchkeeper',
		// utils
		'angularUtils.directives.dirPagination',
		// widgets
		'ngm.widget.calHeatmap',
		'ngm.widget.dropzone',
		'ngm.widget.highchart',
		'ngm.widget.html',
		'ngm.widget.leaflet',
		'ngm.widget.list',
		'ngm.widget.modal',
		'ngm.widget.stats',
		'ngm.widget.table'
	])
	.config([ '$routeProvider', '$locationProvider', '$compileProvider', function ( $routeProvider, $locationProvider, $compileProvider ) {

		// from http://mysite.com/#/notes/1 to http://mysite.com/notes/1
		// $locationProvider.html5Mode(true);

		// extend localstorage to set an object
		Storage.prototype.setObject = function( key, value ) {
			this.setItem( key, JSON.stringify( value ) );
		}

		// extend localstorage to get an object
		Storage.prototype.getObject = function( key ) {
			var value = this.getItem( key );
			return value && JSON.parse( value );
		}

		// https://medium.com/swlh/improving-angular-performance-with-1-line-of-code-a1fb814a6476#.ufea9sjt1
		$compileProvider.debugInfoEnabled( false );

		// all routes prescribed within specific module app.js files
		$routeProvider

			// LOGIN
			.when( '/login', {
				templateUrl: '/views/app/dashboard.html',
				controller: 'DashboardLoginCtrl',
				resolve: {
					access: [ 'ngmAuth', function(ngmAuth) {
						return ngmAuth.isAnonymous();
					}],
				}
			})
			// FORBIDDEN
			.when( '/forbidden', {
				templateUrl: '/views/app/dashboard.html',
				controller: 'DashboardForbiddenCtrl',
				resolve: {
					access: [ 'ngmAuth', function(ngmAuth) {
						return !ngmAuth.isAuthenticated();
					}],
				}
			})
			// PROFILE
			.when( '/profile', {
				templateUrl: '/views/app/dashboard.html',
				controller: 'DashboardProfileCtrl',
				resolve: {
					access: [ 'ngmAuth', function(ngmAuth) {
						return ngmAuth.isAuthenticated();
					}],
				}
			})

			// achievements
			.when( '/reporthub', {
				redirectTo: '/reporthub/2016'
			})
			.when( '/reporthub/login', {
				redirectTo: '/reporthub/2016'
			})
			// achievements
			.when( '/reporthub/:year', {
				templateUrl: '/views/app/dashboard.html',
				controller: 'DashboardReportHubCtrl',
				resolve: {
					access: [ 'ngmAuth', function( ngmAuth ) {
						return ngmAuth.grantPublicAccess();
					}],
				}
			})
			// DEFAULT
			.otherwise({
				redirectTo: '/cluster/projects'
			});
	}])
	.run([ '$rootScope', '$window', '$location', 'ngmAuth', 'ngmUser', function( $rootScope, $window, $location, ngmAuth, ngmUser ) {

		// check session by last login
		ngmAuth.setSessionTimeout( ngmUser.get() );

		// new guest page visit
		if ( ngmUser.get() && ngmUser.get().guest ) {
			ngmUser.unset();
		}

		// check URL
		if ( $location.$$host.search('dev') > -1 ) {
			// add DEV message if necissary
			$('#print').append('
TEST VERSION
');
		}

		// IE checks!!!!!!
		if (/MSIE 10/i.test($window.navigator.userAgent)) {
		   // This is internet explorer 10
		   openIeModal();
		}
		if (/MSIE 9/i.test($window.navigator.userAgent) || /rv:11.0/i.test($window.navigator.userAgent)) {
		    // This is internet explorer 9 or 11
		    openIeModal();
		}
		if (/Edge\/\d./i.test($window.navigator.userAgent)){
		   // This is Microsoft Edge
		   openIeModal();
		}
		// open modal
		function openIeModal() {
			$('#ngm-ie-modal').openModal({dismissible: false});
		}

		// when error on route update redirect
		$rootScope.$on( '$routeChangeError', function( event, current, previous, rejection ) {

			// get app
			var app = current.$$route.originalPath.split('/')[1];
			if ( rejection === ngmAuth.UNAUTHORIZED ) {
				$location.path( '/' + app + '/login' );
			} else if ( rejection === ngmAuth.FORBIDDEN ) {
				$location.path( '/' + app + '/forbidden' );
			}

		});

	}])
	.controller('ngmReportHubCrtl', ['$scope', '$route', '$location', '$http', '$timeout', 'ngmAuth', 'ngmUser', function ($scope, $route, $location, $http, $timeout, ngmAuth, ngmUser) {

		// ngm object
		$scope.ngm = {

			// app name
			title: 'Welcome',

			// current route
			route: $route,

			// active dashboard placeholder
			dashboard: {
				model: {}
			},

			// top navigation page menu
			navigationMenu: false,

			// left menu
			menu: {
				search: true,
				focused: false,
				query: []
			},

			// page height
			height: $( window ).height(),

			// dashboard footer
			footer: false,

			// paint application
			setApplication: function( app ) {

				// set app colors based on
				switch( app ){
          case 'reporthub':
            // set style obj
            $scope.ngm.style = {
              logo: 'logo.png',
              home: '#/reporthub',
              darkPrimaryColor: '#1976D2',
              defaultPrimaryColor: '#2196F3',
              lightPrimaryColor: '#BBDEFB'
            }
            break;
					case 'immap':
						// set style obj
						$scope.ngm.style = {
							logo: 'logo-immap.png',
							home: '#/immap',
							darkPrimaryColor: '#DE696E',
							defaultPrimaryColor: '#EE6E73',
							lightPrimaryColor: '#EF9A9A'
						}
						break;
					case 'who':
						// set style obj
						if ( $location.$$path.split('/')[2] === 'ethiopia' ) {
							$scope.ngm.style = {
								logo: 'logo-health.png',
								home: '#/who/ethiopia',
								darkPrimaryColor: '#1976D2',
								defaultPrimaryColor: '#2196F3',
								lightPrimaryColor: '#BBDEFB'
							}
						} else {
							$scope.ngm.style = {
								logo: 'logo-who.png',
								home: '#/who',
								darkPrimaryColor: '#1976D2',
								defaultPrimaryColor: '#2196F3',
								lightPrimaryColor: '#BBDEFB'
							}
						}
						break;
          case 'epr':
            // set style obj
            $scope.ngm.style = {
              logo: 'logo-health.png',
              home: '#/epr',
              darkPrimaryColor: '#1976D2',
              defaultPrimaryColor: '#2196F3',
              lightPrimaryColor: '#BBDEFB'
            }
            break;
					default:

						// logo
						var logo = 'logo.png';
						if ( ngmUser.get() && ngmUser.get().cluster_id ) {
							logo = 'logo-' + ngmUser.get().cluster_id + '.png';
						}

						// if WHO Ethiopia user!
						if ( ngmUser.get() && ngmUser.get().organization_tag === 'who'
								&& ngmUser.get().admin0pcode === 'ET' ) {
							$scope.ngm.style = {
								logo: 'logo-health.png',
								home: '#/who/ethiopia',
								darkPrimaryColor: '#1976D2',
								defaultPrimaryColor: '#2196F3',
								lightPrimaryColor: '#BBDEFB'
							}
						} else {
							// default
							$scope.ngm.style = {
								logo: logo,
								home: '#/cluster',
								darkPrimaryColor: '#1976D2',
								defaultPrimaryColor: '#2196F3',
								lightPrimaryColor: '#BBDEFB'
							}
						}
				}

				// body footer
				$scope.ngm.footer = '
'
														+	'

'
														+	'
'
															+	'
Supported by iMMAP
'
															+ '
perm_contact_calendarContact
'
															+ '
' +moment().format('DD MMM, YYYY @ h:mm a') + '
'
														+	'
'
													+	'
';

			},

			// user
			getUser: function() {
				// ngmUser
				return ngmUser.get();
			},

			// username
			getUserName: function() {
				// ngmUser
				if ( ngmUser.get() ) {
					return ngmUser.get().username;
				} else {
					return 'welcome';
				}
			},

			// app functions
			logout: function() {
				ngmAuth.logout();
			},

			// open contact modal
			contact: function() {
				// open modal
				$( '#ngm-contact-modal' ).openModal({ dismissible: false });
			},

			// Detect touch screen and enable scrollbar if necessary
			isTouchDevice: function () {
				try {
					document.createEvent( 'TouchEvent' );
					return true;
				} catch (e) {
					return false;
				}
			},

			// toggle search active
			toggleSearch: function(selector) {
				// toggle search input
				$( '#nav-' + selector ).slideToggle();
			},

			//
			toggleNavigationMenu: function() {
				// rotate icon
				$( '.ngm-profile-icon' ).toggleClass( 'rotate' );
				// set class
	    	$( '.ngm-profile' ).toggleClass( 'active' );
	    	$( '.ngm-profile-menu-content' ).toggleClass( 'active' );
	    	// toggle menu dropdown
				$( '.ngm-profile-menu-content' ).slideToggle();
			}

		};

		// nav menu
		if ( $scope.ngm.isTouchDevice() ) {
			$( '#nav-mobile' ).css({ overflow: 'auto'});
		}

		// profile menu dropdown click
		$( '.ngm-profile-icon' ).click( function(){
				// on app load, toggle menu on click
				$scope.ngm.toggleNavigationMenu();
		});

		// paint application
		$scope.$on( '$routeChangeStart', function( next, current ) {

			// get application
			var app = $location.$$path.split('/')[1];
			// set application
			$scope.ngm.setApplication( app );

		});

		// annoying loading artifacts of left menu
    angular.element(document).ready(function () {
      // give a few seconds to render
      $timeout(function() {
				$( '.ngm-navigation-menu' ).css({ 'display': 'block' });
			}, 1000 );
    });

	}]);
<|endoftext|>


<commit_before>function mapApp() {
	/* create leaflet map */
	var map = L.map('map', {
		center: [44.8597, -0.5157],
		zoom: 9
	});

	/**
	 * Object to store svg:element property for future use
	 */
	var props = {
		circle: {
			default: 2,
			active: 5
		}
	};

	/**
	 * Map type of centre index to name
	 * @type {Array}
	 */
	var typeCentre = [ 'epci', 'transfert', 'traitement' ];

	/* add default stamen tile layer */
	new L.tileLayer('http://{s}.tiles.mapbox.com/v3/examples.map-vyofok3q/{z}/{x}/{y}.png', {
		minZoom: 0,
		maxZoom: 18,
		attribution: 'Map data © OpenStreetMap contributors'
	}).addTo(map);

	var svg         = d3.select(map.getPanes().overlayPane).append('svg'),
		g               = svg.append('g').attr('class', 'leaflet-zoom-hide'),
		defs            = svg.append('defs'),
		marker          = defs.append('marker')
								.attr('id', 'arw-end')
								.attr('viewBox', '0 0 10 10')
								.attr('refX', 10)
								.attr('refY', 5)
								.attr('orient', 'auto')
							.append('path')
								.attr('d', 'M 0,0 10,5 0,10'),
		markerMid       = defs.append('marker')
								.attr('id', 'arw-mid')
								.attr('viewBox', '0 0 10 10')
								.attr('refY', 0)
								.attr('refY', 5)
								.attr('orient', 'auto')
							.append('path')
								.attr('d', 'M 0,0 10,5 0,10'),
		entities        = g.append('g').attr('id', 'entities'),
		entitiesLabels  = g.append('g').attr('id', 'entities-labels'),
		centres         = g.append('g').attr('id', 'centres'),
		routes          = g.append('g').attr('id', 'routes')
	;

	var path, entity, label, centre;

	function drawEntities() {
		return new Promise(function (resolve, reject) {
		d3.json('scripts/gironde-epci.topo.json', function (dataset) {
		var geoData = topojson.feature(dataset, dataset.objects['gironde-epci.geo']);
		var bounds = d3.geo.bounds(geoData);
		path = d3.geo.path().projection(projectPoint);

		// addCentre(geoData.features, 'id');

		entity = entities.selectAll('.entity')
			.data(geoData.features)
			.enter()
				.append('path')
				.attr('class', 'entity')
			;
		label = entitiesLabels.selectAll('.entity-label')
			.data(geoData.features)
			.enter()
				.append('text')
				.attr('class', 'entity-label')
			;

		// Reposition the SVG to cover the features.
		function reset() {
			var bottomLeft = projectPoint(bounds[0]),
				topRight = projectPoint(bounds[1]);

			svg.attr('width', topRight[0] - bottomLeft[0])
				.attr('height', bottomLeft[1] - topRight[1])
				.style('margin-left', bottomLeft[0] + 'px')
				.style('margin-top', topRight[1] + 'px');

			g.attr('transform', 'translate(' + -bottomLeft[0] + ',' + -topRight[1] + ')');

			entity.attr('d', path)
				.attr('class', function (d) {
					return 'entity ' + getCentres(idify(d.id)).join(' ');
				})
				.on('mouseover', function (d) {
					var eid = idify(d.id);
					highlightEntity(eid);
					showEntityLabel(eid);
					showEntityRoute(eid);
					// reset style on others elements
					// d3.selectAll('.entity').classed('active', false);
					d3.selectAll('circle')
						.classed('highlight', false)
						.attr('r', props.circle.default)
					;
					// apply style to element(s)
					// d3.select(this).classed('active', true);
					d3.selectAll('circle.' + idify(d.id))
						.classed('highlight', true)
						.attr('r', props.circle.active)
					;
					updateCounter(d.id);
				})
			;

			label.attr('id', function (d) { return idify(d.id); })
				.attr('class', function (d) { return 'entity-label ' + idify(d.id); })
				.attr('transform', function (d) {
					return 'translate(' + path.centroid(d) + ')';
				})
				.attr('x', -20)
				.attr('dy', '.35em')
				.text(function (d) { return toProperCase(d.id); })
			;
		}

		map.on('viewreset', reset);
		reset();
		resolve();
		});
	});
	}

	function drawTransport() {
		d3.csv('scripts/routes-dechets.csv', function (error, dataset) {
		centre = centres.selectAll('.centre')
			.data(dataset)
			.enter()
			.append('g')
		;

		centre
			.on('mouseover', function (d) {
				d3.select(this).attr('r', props.circle.active);
				// reset style on others elements
				d3.selectAll('.route').classed('show', false);
				// apply style to element(s)
				d3.selectAll('.route.' + idify(d.depart)).classed('show', true);
			})
			.on('mouseout', function () {
				d3.selectAll('.route').classed('show', false);
			});

		var centrePlace = centre.append('circle');
		var centreLabel = centre.append('text');

		// Standard enter / update
		var routePath = routes.selectAll('.route')
			.data(dataset)
			.enter()
			.append('path')
		;

		var emissionGroup = routes.append('g').attr('id', 'emission');
		var emission = emissionGroup.selectAll('.emission')
			.data(dataset)
			.enter()
			.append('text')
		;
		var qteGroup = routes.append('g').attr('id', 'qte');
		var qte = qteGroup.selectAll('.qte')
			.data(dataset)
			.enter()
			.append('text')
		;
		var distGroup = routes.append('g').attr('id', 'dist');
		var dist = distGroup.selectAll('.dist')
			.data(dataset)
			.enter()
			.append('text')
		;

		function attach(d) {
			var coordDepart = [ d.lon_depart, d.lat_depart ];
			var coordArrivee = [ d.lon_arrivee, d.lat_arrivee ];
			return 'translate(' + path.centroid({type: 'LineString', coordinates: [coordDepart, coordArrivee ] }) + ')';
		}

		function reset() {
			centre
				.attr('class', function (d) {
					return	' centre ' + idify(d.depart) +
							' from-' + typeCentre[d.niv_depart] +
							' to-' + typeCentre[d.niv_arrivee];
				})
			;
			centrePlace
					.attr('r', props.circle.default)
					.attr('cx', function (d) { return projectDepart(d)[0]; })
					.attr('cy', function (d) { return projectDepart(d)[1]; })
					.attr('title', function (d) { return idify(d.depart); })
			;
			centreLabel
				.attr('class', 'label')
				.attr('transform', function (d) {
					return 'translate(' +  projectDepart(d)[0] + ', ' + projectDepart(d)[1] + ')';
				})
				.text(function (d) { return idify(d.depart); })
			;

			routePath.attr('d', function (d) {
					var coordDepart = [ d.lon_depart, d.lat_depart ];
					var coordArrivee = [ d.lon_arrivee, d.lat_arrivee ];
					var vertex = path.centroid({type: 'LineString', coordinates: [coordDepart, coordArrivee ] });
					return path({
						type: 'LineString',
						coordinates: [
							coordDepart,
							pointToProjection(vertex),
							coordArrivee
						]
					});
				})
				.attr('class', function (d) {
					return [
						getEpci(idify(d.depart)), getEpci(idify(d.arrivee)),
						'route', idify(d.depart), idify(d.arrivee),
						'from-' + typeCentre[d.niv_depart],
						'to-' + typeCentre[d.niv_arrivee],
					].join(' ');
				})
			;
			routePath
				// .attr('class', function (d) {
				// 	return [
				// 		getEpci(idify(d.depart)), getEpci(idify(d.arrivee)),
				// 		'arc route', idify(d.depart), idify(d.arrivee),
				// 		'from-' + typeCentre[d.niv_depart],
				// 		'to-' + typeCentre[d.niv_arrivee],
				// 	].join(' ');
				// })
				.attr('d', function (d) {
					var source = projectDepart(d);
					var target = projectArrivee(d);

					var  dx = target[0] - source[0]
						,dy = target[1] - source[1]
						,dr = Math.sqrt(dx * dx + dy * dy)
						,inOut = Math.round(Math.random(1))
					;
					var arc = 'M ' + source[0] + ', ' + source[1]
							+ 'A ' + dr + ', ' + dr + ',0 0 '+inOut+'  ' + target[0] + ', ' + target[1];

					return arc;
				})
			;

			emission.attr('class', function (d) { return ['emission', getEpci(idify(d.depart)), getEpci(idify(d.arrivee))].join(' '); })
				.attr('y', -5)
				.attr('dy', '.35em')
				.attr('transform', function (d) {return attach(d); })
				.text(function (d) { return Math.round(d.co2, 0) + ' kg'; })
			;
			qte.attr('class', function (d) { return ['qte', getEpci(idify(d.depart)), getEpci(idify(d.arrivee))].join(' '); })
				.attr('y', 5)
				.attr('dy', '.35em')
				.attr('transform', function (d) {return attach(d); })
				.text(function (d) { return Math.round(d.qte, 0) + ' t'; })
			;
			dist.attr('class', function (d) { return ['dist', getEpci(idify(d.depart)), getEpci(idify(d.arrivee))].join(' '); })
				.attr('y', 15)
				.attr('dy', '.35em')
				.attr('transform', function (d) {return attach(d); })
				.text(function (d) { return Math.round(d.dist, 0) + ' km'; })
			;
		}

		map.on('viewreset', reset);
		reset();
	});
	}

	/**
	 * Utility to project a depart point
	 */
	function projectDepart(d) { return projectPoint([Number(d.lon_depart), Number(d.lat_depart)]); }
	function projectArrivee(d) { return projectPoint([Number(d.lon_arrivee), Number(d.lat_arrivee)]); }

	/**
	 * Use Leaflet to implement a D3 geographic projection.
	 * @param  {array} x point as {latitute,longitude} array
	 * @return {array}   d3 coordinates as {x,y} array
	 */
	function projectPoint(x) {
		var point = map.latLngToLayerPoint(new L.LatLng(x[1], x[0]));
		return [point.x, point.y];
	}

	/**
	 * D3 to Leaflet coordinates
	 * @param  {array} p d3 coordinates as {x,y} array
	 * @return {array}   point as {latitute,longitude} array
	 */
	function pointToProjection(p) {
		var projection = map.layerPointToLatLng(new L.point(p[0], p[1]));
		return [projection.lng, projection.lat];
	}

	drawEntities().then(drawTransport);
}
<commit_msg>docs(route): add comment about routes' types<commit_after>function mapApp() {
	/* create leaflet map */
	var map = L.map('map', {
		center: [44.8597, -0.5157],
		zoom: 9
	});

	/**
	 * Object to store svg:element property for future use
	 */
	var props = {
		circle: {
			default: 2,
			active: 5
		}
	};

	/**
	 * Map type of centre index to name
	 * @type {Array}
	 */
	var typeCentre = [ 'epci', 'transfert', 'traitement' ];

	/* add default stamen tile layer */
	new L.tileLayer('http://{s}.tiles.mapbox.com/v3/examples.map-vyofok3q/{z}/{x}/{y}.png', {
		minZoom: 0,
		maxZoom: 18,
		attribution: 'Map data © OpenStreetMap contributors'
	}).addTo(map);

	var svg         = d3.select(map.getPanes().overlayPane).append('svg'),
		g               = svg.append('g').attr('class', 'leaflet-zoom-hide'),
		defs            = svg.append('defs'),
		marker          = defs.append('marker')
								.attr('id', 'arw-end')
								.attr('viewBox', '0 0 10 10')
								.attr('refX', 10)
								.attr('refY', 5)
								.attr('orient', 'auto')
							.append('path')
								.attr('d', 'M 0,0 10,5 0,10'),
		markerMid       = defs.append('marker')
								.attr('id', 'arw-mid')
								.attr('viewBox', '0 0 10 10')
								.attr('refY', 0)
								.attr('refY', 5)
								.attr('orient', 'auto')
							.append('path')
								.attr('d', 'M 0,0 10,5 0,10'),
		entities        = g.append('g').attr('id', 'entities'),
		entitiesLabels  = g.append('g').attr('id', 'entities-labels'),
		centres         = g.append('g').attr('id', 'centres'),
		routes          = g.append('g').attr('id', 'routes')
	;

	var path, entity, label, centre;

	function drawEntities() {
		return new Promise(function (resolve, reject) {
		d3.json('scripts/gironde-epci.topo.json', function (dataset) {
		var geoData = topojson.feature(dataset, dataset.objects['gironde-epci.geo']);
		var bounds = d3.geo.bounds(geoData);
		path = d3.geo.path().projection(projectPoint);

		// addCentre(geoData.features, 'id');

		entity = entities.selectAll('.entity')
			.data(geoData.features)
			.enter()
				.append('path')
				.attr('class', 'entity')
			;
		label = entitiesLabels.selectAll('.entity-label')
			.data(geoData.features)
			.enter()
				.append('text')
				.attr('class', 'entity-label')
			;

		// Reposition the SVG to cover the features.
		function reset() {
			var bottomLeft = projectPoint(bounds[0]),
				topRight = projectPoint(bounds[1]);

			svg.attr('width', topRight[0] - bottomLeft[0])
				.attr('height', bottomLeft[1] - topRight[1])
				.style('margin-left', bottomLeft[0] + 'px')
				.style('margin-top', topRight[1] + 'px');

			g.attr('transform', 'translate(' + -bottomLeft[0] + ',' + -topRight[1] + ')');

			entity.attr('d', path)
				.attr('class', function (d) {
					return 'entity ' + getCentres(idify(d.id)).join(' ');
				})
				.on('mouseover', function (d) {
					var eid = idify(d.id);
					highlightEntity(eid);
					showEntityLabel(eid);
					showEntityRoute(eid);
					// reset style on others elements
					// d3.selectAll('.entity').classed('active', false);
					d3.selectAll('circle')
						.classed('highlight', false)
						.attr('r', props.circle.default)
					;
					// apply style to element(s)
					// d3.select(this).classed('active', true);
					d3.selectAll('circle.' + idify(d.id))
						.classed('highlight', true)
						.attr('r', props.circle.active)
					;
					updateCounter(d.id);
				})
			;

			label.attr('id', function (d) { return idify(d.id); })
				.attr('class', function (d) { return 'entity-label ' + idify(d.id); })
				.attr('transform', function (d) {
					return 'translate(' + path.centroid(d) + ')';
				})
				.attr('x', -20)
				.attr('dy', '.35em')
				.text(function (d) { return toProperCase(d.id); })
			;
		}

		map.on('viewreset', reset);
		reset();
		resolve();
		});
	});
	}

	function drawTransport() {
		d3.csv('scripts/routes-dechets.csv', function (error, dataset) {
		centre = centres.selectAll('.centre')
			.data(dataset)
			.enter()
			.append('g')
		;

		centre
			.on('mouseover', function (d) {
				d3.select(this).attr('r', props.circle.active);
				// reset style on others elements
				d3.selectAll('.route').classed('show', false);
				// apply style to element(s)
				d3.selectAll('.route.' + idify(d.depart)).classed('show', true);
			})
			.on('mouseout', function () {
				d3.selectAll('.route').classed('show', false);
			});

		var centrePlace = centre.append('circle');
		var centreLabel = centre.append('text');

		// Standard enter / update
		var routePath = routes.selectAll('.route')
			.data(dataset)
			.enter()
			.append('path')
		;

		var emissionGroup = routes.append('g').attr('id', 'emission');
		var emission = emissionGroup.selectAll('.emission')
			.data(dataset)
			.enter()
			.append('text')
		;
		var qteGroup = routes.append('g').attr('id', 'qte');
		var qte = qteGroup.selectAll('.qte')
			.data(dataset)
			.enter()
			.append('text')
		;
		var distGroup = routes.append('g').attr('id', 'dist');
		var dist = distGroup.selectAll('.dist')
			.data(dataset)
			.enter()
			.append('text')
		;

		function attach(d) {
			var coordDepart = [ d.lon_depart, d.lat_depart ];
			var coordArrivee = [ d.lon_arrivee, d.lat_arrivee ];
			return 'translate(' + path.centroid({type: 'LineString', coordinates: [coordDepart, coordArrivee ] }) + ')';
		}

		function reset() {
			centre
				.attr('class', function (d) {
					return	' centre ' + idify(d.depart) +
							' from-' + typeCentre[d.niv_depart] +
							' to-' + typeCentre[d.niv_arrivee];
				})
			;
			centrePlace
					.attr('r', props.circle.default)
					.attr('cx', function (d) { return projectDepart(d)[0]; })
					.attr('cy', function (d) { return projectDepart(d)[1]; })
					.attr('title', function (d) { return idify(d.depart); })
			;
			centreLabel
				.attr('class', 'label')
				.attr('transform', function (d) {
					return 'translate(' +  projectDepart(d)[0] + ', ' + projectDepart(d)[1] + ')';
				})
				.text(function (d) { return idify(d.depart); })
			;

			routePath.attr('d', function (d) {
					var coordDepart = [ d.lon_depart, d.lat_depart ];
					var coordArrivee = [ d.lon_arrivee, d.lat_arrivee ];
					var vertex = path.centroid({type: 'LineString', coordinates: [coordDepart, coordArrivee ] });
					return path({
						type: 'LineString',
						coordinates: [
							coordDepart,
							pointToProjection(vertex),
							coordArrivee
						]
					});
				})
				.attr('class', function (d) {
					return [
						getEpci(idify(d.depart)), getEpci(idify(d.arrivee)),
						'route', idify(d.depart), idify(d.arrivee),
						'from-' + typeCentre[d.niv_depart],
						'to-' + typeCentre[d.niv_arrivee],
					].join(' ');
				})
			;
			routePath
				// use line between centers
				// .attr('class', function (d) {
				// 	return [
				// 		getEpci(idify(d.depart)), getEpci(idify(d.arrivee)),
				// 		'arc route', idify(d.depart), idify(d.arrivee),
				// 		'from-' + typeCentre[d.niv_depart],
				// 		'to-' + typeCentre[d.niv_arrivee],
				// 	].join(' ');
				// })

				// use curves between centers
				.attr('d', function (d) {
					var source = projectDepart(d);
					var target = projectArrivee(d);

					var  dx = target[0] - source[0]
						,dy = target[1] - source[1]
						,dr = Math.sqrt(dx * dx + dy * dy)
						,inOut = Math.round(Math.random(1))
					;
					var arc = 'M ' + source[0] + ', ' + source[1]
							+ 'A ' + dr + ', ' + dr + ',0 0 '+inOut+'  ' + target[0] + ', ' + target[1];

					return arc;
				})
			;

			emission.attr('class', function (d) { return ['emission', getEpci(idify(d.depart)), getEpci(idify(d.arrivee))].join(' '); })
				.attr('y', -5)
				.attr('dy', '.35em')
				.attr('transform', function (d) {return attach(d); })
				.text(function (d) { return Math.round(d.co2, 0) + ' kg'; })
			;
			qte.attr('class', function (d) { return ['qte', getEpci(idify(d.depart)), getEpci(idify(d.arrivee))].join(' '); })
				.attr('y', 5)
				.attr('dy', '.35em')
				.attr('transform', function (d) {return attach(d); })
				.text(function (d) { return Math.round(d.qte, 0) + ' t'; })
			;
			dist.attr('class', function (d) { return ['dist', getEpci(idify(d.depart)), getEpci(idify(d.arrivee))].join(' '); })
				.attr('y', 15)
				.attr('dy', '.35em')
				.attr('transform', function (d) {return attach(d); })
				.text(function (d) { return Math.round(d.dist, 0) + ' km'; })
			;
		}

		map.on('viewreset', reset);
		reset();
	});
	}

	/**
	 * Utility to project a depart point
	 */
	function projectDepart(d) { return projectPoint([Number(d.lon_depart), Number(d.lat_depart)]); }
	function projectArrivee(d) { return projectPoint([Number(d.lon_arrivee), Number(d.lat_arrivee)]); }

	/**
	 * Use Leaflet to implement a D3 geographic projection.
	 * @param  {array} x point as {latitute,longitude} array
	 * @return {array}   d3 coordinates as {x,y} array
	 */
	function projectPoint(x) {
		var point = map.latLngToLayerPoint(new L.LatLng(x[1], x[0]));
		return [point.x, point.y];
	}

	/**
	 * D3 to Leaflet coordinates
	 * @param  {array} p d3 coordinates as {x,y} array
	 * @return {array}   point as {latitute,longitude} array
	 */
	function pointToProjection(p) {
		var projection = map.layerPointToLatLng(new L.point(p[0], p[1]));
		return [projection.lng, projection.lat];
	}

	drawEntities().then(drawTransport);
}
<|endoftext|>


<commit_before>/**
 * Confusingly, this module both posts data to the leaderboard when a player
 * scores, AND fetches player names from the leaderboard so new players may
 * select their "account".
 */

import { each, chunk, groupBy, first, sortBy as sort, keys, without, indexOf, get } from 'lodash';
import * as conf from 'conf';
import players from 'players';

let board = {};

// const alpha_chunks = chunk(alphabet, conf.LOGIN_ALPHABET_CHUNK_SIZE);

board.player_list          = {};
board.player_list_parts    = {};
board.alphabet = 'abcdefghijklmnopqrstuvwxyz';

reset_player_selections('n');
reset_player_selections('s');
reset_player_selections('e');
reset_player_selections('w');

function reset_player_selections(playername) {
    board[playername] = {
        selected_player      : {},
        current_player_index : 0,
        current_letter       : 'No letter selected'
    };
}

board.select_next_letter = function select_next_letter(playername) {
    inc_letter(playername, 1);
};

board.select_prev_letter = function select_prev_letter(playername) {
    // add length-1 instead of subtracting to avoid ever having to deal with
    // negative numbers
    inc_letter(playername, keys(board.player_list_parts).length - 1);
};

function inc_letter(playername, inc=0) {
    // get all the letters, sorted
    let letters = sort(keys(board.player_list_parts));

    // find the index of the current letter
    let letter_index = indexOf(letters, board[playername].current_letter);

    // add inc to the index
    letter_index += inc;

    // mod for length
    letter_index %= letters.length;

    // assign current_letter
    board[playername].current_letter = letters[letter_index];

    // assign selected_player
    update_current_player(playername);

    // reset current_player_index
    board[playername].current_player_index = 0;

    console.log(`LOGIN: letter '${board[playername].current_letter}' selected`);
}

board.select_next_player = function select_next_player(playername) {
    select_player(playername, 1);
};

board.select_prev_player = function select_prev_player(playername) {
    // add length-1 instead of subtracting to avoid ever having to deal with
    // negative numbers
    select_player(playername, board.player_list_parts[board[playername].current_letter].length - 1);
};

function select_player(playername, inc=0) {
    board[playername].current_player_index += inc;
    board[playername].current_player_index %= board.player_list_parts[board[playername].current_letter].length;
    update_current_player(playername);
    console.log(`LOGIN: player '${board[playername].selected_player.name}' selected`);
}

function update_current_player(playername) {
    board[playername].selected_player = board.player_list_parts[board[playername].current_letter][board[playername].current_player_index];
}

function score_handler(event) {
    var player = board.player_list[event.detail.player.id],
        score = event.detail.score,
        xhr = new XMLHttpRequest(),
        updatedPlayer = {};

    if (get(player, 'ping.hiscore') && score <= player.ping.hiscore) {
        return;
    }

    updatedPlayer[event.detail.player.id] = {
        ping: {
            hiscore: score,
            color: event.detail.player.color
        }
    };

    xhr.open('PUT', '/leaderboard/leaders.json');
    xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
    xhr.responseType = 'json';

    xhr.onload = function () {
        console.log(xhr.response);
    };

    xhr.onerror = function () {
        console.log('error');
    };

    xhr.send(JSON.stringify(updatedPlayer));
}

function get_player_list() {
    var request = new XMLHttpRequest();
    request.open('GET', 'http://summit-games.usersys.redhat.com/users', true);

    request.onload = function() {
        if (this.status >= 200 && this.status < 400) {
            var data = JSON.parse(this.response);
            board.player_list = data;
            board.player_list_parts = groupBy(board.player_list, n => first(n.name.toLowerCase()));

            each(['n', 's', 'e', 'w'], function(p) {
                board[p].current_letter = first(sort(keys(board.player_list_parts)));
                board[p].selected_player = board.player_list_parts[board[p].current_letter][0];
            });

        } else {
            // We reached our target server, but it returned an error
        }
    };

    request.send();
}

get_player_list();
document.addEventListener('score', score_handler);

export default board;
<commit_msg>miscellaneous tidying<commit_after>/**
 * Confusingly, this module both posts data to the leaderboard when a player
 * scores, AND fetches player names from the leaderboard so new players may
 * select their "account".
 */

import { each, chunk, groupBy, first, sortBy as sort, keys, without, indexOf, get } from 'lodash';
import * as conf from 'conf';
import players from 'players';

let board = {};

// const alpha_chunks = chunk(alphabet, conf.LOGIN_ALPHABET_CHUNK_SIZE);

board.player_list          = {};
board.player_list_parts    = {};
board.alphabet = 'abcdefghijklmnopqrstuvwxyz';

reset_player_selections('n');
reset_player_selections('s');
reset_player_selections('e');
reset_player_selections('w');

function reset_player_selections(playername) {
    board[playername] = {
        selected_player      : {},
        current_player_index : 0,
        current_letter       : 'No letter selected'
    };
}

board.select_next_letter = function select_next_letter(playername) {
    inc_letter(playername, 1);
};

board.select_prev_letter = function select_prev_letter(playername) {
    // add length-1 instead of subtracting to avoid ever having to deal with
    // negative numbers
    inc_letter(playername, keys(board.player_list_parts).length - 1);
};

function inc_letter(playername, inc=0) {
    // get all the letters, sorted
    let letters = sort(keys(board.player_list_parts));

    // find the index of the current letter
    let letter_index = indexOf(letters, board[playername].current_letter);

    // add inc to the index
    letter_index += inc;

    // mod for length
    letter_index %= letters.length;

    // assign current_letter
    board[playername].current_letter = letters[letter_index];

    // assign selected_player
    update_current_player(playername);

    // reset current_player_index
    board[playername].current_player_index = 0;

    console.log(`LOGIN: letter '${board[playername].current_letter}' selected`);
}

board.select_next_player = function select_next_player(playername) {
    select_player(playername, 1);
};

board.select_prev_player = function select_prev_player(playername) {
    // add length-1 instead of subtracting to avoid ever having to deal with
    // negative numbers
    select_player(playername, board.player_list_parts[board[playername].current_letter].length - 1);
};

function select_player(playername, inc=0) {
    board[playername].current_player_index += inc;
    board[playername].current_player_index %= board.player_list_parts[board[playername].current_letter].length;
    update_current_player(playername);
    console.log(`LOGIN: player '${board[playername].selected_player.name}' selected`);
}

function update_current_player(playername) {
    board[playername].selected_player = board.player_list_parts[board[playername].current_letter][board[playername].current_player_index];
}

function score_handler(event) {
    var player = board.player_list[event.detail.player.id],
        score = event.detail.score,
        xhr = new XMLHttpRequest(),
        updatedPlayer = {};

    if (get(player, 'ping.hiscore') && score <= player.ping.hiscore) {
        return;
    }

    updatedPlayer[event.detail.player.id] = {
        ping: {
            hiscore: score,
            color: event.detail.player.color
        }
    };

    xhr.open('PUT', '/leaderboard/leaders.json');
    xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
    xhr.responseType = 'json';

    xhr.onload = function () {
        // console.log(xhr.response);
    };

    xhr.onerror = function () {
        console.log('error');
    };

    xhr.send(JSON.stringify(updatedPlayer));
}

function get_player_list() {
    var request = new XMLHttpRequest();
    request.open('GET',  '/leaderboard/leaders.json', true);

    request.onload = function() {
        if (this.status >= 200 && this.status < 400) {
            var data = JSON.parse(this.response);
            board.player_list = data;
            board.player_list_parts = groupBy(board.player_list, n => first(n.name.toLowerCase()));

            each(['n', 's', 'e', 'w'], function(p) {
                board[p].current_letter = first(sort(keys(board.player_list_parts)));
                board[p].selected_player = board.player_list_parts[board[p].current_letter][0];
            });

        } else {
            // We reached our target server, but it returned an error
        }
    };

    request.send();
}

get_player_list();
document.addEventListener('score', score_handler);

export default board;
<|endoftext|>


<commit_before>const { LitElement, html, css } = dashboard.lit;

module.exports = class ComboboxChooser extends LitElement {

  static get properties() {
    return {
      label: { type: String },
      selected: { type: Object },
      options: { type: Array }
    }
  }

  static get styles() {
    return css`
      :host {
        display: inline-block;
      }
    `;
  }

  constructor() {
    super();
    this.options = [];
    this.selected = '';
    this.label = '';
  }

  onChange(ev) {
    if (this.ntRoot) {
      const value = ev.detail.value;
      NetworkTables.putValue(this.ntRoot + 'selected', value);
    }
  }

  updated(changes) {
    if (changes.has('table')) {
      this.options = this.table.options || [];
      this.selected = this.table.selected || '';
    }
  }

  render() {
    return html`
      <vaadin-combo-box
        label="${this.label}"
        .items="${this.options}"
        value="${this.selected}"
        @selected-item-changed="${this.onChange}"
      >

      </vaadin-combo-box>

    `;
  }
}
<commit_msg>Renamed variable<commit_after>const { LitElement, html, css } = dashboard.lit;

module.exports = class ComboboxChooser extends LitElement {

  static get properties() {
    return {
      label: { type: String },
      selected: { type: Object },
      options: { type: Array }
    }
  }

  static get styles() {
    return css`
      :host {
        display: inline-block;
      }
    `;
  }

  constructor() {
    super();
    this.options = [];
    this.selected = '';
    this.label = '';
  }

  onChange(ev) {
    if (this.ntRoot) {
      const value = ev.detail.value;
      NetworkTables.putValue(this.ntRoot + 'selected', value);
    }
  }

  updated(changedProperties) {
    if (changedProperties.has('table')) {
      this.options = this.table.options || [];
      this.selected = this.table.selected || '';
    }
  }

  render() {
    return html`
      <vaadin-combo-box
        label="${this.label}"
        .items="${this.options}"
        value="${this.selected}"
        @selected-item-changed="${this.onChange}"
      >

      </vaadin-combo-box>

    `;
  }
}
<|endoftext|>


<commit_before>import {
  getComponentsTargetsByComponent,
  getComponentsTargetsByPosition,
} from 'utils/model/redirections-utils';

export function getTargets(
  componentsStore,
  selectedTarget,
  editingComponentId,
  selectedComponentId,
  componentType,
) {
  let allowedTargets;

  if (editingComponentId !== '') {
    // When a component is been edited.
    allowedTargets = getComponentsTargetsByComponent(
      componentsStore,
      componentsStore[editingComponentId],
    );
  } else {
    // When the component is a new one.
    allowedTargets = getComponentsTargetsByPosition(
      componentsStore,
      componentType,
      selectedComponentId,
    );
  }

  if (
    selectedTarget !== '' &&
    componentsStore[selectedTarget] &&
    allowedTargets.indexOf(selectedTarget) === -1
  ) {
    allowedTargets.unshift(selectedTarget);
  }

  return allowedTargets
    .filter(key => key !== 'idendquest')
    .map(key => {
      return {
        value: key,
        label: `${componentsStore[key].name} - ${componentsStore[key].label}`,
      };
    });
}
<commit_msg>redirection-end-allowtarged<commit_after>import {
  getComponentsTargetsByComponent,
  getComponentsTargetsByPosition,
} from 'utils/model/redirections-utils';

export function getTargets(
  componentsStore,
  selectedTarget,
  editingComponentId,
  selectedComponentId,
  componentType,
) {
  let allowedTargets;

  if (editingComponentId !== '') {
    // When a component is been edited.
    allowedTargets = getComponentsTargetsByComponent(
      componentsStore,
      componentsStore[editingComponentId],
    );
  } else {
    // When the component is a new one.
    allowedTargets = getComponentsTargetsByPosition(
      componentsStore,
      componentType,
      selectedComponentId,
    );
  }

  if (
    selectedTarget !== '' &&
    componentsStore[selectedTarget] &&
    allowedTargets.indexOf(selectedTarget) === -1
  ) {
    allowedTargets.unshift(selectedTarget);
  }

  return allowedTargets.map(key => {
    return {
      value: key,
      label: `${componentsStore[key].name} - ${componentsStore[key].label}`,
    };
  });
}
<|endoftext|>


<commit_before>'use strict';

$(function () {
    // Handler for .ready() called.
    $('[data-scrollToLink]').each(function (i, l) {
        var $link = $(l);
        $link.on('click', function () {
            $('body').scrollTo('#' + $link.attr('data-scrollToLink'), 500, {offset: {top: -50} });
        });
    });
    $("#owl-example").owlCarousel({
                                      items: 7, //10 items above 1000px browser width
                                      itemsDesktop: [1000, 5], //5 items between 1000px and 901px
                                      itemsDesktopSmall: [900, 4], // betweem 900px and 601px
                                      itemsTablet: [600, 2], //2 items between 600 and 0
                                      itemsMobile: false, // itemsMobile disabled - inherit from itemsTablet option
                                      autoPlay: 3000,
                                      stopOnHover: true,
                                      lazyLoad: true,
                                      afterInit: function () {
                                          $("[title]").tooltip();
                                      }
                                  });
});<commit_msg>fix scroll low framerate<commit_after>'use strict';

$(function () {
    // Handler for .ready() called.
    $('[data-scrollToLink]').each(function (i, l) {
        var $link = $(l);
        $link.on('click', function () {
            $('body').scrollTo('#' + $link.attr('data-scrollToLink'), 500, {offset: {top: -50} });
        });
    });
    $(window).on('scroll', function() {
        window.requestAnimationFrame(scrollHandler);
    });
    $("#owl-example").owlCarousel({
                                      items: 7, //10 items above 1000px browser width
                                      itemsDesktop: [1000, 5], //5 items between 1000px and 901px
                                      itemsDesktopSmall: [900, 4], // betweem 900px and 601px
                                      itemsTablet: [600, 2], //2 items between 600 and 0
                                      itemsMobile: false, // itemsMobile disabled - inherit from itemsTablet option
                                      autoPlay: 3000,
                                      stopOnHover: true,
                                      lazyLoad: true,
                                      afterInit: function () {
                                          $("[title]").tooltip();
                                      }
                                  });
});<|endoftext|>


<commit_before>/* global Stripe */
import config from '../config/environment';
import Ember from 'ember';
var debug = config.LOG_STRIPE_SERVICE;

function createToken (card) {
  if (debug) {
    Ember.Logger.info('StripeService: getStripeToken - card:', card);
  }

  // manually start Ember loop
  Ember.run.begin();

  return new Ember.RSVP.Promise(function (resolve, reject) {
    Stripe.card.createToken(card, function (status, response) {

      if (debug) {
        Ember.Logger.info('StripeService: createToken handler - status %s, response:', status, response);
      }

      if (response.error) {
        reject(response);
        return Ember.run.end();
      }

      resolve(response);

      Ember.run.end();
    });
  });
}

export default Ember.Object.extend({
  createToken: createToken
});
<commit_msg>Add a create bank account token method to the service<commit_after>/* global Stripe */
import config from '../config/environment';
import Ember from 'ember';
var debug = config.LOG_STRIPE_SERVICE;

function createToken (card) {
  if (debug) {
    Ember.Logger.info('StripeService: getStripeToken - card:', card);
  }

  // manually start Ember loop
  Ember.run.begin();

  return new Ember.RSVP.Promise(function (resolve, reject) {
    Stripe.card.createToken(card, function (status, response) {

      if (debug) {
        Ember.Logger.info('StripeService: createToken handler - status %s, response:', status, response);
      }

      if (response.error) {
        reject(response);
        return Ember.run.end();
      }

      resolve(response);

      Ember.run.end();
    });
  });
}

function createBankAccountToken(bankAccount) {
  if (debug) {
    Ember.Logger.info('StripeService: getStripeToken - bankAccount:', bankAccount);
  }

  // manually start Ember loop
  Ember.run.begin();

  return new Ember.RSVP.Promise(function (resolve, reject) {
    Stripe.bankAccount.createToken(bankAccount, function (status, response) {

      if (debug) {
        Ember.Logger.info('StripeService: createBankAccountToken handler - status %s, response:', status, response);
      }

      if (response.error) {
        reject(response);
        return Ember.run.end();
      }

      resolve(response);

      Ember.run.end();
    });
  });
}

export default Ember.Object.extend({
  createToken: createToken,
  createBankAccountToken: createBankAccountToken,
});
<|endoftext|>


<commit_before>angular.module('opApp').directive('opResultsTable', ['$timeout', '$window', '$rootScope',
    function ($timeout, $window, $rootScope) {
    'use strict';

    return {
        restrict: 'EA',
        templateUrl: 'modules/results/opResultsTable.html',
        scope: {
            opModel: '=',
            loading: '=',
            error: '=',
            layer: '='
        },
        link: function (scope, element) {
            var table = null;
            scope.idColumn = null;
            scope.$watch('opModel', function () {

                var dataSet = [];
                var columns = [];
                var selectStyle = false;

                if(scope.opModel.length){

                    var columnKeys = scope.opModel[0].properties;
                    var columnIndex = 0;
                    for(var property in columnKeys){
                        columns.push({"sTitle":property});
                        columnIndex++;
                    }

                    if(scope.opModel[0].id)
                    {
                        columns.push({"sTitle": "fid"});
                        selectStyle = {style: 'os'};
                        $rootScope.selectDisabled = false;
                    }
                    else
                    {
                        $rootScope.selectDisabled = true;
                    }

                    if(table != null){
                        table.fnClearTable();
                        table.fnDestroy();
                        $('#table').empty();
                    }

                    table = $('#table').dataTable(
                    {
                        "bPaginate": false,
                        "bLengthChange": false,
                        "bDestroy": true,
                        "bInfo": false,
                        select: selectStyle,
                        columns: columns
                    });

                    for (var i = 0; i < scope.opModel.length; i++) {
                        var row = scope.opModel[i].properties;
                        var item = []

                        for(var property in row)
                            item.push(row[property]);
                        if(scope.opModel[i].id)
                            item.push(scope.opModel[i].id);
                        dataSet.push(item);
                    }
                    $.fn.dataTableExt.sErrMode = 'none';
                    table.fnAddData(dataSet);

                    scope.noData = false;

                    if(selectStyle)
                    {
                        $(document).keydown(function (event) {
                            switch(event.keyCode)
                            {
                                //arrow down
                                case 40:
                                    event.preventDefault();
                                    var currentRow = $(".selected:last").get(0);

                                    if(!currentRow)
                                    {
                                        table.api().row(':first').select();
                                        $(window).scrollTop(0);
                                        var rowData = table.api().rows( {selected:true, filter: 'applied'} ).data();
                                        $window.opener.resultsSelected(scope.layer, rowData);
                                    }
                                    if(currentRow.nextSibling)
                                    {
                                        if(!event.shiftKey)
                                            table.api().rows('.selected').deselect();
                                        $(window).scrollTop(currentRow.offsetTop);

                                        table.api().row(currentRow.nextSibling).select();

                                        var rowData = table.api().rows( {selected:true, filter: 'applied'} ).data();
                                        $window.opener.resultsSelected(scope.layer, rowData);

                                    }
                                    break;
                                //arrow up
                                case 38:
                                    event.preventDefault();
                                    var currentRow = $(".selected:first").get(0);

                                    if(!currentRow)
                                    {
                                        table.api().row(':last').select();
                                        $(window).scrollTop($(document).height());
                                        var rowData = table.api().rows( {selected:true, filter: 'applied'} ).data();
                                        $window.opener.resultsSelected(scope.layer, rowData);
                                    }
                                    if(currentRow.previousSibling)
                                    {
                                        if(!event.shiftKey)
                                            table.api().rows('.selected').deselect();
                                        $(window).scrollTop(currentRow.offsetTop);

                                        table.api().row(currentRow.previousSibling).select();
                                        var rowData = table.api().rows( {selected:true, filter: 'applied'} ).data();
                                        $window.opener.resultsSelected(scope.layer, rowData);

                                    }
                                    break;
                            }
                        });

                        table.api().on( 'search.dt', function () {
                            var rowData = table.api().rows( {selected:true, filter: 'applied'} ).data();
                            $window.opener.resultsSelected(scope.layer, rowData);
                        });

                        $('#table tbody').on( 'click', 'tr', function () {
                            var rowData = table.api().rows( {selected:true, filter: 'applied'} ).data();
                            $window.opener.resultsSelected(scope.layer, rowData);
                        });
                    }
                }
                else
                {
                    scope.noData = true;
                }
            });
        }
    };
}]);
<commit_msg>Additional check for fid-.<commit_after>angular.module('opApp').directive('opResultsTable', ['$timeout', '$window', '$rootScope',
    function ($timeout, $window, $rootScope) {
    'use strict';

    return {
        restrict: 'EA',
        templateUrl: 'modules/results/opResultsTable.html',
        scope: {
            opModel: '=',
            loading: '=',
            error: '=',
            layer: '='
        },
        link: function (scope, element) {
            var table = null;
            scope.idColumn = null;
            scope.$watch('opModel', function () {

                var dataSet = [];
                var columns = [];
                var selectStyle = false;

                if(scope.opModel.length){

                    var columnKeys = scope.opModel[0].properties;
                    var columnIndex = 0;
                    for(var property in columnKeys){
                        columns.push({"sTitle":property});
                        columnIndex++;
                    }

                    if(scope.opModel[0].id && scope.opModel[0].id.indexOf('fid-') < 0)
                    {
                        columns.push({"sTitle": "fid"});
                        selectStyle = {style: 'os'};
                        $rootScope.selectDisabled = false;
                    }
                    else
                    {
                        $rootScope.selectDisabled = true;
                    }

                    if(table != null){
                        table.fnClearTable();
                        table.fnDestroy();
                        $('#table').empty();
                    }

                    table = $('#table').dataTable(
                    {
                        "bPaginate": false,
                        "bLengthChange": false,
                        "bDestroy": true,
                        "bInfo": false,
                        select: selectStyle,
                        columns: columns
                    });

                    for (var i = 0; i < scope.opModel.length; i++) {
                        var row = scope.opModel[i].properties;
                        var item = []

                        for(var property in row)
                            item.push(row[property]);
                        if(scope.opModel[i].id)
                            item.push(scope.opModel[i].id);
                        dataSet.push(item);
                    }
                    $.fn.dataTableExt.sErrMode = 'none';
                    table.fnAddData(dataSet);

                    scope.noData = false;

                    if(selectStyle)
                    {
                        $(document).keydown(function (event) {
                            switch(event.keyCode)
                            {
                                //arrow down
                                case 40:
                                    event.preventDefault();
                                    var currentRow = $(".selected:last").get(0);

                                    if(!currentRow)
                                    {
                                        table.api().row(':first').select();
                                        $(window).scrollTop(0);
                                        var rowData = table.api().rows( {selected:true, filter: 'applied'} ).data();
                                        $window.opener.resultsSelected(scope.layer, rowData);
                                    }
                                    if(currentRow.nextSibling)
                                    {
                                        if(!event.shiftKey)
                                            table.api().rows('.selected').deselect();
                                        $(window).scrollTop(currentRow.offsetTop);

                                        table.api().row(currentRow.nextSibling).select();

                                        var rowData = table.api().rows( {selected:true, filter: 'applied'} ).data();
                                        $window.opener.resultsSelected(scope.layer, rowData);

                                    }
                                    break;
                                //arrow up
                                case 38:
                                    event.preventDefault();
                                    var currentRow = $(".selected:first").get(0);

                                    if(!currentRow)
                                    {
                                        table.api().row(':last').select();
                                        $(window).scrollTop($(document).height());
                                        var rowData = table.api().rows( {selected:true, filter: 'applied'} ).data();
                                        $window.opener.resultsSelected(scope.layer, rowData);
                                    }
                                    if(currentRow.previousSibling)
                                    {
                                        if(!event.shiftKey)
                                            table.api().rows('.selected').deselect();
                                        $(window).scrollTop(currentRow.offsetTop);

                                        table.api().row(currentRow.previousSibling).select();
                                        var rowData = table.api().rows( {selected:true, filter: 'applied'} ).data();
                                        $window.opener.resultsSelected(scope.layer, rowData);

                                    }
                                    break;
                            }
                        });

                        table.api().on( 'search.dt', function () {
                            var rowData = table.api().rows( {selected:true, filter: 'applied'} ).data();
                            $window.opener.resultsSelected(scope.layer, rowData);
                        });

                        $('#table tbody').on( 'click', 'tr', function () {
                            var rowData = table.api().rows( {selected:true, filter: 'applied'} ).data();
                            $window.opener.resultsSelected(scope.layer, rowData);
                        });
                    }
                }
                else
                {
                    scope.noData = true;
                }
            });
        }
    };
}]);
<|endoftext|>


<commit_before>/*
 * A source to get weather using the OpenWeatherMap API. On update(), all
 * relevant data is stored in mongo, ready to be used by the front-end.
 */
let request = require('request');
let config = require('config');
let weatherConf = config.get('weather');
let token = weatherConf.get('token');
let zip = weatherConf.get('zip');

/**
 * Updates all data for this module.
 * @param {database} db The mongo database/
 */
function update(db) {
  updateCurrent(db);
  updateForcast(db);
};

/**
 * Requests current weather and commits to mongo.
 * @param {database} db The mongo database.
 */
function updateCurrent(db) {
  let host = 'http://api.openweathermap.org';
  let path = '/data/2.5/weather?zip=' + zip + '&appid=' + token;
  request(host + path, function(error, response, body) {
    console.log('weather error:', error);
    console.log('weather statusCode:', response && response.statusCode);
    let jbody = JSON.parse(body);
    let commit = {
      city: jbody.name,
      weather: jbody.weather,
      temp: jbody.main.temp,
    };
    db.createCollection('weather', function(err, collection) {
      let docs = collection.find({}).toArray();
      collection.insertOne(commit);
      for (let i = 0; i < docs.length; ++i) {
        collection.deleteOne(docs[i]);
      }
      console.log('Updated weather successfully.');
    });
  });
};

/**
 * Requests forcasted weather and commits to mongo.
 * @param {database} db The mongo database/
 */
function updateForcast(db) {
  let host = 'http://api.openweathermap.org';
  let path = '/data/2.5/forecast?zip=' + zip + '&appid=' + token;
  request(host + path, function(error, response, body) {
    console.log('forecast error:', error);
    console.log('forecast statusCode:', response && response.statusCode);
    let jbody = JSON.parse(body);
    db.createCollection('forecast', function(err, collection) {
      for (let i = 0; i < jbody.list.size; ++i) {
        collection.deleteMany({dt: jbody.list[i].dt});
        collection.insertOne(jbody.list[i]);
      }
      console.log('Updated forecast successfully.');
    });
  });
};

module.exports = {update};
<commit_msg>Fix typo in forecast<commit_after>/*
 * A source to get weather using the OpenWeatherMap API. On update(), all
 * relevant data is stored in mongo, ready to be used by the front-end.
 */
let request = require('request');
let config = require('config');
let weatherConf = config.get('weather');
let token = weatherConf.get('token');
let zip = weatherConf.get('zip');

/**
 * Updates all data for this module.
 * @param {database} db The mongo database/
 */
function update(db) {
  updateCurrent(db);
  updateForecast(db);
};

/**
 * Requests current weather and commits to mongo.
 * @param {database} db The mongo database.
 */
function updateCurrent(db) {
  let host = 'http://api.openweathermap.org';
  let path = '/data/2.5/weather?zip=' + zip + '&appid=' + token;
  request(host + path, function(error, response, body) {
    console.log('weather error:', error);
    console.log('weather statusCode:', response && response.statusCode);
    let jbody = JSON.parse(body);
    let commit = {
      city: jbody.name,
      weather: jbody.weather,
      temp: jbody.main.temp,
    };
    db.createCollection('weather', function(err, collection) {
      let docs = collection.find({}).toArray();
      collection.insertOne(commit);
      for (let i = 0; i < docs.length; ++i) {
        collection.deleteOne(docs[i]);
      }
      console.log('Updated weather successfully.');
    });
  });
};

/**
 * Requests forecasted weather and commits to mongo.
 * @param {database} db The mongo database/
 */
function updateForecast(db) {
  let host = 'http://api.openweathermap.org';
  let path = '/data/2.5/forecast?zip=' + zip + '&appid=' + token;
  request(host + path, function(error, response, body) {
    console.log('forecast error:', error);
    console.log('forecast statusCode:', response && response.statusCode);
    let jbody = JSON.parse(body);
    db.createCollection('forecast', function(err, collection) {
      for (let i = 0; i < jbody.list.size; ++i) {
        collection.deleteMany({dt: jbody.list[i].dt});
        collection.insertOne(jbody.list[i]);
      }
      console.log('Updated forecast successfully.');
    });
  });
};

module.exports = {update};
<|endoftext|>


<commit_before>export default class HttpApi {
  constructor (prefix = '') {
    this.prefix = prefix
    this.opts = {
      credentials: 'same-origin',
      headers: new Headers({
        'Content-Type': 'application/json',
      })
    }

    return this.callApi
  }

  callApi = (method, url, opts = {}) => {
    opts = Object.assign({}, this.opts, opts)
    opts.method = method

    if (typeof opts.body === 'object') {
      opts.body = JSON.stringify(opts.body)
    }

    return fetch(`/api/${this.prefix}${url}`, opts)
      .then(res => {
        if (res.ok) {
          const type = res.headers.get('Content-Type')
          return (type && type.includes('application/json')) ? res.json() : res.text()
        }

        // error
        return res.text().then(txt => {
          return Promise.reject(new Error(txt))
        })
      })
  }
}
<commit_msg>Fix fetch api when returning non-JSON<commit_after>export default class HttpApi {
  constructor (prefix = '') {
    this.prefix = prefix
    this.opts = {
      credentials: 'same-origin',
      headers: new Headers({
        'Content-Type': 'application/json',
      })
    }

    return this.callApi
  }

  callApi = (method, url, opts = {}) => {
    opts = Object.assign({}, this.opts, opts)
    opts.method = method

    if (typeof opts.body === 'object') {
      opts.body = JSON.stringify(opts.body)
    }

    return fetch(`/api/${this.prefix}${url}`, opts)
      .then(res => {
        if (res.ok) {
          const type = res.headers.get('Content-Type')
          return (type && type.includes('application/json')) ? res.json() : res
        }

        // error
        return res.text().then(txt => {
          return Promise.reject(new Error(txt))
        })
      })
  }
}
<|endoftext|>


<commit_before>import api from 'jspm/api';
import whacko from 'whacko';
import glob from 'glob';
import fs from 'fs';
import url from 'url';
import path from 'path';

var pluginName = 'view';

function bundleJS(moduleExpression, outfile, options) {
  api.bundle(moduleExpression, outfile, options);
}

export default function bundle(config) {

  var loader = api.Builder().loader;
  var baseURL = loader.baseURL;
  var paths = loader.paths;

  var jsConfig = config.js;
  var templateConfig = config.template;

  Object.keys(jsConfig)
    .forEach(function(key) {
      var cfg = jsConfig[key];
      var outfile = key + '.js';
      var moduleExpr = cfg.modules.join(' + ');
      var opt = cfg.options;

      bundleJS(moduleExpr, outfile, opt);
    });

  if (!templateConfig) return;

  Object.keys(templateConfig)
    .forEach(function(key) {
      var cfg = templateConfig[key];
      var outfile = key + '.html';
      var pattern = cfg.pattern;
      var options = cfg.options;

      bundleTemplate(pattern, outfile, options, baseURL, paths);
    });
}

function bundleTemplate(pattern, outfile, options, baseURL, paths) {
  var templates = [];
  var cwd = baseURL.replace(/^file:/, '');

    glob
      .sync(pattern, {
        cwd: cwd
      })
      .forEach(function(file) {

        file = path.resolve(cwd, file);

        var content = fs.readFileSync(file, {
          encoding: 'utf8'
        });
        var $ = whacko.load(content);
        var tid = getTemplateId(file, baseURL, paths);

        $('template').attr('id', tid);
        var template = $.html('template');
        templates.push(template);
      });

    fs.writeFileSync(outfile, templates.join('\n'));

  if (options.inject) {
    injectLink(outfile, baseURL);
  }
}

function injectLink(outfile, baseURL) {
  var bu = baseURL.replace(/^file:/, '') + path.sep;
  var link = '';
  var bundle = path.resolve(bu, path.relative(bu, outfile));
  var index = path.resolve(bu, 'index.html');

  var relpath = path.relative(path.dirname(index), path.dirname(bundle)).replace(/\\/g, '/');

  //regex : !link.startsWith('.')
  if (!(/^\./.test(relpath))) {
    link = relpath ? './' + relpath + '/' + path.basename(bundle) : './' + path.basename(bundle);
  } else {
    link = relpath + '/' + path.basename(bundle);
  }

  var content = fs.readFileSync(index, {
    encoding: 'utf8'
  });

  var $ = whacko.load(content);

  $('body').append('<link aurlia-view-bundle rel="import" href="' + link + '">');

  fs.writeFileSync(index, $.html());
}

function getTemplateId(file, baseURL, paths) {
  var bu = baseURL.replace(/\\/g, '/') + '/';
  var address = 'file:' + file.replace(/\\/g, '/');
  return getModuleName(address, bu, paths);
}

function getModuleName(address, baseURL, paths) {
  var pathMatch, curMatchLength, curPath, wIndex, pathMatchLength = 0;

  if (pluginName) {
    var extension = address.split('/').pop();
    extension = extension.substr(extension.lastIndexOf('.'));
    if (extension != address && extension != '.js')
      address = address.substr(0, address.length - extension.length) + '.js';
  }

  for (var p in paths) {

    curPath = decodeURI(url.resolve(encodeURI(baseURL), paths[p].replace(/\\/g, '/')));
    wIndex = curPath.indexOf('*');

    if (wIndex === -1) {
      if (address === curPath) {
        curMatchLength = curPath.split('/').length;
        if (curMatchLength > pathMatchLength) {
          pathMatch = p;
          pathMatchLength = curMatchLength;
        }
      }
    } else {
      if (address.substr(0, wIndex) === curPath.substr(0, wIndex) && address.substr(address.length - curPath.length + wIndex + 1) === curPath.substr(wIndex + 1)) {
        curMatchLength = curPath.split('/').length;
        if (curMatchLength > pathMatchLength) {
          pathMatch = p.replace('*', address.substr(wIndex, address.length - curPath.length + 1));
          pathMatchLength = curMatchLength;
        }
      }
    }
  }

  if (!pathMatch)
    throw "Unable to calculate path for " + address;

  if (pluginName)
    pathMatch += extension + '!' + (pluginName == extension ? '' : pluginName);

  return pathMatch;
}
<commit_msg>feat(view bundle): `inject` will only inject if the link is not present<commit_after>import api from 'jspm/api';
import whacko from 'whacko';
import glob from 'glob';
import fs from 'fs';
import url from 'url';
import path from 'path';

var pluginName = 'view';

function bundleJS(moduleExpression, outfile, options) {
  api.bundle(moduleExpression, outfile, options);
}

export default function bundle(config) {

  var loader = api.Builder().loader;
  var baseURL = loader.baseURL;
  var paths = loader.paths;

  var jsConfig = config.js;
  var templateConfig = config.template;

  Object.keys(jsConfig)
    .forEach(function(key) {
      var cfg = jsConfig[key];
      var outfile = key + '.js';
      var moduleExpr = cfg.modules.join(' + ');
      var opt = cfg.options;

      bundleJS(moduleExpr, outfile, opt);
    });

  if (!templateConfig) return;

  Object.keys(templateConfig)
    .forEach(function(key) {
      var cfg = templateConfig[key];
      var outfile = key + '.html';
      var pattern = cfg.pattern;
      var options = cfg.options;

      bundleTemplate(pattern, outfile, options, baseURL, paths);
    });
}

function bundleTemplate(pattern, outfile, options, baseURL, paths) {
  var templates = [];
  var cwd = baseURL.replace(/^file:/, '');

    glob
      .sync(pattern, {
        cwd: cwd
      })
      .forEach(function(file) {

        file = path.resolve(cwd, file);

        var content = fs.readFileSync(file, {
          encoding: 'utf8'
        });
        var $ = whacko.load(content);
        var tid = getTemplateId(file, baseURL, paths);

        $('template').attr('id', tid);
        var template = $.html('template');
        templates.push(template);
      });

    fs.writeFileSync(outfile, templates.join('\n'));

  if (options.inject) {
    injectLink(outfile, baseURL);
  }
}

function injectLink(outfile, baseURL) {
  var bu = baseURL.replace(/^file:/, '') + path.sep;
  var link = '';
  var bundle = path.resolve(bu, path.relative(bu, outfile));
  var index = path.resolve(bu, 'index.html');

  var relpath = path.relative(path.dirname(index), path.dirname(bundle)).replace(/\\/g, '/');

  //regex : !link.startsWith('.')
  if (!(/^\./.test(relpath))) {
    link = relpath ? './' + relpath + '/' + path.basename(bundle) : './' + path.basename(bundle);
  } else {
    link = relpath + '/' + path.basename(bundle);
  }

  var content = fs.readFileSync(index, {
    encoding: 'utf8'
  });

  var $ = whacko.load(content);

  if($('link[aurelia-view-bundle][href="'+ link +'"]').length === 0 ){
    $('body').append('<link aurelia-view-bundle rel="import" href="' + link + '">');
  }

  fs.writeFileSync(index, $.html());
}

function getTemplateId(file, baseURL, paths) {
  var bu = baseURL.replace(/\\/g, '/') + '/';
  var address = 'file:' + file.replace(/\\/g, '/');
  return getModuleName(address, bu, paths);
}

function getModuleName(address, baseURL, paths) {
  var pathMatch, curMatchLength, curPath, wIndex, pathMatchLength = 0;

  if (pluginName) {
    var extension = address.split('/').pop();
    extension = extension.substr(extension.lastIndexOf('.'));
    if (extension != address && extension != '.js')
      address = address.substr(0, address.length - extension.length) + '.js';
  }

  for (var p in paths) {

    curPath = decodeURI(url.resolve(encodeURI(baseURL), paths[p].replace(/\\/g, '/')));
    wIndex = curPath.indexOf('*');

    if (wIndex === -1) {
      if (address === curPath) {
        curMatchLength = curPath.split('/').length;
        if (curMatchLength > pathMatchLength) {
          pathMatch = p;
          pathMatchLength = curMatchLength;
        }
      }
    } else {
      if (address.substr(0, wIndex) === curPath.substr(0, wIndex) && address.substr(address.length - curPath.length + wIndex + 1) === curPath.substr(wIndex + 1)) {
        curMatchLength = curPath.split('/').length;
        if (curMatchLength > pathMatchLength) {
          pathMatch = p.replace('*', address.substr(wIndex, address.length - curPath.length + 1));
          pathMatchLength = curMatchLength;
        }
      }
    }
  }

  if (!pathMatch)
    throw "Unable to calculate path for " + address;

  if (pluginName)
    pathMatch += extension + '!' + (pluginName == extension ? '' : pluginName);

  return pathMatch;
}
<|endoftext|>


<commit_before>// expose the attribures of the nodes

const rmElement = require('../helpers/rmElement.js')

let buttonToken = false
module.exports = function expose (cy) {
  // when button is pressed
  const exposeButton = document.getElementById('expose-button')

  if (buttonToken === false) {
    const graph = document.getElementById('window-id')

    cy.nodes().map(node => {
      let nodeInfo = ''
      const nodeData = node.data().asto
      Object.keys(nodeData).map(i => {
        // adds the keys of the object to the string
        if (nodeData.hasOwnProperty(i) === true) {
          nodeInfo = `${nodeInfo} • ${i}:`
        }
        // adds the values of the object to the string
        nodeInfo = `${nodeInfo} ${nodeData[i]}\n`
      })

      // create a container for each node
      const container = document.createElement('span')
      container.id = node.data().id
      container.innerHTML = `

${nodeInfo}

`

      graph.appendChild(container)
    })

    // show active expose with colored button
    exposeButton.setAttribute('class', 'active-button')
    buttonToken = true
  } else {
    // removes the exposed containers
    cy.nodes().map(node => {
      rmElement('window-id', node.data().id)
    })

    // restores the original button color
    exposeButton.setAttribute('class', 'button-icon')
    buttonToken = false
  }
}
<commit_msg>:art: rename button -> btn<commit_after>// expose the attribures of the nodes

const rmElement = require('../helpers/rmElement.js')

let btnToken = false
module.exports = function expose (cy) {
  const exposeBtn = document.getElementById('expose-button')

  // when button is pressed
  if (btnToken === false) {
    const graph = document.getElementById('window-id')

    cy.nodes().map(node => {
      let nodeInfo = ''
      const nodeData = node.data().asto
      Object.keys(nodeData).map(i => {
        // adds the keys of the object to the string
        if (nodeData.hasOwnProperty(i) === true) {
          nodeInfo = `${nodeInfo} • ${i}:`
        }
        // adds the values of the object to the string
        nodeInfo = `${nodeInfo} ${nodeData[i]}\n`
      })

      // create a container for each node
      const container = document.createElement('span')
      container.id = node.data().id
      container.innerHTML = `

${nodeInfo}

`

      graph.appendChild(container)
    })

    // show active expose with colored button
    exposeBtn.setAttribute('class', 'active-button')
    btnToken = true
  } else {
    // removes the exposed containers
    cy.nodes().map(node => {
      rmElement('window-id', node.data().id)
    })

    // restores the original button color
    exposeBtn.setAttribute('class', 'button-icon')
    btnToken = false
  }
}
<|endoftext|>


<commit_before>import styles from './Quotes.css';
import Time from 'app/components/Time';
import React, { Component } from 'react';
import { Link } from 'react-router';
import Dropdown from 'app/components/Dropdown';
import Icon from 'app/components/Icon';

type Props = {
  quote: Object,
  deleteQuote: () => void,
  approve: () => void,
  unapprove: () => void,
  actionGrant: Array<string>,
  setDisplayAdmin: () => void,
  displayAdmin: boolean
};

export default class Quote extends Component {
  props: Props;

  state = {
    deleting: false
  };

  render() {
    const {
      quote,
      deleteQuote,
      approve,
      unapprove,
      actionGrant,
      setDisplayAdmin,
      displayAdmin
    } = this.props;

    return (

            <Link to={`/quotes/${quote.id}`}>
              {quote.text}
            </Link>

              - {quote.source}

              {<Time time={quote.createdAt} wordsAgo />}

                <Link to={`/quotes/${quote.id}`}>
                  {' '}
                  {(quote.comments || []).length}
                </Link>

              {actionGrant &&
                actionGrant.includes('approve') &&

                  <Dropdown
                    show={displayAdmin}
                    toggle={() => setDisplayAdmin(quote.id)}
                    contentClassName={'adminDropdown2'}
                    triggerComponent={
                      <Icon
                        name="arrow-dropdown"
                        className={styles.dropdownIcon}
                      />
                    }
                  >
                    <Dropdown.List>
                      <Dropdown.ListItem>

                            quote.approved
                              ? unapprove(quote.id)
                              : approve(quote.id)}
                        >
                          {' '}{quote.approved
                            ? 'Fjern Godkjenning'
                            : 'Godkjenn'}

                      </Dropdown.ListItem>
                      <Dropdown.Divider />
                      {!this.state.deleting
                        ? <Dropdown.ListItem>
                             this.setState({ deleting: true })}
                            >
                              Slett

                          </Dropdown.ListItem>
                        : <Dropdown.ListItem>
                             deleteQuote(quote.id)}
                              style={{ fontWeight: 600 }}
                            >
                              Er du sikker?

                          </Dropdown.ListItem>}
                    </Dropdown.List>
                  </Dropdown>

}

    );
  }
}
<commit_msg>Fix comment count<commit_after>import styles from './Quotes.css';
import Time from 'app/components/Time';
import React, { Component } from 'react';
import { Link } from 'react-router';
import Dropdown from 'app/components/Dropdown';
import Icon from 'app/components/Icon';

type Props = {
  quote: Object,
  deleteQuote: () => void,
  approve: () => void,
  unapprove: () => void,
  actionGrant: Array<string>,
  setDisplayAdmin: () => void,
  displayAdmin: boolean
};

export default class Quote extends Component {
  props: Props;

  state = {
    deleting: false
  };

  render() {
    const {
      quote,
      deleteQuote,
      approve,
      unapprove,
      actionGrant,
      setDisplayAdmin,
      displayAdmin
    } = this.props;

    return (

            <Link to={`/quotes/${quote.id}`}>
              {quote.text}
            </Link>

              - {quote.source}

              {<Time time={quote.createdAt} wordsAgo />}

                <Link to={`/quotes/${quote.id}`}>
                  {' '}
                  {quote.comments ? quote.comments.length : quote.commentCount}
                </Link>

              {actionGrant &&
                actionGrant.includes('approve') &&

                  <Dropdown
                    show={displayAdmin}
                    toggle={() => setDisplayAdmin(quote.id)}
                    contentClassName={'adminDropdown2'}
                    triggerComponent={
                      <Icon
                        name="arrow-dropdown"
                        className={styles.dropdownIcon}
                      />
                    }
                  >
                    <Dropdown.List>
                      <Dropdown.ListItem>

                            quote.approved
                              ? unapprove(quote.id)
                              : approve(quote.id)}
                        >
                          {' '}{quote.approved
                            ? 'Fjern Godkjenning'
                            : 'Godkjenn'}

                      </Dropdown.ListItem>
                      <Dropdown.Divider />
                      {!this.state.deleting
                        ? <Dropdown.ListItem>
                             this.setState({ deleting: true })}
                            >
                              Slett

                          </Dropdown.ListItem>
                        : <Dropdown.ListItem>
                             deleteQuote(quote.id)}
                              style={{ fontWeight: 600 }}
                            >
                              Er du sikker?

                          </Dropdown.ListItem>}
                    </Dropdown.List>
                  </Dropdown>

}

    );
  }
}
<|endoftext|>


<commit_before>'use strict';

/**
* @ngdoc function
* @name dashboard.controller:loginCtrl
* @description
* # loginCtrl
* Controller of the dashboard
*/
angular.module('dashboard')
    .controller('loginCtrl', ['$log', '$http', '$state', 'ENV', 'CONST', '$timeout', 'Utils', 'StorageSrv', 'DialogUtils', function ($log, $http, $state, ENV, CONST, $timeout, Utils, StorageSrv, DialogUtils) {
        $log.log("loginCtrl.CONSTRUCT");

        var self = this;
        self.data = { selection: null, options: [] };
        self.meetings = [];
        self.loadingUsers = true;
        self.login = false;
        self.error = null;

        $log.debug("loginCtrl GET options start");
        $http({
            method: 'GET',
            url: ENV.AhjoApi_UserLogin
        }).then(function successCallback(response) {
            $log.debug("loginCtrl GET options success");
            $timeout(function () {
                // $log.debug("loginCtrl GET options find starting");
                var sel_resp = angular.element(response.data).find('option');

                var sel = [];
                // Collect only relevant properties
                angular.forEach(sel_resp, function (value) {
                    this.push(value);
                }, sel);

                self.data.options = sel;
                self.loadingUsers = false;
                $log.debug("loginCtrl GET options done, count=" + self.data.options.length);
            }, 0);
        }, function errorCallback(error) {
            $log.error(error);
            self.error = error;
            self.loadingUsers = false;
        }).finally(function () {
            $log.debug("loginCtrl GET options finally");
        });

        function loginRest() {
            var dlg = DialogUtils.showProgress('STR_LOGGING_IN', '' + self.data.selection);
            self.login = true;

            $http({
                method: 'POST',
                data: 'ADID=' + self.data.selection,
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                withCredentials: true,
                url: ENV.AhjoApi_UserLoginRest
            }).then(function (resp) {
                $log.error("loginCtrl.loginRest: done");
                if (!Utils.processAhjoError(resp)) { // LoginRest result: OK
                    // Setting TESTENV_USERID to store doesn't reflect the userid used by backend if in some error cases if response doesn't include a  Set-Cookie or similar issue.
                    // That might happen e.g. due to backend completing 200OK but rejecting bad arguments for the request.
                    // Result would be client thinking user was set successfully but in fact userid authenticated by backend would be used.
                    StorageSrv.setKey(CONST.KEY.TESTENV_USERID, self.data.selection);

                    $state.go(CONST.APPSTATE.HOME).finally(function () {
                        $log.debug("loginCtrl.loginRest: state.go finally");
                    });

                } else { // LoginRest result: RESET error
                }

            }, function (error) { // LoginRest result: HTTP error
                $log.error("loginCtrl.loginRest");
                Utils.processAhjoError(error);
            }).finally(function () {
                $log.debug("loginCtrl.loginRest: finally");
                self.data.selection = null;
                self.login = false;
                DialogUtils.close(dlg);
                dlg = null;
            });
        }

        self.selectUser = function () {
            $log.debug('loginCtrl.selectUser: ' + self.data.selection);
            loginRest();
        };

        self.selectOwn = function () {
            $log.debug('loginCtrl.selectOwn');
            var dlg = DialogUtils.showProgress('STR_LOGGING_IN');
            $state.go(CONST.APPSTATE.HOME).finally(function () {
                $log.debug("loginCtrl.selectOwn: state.go finally");
                DialogUtils.close(dlg);
            });
        };

    }]);
<commit_msg>Remove progress dialog for login on own userid<commit_after>'use strict';

/**
* @ngdoc function
* @name dashboard.controller:loginCtrl
* @description
* # loginCtrl
* Controller of the dashboard
*/
angular.module('dashboard')
    .controller('loginCtrl', ['$log', '$http', '$state', 'ENV', 'CONST', '$timeout', 'Utils', 'StorageSrv', 'DialogUtils', function ($log, $http, $state, ENV, CONST, $timeout, Utils, StorageSrv, DialogUtils) {
        $log.log("loginCtrl.CONSTRUCT");

        var self = this;
        self.data = { selection: null, options: [] };
        self.meetings = [];
        self.loadingUsers = true;
        self.login = false;
        self.error = null;

        $log.debug("loginCtrl GET options start");
        $http({
            method: 'GET',
            url: ENV.AhjoApi_UserLogin
        }).then(function successCallback(response) {
            $log.debug("loginCtrl GET options success");
            $timeout(function () {
                // $log.debug("loginCtrl GET options find starting");
                var sel_resp = angular.element(response.data).find('option');

                var sel = [];
                // Collect only relevant properties
                angular.forEach(sel_resp, function (value) {
                    this.push(value);
                }, sel);

                self.data.options = sel;
                self.loadingUsers = false;
                $log.debug("loginCtrl GET options done, count=" + self.data.options.length);
            }, 0);
        }, function errorCallback(error) {
            $log.error(error);
            self.error = error;
            self.loadingUsers = false;
        }).finally(function () {
            $log.debug("loginCtrl GET options finally");
        });

        function loginRest() {
            var dlg = DialogUtils.showProgress('STR_LOGGING_IN', '' + self.data.selection);
            self.login = true;

            $http({
                method: 'POST',
                data: 'ADID=' + self.data.selection,
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                withCredentials: true,
                url: ENV.AhjoApi_UserLoginRest
            }).then(function (resp) {
                $log.error("loginCtrl.loginRest: done");
                if (!Utils.processAhjoError(resp)) { // LoginRest result: OK
                    // Setting TESTENV_USERID to store doesn't reflect the userid used by backend if in some error cases if response doesn't include a  Set-Cookie or similar issue.
                    // That might happen e.g. due to backend completing 200OK but rejecting bad arguments for the request.
                    // Result would be client thinking user was set successfully but in fact userid authenticated by backend would be used.
                    StorageSrv.setKey(CONST.KEY.TESTENV_USERID, self.data.selection);

                    $state.go(CONST.APPSTATE.HOME).finally(function () {
                        $log.debug("loginCtrl.loginRest: state.go finally");
                    });

                } else { // LoginRest result: RESET error
                }

            }, function (error) { // LoginRest result: HTTP error
                $log.error("loginCtrl.loginRest");
                Utils.processAhjoError(error);
            }).finally(function () {
                $log.debug("loginCtrl.loginRest: finally");
                self.data.selection = null;
                self.login = false;
                DialogUtils.close(dlg);
                dlg = null;
            });
        }

        self.selectUser = function () {
            $log.debug('loginCtrl.selectUser: ' + self.data.selection);
            loginRest();
        };

        self.selectOwn = function () {
            $log.debug('loginCtrl.selectOwn');
            $state.go(CONST.APPSTATE.HOME).finally(function () {
                $log.debug("loginCtrl.selectOwn: state.go finally");
            });
        };

    }]);
<|endoftext|>