<commit_before>    function multiplySumArc(maskCanvas, data, dims, center_x_coord, center_y_coord, r1_coord, r2_coord) {
         //var maskCanvas = document.getElementById('mask');
         var dxpos = (dims.xmax - dims.xmin) / (dims.xdim);
         var dypos = (dims.ymax - dims.ymin) / (dims.ydim);
         var center_x = (center_x_coord - dims.xmin) / dxpos;
         var center_y = (dims.ymax - center_y_coord) / dypos;
         var r1 = r1_coord / dxpos; // square pixels only!
         var r2 = r2_coord / dxpos; // square pixels only!
         var PHI_STEP = (window.PHI_STEP == undefined) ? 2.0 : window.PHI_STEP;
         var ch = maskCanvas.height;
         var cw = maskCanvas.width;
         var maskCtx = maskCanvas.getContext('2d');
         var angle_start = radians(-10.5);
         var stepsize = radians(PHI_STEP);
         var steps = Math.PI * 2.0 / stepsize + 1;
         var width = Math.abs(r2 - r1);
         var r = (r1 + r2) / 2.0;
         var angle=angle_start, maskData, sum, normalize, data;
         maskCtx.fillStyle='#000000'; // for erasing
         maskCtx.strokeStyle = '#ffffff'; // for drawing
         maskCtx.lineWidth = width;
         var angle_list=[], sum_list=[], normalize_list=[], xy_list=[];
         var max_x, max_y, min_x, min_y, x1, x2, y1, y2, dx, dy;
         var buffer_pixels = 3; // border around selection rectangle
         maskCtx.fillRect(0,0,cw,ch);
         for (var s=0; s<steps; s++) {
            maskCtx.beginPath();
            maskCtx.arc(center_x, center_y, r, -angle, -(angle + stepsize), true);
            maskCtx.stroke();
            // assuming small steps: linear!
            x1 = center_x + (Math.cos(angle) * r1);
            y1 = center_y - (Math.sin(angle) * r1); // plus is down
            x2 = center_x + (Math.cos(angle + stepsize) * r1);
            y2 = center_y - (Math.sin(angle + stepsize) * r1);
            x3 = center_x + (Math.cos(angle) * r2);
            y3 = center_y - (Math.sin(angle) * r2); // plus is down
            x4 = center_x + (Math.cos(angle + stepsize) * r2);
            y4 = center_y - (Math.sin(angle + stepsize) * r2);
            x1 = Math.round(x1);
            x2 = Math.round(x2);
            y1 = Math.round(y1);
            y2 = Math.round(y2);
            x3 = Math.round(x3);
            x4 = Math.round(x4);
            y3 = Math.round(y3);
            y4 = Math.round(y4);
            max_x = Math.min(cw, Math.max(x1, x2, x3, x4) + buffer_pixels);
            min_x = Math.max(0, Math.min(x1, x2, x3, x4) - buffer_pixels);
            max_y = Math.min(ch, Math.max(y1, y2, y3, y4) + buffer_pixels);
            min_y = Math.max(0, Math.min(y1, y2, y3, y4) - buffer_pixels);
            dx = max_x - min_x;
            dy = max_y - min_y;
            //console.log(min_x, max_x, min_y, max_y, dx, dy);

            sum = 0;
            normalize = 0;

            if (dx > 0 && dy > 0) {
                var maskData = maskCtx.getImageData(min_x,min_y,dx,dy).data;
                //data = imgCtx.getImageData(min_x,min_y,dx,dy).data;

                for (var i=0; i<dx; i++) {
                    for (var j=0; j<dy; j++) {
                        var mi = (j*dx + i) * 4;
                        var n = maskData[mi];
                        normalize += n;
                        //sum += maskData[mi] * data[min_y + j][min_x + i];
                        sum += n * data[ch - min_y - j -1][min_x + i];
                    }
                }
            }
            angle_list[s] = angle;
            sum_list[s] = sum;
            normalize_list[s] = normalize;
            xy_list[s] = [degrees(angle), (normalize == 0)? NaN : sum/normalize];
            angle += stepsize;
            maskCtx.fillRect(min_x,min_y,dx,dy);
         }
         return {xy: xy_list, angle: angle_list, sum: sum_list, normalize: normalize_list}
    }

    function multiplySumRadial(maskCanvas, data, dims, center_x_coord, center_y_coord) {
         var dxpos = (dims.xmax - dims.xmin) / (dims.xdim);
         var dypos = (dims.ymax - dims.ymin) / (dims.ydim);
         var center_x = (center_x_coord - dims.xmin) / dxpos;
         //var center_y = (center_y_coord - dims.ymin) / dypos;
         var center_y = (dims.ymax - center_y_coord) / dypos;

         var ch = maskCanvas.height;
         var cw = maskCanvas.width;
         var maskCtx = maskCanvas.getContext('2d');
         var r_min = 1;
         var r_max = Math.sqrt(Math.max(
            Math.pow((center_x - 0), 2) + Math.pow((center_y - 0), 2),
            Math.pow((center_x - 0), 2) + Math.pow((center_y - dims.ymax), 2),
            Math.pow((center_x - dims.xmax), 2) + Math.pow((center_y - dims.ymax), 2),
            Math.pow((center_x - dims.xmax), 2) + Math.pow((center_y - 0), 2)
         ));
         var stepsize = 1;
         var steps = (r_max - r_min)/ stepsize + 1;
         var width = 1.0; // integration step for radial
         maskCtx.fillStyle='#000000'; // for erasing
         maskCtx.strokeStyle = '#ffffff'; // for drawing
         maskCtx.lineWidth = width;
         var radius_list=[], sum_list=[], normalize_list=[], xy_list=[];
         var r, max_x, max_y, min_x, min_y, x1, x2, y1, y2, dx, dy;
         var tau = Math.PI * 2.0;
         var buffer_pixels = 3; // border around selection rectangle
         maskCtx.fillRect(0,0,cw,ch);
         for (var s=0; s<steps; s++) {
            maskCtx.beginPath();
            r = r_min + s*stepsize;
            maskCtx.arc(center_x, center_y, r, 0, tau);
            maskCtx.stroke();
            // assuming small steps: linear!
            x1 = center_x + r;
            y1 = center_y - r; // plus is down
            x2 = center_x - r;
            y2 = center_y + r;
            x1 = Math.round(x1);
            x2 = Math.round(x2);
            y1 = Math.round(y1);
            y2 = Math.round(y2);
            max_x = Math.min(cw, Math.max(x1, x2) + buffer_pixels);
            min_x = Math.max(0, Math.min(x1, x2) - buffer_pixels);
            max_y = Math.min(ch, Math.max(y1, y2) + buffer_pixels);
            min_y = Math.max(0, Math.min(y1, y2) - buffer_pixels);
            dx = max_x - min_x;
            dy = max_y - min_y;
            //console.log(min_x, max_x, min_y, max_y, dx, dy);

            sum = 0;
            normalize = 0;

            if (dx > 0 && dy > 0) {
                var maskData = maskCtx.getImageData(min_x,min_y,dx,dy).data;
                //data = imgCtx.getImageData(min_x,min_y,dx,dy).data;

                for (var i=0; i<dx; i++) {
                    for (var j=0; j<dy; j++) {
                        var mi = (j*dx + i) * 4;
                        var n = maskData[mi];
                        normalize += n;
                        //sum += maskData[mi] * data[min_y + j][min_x + i];
                        sum += n * data[ch - min_y - j - 1][min_x + i];
                    }
                }
            }
            radius_list[s] = r;
            sum_list[s] = sum;
            normalize_list[s] = normalize;
            xy_list[s] = [r, (normalize == 0)? NaN : sum/normalize];
            maskCtx.fillRect(min_x,min_y,dx,dy);
         }
         return {xy: xy_list, radius: radius_list, sum: sum_list, normalize: normalize_list}
    }
<commit_msg>fix normalization sum so 1.0 represents whole pixel (instead of 255.0)<commit_after>    function multiplySumArc(maskCanvas, data, dims, center_x_coord, center_y_coord, r1_coord, r2_coord) {
         //var maskCanvas = document.getElementById('mask');
         var dxpos = (dims.xmax - dims.xmin) / (dims.xdim);
         var dypos = (dims.ymax - dims.ymin) / (dims.ydim);
         var center_x = (center_x_coord - dims.xmin) / dxpos;
         var center_y = (dims.ymax - center_y_coord) / dypos;
         var r1 = r1_coord / dxpos; // square pixels only!
         var r2 = r2_coord / dxpos; // square pixels only!
         var PHI_STEP = (window.PHI_STEP == undefined) ? 2.0 : window.PHI_STEP;
         var ch = maskCanvas.height;
         var cw = maskCanvas.width;
         var maskCtx = maskCanvas.getContext('2d');
         var angle_start = radians(-10.5);
         var stepsize = radians(PHI_STEP);
         var steps = Math.PI * 2.0 / stepsize + 1;
         var width = Math.abs(r2 - r1);
         var r = (r1 + r2) / 2.0;
         var angle=angle_start, maskData, sum, normalize, data;
         maskCtx.fillStyle='#000000'; // for erasing
         maskCtx.strokeStyle = '#ffffff'; // for drawing
         maskCtx.lineWidth = width;
         var angle_list=[], sum_list=[], normalize_list=[], xy_list=[];
         var max_x, max_y, min_x, min_y, x1, x2, y1, y2, dx, dy;
         var buffer_pixels = 3; // border around selection rectangle
         maskCtx.fillRect(0,0,cw,ch);
         for (var s=0; s<steps; s++) {
            maskCtx.beginPath();
            maskCtx.arc(center_x, center_y, r, -angle, -(angle + stepsize), true);
            maskCtx.stroke();
            // assuming small steps: linear!
            x1 = center_x + (Math.cos(angle) * r1);
            y1 = center_y - (Math.sin(angle) * r1); // plus is down
            x2 = center_x + (Math.cos(angle + stepsize) * r1);
            y2 = center_y - (Math.sin(angle + stepsize) * r1);
            x3 = center_x + (Math.cos(angle) * r2);
            y3 = center_y - (Math.sin(angle) * r2); // plus is down
            x4 = center_x + (Math.cos(angle + stepsize) * r2);
            y4 = center_y - (Math.sin(angle + stepsize) * r2);
            x1 = Math.round(x1);
            x2 = Math.round(x2);
            y1 = Math.round(y1);
            y2 = Math.round(y2);
            x3 = Math.round(x3);
            x4 = Math.round(x4);
            y3 = Math.round(y3);
            y4 = Math.round(y4);
            max_x = Math.min(cw, Math.max(x1, x2, x3, x4) + buffer_pixels);
            min_x = Math.max(0, Math.min(x1, x2, x3, x4) - buffer_pixels);
            max_y = Math.min(ch, Math.max(y1, y2, y3, y4) + buffer_pixels);
            min_y = Math.max(0, Math.min(y1, y2, y3, y4) - buffer_pixels);
            dx = max_x - min_x;
            dy = max_y - min_y;
            //console.log(min_x, max_x, min_y, max_y, dx, dy);

            sum = 0;
            normalize = 0;

            if (dx > 0 && dy > 0) {
                var maskData = maskCtx.getImageData(min_x,min_y,dx,dy).data;
                //data = imgCtx.getImageData(min_x,min_y,dx,dy).data;

                for (var i=0; i<dx; i++) {
                    for (var j=0; j<dy; j++) {
                        var mi = (j*dx + i) * 4;
                        var n = maskData[mi] / 255.0; // put it back on scale [0..1]
                        normalize += n;
                        //sum += maskData[mi] * data[min_y + j][min_x + i];
                        sum += n * data[ch - min_y - j -1][min_x + i];
                    }
                }
            }
            angle_list[s] = angle;
            sum_list[s] = sum;
            normalize_list[s] = normalize;
            xy_list[s] = [degrees(angle), (normalize == 0)? NaN : sum/normalize];
            angle += stepsize;
            maskCtx.fillRect(min_x,min_y,dx,dy);
         }
         return {xy: xy_list, angle: angle_list, sum: sum_list, normalize: normalize_list}
    }

    function multiplySumRadial(maskCanvas, data, dims, center_x_coord, center_y_coord) {
         var dxpos = (dims.xmax - dims.xmin) / (dims.xdim);
         var dypos = (dims.ymax - dims.ymin) / (dims.ydim);
         var center_x = (center_x_coord - dims.xmin) / dxpos;
         //var center_y = (center_y_coord - dims.ymin) / dypos;
         var center_y = (dims.ymax - center_y_coord) / dypos;

         var ch = maskCanvas.height;
         var cw = maskCanvas.width;
         var maskCtx = maskCanvas.getContext('2d');
         var r_min = 1;
         var r_max = Math.sqrt(Math.max(
            Math.pow((center_x - 0), 2) + Math.pow((center_y - 0), 2),
            Math.pow((center_x - 0), 2) + Math.pow((center_y - dims.ymax), 2),
            Math.pow((center_x - dims.xmax), 2) + Math.pow((center_y - dims.ymax), 2),
            Math.pow((center_x - dims.xmax), 2) + Math.pow((center_y - 0), 2)
         ));
         var stepsize = 1;
         var steps = (r_max - r_min)/ stepsize + 1;
         var width = 1.0; // integration step for radial
         maskCtx.fillStyle='#000000'; // for erasing
         maskCtx.strokeStyle = '#ffffff'; // for drawing
         maskCtx.lineWidth = width;
         var radius_list=[], sum_list=[], normalize_list=[], xy_list=[];
         var r, max_x, max_y, min_x, min_y, x1, x2, y1, y2, dx, dy;
         var tau = Math.PI * 2.0;
         var buffer_pixels = 3; // border around selection rectangle
         maskCtx.fillRect(0,0,cw,ch);
         for (var s=0; s<steps; s++) {
            maskCtx.beginPath();
            r = r_min + s*stepsize;
            maskCtx.arc(center_x, center_y, r, 0, tau);
            maskCtx.stroke();
            // assuming small steps: linear!
            x1 = center_x + r;
            y1 = center_y - r; // plus is down
            x2 = center_x - r;
            y2 = center_y + r;
            x1 = Math.round(x1);
            x2 = Math.round(x2);
            y1 = Math.round(y1);
            y2 = Math.round(y2);
            max_x = Math.min(cw, Math.max(x1, x2) + buffer_pixels);
            min_x = Math.max(0, Math.min(x1, x2) - buffer_pixels);
            max_y = Math.min(ch, Math.max(y1, y2) + buffer_pixels);
            min_y = Math.max(0, Math.min(y1, y2) - buffer_pixels);
            dx = max_x - min_x;
            dy = max_y - min_y;
            //console.log(min_x, max_x, min_y, max_y, dx, dy);

            sum = 0;
            normalize = 0;

            if (dx > 0 && dy > 0) {
                var maskData = maskCtx.getImageData(min_x,min_y,dx,dy).data;
                //data = imgCtx.getImageData(min_x,min_y,dx,dy).data;

                for (var i=0; i<dx; i++) {
                    for (var j=0; j<dy; j++) {
                        var mi = (j*dx + i) * 4;
                        var n = maskData[mi] / 255.0; // put it back on [0..1] scale
                        normalize += n;
                        //sum += maskData[mi] * data[min_y + j][min_x + i];
                        sum += n * data[ch - min_y - j - 1][min_x + i];
                    }
                }
            }
            radius_list[s] = r;
            sum_list[s] = sum;
            normalize_list[s] = normalize;
            xy_list[s] = [r, (normalize == 0)? NaN : sum/normalize];
            maskCtx.fillRect(min_x,min_y,dx,dy);
         }
         return {xy: xy_list, radius: radius_list, sum: sum_list, normalize: normalize_list}
    }
<|endoftext|>


<commit_before>NGApp.config(['$routeProvider', function($routeProvider) {
	$routeProvider
		.when('/support', {
			action: 'support',
			controller: 'SupportCtrl',
			templateUrl: 'assets/view/support.html',
			title: 'Support',
			reloadOnSearch: false
		})
		.when('/chat', {
			action: 'chat',
			controller: 'ChatCtrl',
			templateUrl: 'assets/view/chat.html',
			title: 'Chat'
		})
		.when('/chat/:room', {
			action: 'chat',
			controller: 'ChatCtrl',
			templateUrl: 'assets/view/chat.html',
			title: 'Chat'
		})
		.when('/support/phone', {
			action: 'support',
			controller: 'SupportPhoneCtrl',
			templateUrl: 'assets/view/support-phone.html',
			title: 'Support',
			reloadOnSearch: false
		});
}]);

NGApp.controller('ChatCtrl', function($scope, $rootScope, $routeParams, SocketService, AccountService) {
	$scope.room = $routeParams.room || 'lobby';

	SocketService.listen('chat.' + $scope.room, $scope)
		.on('message', function(d) {
			console.log(d);
		});
	/*
	$scope.send = function() {
		//SocketService.socket.emit('chat.' + $scope.room, 'message');
		SocketService.socket.emit('event.message', {
			url: 'api/'
		});
	};
	*/
});

NGApp.controller('SideTicketsCtrl', function($scope, $rootScope, $location, TicketService, TicketViewService, AccountService) {

	$scope.params = { status: 'open' };

	var getTickets = function() {
		if (!AccountService || !AccountService.user || !AccountService.user.permissions) {
			return;
		}
		TicketService.shortlist( $scope.params, function(tickets) {
			TicketViewService.scope.tickets = tickets.results;
		});
	};

	if (!TicketViewService.scope.tickets) {
		getTickets();
	}

	$scope.loadTicket = function( id_support ){
		TicketViewService.setViewTicket( id_support );
	}

	$rootScope.$watch('supportMessages', function(newValue, oldValue) {
		if (!newValue) {
			return;
		}
		if (!oldValue || newValue.count != oldValue.count || newValue.timestamp != oldValue.timestamp ) {
			getTickets();
		}
	}, true);
});

NGApp.controller( 'SideTicketCtrl', function($scope, $rootScope, $routeParams, $timeout, TicketService, TicketViewService, SocketService, MainNavigationService ) {

	var id_support = null;

	if (typeof TicketViewService.scope.viewTicket == 'string') {
		id_support = TicketViewService.scope.viewTicket;
	} else {
		id_support = TicketViewService.scope.viewTicket.id;
	}

	TicketViewService.sideInfo.setTicket( id_support );

	var loadData = function(){
		if( TicketViewService.sideInfo.load() ){
			$scope.isLoading = true;
		}
	}

	// $scope.$watchCollection( 'ticket', function( newValue, oldValue ) {
	// 	if( newValue && newValue.total && !$rootScope.supportToggled ){
	// 		$timeout( function(){
	// 			$rootScope.supportToggled = true;
	// 		}, 300 );
	// 	}
	// } );

	$scope.isLoading = false;

	$scope.loadMoreMessages = function(){
		loadData()
	}

	$rootScope.$on( 'triggerTicketInfoUpdated', function(e, data) {

		$rootScope.$safeApply( function(){
			console.log('$scope.ticket',$scope.ticket);
			console.log('data',data);
			if( $scope.ticket.id_support != data.id_support ){
				$scope.ticket = data;
			} else {
				if( !angular.equals( $scope.ticket.messages, data.messages ) ){
					// if( !$scope.ticket.messages || ( $scope.ticket.messages && $scope.ticket.messages.length < data.messages.length ) ){
					$scope.ticket.messages = data.messages;
					// }

					console.log('!=!=!=!=!=');
				} else {
					console.log('=====');
				}

				if( $scope.ticket.total != data.total ){
					$timeout( function(){
						$scope.ticket.has_more = data.has_more;
						$scope.ticket.loaded = data.loaded;
						$scope.ticket.page = data.page;
						$scope.ticket.total = data.total;
						console.log('update everything else');
					 }, 300 );
				}
			}
		} );

		$scope.isLoading = false;
		if( !$rootScope.supportToggled ){
			$timeout( function(){ $rootScope.supportToggled = true; }, 300 );
		}
	} );

	$rootScope.$on( 'loadMoreMessages', function(e, data) {
		$scope.loadMoreMessages();
	} );

	var socketStuff = function(){
		SocketService.listen('ticket.' + id_support, TicketViewService.scope ).on('message', function(d) {
			if( d.guid ){
				for ( var x in TicketViewService.sideInfo.data.messages ) {
					if ( TicketViewService.sideInfo.data.messages[x].guid == d.guid ) {
						if( TicketViewService.sideInfo.data.messages[x].sending ){
							TicketViewService.sideInfo.data.messages[x] = d;
							console.log('updated status');
						}
						console.log('message already added!');
						return;
					}
				}
			}
			TicketViewService.sideInfo.add_message( d );
		});
	}

	$rootScope.$on( 'triggerViewTicket', function(e, ticket) {
		if( ticket.id_support != TicketViewService.sideInfo.id_support ){
			TicketViewService.sideInfo.setTicket( 0 );
			TicketViewService.sideInfo.setTicket( ticket.id_support );
			loadData();
			socketStuff();
		}
	} );

	$scope.send = TicketViewService.send;
	loadData();
	socketStuff();

} );

NGApp.controller('SideSupportCtrl', function($scope, $rootScope, TicketViewService) {
	TicketViewService.scope = $scope;
	$scope.setViewTicket = TicketViewService.setViewTicket;
});

NGApp.controller('SideSupportPexCardCtrl', function( $scope, StaffPayInfoService, PexCardService ) {

	$scope.add_funds = function(){
		if( $scope.ticket && $scope.ticket.pexcard && $scope.ticket.pexcard.id_pexcard ){
			if( $scope.form.$invalid ){
				App.alert( 'Please fill in all required fields' );
				$scope.submitted = true;
				return;
			}
			$scope.pexcard.id_pexcard = $scope.ticket.pexcard.id_pexcard;
			$scope.isAdding = true;
			PexCardService.add_funds( $scope.pexcard, function( data ){
				if( data.error ){
					App.alert( data.error);
					$scope.isAdding = false;
					return;
				} else {
					$scope.isAdding = false;
					$scope.flash.setMessage( 'Funds Added!' );
					$scope.pexcard = {};
					$scope.isLoadingBalance = true;
					setTimeout( function(){ $scope.current_balanced(); }, 3000 );
				}
			} );
		} else {
			App.alert( 'Oops, it seems the driver doesn\'t have a PexCard!' );
		}
	}

	$scope.current_balanced = function(){
		if( $scope.ticket && $scope.ticket.pexcard && $scope.ticket.pexcard.card_serial ){

			$scope.isLoadingBalance = true;

			PexCardService.pex_id( $scope.ticket.pexcard.card_serial,
				function( json ){
					$scope.isLoadingBalance = false;
					if( json.id ){
						$scope.card = json;
					} else {
						$scope.flash.setMessage( json.error, 'error' );
					}
				}
			);
		} else {
			App.alert( 'Oops, it seems the driver doesn\'t have a PexCard!' );
		}
	}

} );

NGApp.controller('SupportPhoneCtrl', function( $scope, $rootScope, StaffService, CallService, MainNavigationService, TwilioService) {

	$scope.call = { staff : '', to : 'customer', _to: CallService.call_to() };
	$scope.sms = { staff : '', to : 'customer', _to: CallService.call_to() };

	$scope.$watch( 'call.staff', function( newValue, oldValue, scope ) {
		$scope.call.phone = newValue.phone;
	}	);

	$scope.$watch( 'sms.staff', function( newValue, oldValue, scope ) {
		$scope.sms.phone = newValue.phone;
		$scope.sms.name = newValue.name;
	}	);

	StaffService.phones( function( response ){
		$scope.staff = response;
	} );

	$scope.formCallSending = false;
	$scope.formSMSSending = false;

	$scope.reset = function(){
		$scope.call.phone = '';
		$scope.sms.phone = '';
		$scope.sms.message = '';
	}

	$scope.sms.send = function(){

		if( $scope.formSMS.$invalid ){
			$scope.formSMSSubmitted = true;
			return;
		}

		$scope.formSMSSending = true;
		CallService.send_sms( $scope.sms, function( json ){
			$scope.formSMSSending = false;
			if( json.success ){
				MainNavigationService.link( '/ticket/' + json.success);
				if( $scope.complete ){
					$scope.complete();
				}
				$scope.reset();
			} else {
				App.alert( json.error );
			}
		} );
	}

	$scope.call.make = function(){
		if( $scope.formCall.$invalid ){
			$scope.formCallSubmitted = true;
			return;
		}
		$scope.formCallSending = true;
		CallService.make_call( $scope.call, function( json ){
			$scope.formCallSending = false;
			if( json.success ){
				App.alert( json.success );
				$scope.reset();
			} else {
				App.alert( json.error );
			}
		} );
	}

	$scope.call.voip = function() {
		TwilioService.call($scope.call.phone);
		App.dialog.close();
	};

	// Reset stuff when calling from modal
	$rootScope.$on('callText', function(e, num) {
		$scope.reset();
		$scope.call.phone = num;
		$scope.sms.phone = num;
	} );

} );

NGApp.controller('SupportCtrl', function($scope, $rootScope, $timeout, TicketService, TicketViewService, CallService) {

	$scope.ticketparams = {
		status: 'open'
	};

	$scope.callparams = {
		status: ['in-progress','ringing'],
		limit: 5,
		today: true
	};

	$scope.closeTicket = function( id_support ){
		TicketService.openClose( id_support, function() { update(); } );
	}

	$rootScope.$watch('supportMessages', function(newValue, oldValue) {
		if (!newValue) {
			return;
		}
		if (!oldValue || newValue.count != oldValue.count || newValue.timestamp != oldValue.timestamp ) {
			update();
		}
	}, true);

	var update = function(){
		TicketService.list($scope.ticketparams, function(d) {
			$scope.lotsoftickets = d.results;
			TicketViewService.scope.tickets = d.results;
		});
	}

	CallService.list($scope.callparams, function(d) {
		$scope.calls = d.results;
	});

	update();
});
<commit_msg>partial #6135<commit_after>NGApp.config(['$routeProvider', function($routeProvider) {
	$routeProvider
		.when('/support', {
			action: 'support',
			controller: 'SupportCtrl',
			templateUrl: 'assets/view/support.html',
			title: 'Support',
			reloadOnSearch: false
		})
		.when('/chat', {
			action: 'chat',
			controller: 'ChatCtrl',
			templateUrl: 'assets/view/chat.html',
			title: 'Chat'
		})
		.when('/chat/:room', {
			action: 'chat',
			controller: 'ChatCtrl',
			templateUrl: 'assets/view/chat.html',
			title: 'Chat'
		})
		.when('/support/phone', {
			action: 'support',
			controller: 'SupportPhoneCtrl',
			templateUrl: 'assets/view/support-phone.html',
			title: 'Support',
			reloadOnSearch: false
		});
}]);

NGApp.controller('ChatCtrl', function($scope, $rootScope, $routeParams, SocketService, AccountService) {
	$scope.room = $routeParams.room || 'lobby';

	SocketService.listen('chat.' + $scope.room, $scope)
		.on('message', function(d) {
			console.log(d);
		});
	/*
	$scope.send = function() {
		//SocketService.socket.emit('chat.' + $scope.room, 'message');
		SocketService.socket.emit('event.message', {
			url: 'api/'
		});
	};
	*/
});

NGApp.controller('SideTicketsCtrl', function($scope, $rootScope, $location, TicketService, TicketViewService, AccountService) {

	$scope.params = { status: 'open' };

	var getTickets = function() {
		if (!AccountService || !AccountService.user || !AccountService.user.permissions) {
			return;
		}
		TicketService.shortlist( $scope.params, function(tickets) {
			TicketViewService.scope.tickets = tickets.results;
		});
	};

	if (!TicketViewService.scope.tickets) {
		getTickets();
	}

	$scope.loadTicket = function( id_support ){
		TicketViewService.setViewTicket( id_support );
	}

	$rootScope.$watch('supportMessages', function(newValue, oldValue) {
		if (!newValue) {
			return;
		}
		if (!oldValue || newValue.count != oldValue.count || newValue.timestamp != oldValue.timestamp ) {
			getTickets();
		}
	}, true);
});

NGApp.controller( 'SideTicketCtrl', function($scope, $rootScope, $routeParams, $timeout, TicketService, TicketViewService, SocketService, MainNavigationService ) {

	var id_support = null;

	if (typeof TicketViewService.scope.viewTicket == 'string') {
		id_support = TicketViewService.scope.viewTicket;
	} else {
		id_support = TicketViewService.scope.viewTicket.id;
	}

	TicketViewService.sideInfo.setTicket( id_support );

	var loadData = function(){
		if( TicketViewService.sideInfo.load() ){
			$scope.isLoading = true;
		}
	}

	// $scope.$watchCollection( 'ticket', function( newValue, oldValue ) {
	// 	if( newValue && newValue.total && !$rootScope.supportToggled ){
	// 		$timeout( function(){
	// 			$rootScope.supportToggled = true;
	// 		}, 300 );
	// 	}
	// } );

	$scope.isLoading = false;

	$scope.loadMoreMessages = function(){
		loadData()
	}

	$rootScope.$on( 'triggerTicketInfoUpdated', function(e, data) {

		$rootScope.$safeApply( function(){
			console.log('$scope.ticket',$scope.ticket);
			console.log('data',data);
			if( $scope.ticket.id_support != data.id_support ){
				$scope.ticket = data;
			} else {
				if( !angular.equals( $scope.ticket.messages, data.messages ) ){
					if( data.messages.length > 0 ){
						$scope.ticket.messages = data.messages;
					}
					// if( !$scope.ticket.messages || ( $scope.ticket.messages && $scope.ticket.messages.length < data.messages.length ) ){

					// }

					console.log('!=!=!=!=!=');
				} else {
					console.log('=====');
				}

				if( $scope.ticket.total != data.total ){
					$timeout( function(){
						$scope.ticket.has_more = data.has_more;
						$scope.ticket.loaded = data.loaded;
						$scope.ticket.page = data.page;
						$scope.ticket.total = data.total;
						console.log('update everything else');
					 }, 300 );
				}
			}
		} );

		$scope.isLoading = false;
		if( !$rootScope.supportToggled ){
			$timeout( function(){ $rootScope.supportToggled = true; }, 300 );
		}
	} );

	$rootScope.$on( 'loadMoreMessages', function(e, data) {
		$scope.loadMoreMessages();
	} );

	var socketStuff = function(){
		SocketService.listen('ticket.' + id_support, TicketViewService.scope ).on('message', function(d) {
			if( d.guid ){
				for ( var x in TicketViewService.sideInfo.data.messages ) {
					if ( TicketViewService.sideInfo.data.messages[x].guid == d.guid ) {
						if( TicketViewService.sideInfo.data.messages[x].sending ){
							TicketViewService.sideInfo.data.messages[x] = d;
							console.log('updated status');
						}
						console.log('message already added!');
						return;
					}
				}
			}
			TicketViewService.sideInfo.add_message( d );
		});
	}

	$rootScope.$on( 'triggerViewTicket', function(e, ticket) {
		if( ticket.id_support != TicketViewService.sideInfo.id_support ){
			TicketViewService.sideInfo.setTicket( 0 );
			TicketViewService.sideInfo.setTicket( ticket.id_support );
			loadData();
			socketStuff();
		}
	} );

	$scope.send = TicketViewService.send;
	loadData();
	socketStuff();

} );

NGApp.controller('SideSupportCtrl', function($scope, $rootScope, TicketViewService) {
	TicketViewService.scope = $scope;
	$scope.setViewTicket = TicketViewService.setViewTicket;
});

NGApp.controller('SideSupportPexCardCtrl', function( $scope, StaffPayInfoService, PexCardService ) {

	$scope.add_funds = function(){
		if( $scope.ticket && $scope.ticket.pexcard && $scope.ticket.pexcard.id_pexcard ){
			if( $scope.form.$invalid ){
				App.alert( 'Please fill in all required fields' );
				$scope.submitted = true;
				return;
			}
			$scope.pexcard.id_pexcard = $scope.ticket.pexcard.id_pexcard;
			$scope.isAdding = true;
			PexCardService.add_funds( $scope.pexcard, function( data ){
				if( data.error ){
					App.alert( data.error);
					$scope.isAdding = false;
					return;
				} else {
					$scope.isAdding = false;
					$scope.flash.setMessage( 'Funds Added!' );
					$scope.pexcard = {};
					$scope.isLoadingBalance = true;
					setTimeout( function(){ $scope.current_balanced(); }, 3000 );
				}
			} );
		} else {
			App.alert( 'Oops, it seems the driver doesn\'t have a PexCard!' );
		}
	}

	$scope.current_balanced = function(){
		if( $scope.ticket && $scope.ticket.pexcard && $scope.ticket.pexcard.card_serial ){

			$scope.isLoadingBalance = true;

			PexCardService.pex_id( $scope.ticket.pexcard.card_serial,
				function( json ){
					$scope.isLoadingBalance = false;
					if( json.id ){
						$scope.card = json;
					} else {
						$scope.flash.setMessage( json.error, 'error' );
					}
				}
			);
		} else {
			App.alert( 'Oops, it seems the driver doesn\'t have a PexCard!' );
		}
	}

} );

NGApp.controller('SupportPhoneCtrl', function( $scope, $rootScope, StaffService, CallService, MainNavigationService, TwilioService) {

	$scope.call = { staff : '', to : 'customer', _to: CallService.call_to() };
	$scope.sms = { staff : '', to : 'customer', _to: CallService.call_to() };

	$scope.$watch( 'call.staff', function( newValue, oldValue, scope ) {
		$scope.call.phone = newValue.phone;
	}	);

	$scope.$watch( 'sms.staff', function( newValue, oldValue, scope ) {
		$scope.sms.phone = newValue.phone;
		$scope.sms.name = newValue.name;
	}	);

	StaffService.phones( function( response ){
		$scope.staff = response;
	} );

	$scope.formCallSending = false;
	$scope.formSMSSending = false;

	$scope.reset = function(){
		$scope.call.phone = '';
		$scope.sms.phone = '';
		$scope.sms.message = '';
	}

	$scope.sms.send = function(){

		if( $scope.formSMS.$invalid ){
			$scope.formSMSSubmitted = true;
			return;
		}

		$scope.formSMSSending = true;
		CallService.send_sms( $scope.sms, function( json ){
			$scope.formSMSSending = false;
			if( json.success ){
				MainNavigationService.link( '/ticket/' + json.success);
				if( $scope.complete ){
					$scope.complete();
				}
				$scope.reset();
			} else {
				App.alert( json.error );
			}
		} );
	}

	$scope.call.make = function(){
		if( $scope.formCall.$invalid ){
			$scope.formCallSubmitted = true;
			return;
		}
		$scope.formCallSending = true;
		CallService.make_call( $scope.call, function( json ){
			$scope.formCallSending = false;
			if( json.success ){
				App.alert( json.success );
				$scope.reset();
			} else {
				App.alert( json.error );
			}
		} );
	}

	$scope.call.voip = function() {
		TwilioService.call($scope.call.phone);
		App.dialog.close();
	};

	// Reset stuff when calling from modal
	$rootScope.$on('callText', function(e, num) {
		$scope.reset();
		$scope.call.phone = num;
		$scope.sms.phone = num;
	} );

} );

NGApp.controller('SupportCtrl', function($scope, $rootScope, $timeout, TicketService, TicketViewService, CallService) {

	$scope.ticketparams = {
		status: 'open'
	};

	$scope.callparams = {
		status: ['in-progress','ringing'],
		limit: 5,
		today: true
	};

	$scope.closeTicket = function( id_support ){
		TicketService.openClose( id_support, function() { update(); } );
	}

	$rootScope.$watch('supportMessages', function(newValue, oldValue) {
		if (!newValue) {
			return;
		}
		if (!oldValue || newValue.count != oldValue.count || newValue.timestamp != oldValue.timestamp ) {
			update();
		}
	}, true);

	var update = function(){
		TicketService.list($scope.ticketparams, function(d) {
			$scope.lotsoftickets = d.results;
			TicketViewService.scope.tickets = d.results;
		});
	}

	CallService.list($scope.callparams, function(d) {
		$scope.calls = d.results;
	});

	update();
});
<|endoftext|>


<commit_before>define("ace/mode/beancount_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var SqlHighlightRules = require("ace/mode/sql_highlight_rules").SqlHighlightRules;

var BeancountHighlightRules = function() {

    this.$rules = {
        start: [{
            token: "comment.line.beancount",
            regex: /;.*/,
            comment: "Commented text"
        }, {
            token: "comment.line.shebang",
            regex: /^#!.*/,
            comment: "Shebangs"
        }, {
            token: "section.line.beancount",
            regex: /^\*+ .+$/,
            comment: "Section marker"
        }, {
            token: "string.quoted.triple.beancount",
            regex: /"""/,
            comment: "Multi-line strings (embedded SQL)",
            next: "sql-start"
        }, {
            token: "string.quoted.double.beancount",
            regex: /"[^"]*"/,
            comment: "strings"
        }, {
            token: [
                "text",
                "constant.language.beancount",
                "punctuation.separator.beancount"
            ],
            regex: /(\s)([A-Z][A-Za-z0-9\-]+)(:)/,
            comment: "Root Accounts"
        }, {
                token: [
                    "punctuation.separator.beancount",
                    "variable.account.beancount"
                ],
                regex: /([:]?)([A-Z][A-Za-z0-9\-]+)/,
            comment: "Accounts"
        }, {
            token: [
                "text",
                "constant.language.beancount",
                "punctuation.separator.beancount"
            ],
            regex: /(\s)([a-z][A-Za-z0-9\-\_]+)(:)/,
            comment: "Metadata"
        }, {
            token: [
                "support.function.directive.option.beancount",
                "meta.directive.option.beancount",
                "support.variable.language.option.beancount",
                "meta.directive.option.beancount",
                "support.class.option.beancount",
                "meta.directive.option.beancount"
            ],
            regex: /^(option)(\s*)(\".*\")(\s*)(\".*\")(\s*)/,
            comment: "Option directives"
        }, {
            token: "keyword.operator.directive.beancount",
            regex: /^(?:poptag|pushtag)\s/,
            comment: "Directives (no date)"
        }, {
            token: "variable.other.currency.beancount",
            regex: /\s[A-Z][A-Z0-9\'\.\_\-]{0,10}[A-Z0-9][\,?|\s]/,
            comment: "Currencies"
        }, {
            token: [
                "constant.numeric.date.year.beancount",
                "text",
                "constant.numeric.date.month.beancount",
                "text",
                "constant.numeric.date.day.beancount",
                "text",
                "support.function.directive.beancount"
            ],
            regex: /([0-9]{4})(\-)([0-9]{2})(\-)([0-9]{2})(\s)(open|close|pad|balance|note|price|event|document|commodity|query)/,
            comment: "Dated directives"
        }, {
            token: [
                "constant.numeric.date.year.beancount",
                "text",
                "constant.numeric.date.month.beancount",
                "text",
                "constant.numeric.date.day.beancount",
                "support.function.directive.beancount",
                "text"
            ],
            regex: /([0-9]{4})(\-)([0-9]{2})(\-)([0-9]{2})((?:\stxn)?)(\s)/,
            comment: "Transactions"
        }, {
            token: "keyword.other.beancount",
            regex: /\!\s/,
            comment: "flag"
        }, {
            token: "keyword.operator.assignment.beancount",
            regex: /\@/,
            comment: "Price assignment"
        }, {
            token: "keyword.operator.assignment.beancount",
            regex: /\{/,
            comment: "cost assignment"
        }, {
            token: ["text", "string.unquoted.tag.beancount"],
            regex: /(#)([A-Za-z0-9\-_\/.]+)/,
            comment: "Tags and links"
        }, {
            token: ["text", "string.unquoted.link.beancount"],
            regex: /(\^)([A-Za-z0-9\-_\/.]+)/,
            comment: "Links"
        }, {
            token: [
                "keyword.operator.modifier.beancount",
                "constant.numeric.currency.beancount"
            ],
            regex: /([\-|\+]?)([\d]+[\.]?[\d]*)/,
            comment: "numbers"
        }, {
            token: "invalid.illegal.unrecognized.beancount",
            regex: /[^\s}]/,
            comment: "Illegal"
        }],
        "#account-names": [{
            token: "text",
            regex: /[A-Z][A-Za-z0-9\-]+/
        }],
        "#dates": [{
            token: [
                "constant.numeric.date.year.beancount",
                "punctuation.separator.beancount",
                "constant.numeric.date.month.beancount",
                "punctuation.separator.beancount",
                "constant.numeric.date.day.beancount"
            ],
            regex: /([0-9]{4})(\-)([0-9]{2})(\-)([0-9]{2})/
        }],
        "#numbers": [{
            token: [
                "keyword.operator.modifier.beancount",
                "constant.numeric.currency.beancount"
            ],
            regex: /([\-|\+]?)([\d]+[\.]?[\d]*)/
        }, {
            token: "comment.line.beancount",
            regex: /\*.*/,
            comment: "Commented text"
        }]
    }

    this.embedRules(SqlHighlightRules, "sql-", [{
        token: "string.quoted.triple.beancount",
        regex: /"""/,
        comment: "Multi-line strings",
        next: "start"
    }]);

    this.normalizeRules();
};

BeancountHighlightRules.metaData = {
    fileTypes: ["beancount"],
    name: "Beancount",
    scopeName: "source.beancount"
}

oop.inherits(BeancountHighlightRules, TextHighlightRules);

exports.BeancountHighlightRules = BeancountHighlightRules;
});

define("ace/mode/folding/orgstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(require, exports, module) {
"use strict";

var oop = require("../../lib/oop");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;

var FoldMode = exports.FoldMode = function() {};
oop.inherits(FoldMode, BaseFoldMode);

(function() {
    this.foldingStartMarker = /^(\*+) (.+)$/;
    this.foldingStopMarker;

    this._getFoldWidgetBase = this.getFoldWidget;
    this.getFoldWidget = function(session, foldStyle, row) {
        var line = session.getLine(row);

        if (!this.foldingStartMarker.test(line)) {
            return "";
        }

        var fw = this._getFoldWidgetBase(session, foldStyle, row);

        if (!fw && this.foldingStartMarker.test(line))
            return "start";

        return fw;
    };

    this.getFoldWidgetRange = function(session, foldStyle, row) {
        var line = session.getLine(row);

        var match = line.match(this.foldingStartMarker);
        if (match) {
            console.log(match);
            var startColumn = line.length;
            var maxRow = session.getLength();
            var startRow = row;
            var level = match[1].length

            while (++row < maxRow) {
                line = session.getLine(row);
                var m = this.foldingStartMarker.exec(line);
                if (!m) continue;
                if (m[1].length <= level) break;
            }

            var endRow = row;
            if (endRow > startRow) {
                if (endRow < maxRow) endRow--;
                return new Range(startRow, startColumn, endRow, line.length);
            }
        }
    };

}).call(FoldMode.prototype);

});
define("ace/mode/beancount",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/beancount_highlight_rules","ace/mode/folding/cstyle"], function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var BeancountHighlightRules = require("./beancount_highlight_rules").BeancountHighlightRules;
//var FoldMode = require("./folding/cstyle").FoldMode;
var FoldMode = require("./folding/orgstyle").FoldMode;

var Mode = function() {
    this.HighlightRules = BeancountHighlightRules;
    this.foldingRules = new FoldMode();
};
oop.inherits(Mode, TextMode);

(function() {
    this.$id = "ace/mode/beancount"
}).call(Mode.prototype);

exports.Mode = Mode;
});
<commit_msg>Remove leftover comment<commit_after>define("ace/mode/beancount_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var SqlHighlightRules = require("ace/mode/sql_highlight_rules").SqlHighlightRules;

var BeancountHighlightRules = function() {

    this.$rules = {
        start: [{
            token: "comment.line.beancount",
            regex: /;.*/,
            comment: "Commented text"
        }, {
            token: "comment.line.shebang",
            regex: /^#!.*/,
            comment: "Shebangs"
        }, {
            token: "section.line.beancount",
            regex: /^\*+ .+$/,
            comment: "Section marker"
        }, {
            token: "string.quoted.triple.beancount",
            regex: /"""/,
            comment: "Multi-line strings (embedded SQL)",
            next: "sql-start"
        }, {
            token: "string.quoted.double.beancount",
            regex: /"[^"]*"/,
            comment: "strings"
        }, {
            token: [
                "text",
                "constant.language.beancount",
                "punctuation.separator.beancount"
            ],
            regex: /(\s)([A-Z][A-Za-z0-9\-]+)(:)/,
            comment: "Root Accounts"
        }, {
                token: [
                    "punctuation.separator.beancount",
                    "variable.account.beancount"
                ],
                regex: /([:]?)([A-Z][A-Za-z0-9\-]+)/,
            comment: "Accounts"
        }, {
            token: [
                "text",
                "constant.language.beancount",
                "punctuation.separator.beancount"
            ],
            regex: /(\s)([a-z][A-Za-z0-9\-\_]+)(:)/,
            comment: "Metadata"
        }, {
            token: [
                "support.function.directive.option.beancount",
                "meta.directive.option.beancount",
                "support.variable.language.option.beancount",
                "meta.directive.option.beancount",
                "support.class.option.beancount",
                "meta.directive.option.beancount"
            ],
            regex: /^(option)(\s*)(\".*\")(\s*)(\".*\")(\s*)/,
            comment: "Option directives"
        }, {
            token: "keyword.operator.directive.beancount",
            regex: /^(?:poptag|pushtag)\s/,
            comment: "Directives (no date)"
        }, {
            token: "variable.other.currency.beancount",
            regex: /\s[A-Z][A-Z0-9\'\.\_\-]{0,10}[A-Z0-9][\,?|\s]/,
            comment: "Currencies"
        }, {
            token: [
                "constant.numeric.date.year.beancount",
                "text",
                "constant.numeric.date.month.beancount",
                "text",
                "constant.numeric.date.day.beancount",
                "text",
                "support.function.directive.beancount"
            ],
            regex: /([0-9]{4})(\-)([0-9]{2})(\-)([0-9]{2})(\s)(open|close|pad|balance|note|price|event|document|commodity|query)/,
            comment: "Dated directives"
        }, {
            token: [
                "constant.numeric.date.year.beancount",
                "text",
                "constant.numeric.date.month.beancount",
                "text",
                "constant.numeric.date.day.beancount",
                "support.function.directive.beancount",
                "text"
            ],
            regex: /([0-9]{4})(\-)([0-9]{2})(\-)([0-9]{2})((?:\stxn)?)(\s)/,
            comment: "Transactions"
        }, {
            token: "keyword.other.beancount",
            regex: /\!\s/,
            comment: "flag"
        }, {
            token: "keyword.operator.assignment.beancount",
            regex: /\@/,
            comment: "Price assignment"
        }, {
            token: "keyword.operator.assignment.beancount",
            regex: /\{/,
            comment: "cost assignment"
        }, {
            token: ["text", "string.unquoted.tag.beancount"],
            regex: /(#)([A-Za-z0-9\-_\/.]+)/,
            comment: "Tags and links"
        }, {
            token: ["text", "string.unquoted.link.beancount"],
            regex: /(\^)([A-Za-z0-9\-_\/.]+)/,
            comment: "Links"
        }, {
            token: [
                "keyword.operator.modifier.beancount",
                "constant.numeric.currency.beancount"
            ],
            regex: /([\-|\+]?)([\d]+[\.]?[\d]*)/,
            comment: "numbers"
        }, {
            token: "invalid.illegal.unrecognized.beancount",
            regex: /[^\s}]/,
            comment: "Illegal"
        }],
        "#account-names": [{
            token: "text",
            regex: /[A-Z][A-Za-z0-9\-]+/
        }],
        "#dates": [{
            token: [
                "constant.numeric.date.year.beancount",
                "punctuation.separator.beancount",
                "constant.numeric.date.month.beancount",
                "punctuation.separator.beancount",
                "constant.numeric.date.day.beancount"
            ],
            regex: /([0-9]{4})(\-)([0-9]{2})(\-)([0-9]{2})/
        }],
        "#numbers": [{
            token: [
                "keyword.operator.modifier.beancount",
                "constant.numeric.currency.beancount"
            ],
            regex: /([\-|\+]?)([\d]+[\.]?[\d]*)/
        }, {
            token: "comment.line.beancount",
            regex: /\*.*/,
            comment: "Commented text"
        }]
    }

    this.embedRules(SqlHighlightRules, "sql-", [{
        token: "string.quoted.triple.beancount",
        regex: /"""/,
        comment: "Multi-line strings",
        next: "start"
    }]);

    this.normalizeRules();
};

BeancountHighlightRules.metaData = {
    fileTypes: ["beancount"],
    name: "Beancount",
    scopeName: "source.beancount"
}

oop.inherits(BeancountHighlightRules, TextHighlightRules);

exports.BeancountHighlightRules = BeancountHighlightRules;
});

define("ace/mode/folding/orgstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(require, exports, module) {
"use strict";

var oop = require("../../lib/oop");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;

var FoldMode = exports.FoldMode = function() {};
oop.inherits(FoldMode, BaseFoldMode);

(function() {
    this.foldingStartMarker = /^(\*+) (.+)$/;
    this.foldingStopMarker;

    this._getFoldWidgetBase = this.getFoldWidget;
    this.getFoldWidget = function(session, foldStyle, row) {
        var line = session.getLine(row);

        if (!this.foldingStartMarker.test(line)) {
            return "";
        }

        var fw = this._getFoldWidgetBase(session, foldStyle, row);

        if (!fw && this.foldingStartMarker.test(line))
            return "start";

        return fw;
    };

    this.getFoldWidgetRange = function(session, foldStyle, row) {
        var line = session.getLine(row);

        var match = line.match(this.foldingStartMarker);
        if (match) {
            console.log(match);
            var startColumn = line.length;
            var maxRow = session.getLength();
            var startRow = row;
            var level = match[1].length

            while (++row < maxRow) {
                line = session.getLine(row);
                var m = this.foldingStartMarker.exec(line);
                if (!m) continue;
                if (m[1].length <= level) break;
            }

            var endRow = row;
            if (endRow > startRow) {
                if (endRow < maxRow) endRow--;
                return new Range(startRow, startColumn, endRow, line.length);
            }
        }
    };

}).call(FoldMode.prototype);

});

define("ace/mode/beancount",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/beancount_highlight_rules","ace/mode/folding/cstyle"], function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var BeancountHighlightRules = require("./beancount_highlight_rules").BeancountHighlightRules;
var FoldMode = require("./folding/orgstyle").FoldMode;

var Mode = function() {
    this.HighlightRules = BeancountHighlightRules;
    this.foldingRules = new FoldMode();
};
oop.inherits(Mode, TextMode);

(function() {
    this.$id = "ace/mode/beancount"
}).call(Mode.prototype);

exports.Mode = Mode;
});
<|endoftext|>


<commit_before>// native imports
import util from 'util';

// libraries
import arginfo from 'arginfo';
import rmprop from 'rmprop';

// local modules
import overloader from './overloader';

/**
* private static:
**/

//
const __class_name = 'QueryPatterns';

//
const restruct = () => {

};

/**
* @class QueryPatterns
* using closure for private methods and fields
**/
const __construct = function(h_init) {

	/**
	* private:
	**/

	let h_prefixes = h_init.prefixes;
	let a_where = h_init.where;

	//
	let h_struct = rmprop({});
	let h_graph = {};
	let as_top_nodes = new Set();

	// each triple
	a_where.forEach((h_pattern) => {

		//
		if('bgp' === h_pattern.type) {

			// each triple in basic graph pattern
			h_pattern.triples.forEach((h_triple) => {

				// ref subject
				let s_subject = h_triple.subject;

				// first triple using this subject
				if(!h_graph[s_subject]) {

					// create list to store triples sharing this subject
					h_graph[s_subject] = [];
				}

				// group triple into buckets by same subject
				h_graph[s_subject].push(h_triple);

				// only add non-blanknodes to top-level
				if(!s_subject.startsWith('_:')) {
					as_top_nodes.add(s_subject);
				}
			});
		}
	});

	// ------------------------------

	//
	const depth_first = function*(h_object) {

		// each triple in this node
		for(let h_triple of h_object) {

			// destructure triple
			let {subject: s_subject, predicate: s_predicate, object: s_object} = h_triple;

			// triple points to a blanknode
			if(s_object.startsWith('_:')) {

				// yield depth first triples down that path
				yield *depth_first(h_graph[s_object]);
			}

			// then yield this container triple
			yield [h_triple, s_subject, s_predicate, s_object];
		}
	};

	return {

		// defines a simpler iterator
		depth_first: function*() {

			// each top level node
			for(let s_node_id of as_top_nodes) {

				// yield depth first triples
				yield *depth_first(h_graph[s_node_id]);
			}
		}
	};
};

/**
* public static operator() ():
**/
const local = function() {

	return __construct.apply(this, arguments);

	// // called with `new`
	// if(new.target) {
	// 	return __construct.apply(this, arguments);
	// }
	// // called directly
	// else {
	// 	return local.fail('not allowed to call '+local+' without `new` operator');
	// }
};

/**
* public static:
**/
{

	//
	local.toString = function() {
		return __class_name+'()';
	};

	// prefix output messages to console with class's tag
	require('./log-tag.js').extend(local, __class_name);
}

export default local;
<commit_msg>top_level iteration<commit_after>// native imports
import util from 'util';

// libraries
import arginfo from 'arginfo';
import rmprop from 'rmprop';

// local modules
import overloader from './overloader';

/**
* private static:
**/

//
const __class_name = 'QueryPatterns';

//
const restruct = () => {

};

/**
* @class QueryPatterns
* using closure for private methods and fields
**/
const __construct = function(h_init) {

	/**
	* private:
	**/

	let h_prefixes = h_init.prefixes;
	let a_where = h_init.where;

	//
	let h_struct = rmprop({});
	let h_graph = {};
	let as_top_nodes = new Set();

	// each triple
	a_where.forEach((h_pattern) => {

		//
		if('bgp' === h_pattern.type) {

			// each triple in basic graph pattern
			h_pattern.triples.forEach((h_triple) => {

				// ref subject
				let s_subject = h_triple.subject;

				// first triple using this subject
				if(!h_graph[s_subject]) {

					// create list to store triples sharing this subject
					h_graph[s_subject] = [];
				}

				// group triple into buckets by same subject
				h_graph[s_subject].push(h_triple);

				// only add non-blanknodes to top-level
				if(!s_subject.startsWith('_:')) {
					as_top_nodes.add(s_subject);
				}
			});
		}
	});

	// ------------------------------

	//
	const depth_first = function*(h_container) {

		// each triple in this node
		for(let h_triple of h_container) {

			// destructure triple
			let {subject: s_subject, predicate: s_predicate, object: s_object} = h_triple;

			// triple points to a blanknode
			if(s_object.startsWith('_:')) {

				// yield depth first triples down that path
				yield *depth_first(h_graph[s_object]);
			}

			// then yield this container triple
			yield [h_triple, s_subject, s_predicate, s_object];
		}
	};

	return {

		// depth-first iteration
		depth_first: function*() {

			// each top level node
			for(let s_node_id of as_top_nodes) {

				// yield depth first triples
				yield *depth_first(h_graph[s_node_id]);
			}
		},

		// top-level iteration
		top_level: function*() {

			// each top level node
			for(let s_node_id of as_top_nodes) {

				// each triple pointed to by this subject
				for(let h_triple of graph[s_node_id]) {

					// destructure triple
					let {subject: s_subject, predicate: s_predicate, object: s_object} = h_triple;

					// yield top-level triples
					yield [h_triple, s_subject, s_predicate, s_object];
				}
			}
		},
	};
};

/**
* public static operator() ():
**/
const local = function() {

	return __construct.apply(this, arguments);

	// // called with `new`
	// if(new.target) {
	// 	return __construct.apply(this, arguments);
	// }
	// // called directly
	// else {
	// 	return local.fail('not allowed to call '+local+' without `new` operator');
	// }
};

/**
* public static:
**/
{

	//
	local.toString = function() {
		return __class_name+'()';
	};

	// prefix output messages to console with class's tag
	require('./log-tag.js').extend(local, __class_name);
}

export default local;
<|endoftext|>


<commit_before>"use strict";

/**
 * Class for game maps
 *
 * Class for ELM game maps, used in Eternal Lands and Other Life.
 */
function GameMap(fname)
{
	var _map_obj = this;

	/// Is this map inside
	this.dungeon = false;
	/// Color of ambient light
	this.ambientColor = [1.0, 1.0, 1.0];
	/// Ground tiles on this map
	this.tile_map = null;
	/// Elevation map
	this.elevation_map = null;
	/// two-dimensional objects
	this.objects_2d = new Object2DMap();
	/// three-dimensional objects
	this.objects_3d = [];

	$.ajax(fname, {
		dataType: "arraybuffer",
		error: function() {
			logError("Failed to get map " + fname);
		},
		success: function(data) {
			_map_obj._construct(data);
		}
	});
}

/// Extract the map data from @a data
GameMap.prototype._construct = function(data)
{
	var view = new DataView(data);
	if (view.getUint32(0, true) != fourCC("elmf"))
	{
		logError("Not a valid map file");
		return;
	}

	var tile_map_width = view.getUint32(4, true);
	var tile_map_height = view.getUint32(8, true);
	var tile_map_offset = view.getUint32(12, true);
	var elev_map_width = GroundTileMap.tile_size * tile_map_width;
	var elev_map_height = GroundTileMap.tile_size * tile_map_height;
	var elev_map_offset = view.getUint32(16, true);
	var obj_3d_size = view.getUint32(20, true);
	var obj_3d_count = view.getUint32(24, true);
	var obj_3d_offset = view.getUint32(28, true);
	var obj_2d_size = view.getUint32(32, true);
	var obj_2d_count = view.getUint32(36, true);
	var obj_2d_offset = view.getUint32(40, true);
	var light_size = view.getUint32(44, true);
	var light_count = view.getUint32(48, true);
	var light_offset = view.getUint32(52, true);
	this.dungeon = view.getUint8(56);
	this.ambientColor[0] = view.getFloat32(60, true);
	this.ambientColor[1] = view.getFloat32(64, true);
	this.ambientColor[2] = view.getFloat32(68, true);
	var particles_size = view.getUint32(72, true);
	var particles_count = view.getUint32(76, true);
	var particles_offset = view.getUint32(80, true);
	var clusters_offset = view.getUint32(84, true);

	this.tile_map = new GroundTileMap(tile_map_width, tile_map_height,
		new Uint8Array(data, tile_map_offset, tile_map_width*tile_map_height));
	this.elevation_map = new ElevationMap(elev_map_width, elev_map_height,
		new Uint8Array(data, elev_map_offset, elev_map_width*elev_map_height));

	var off = obj_2d_offset;
	for (var i = 0; i < obj_2d_count; ++i, off += obj_2d_size)
	{
		var str = extractString(view, off, 80);
		var pos = new Float32Array(data, off+80, 3);
		var rot = new Float32Array(data, off+92, 3);
		this.objects_2d.add(new Object2D(str, pos, rot));
	}
	this.objects_2d.setAllDefinitions();

	var off = obj_3d_offset;
	for (var i = 0; i < obj_3d_count; ++i, off += obj_3d_size)
	{
		var str = extractString(view, off, 80);
		var pos = new Float32Array(data, off+80, 3);
		var rot = new Float32Array(data, off+92, 3);
		var self_lit = view.getUint8(off+104);
		var blended = view.getUint8(off+105);
		var col = new Float32Array(data, off+108, 3);
		var scale = view.getFloat32(off+120, true);
		this.objects_3d.push(
			new Object3D(str, pos, rot, col, scale, self_lit, blended));
	}

	camera.set(this.elevation_map, elev_map_width>>1, elev_map_height>>1);
	console.log(this);
};

var ic = 0;
var dtt = 0;
var dt2 = 0;
/**
 * Draw the map
 *
 * Draw the map, and all the objects in it, on the screen
 */
GameMap.prototype.draw = function()
{
	// All objects are textured, disable vertex coloring and enable texture
	// coordinates
	gl.disableVertexAttribArray(shaders.program.vertexColorAttribute);
	gl.vertexAttrib4f(shaders.program.vertexColorAttribute, 1, 1, 1, 1);
	gl.enableVertexAttribArray(shaders.program.textureCoordAttribute);

	gl.disable(gl.BLEND);
	gl.enable(gl.DEPTH_TEST);

	this.tile_map.draw();
	this.objects_2d.draw();
}
<commit_msg>Don't start on an unwalkable tile when the map is loaded<commit_after>"use strict";

/**
 * Class for game maps
 *
 * Class for ELM game maps, used in Eternal Lands and Other Life.
 */
function GameMap(fname)
{
	var _map_obj = this;

	/// Is this map inside
	this.dungeon = false;
	/// Color of ambient light
	this.ambientColor = [1.0, 1.0, 1.0];
	/// Ground tiles on this map
	this.tile_map = null;
	/// Elevation map
	this.elevation_map = null;
	/// two-dimensional objects
	this.objects_2d = new Object2DMap();
	/// three-dimensional objects
	this.objects_3d = [];

	$.ajax(fname, {
		dataType: "arraybuffer",
		error: function() {
			logError("Failed to get map " + fname);
		},
		success: function(data) {
			_map_obj._construct(data);
		}
	});
}

/// Extract the map data from @a data
GameMap.prototype._construct = function(data)
{
	var view = new DataView(data);
	if (view.getUint32(0, true) != fourCC("elmf"))
	{
		logError("Not a valid map file");
		return;
	}

	var tile_map_width = view.getUint32(4, true);
	var tile_map_height = view.getUint32(8, true);
	var tile_map_offset = view.getUint32(12, true);
	var elev_map_width = GroundTileMap.tile_size * tile_map_width;
	var elev_map_height = GroundTileMap.tile_size * tile_map_height;
	var elev_map_offset = view.getUint32(16, true);
	var obj_3d_size = view.getUint32(20, true);
	var obj_3d_count = view.getUint32(24, true);
	var obj_3d_offset = view.getUint32(28, true);
	var obj_2d_size = view.getUint32(32, true);
	var obj_2d_count = view.getUint32(36, true);
	var obj_2d_offset = view.getUint32(40, true);
	var light_size = view.getUint32(44, true);
	var light_count = view.getUint32(48, true);
	var light_offset = view.getUint32(52, true);
	this.dungeon = view.getUint8(56);
	this.ambientColor[0] = view.getFloat32(60, true);
	this.ambientColor[1] = view.getFloat32(64, true);
	this.ambientColor[2] = view.getFloat32(68, true);
	var particles_size = view.getUint32(72, true);
	var particles_count = view.getUint32(76, true);
	var particles_offset = view.getUint32(80, true);
	var clusters_offset = view.getUint32(84, true);

	this.tile_map = new GroundTileMap(tile_map_width, tile_map_height,
		new Uint8Array(data, tile_map_offset, tile_map_width*tile_map_height));
	this.elevation_map = new ElevationMap(elev_map_width, elev_map_height,
		new Uint8Array(data, elev_map_offset, elev_map_width*elev_map_height));

	var off = obj_2d_offset;
	for (var i = 0; i < obj_2d_count; ++i, off += obj_2d_size)
	{
		var str = extractString(view, off, 80);
		var pos = new Float32Array(data, off+80, 3);
		var rot = new Float32Array(data, off+92, 3);
		this.objects_2d.add(new Object2D(str, pos, rot));
	}
	this.objects_2d.setAllDefinitions();

	var off = obj_3d_offset;
	for (var i = 0; i < obj_3d_count; ++i, off += obj_3d_size)
	{
		var str = extractString(view, off, 80);
		var pos = new Float32Array(data, off+80, 3);
		var rot = new Float32Array(data, off+92, 3);
		var self_lit = view.getUint8(off+104);
		var blended = view.getUint8(off+105);
		var col = new Float32Array(data, off+108, 3);
		var scale = view.getFloat32(off+120, true);
		this.objects_3d.push(
			new Object3D(str, pos, rot, col, scale, self_lit, blended));
	}

	var x = elev_map_width>>1;
	var y = elev_map_height>>1;
	var d = 1;
	while (!this.elevation_map.isWalkable(x, y))
	{
		x += Math.round(d*Math.random());
		y += Math.round(d*Math.random());
		d += 1;
	}
	camera.set(this.elevation_map, x, y);
	console.log(this);
};

var ic = 0;
var dtt = 0;
var dt2 = 0;
/**
 * Draw the map
 *
 * Draw the map, and all the objects in it, on the screen
 */
GameMap.prototype.draw = function()
{
	// All objects are textured, disable vertex coloring and enable texture
	// coordinates
	gl.disableVertexAttribArray(shaders.program.vertexColorAttribute);
	gl.vertexAttrib4f(shaders.program.vertexColorAttribute, 1, 1, 1, 1);
	gl.enableVertexAttribArray(shaders.program.textureCoordAttribute);

	gl.disable(gl.BLEND);
	gl.enable(gl.DEPTH_TEST);

	this.tile_map.draw();
	this.objects_2d.draw();
}
<|endoftext|>


<commit_before>var web3 = require("web3");

var bzzKeyLength = 32;
var mruMetaHashLength = bzzKeyLength;
var mruRootAddrLength = bzzKeyLength;
var mruUpdateVersionLength = 4;
var mruUpdatePeriodLength = 4;
var mruUpdateFlagLength = 1;
var mruUpdateDataLengthLength = 2;
var mruUpdateHeaderLengthLength = 2;
var mruUpdateHeaderLength = mruUpdateFlagLength + mruUpdatePeriodLength + mruUpdateVersionLength + mruMetaHashLength + mruRootAddrLength;
var mruUpdateMinLength = mruUpdateHeaderLength + mruUpdateDataLengthLength + mruUpdateHeaderLengthLength;

function mruUpdateDigest(o) {

	var metaHashBytes = undefined;
	var rootAddrBytes = undefined;
	var dataBytes = web3.utils.hexToBytes(o.data);

	if (!web3.utils.isHexStrict(o.data)) {
		console.error("data must be a valid 0x prefixed hex value");
		return undefined;
	}

	try {
		metaHashBytes = web3.utils.hexToBytes(o.metaHash);
	} catch(err) {
		console.error("metaHash: " + err);
		return undefined;
	}
	if (metaHashBytes.length < mruMetaHashLength) {
		console.error("metaHash must be exactly " + mruMetaHashLength + " bytes long");
		return undefined;
	}

	try {
		rootAddrBytes = web3.utils.hexToBytes(o.rootAddr)
	} catch(err) {
		console.error("rootAddr: " + err);
		return undefined;
	}
	if (rootAddrBytes.length < mruRootAddrLength) {
		console.error("rootAddr must be exactly " + mruRootAddrLength + " bytes long");
		return undefined;
	}

	var buf = new ArrayBuffer(mruUpdateMinLength + dataBytes.length);
	var view = new DataView(buf);
	var cursor = 0;

	view.setUint16(cursor, mruUpdateHeaderLength, true);
	cursor += mruUpdateHeaderLengthLength;

	view.setUint16(cursor, dataBytes.length, true);
	cursor += mruUpdateDataLengthLength;

	view.setUint32(cursor, o.period, true);
	cursor += mruUpdatePeriodLength;

	view.setUint32(cursor, o.version, true);
	cursor += mruUpdateVersionLength;

	rootAddrBytes.forEach(function(v) {
		view.setUint8(cursor, v);
		cursor++;
	});

	metaHashBytes.forEach(function(v) {
		view.setUint8(cursor, v);
		cursor++;
	});

	if (o.multihash) {
		view.setUint8(cursor, 1);
	} else {
		view.setUint8(cursor, 0);
	}
	cursor++;

	dataBytes.forEach(function(v) {
		view.setUint8(cursor, v);
		cursor++;
	});

	return web3.utils.sha3(web3.utils.bytesToHex(new Uint8Array(buf)));
}
mru = mruUpdateDigest({
	"period": 42,
	"version": 13,
	"multihash": false,
	"data": "0x666f6f",
	"metaHash": "0x2c1183eed6a4b0046da699e2655a406d20754ef02fcc7625ee24579a4c0970eb",
	"rootAddr": "0xfe9a53da332939697dd3b2d706f161ba75162805752efe7d365f2ed3f5cbd380"
});

console.log(mru);
<commit_msg>Adaptive frequency digest refactor<commit_after>var web3 = require("web3");

//var bzzKeyLength = 32;
//var mruMetaHashLength = bzzKeyLength;
//var mruRootAddrLength = bzzKeyLength;
//var mruUpdateVersionLength = 4;
//var mruUpdatePeriodLength = 4;
//var mruUpdateFlagLength = 1;
//var mruUpdateDataLengthLength = 2;
//var mruUpdateHeaderLengthLength = 2;
//var mruUpdateHeaderLength = mruUpdateFlagLength + mruUpdatePeriodLength + mruUpdateVersionLength + mruMetaHashLength + mruRootAddrLength;
//var mruUpdateMinLength = mruUpdateHeaderLength + mruUpdateDataLengthLength + mruUpdateHeaderLengthLength;

var topicLength = 32;
var userLength = 20;
var timeLength = 7;
var levelLength = 1;
var updateMinLength = topicLength + userLength + timeLength + levelLength;

function mruUpdateDigest(o) {
	var topicBytes = undefined;
	var dataBytes = undefined;
	var userBytes = undefined;

	if (!web3.utils.isHexStrict(o.data)) {
		console.error("data must be a valid 0x prefixed hex value");
		return undefined;
	}

	dataBytes = web3.utils.hexToBytes(o.data);

	try {
		topicBytes = web3.utils.hexToBytes(o.topic);
	} catch(err) {
		console.error("topicBytes: " + err);
		return undefined;
	}

	try {
		userBytes = web3.utils.hexToBytes(o.user);
	} catch(err) {
		console.error("topicBytes: " + err);
		return undefined;
	}

	var buf = new ArrayBuffer(updateMinLength + dataBytes.length);
	var view = new DataView(buf);
	var cursor = 0;

	topicBytes.forEach(function(v) {
		view.setUint8(cursor, v);
		cursor++;
	});

	userBytes.forEach(function(v) {
		view.setUint8(cursor, v);
		cursor++;
	});

	for (i = 0; i < 3; i++) {
		view.setUint8(cursor, 0);
		cursor++;
	}

	view.setUint32(cursor, o.time);
	cursor += 4;
	view.setUint8(cursor, o.level);
	cursor++;

	dataBytes.forEach(function(v) {
		view.setUint8(cursor, v);
		cursor++;
	});

	return web3.utils.bytesToHex(new Uint8Array(buf));
}

function mruUpdateDigest_(o) {

	var metaHashBytes = undefined;
	var rootAddrBytes = undefined;
	var dataBytes = web3.utils.hexToBytes(o.data);

	if (!web3.utils.isHexStrict(o.data)) {
		console.error("data must be a valid 0x prefixed hex value");
		return undefined;
	}

	try {
		metaHashBytes = web3.utils.hexToBytes(o.metaHash);
	} catch(err) {
		console.error("metaHash: " + err);
		return undefined;
	}
	if (metaHashBytes.length < mruMetaHashLength) {
		console.error("metaHash must be exactly " + mruMetaHashLength + " bytes long");
		return undefined;
	}

	try {
		rootAddrBytes = web3.utils.hexToBytes(o.rootAddr)
	} catch(err) {
		console.error("rootAddr: " + err);
		return undefined;
	}
	if (rootAddrBytes.length < mruRootAddrLength) {
		console.error("rootAddr must be exactly " + mruRootAddrLength + " bytes long");
		return undefined;
	}

	var buf = new ArrayBuffer(mruUpdateMinLength + dataBytes.length);
	var view = new DataView(buf);
	var cursor = 0;

	view.setUint16(cursor, mruUpdateHeaderLength, true);
	cursor += mruUpdateHeaderLengthLength;

	view.setUint16(cursor, dataBytes.length, true);
	cursor += mruUpdateDataLengthLength;

	view.setUint32(cursor, o.period, true);
	cursor += mruUpdatePeriodLength;

	view.setUint32(cursor, o.version, true);
	cursor += mruUpdateVersionLength;

	rootAddrBytes.forEach(function(v) {
		view.setUint8(cursor, v);
		cursor++;
	});

	metaHashBytes.forEach(function(v) {
		view.setUint8(cursor, v);
		cursor++;
	});

	if (o.multihash) {
		view.setUint8(cursor, 1);
	} else {
		view.setUint8(cursor, 0);
	}
	cursor++;

	dataBytes.forEach(function(v) {
		view.setUint8(cursor, v);
		cursor++;
	});

	return web3.utils.sha3(web3.utils.bytesToHex(new Uint8Array(buf)));
}

//mru = mruUpdateDigest(
//{
//  "rootAddr": "0x1c2692b93e594a47af49f3cff10e2c958e00d8e5014b37e4150809f789ccd16a",
//  "metaHash": "0xa5e0aa94cce20457061e35a3b0b698e6e2cfb82b1e7ea211d9d92284f3d18b17",
//  "version": 1,
//  "period": 2,
//  "multihash": true,
//  "data": "0x1b20d7d24499dcff78f02db5291fca0f4cbbcbd691ad15d67268d0cb14ee3fc9fb86",
//});

mru = mruUpdateDigest(
	{
		"topic": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
		"data": "0x666f6f",
		"user": "0x44defd3d4e99c2f97e68f3a0a6462e590fd10b91",
		"time": 1536410917,
		"level": 0
	}
);

console.log(mru);
<|endoftext|>


<commit_before>module.exports = {
    'attr-bans': ['style'],
    'indent-style': 'nonmixed',
    'indent-width': 4,
    'text-escape-spec-char': true,
    'tag-self-close': false,
    'tag-bans': ['style', 'b', 'i'],
    'tag-name-lowercase': true,
    'doctype-first': false,
    'doctype-html5': false,
    'attr-name-style': 'lowercase',
    'attr-no-dup': true,
    'attr-no-unsafe-chars': true,
    'attr-quote-style': 'double',
    'attr-req-value': true,
    'id-no-dup': true,
    'id-class-no-ad': true,
    'id-class-style': 'underscore',
    'img-req-alt': true,
    'img-req-src': true,
    'href-style': false,
    'csslint': false,
    'label-req-for': true,
    'line-end-style': 'lf',
    'head-req-title': true,
    'title-no-dup': true,
    'title-max-length': 60
};
<commit_msg>added some more banned attributes, starting to address #88<commit_after>module.exports = {
    'attr-bans': [
        'align',
        'background',
        'bgcolor',
        'border',
        'frameborder',
        'longdesc',
        'marginwidth',
        'marginheight',
        'scrolling',
        'style',
        'width'
    ],
    'indent-style': 'nonmixed',
    'indent-width': 4,
    'text-escape-spec-char': true,
    'tag-self-close': false,
    'tag-bans': ['style', 'b', 'i'],
    'tag-name-lowercase': true,
    'doctype-first': false,
    'doctype-html5': false,
    'attr-name-style': 'lowercase',
    'attr-no-dup': true,
    'attr-no-unsafe-chars': true,
    'attr-quote-style': 'double',
    'attr-req-value': true,
    'id-no-dup': true,
    'id-class-no-ad': true,
    'id-class-style': 'underscore',
    'img-req-alt': true,
    'img-req-src': true,
    'href-style': false,
    'csslint': false,
    'label-req-for': true,
    'line-end-style': 'lf',
    'head-req-title': true,
    'title-no-dup': true,
    'title-max-length': 60
};
<|endoftext|>


<commit_before>var winston = require('winston');
var express = require('express');
var router = express.Router();
var Contact = require('mongoose').model('Contact');
var ObjectId = require('mongoose').Types.ObjectId;

router.get('/', function(req, res, next){

});

router.get('/:id', function (req, res, next) {

});

router.post('/', function(req, res, next) {

});

router.delete('/:id', function(req, res, next) {

});

router.patch('/:id', function(req, res, next) {

});

module.exports = router; //When calling require('tasks'), we get the router.<commit_msg>added addcontact backend<commit_after>var winston = require('winston');
var express = require('express');
var router = express.Router();
var Contact = require('mongoose').model('Contact');
var ObjectId = require('mongoose').Types.ObjectId;

router.get('/', function(req, res, next){

});

router.get('/:id', function (req, res, next) {

});

router.post('/', function(req, res, next) {
    var contactData = req.body;
    var newContact = new Contact(contactData);
    newContact.save(function(err, saved) {
        if(!err) {
            res.status(200).json(saved);
        } else {
            console.log(err);
        }
    })
});

router.delete('/:id', function(req, res, next) {

});

router.patch('/:id', function(req, res, next) {

});

module.exports = router; //When calling require('tasks'), we get the router.<|endoftext|>


<commit_before>/*!
* deja
* Copyright(c) 2011 Mike Cantelon
* MIT Licensed
*/

var path = require('path'),
  fs = require('fs'),
  spawn = require('child_process').spawn,
  wrench = require('wrench')

exports.usage = function() {

  return "Usage:\n\
  deja clone <GIT REPO URL>\n\
  deja ls [REPO NAME][/SUBDIRECTORY]\n\
  deja pull <REPO NAME>\n\
  deja rm <REPO NAME>\n\
  deja diff <REPO NAME>\n\
  deja link <REPO NAME>[/SUBDIRECTORY]\n\
  deja unlink <REPO NAME>[/SUBDIRECTORY]\n\
  deja version"
}

function traverseDir(dir, callback) {

  children = fs.readdirSync(dir)

  for(var index in children) {
    callback(children[index])
  }
}

function findUnusedBasename(dejaHome, repoUrl, callback, counter) {

  counter = (counter == undefined) ? 0 : counter

  // strip ".git" and pad with counter if the basename's already been used
  var basename = path.basename(repoUrl, '.git')
  basename += (counter > 0) ? '_' + counter : ''

  path.exists(dejaHome + '/' + basename, function(exists) {

    if (exists) {
      // recurse, increasing counter, if basename has already been used
      findUnusedBasename(dejaHome, repoUrl, callback, counter + 1)
    }
    else {
      // provide callback with unused basename
      callback(basename)
    }
  })
}

function createSymlinkIfPathExists(symlinkPath, filePath) {

  path.exists(symlinkPath, function(exists) {

    if (!exists) {

      console.log('  ' + symlinkPath + ' -> ' + filePath)
      fs.symlinkSync(filePath, symlinkPath)
    }
    else {

      console.log('  Skipped ' + filePath + ': already exists.')
    }
  })
}

function deleteSymlinksToRepo(home, pathToRepo) {

  traverseDir(pathToRepo, function(entry) {

    var pathToEntry = home + '/' + entry

    path.exists(pathToEntry, function(exists) {
      if (exists) {
        fs.lstat(pathToEntry, function(err, stats) {
          if (stats.isSymbolicLink()) {

            // get path link leads to
            var destPath = fs.readlinkSync(pathToEntry)

            if (destPath == pathToRepo + '/' + entry) {

              fs.unlink(pathToEntry, function (err) {
                if (err) {
                  console.log ('Error: Could not delete symlink ' + pathToEntry + '.')
                }
                else {
                  console.log('Deleted symlink ' + pathToEntry + '.')
                }
              })
            }
          }
        })
      }
    })
  })
}

function diffIfNotSymbolicLink(home, repoHome, file) {

  var homeFilePath = home + '/' + file
  var repoFilePath = repoHome + '/' + file

  fs.lstat(homeFilePath, function(err, stats) {
    if (!stats.isSymbolicLink()) {

      var diff = spawn('diff', [homeFilePath, repoFilePath])

      diff.stdout.on('data', function (data) {
        console.log('diff ' + homeFilePath + ' ' + repoFilePath)
        console.log(data.toString())
      })
    }
  })
}

exports.ls = function(dir) {

  path.exists(dir, function(exists) {

    if (exists) {
      traverseDir(dir, function(entry) {
        console.log(entry)
      })
    }
    else {
      console.log('Error: directory not found.')
    }
  })
}

exports.cloneRepo = function(home, dejaHome, repoUrl) {

  // allow user to leave off .git or .git/
  if (repoUrl.indexOf('.git') == -1) {
    repoUrl = repoUrl + '.git'
  }

  // default to Github if protocal not specified
  if (repoUrl.indexOf(':') == -1) {
    repoUrl = 'git://github.com/' + repoUrl
  }

  var basename = findUnusedBasename(dejaHome, repoUrl, function(basename) {

    var pathToRepo = dejaHome + '/' + basename

    path.exists(pathToRepo, function(exists) {

      if (exists) {

        console.log('Error: Repo already exists.')
        process.exit(1)
      }
      else {

        console.log('Cloning repository...')

        var clone = spawn('git', ['clone', repoUrl, pathToRepo])

        clone.on('exit', function(code) {

          if (code != 0) {

            console.log('Error: could not clone.')
            process.exit(code)
          }
          else {
            exports.linkRepo(home, dejaHome, basename)
          }
        })
      }
    })
  })
}

function parseOutRepoAndSubdir(repo) {

  var pathData,
      subDir = ''

  // if repo contains slashes, then user wants to link a repo subdirectory
  if (repo.indexOf('/') != -1) {

    pathData = repo.split('/')
    repo = pathData.shift()
    subDir = pathData.join('/')
  }

  return {
    repo:   repo,
    subDir: subDir
  }
}

exports.linkRepo = function(home, dejaHome, repo) {

  var pathToRepo = dejaHome + '/' + repo,
      subDir

  var repoAndSubDir = parseOutRepoAndSubdir(repo)
  repo = repoAndSubDir.repo
  subDir = repoAndSubDir.subDir
  subDir += (subDir != '')
    ? '/'
    : ''

  var symlinkRootPath = home + '/' + subDir

  path.exists(symlinkRootPath, function(exists) {

    if (exists) {

      console.log('Creating symbolic links...')

      // cycle through cloned repo making symlinks to home
      traverseDir(pathToRepo, function(file) {

        if (file != '.git') {

          var filePath     = pathToRepo + '/' + file
          var symlinkPath  = symlinkRootPath + file

          createSymlinkIfPathExists(symlinkPath, filePath)
        }
      })
    }
    else {

      console.log('Error: Not a valid repo.')
    }
  })
}

exports.pullRepo = function (dejaHome, repo) {

  var pathToRepo = dejaHome + '/' + repo

  path.exists(pathToRepo, function(exists) {

    if (exists) {

      console.log('Pulling...')

      process.chdir(pathToRepo)

      var pull = spawn('git', ['pull'])

      pull.on('exit', function(code) {

        console.log((code == 0)
          ? 'Pull complete.'
          : 'Error: Could not pull.'
        )

        process.exit(code)
      })
    }
    else {

      console.log('Error: Not a valid repo.')
    }
  })
}

exports.rmRepo = function(home, dejaHome, repo) {

  var pathToRepo = dejaHome + '/' + repo

  path.exists(pathToRepo, function(exists) {

    if (exists) {

      deleteSymlinksToRepo(home, pathToRepo)
      wrench.rmdirSyncRecursive(pathToRepo)
      console.log('Repo removed.')
    }
    else {

      console.log('Error: Not a valid repo.')
    }
  })
}

exports.unlinkRepo = function(home, dejaHome, repo) {

  var pathToRepo = dejaHome + '/' + repo,
      subDir

  var repoAndSubDir = parseOutRepoAndSubdir(repo)
  subDir = repoAndSubDir.subDir
  subDir = (subDir != '')
    ? '/' + subDir
    : ''

  path.exists(pathToRepo, function(exists) {

    if (exists) {
      deleteSymlinksToRepo(home + subDir, pathToRepo)
    }
    else {
      console.log('Error: Not a valid repo.')
    }
  })
}

exports.diffRepo = function (home, dejaHome, param) {

  var pathToRepo = dejaHome + '/' + param

  path.exists(pathToRepo, function(exists) {

    if (exists) {

      traverseDir(pathToRepo, function(file) {
        if (file != '.git') {
          diffIfNotSymbolicLink(home, pathToRepo, file)
        }
      })
    }
    else {

      console.log('Error: Not a valid repo.')
    }
  })
}

exports.version = function() {

  var package_json = fs.readFileSync(__dirname + '/../package.json')
  var package_data = JSON.parse(package_json)
  return 'deja version ' + package_data.version
}
<commit_msg>Added auto-updating/init of submodules.<commit_after>/*!
* deja
* Copyright(c) 2011 Mike Cantelon
* MIT Licensed
*/

var path = require('path'),
  fs = require('fs'),
  spawn = require('child_process').spawn,
  wrench = require('wrench')

exports.usage = function() {

  return "Usage:\n\
  deja clone <GIT REPO URL>\n\
  deja ls [REPO NAME][/SUBDIRECTORY]\n\
  deja pull <REPO NAME>\n\
  deja rm <REPO NAME>\n\
  deja diff <REPO NAME>\n\
  deja link <REPO NAME>[/SUBDIRECTORY]\n\
  deja unlink <REPO NAME>[/SUBDIRECTORY]\n\
  deja version"
}

function traverseDir(dir, callback) {

  children = fs.readdirSync(dir)

  for(var index in children) {
    callback(children[index])
  }
}

function findUnusedBasename(dejaHome, repoUrl, callback, counter) {

  counter = (counter == undefined) ? 0 : counter

  // strip ".git" and pad with counter if the basename's already been used
  var basename = path.basename(repoUrl, '.git')
  basename += (counter > 0) ? '_' + counter : ''

  path.exists(dejaHome + '/' + basename, function(exists) {

    if (exists) {
      // recurse, increasing counter, if basename has already been used
      findUnusedBasename(dejaHome, repoUrl, callback, counter + 1)
    }
    else {
      // provide callback with unused basename
      callback(basename)
    }
  })
}

function createSymlinkIfPathExists(symlinkPath, filePath) {

  path.exists(symlinkPath, function(exists) {

    if (!exists) {

      console.log('  ' + symlinkPath + ' -> ' + filePath)
      fs.symlinkSync(filePath, symlinkPath)
    }
    else {

      console.log('  Skipped ' + filePath + ': already exists.')
    }
  })
}

function deleteSymlinksToRepo(home, pathToRepo) {

  traverseDir(pathToRepo, function(entry) {

    var pathToEntry = home + '/' + entry

    path.exists(pathToEntry, function(exists) {
      if (exists) {
        fs.lstat(pathToEntry, function(err, stats) {
          if (stats.isSymbolicLink()) {

            // get path link leads to
            var destPath = fs.readlinkSync(pathToEntry)

            if (destPath == pathToRepo + '/' + entry) {

              fs.unlink(pathToEntry, function (err) {
                if (err) {
                  console.log ('Error: Could not delete symlink ' + pathToEntry + '.')
                }
                else {
                  console.log('Deleted symlink ' + pathToEntry + '.')
                }
              })
            }
          }
        })
      }
    })
  })
}

function diffIfNotSymbolicLink(home, repoHome, file) {

  var homeFilePath = home + '/' + file
  var repoFilePath = repoHome + '/' + file

  fs.lstat(homeFilePath, function(err, stats) {
    if (!stats.isSymbolicLink()) {

      var diff = spawn('diff', [homeFilePath, repoFilePath])

      diff.stdout.on('data', function (data) {
        console.log('diff ' + homeFilePath + ' ' + repoFilePath)
        console.log(data.toString())
      })
    }
  })
}

exports.ls = function(dir) {

  path.exists(dir, function(exists) {

    if (exists) {
      traverseDir(dir, function(entry) {
        console.log(entry)
      })
    }
    else {
      console.log('Error: directory not found.')
    }
  })
}

exports.cloneRepo = function(home, dejaHome, repoUrl) {

  // allow user to leave off .git or .git/
  if (repoUrl.indexOf('.git') == -1) {
    repoUrl = repoUrl + '.git'
  }

  // default to Github if protocal not specified
  if (repoUrl.indexOf(':') == -1) {
    repoUrl = 'git://github.com/' + repoUrl
  }

  var basename = findUnusedBasename(dejaHome, repoUrl, function(basename) {

    var pathToRepo = dejaHome + '/' + basename

    path.exists(pathToRepo, function(exists) {

      if (exists) {

        console.log('Error: Repo already exists.')
        process.exit(1)
      }
      else {

        console.log('Cloning repository...')

        var clone = spawn('git', ['clone', repoUrl, pathToRepo])

        clone.on('exit', function(code) {

          if (code != 0) {

            console.log('Error: could not clone.')
            process.exit(code)
          }
          else {

            // check if the repo has submodules
            path.exists(pathToRepo + '/.gitmodules', function(exists) {

              // if submodules found, initialize and update them
              if (exists) {

                console.log('Initializing and updating submodules...')
                process.chdir(pathToRepo)

                var submodules = spawn('git', ['submodule', 'update', '--init'])

                submodules.on('exit', function(code) {
                  // create symlinks to items in first level of repo directory
                  exports.linkRepo(home, dejaHome, basename)
                })
              }
              else {

                // create symlinks to items in first level of repo directory
                exports.linkRepo(home, dejaHome, basename)
              }
            })
          }
        })
      }
    })
  })
}

function parseOutRepoAndSubdir(repo) {

  var pathData,
      subDir = ''

  // if repo contains slashes, then user wants to link a repo subdirectory
  if (repo.indexOf('/') != -1) {

    pathData = repo.split('/')
    repo = pathData.shift()
    subDir = pathData.join('/')
  }

  return {
    repo:   repo,
    subDir: subDir
  }
}

exports.linkRepo = function(home, dejaHome, repo) {

  var pathToRepo = dejaHome + '/' + repo,
      subDir

  var repoAndSubDir = parseOutRepoAndSubdir(repo)
  repo = repoAndSubDir.repo
  subDir = repoAndSubDir.subDir
  subDir += (subDir != '')
    ? '/'
    : ''

  var symlinkRootPath = home + '/' + subDir

  path.exists(symlinkRootPath, function(exists) {

    if (exists) {

      console.log('Creating symbolic links...')

      // cycle through cloned repo making symlinks to home
      traverseDir(pathToRepo, function(file) {

        if (file != '.git') {

          var filePath     = pathToRepo + '/' + file
          var symlinkPath  = symlinkRootPath + file

          createSymlinkIfPathExists(symlinkPath, filePath)
        }
      })
    }
    else {

      console.log('Error: Not a valid repo.')
    }
  })
}

exports.pullRepo = function (dejaHome, repo) {

  var pathToRepo = dejaHome + '/' + repo

  path.exists(pathToRepo, function(exists) {

    if (exists) {

      console.log('Pulling...')

      process.chdir(pathToRepo)

      var pull = spawn('git', ['pull'])

      pull.on('exit', function(code) {

        console.log((code == 0)
          ? 'Pull complete.'
          : 'Error: Could not pull.'
        )

        process.exit(code)
      })
    }
    else {

      console.log('Error: Not a valid repo.')
    }
  })
}

exports.rmRepo = function(home, dejaHome, repo) {

  var pathToRepo = dejaHome + '/' + repo

  path.exists(pathToRepo, function(exists) {

    if (exists) {

      deleteSymlinksToRepo(home, pathToRepo)
      wrench.rmdirSyncRecursive(pathToRepo)
      console.log('Repo removed.')
    }
    else {

      console.log('Error: Not a valid repo.')
    }
  })
}

exports.unlinkRepo = function(home, dejaHome, repo) {

  var pathToRepo = dejaHome + '/' + repo,
      subDir

  var repoAndSubDir = parseOutRepoAndSubdir(repo)
  subDir = repoAndSubDir.subDir
  subDir = (subDir != '')
    ? '/' + subDir
    : ''

  path.exists(pathToRepo, function(exists) {

    if (exists) {
      deleteSymlinksToRepo(home + subDir, pathToRepo)
    }
    else {
      console.log('Error: Not a valid repo.')
    }
  })
}

exports.diffRepo = function (home, dejaHome, param) {

  var pathToRepo = dejaHome + '/' + param

  path.exists(pathToRepo, function(exists) {

    if (exists) {

      traverseDir(pathToRepo, function(file) {
        if (file != '.git') {
          diffIfNotSymbolicLink(home, pathToRepo, file)
        }
      })
    }
    else {

      console.log('Error: Not a valid repo.')
    }
  })
}

exports.version = function() {

  var package_json = fs.readFileSync(__dirname + '/../package.json')
  var package_data = JSON.parse(package_json)
  return 'deja version ' + package_data.version
}
<|endoftext|>