<commit_before>routes.define(function($routeProvider){
    $routeProvider
        .when('/view/thread/:threadId', {
            action: 'viewThread'
        })
        .when('/view/thread/:threadId/info/:infoId', {
            action: 'viewInfo'
        })
        .when('/view/info/:infoId/comment/:commentId', {
            action: 'viewInfo'
        })
		.when('/default', {
			action: 'main'
		})
		.when('/admin', {
			action: 'admin'
		})
        .otherwise({
        	redirectTo: '/default'
        });
});

function ActualitesController($scope, template, route, model, date, $location){

    template.open('info-read', 'info-read');

    this.initialize = function(){
    	$scope.notFound = false;

    	route({
    		// Routes viewThread, viewInfo adn viewComment are used by notifications
            viewThread: function(params){
            	model.threads.one('sync', function(){
            		var aThread = model.threads.find(function(thread){
    					return thread._id === parseInt(params.threadId);
    				});
    				if(aThread !== undefined){
    					$scope.notFound = false;
                        $scope.openThread(aThread._id, aThread.thread_title);
    				}
    				else{
						$scope.notFound = true;
                        template.open('error', '404');
    				}
				});
				model.threads.sync();
            },
            viewInfo: function(params){
            	model.infos.one('sync', function() {
					$scope.info = undefined;
					$scope.info = model.infos.find(function(info){
						return info._id === parseInt(params.infoId);
					});
					if ($scope.info !== undefined) {
						if($scope.info.allow('view')) {
							$scope.notFound = false;
							$scope.info.thread.selected = true;
							$scope.display.infoRead = true;
						}
						else {
						    $scope.display.infoRead = true;
							$scope.notFound = true;
							template.open('error', '401');
						}
					}
					else {
					    $scope.display.infoRead = true;
						$scope.notFound = true;
						template.open('error', '404');
					}
				});
				model.one('threads.sync', function(){
					model.threads.selectAll();
				});
				model.one('infos.sync', function(){
					model.threads.selectAll();
				});
				model.infos.sync();
            },
            viewComment: function(params){
            	model.infos.one('sync', function() {
    				if(params.infoId !== undefined) {
                        $scope.info = undefined;
                        $scope.info = model.infos.find(function(info){
                            return info._id === parseInt(params.infoId);
                        });
                        if ($scope.info !== undefined) {
                            if($scope.info.allow('view') && $scope.info.comments.all.length > 0) {
                                $scope.notFound = false;
                                $scope.display.commentInfo = $scope.info;
                                template.open('main', 'single-info');
                            }
                            else {
                                $scope.notFound = true;
                                template.open('error', '401');
                            }
                        }
                        else {
                            $scope.notFound = true;
                            template.open('error', '404');
                        }
    				}
    				else {
    					$scope.notFound = true;
                        template.open('error', '404');
    				}
				});
				model.infos.sync();
            },
            main: function(params){
				model.infos.unbind('sync');
				model.threads.unbind('sync');
				$scope.info = undefined;
				$scope.currentInfo = new Info();
            	template.open('main', 'main');
				model.threads.selectAll();

				model.one('threads.sync', function(){
					model.threads.selectAll();
				});
				model.one('infos.sync', function(){
					model.threads.selectAll();
				});
            },
			admin: function(params){
				model.infos.unbind('sync');
				model.threads.unbind('sync');
				model.threads.deselectAll();
				template.open('main', 'threads-view');

				model.one('threads.sync', function(){
					model.threads.deselectAll();
				});
				model.one('infos.sync', function(){
					model.threads.deselectAll();
				});
			}
        });

        // Model
        $scope.template = template;
        $scope.me = model.me;
        $scope.threads = model.threads;
        $scope.threadFilters = [
            {label: "public", value: ACTUALITES_CONFIGURATION.threadFilters.PUBLIC},
            {label: "all", value: ACTUALITES_CONFIGURATION.threadFilters.ALL}
        ];

        $scope.threadFilter = ACTUALITES_CONFIGURATION.threadFilters.PUBLIC;

        // Variables
        $scope.infos = model.infos;
        $scope.currentInfo = new Info();
        $scope.display = {
			emptyThread: false,
			showCommentsPanel: false,
			showComments: false,
			filters: {
				show1: true,
				show2: true,
				show3: true,
				all: true
			},
			limit: 8
		};

        $scope.startDate = new Date();
        $scope.appPrefix = 'actualites';
        $scope.currentThread = {};

        // View initialization
		template.open('threadsView', 'threads-view');
        template.open('comments', 'info-comments');
        template.open('infoEdit', 'info-edit');
        template.open('infoView', 'info-view');
		template.open('filters', 'filters');
		template.open('main', 'main');
    };

	$scope.checkMinExpirationDate = function(info) {
        if(!info.publication_date || !info.expiration_date)
            return;
        var publicationDateMin = moment(info.publication_date).add('day', 1)
        var expirationDate = moment(info.expiration_date)
        if(expirationDate.isBefore(publicationDateMin)){
            info.expiration_date = publicationDateMin.toISOString()
        }
	};

	$scope.sortByIsHeadline = function(info) {
		return info.is_headline;
	};

	$scope.increaseLimit = function(){
		$scope.display.limit += 5;
	}

    $scope.openMainPage = function(){
    	$location.path('/default');
	};

	$scope.allowForSelection = function(action){
		return _.filter(model.infos.selection(), function(info){
			return !info.allow(action);
		}).length === 0;
	};

	$scope.editInfo = function(info){
		model.infos.deselectAll();
		info.edit = true;
		info.expanded = true;
	};

    $scope.createInfo = function(info){
		$scope.currentInfo = new Info();
		template.open('createInfo', 'info-create');
    };

    $scope.showShareInfo = function(info) {
    	$scope.display.showInfoSharePanel = true;
    };

    $scope.cancelShareInfo = function() {
    	$scope.display.showInfoSharePanel = false;
    };

    $scope.saveDraft = function(){
		if($scope.currentInfo.save()){
			template.close('createInfo');
			$scope.currentInfo = new Info();
		}
    };

    $scope.saveSubmitted = function(){
		if($scope.currentInfo.createPending()){
			template.close('createInfo');
			$scope.currentInfo = new Info();
		}
    };

    $scope.savePublished = function(){
		if($scope.currentInfo.createPublished()){
			template.close('createInfo');
			$scope.currentInfo = new Info();
		}
    };

	$scope.cancelCreateInfo = function(){
		template.close('createInfo');
		$scope.currentInfo = new Info();
	};

	$scope.openThread = function(thread_id){
		$scope.threads.deselectAll();
		$scope.threads.findWhere({ _id: thread_id }).selected = true;
	};

	$scope.switchSselectThread = function(thread){
		thread.selected = !thread.selected;
		if(thread.selected){
			return;
		}
		model.infos.forEach(function(info){
			if(info.thread_id === thread._id){
				info.selected = false;
			}
		});
	};

    $scope.getState = function(info){
    	if(info.status === ACTUALITES_CONFIGURATION.infoStatus.PUBLISHED){
    		if(info.hasPublicationDate && moment().isBefore(getDateAsMoment(info.publication_date)) ){
    			// label (A venir)
    			return "actualites.edition.status.4" ;
    		}
    		if(info.hasExpirationDate && moment().isAfter(getDateAsMoment(info.expiration_date).add(1, 'days')) ){
    			// label (Expiree)
    			return "actualites.edition.status.5" ;
    		}
    		if(info.owner !== model.me.userId){
    			return "actualites.edition.status.empty";
    		}
    	}
    	return "actualites.edition.status." + info.status;
    };

	$scope.switchAll = function(){
		for(var filter in $scope.display.filters){
			$scope.display.filters[filter] = $scope.display.filters.all;
		}
	};

	$scope.checkAll = function(){
		$scope.display.filters.all = true;
		for(var filter in $scope.display.filters){
			$scope.display.filters.all = $scope.display.filters[filter] && $scope.display.filters.all;
		}
	};

	$scope.setFilter = function(state){
    	switch(state) {
			case ACTUALITES_CONFIGURATION.infoStatus.DRAFT:
				$scope.display.show1 = true;
				$scope.display.show2 = false;
				$scope.display.show3 = false;
				break;
			case ACTUALITES_CONFIGURATION.infoStatus.PENDING:
				$scope.display.show1 = false;
				$scope.display.show2 = true;
				$scope.display.show3 = false;
				break;
			case ACTUALITES_CONFIGURATION.infoStatus.PUBLISHED:
				$scope.display.show1 = false;
				$scope.display.show2 = false;
				$scope.display.show3 = true;
				break;
			default:
				$scope.display.show1 = true;
				$scope.display.show2 = true;
				$scope.display.show3 = true;
		}
    };

    /* Comments */
    $scope.hasInfoComments = function(info){
        return (info.comments !== undefined && info.comments.length > 0);
    };

    $scope.postInfoComment = function(info){
        if ((!_.isString(info.newComment.comment)) || (info.newComment.comment.trim() === "")) {
            return;
        }

        info.comment(info.newComment.comment);
        info.newComment = new Comment();

    };

    // Threads
    $scope.threadsView = function(){
		$location.path('/admin');
	};

	$scope.newThreadView = function(){
		$scope.currentThread = new Thread();
		template.open('main', 'thread-edit');
	};

	$scope.editSelectedThread = function(){
		$scope.currentThread = model.threads.selection()[0];
		model.threads.deselectAll();
		template.open('main', 'thread-edit');
	};

    $scope.saveThread = function(){
       	$scope.currentThread.save();
        template.open('main', 'threads-view');
		$scope.currentThread = undefined;
    };

    $scope.cancelEditThread = function(){
        $scope.currentThread = undefined;
		template.open('main', 'threads-view');
    };

    /* Util */
    $scope.formatDate = function(date){
    	var momentDate = getDateAsMoment(date);
		return moment(momentDate).calendar();
    };

	$scope.formatDateLocale = function(date){
		if(moment(date) > moment().add(-1, 'days').startOf('day') && moment(date) < moment().endOf('day'))
			return moment(date).calendar();

		if(moment(date) > moment().add(-7, 'days').startOf('day') && moment(date) < moment().endOf('day'))
			return moment(date).fromNow(); //this week

		return moment(date).format("L");
	};

	$scope.oneContribRight = function(){
		return model.threads.find(function(thread){
			return thread.myRights.contrib;
		});
	};

	//hack to avoid infinite digest
	var _threadsInSelection = [];
	$scope.threadsInSelection = function(){
		var selectionThreads = model.infos.map(function(info){
			return info.thread;
		});
		if(selectionThreads.length !== _threadsInSelection.length){
			_threadsInSelection = selectionThreads;
		}
		return _threadsInSelection;
	};

	$scope.filterByThreads = function(unpublished){
		return function(info){
			return ((unpublished && info.status <= 2) || (!unpublished && info.status > 2))
				&& ($scope.display.filters['show' + info.status || $scope.display.filters.all])
				&& _.findWhere($scope.threads.selection(), { _id: info.thread_id })
				&& info.allow('view');
		};
	}

    this.initialize();
}
<commit_msg>Fix #13383 : fixed log spam javascript errors on selecting news<commit_after>routes.define(function($routeProvider){
    $routeProvider
        .when('/view/thread/:threadId', {
            action: 'viewThread'
        })
        .when('/view/thread/:threadId/info/:infoId', {
            action: 'viewInfo'
        })
        .when('/view/info/:infoId/comment/:commentId', {
            action: 'viewInfo'
        })
		.when('/default', {
			action: 'main'
		})
		.when('/admin', {
			action: 'admin'
		})
        .otherwise({
        	redirectTo: '/default'
        });
});

function ActualitesController($scope, template, route, model, date, $location){

    template.open('info-read', 'info-read');

    this.initialize = function(){
    	$scope.notFound = false;

    	route({
    		// Routes viewThread, viewInfo adn viewComment are used by notifications
            viewThread: function(params){
            	model.threads.one('sync', function(){
            		var aThread = model.threads.find(function(thread){
    					return thread._id === parseInt(params.threadId);
    				});
    				if(aThread !== undefined){
    					$scope.notFound = false;
                        $scope.openThread(aThread._id, aThread.thread_title);
    				}
    				else{
						$scope.notFound = true;
                        template.open('error', '404');
    				}
				});
				model.threads.sync();
            },
            viewInfo: function(params){
            	model.infos.one('sync', function() {
					$scope.info = undefined;
					$scope.info = model.infos.find(function(info){
						return info._id === parseInt(params.infoId);
					});
					if ($scope.info !== undefined) {
						if($scope.info.allow('view')) {
							$scope.notFound = false;
							$scope.info.thread.selected = true;
							$scope.display.infoRead = true;
						}
						else {
						    $scope.display.infoRead = true;
							$scope.notFound = true;
							template.open('error', '401');
						}
					}
					else {
					    $scope.display.infoRead = true;
						$scope.notFound = true;
						template.open('error', '404');
					}
				});
				model.one('threads.sync', function(){
					model.threads.selectAll();
				});
				model.one('infos.sync', function(){
					model.threads.selectAll();
				});
				model.infos.sync();
            },
            viewComment: function(params){
            	model.infos.one('sync', function() {
    				if(params.infoId !== undefined) {
                        $scope.info = undefined;
                        $scope.info = model.infos.find(function(info){
                            return info._id === parseInt(params.infoId);
                        });
                        if ($scope.info !== undefined) {
                            if($scope.info.allow('view') && $scope.info.comments.all.length > 0) {
                                $scope.notFound = false;
                                $scope.display.commentInfo = $scope.info;
                                template.open('main', 'single-info');
                            }
                            else {
                                $scope.notFound = true;
                                template.open('error', '401');
                            }
                        }
                        else {
                            $scope.notFound = true;
                            template.open('error', '404');
                        }
    				}
    				else {
    					$scope.notFound = true;
                        template.open('error', '404');
    				}
				});
				model.infos.sync();
            },
            main: function(params){
				model.infos.unbind('sync');
				model.threads.unbind('sync');
				$scope.info = undefined;
				$scope.currentInfo = new Info();
            	template.open('main', 'main');
				model.threads.selectAll();

				model.one('threads.sync', function(){
					model.threads.selectAll();
				});
				model.one('infos.sync', function(){
					model.threads.selectAll();
				});
            },
			admin: function(params){
				model.infos.unbind('sync');
				model.threads.unbind('sync');
				model.threads.deselectAll();
				template.open('main', 'threads-view');

				model.one('threads.sync', function(){
					model.threads.deselectAll();
				});
				model.one('infos.sync', function(){
					model.threads.deselectAll();
				});
			}
        });

        // Model
        $scope.template = template;
        $scope.me = model.me;
        $scope.threads = model.threads;
        $scope.threadFilters = [
            {label: "public", value: ACTUALITES_CONFIGURATION.threadFilters.PUBLIC},
            {label: "all", value: ACTUALITES_CONFIGURATION.threadFilters.ALL}
        ];

        $scope.threadFilter = ACTUALITES_CONFIGURATION.threadFilters.PUBLIC;

        // Variables
        $scope.infos = model.infos;
        $scope.currentInfo = new Info();
        $scope.display = {
			emptyThread: false,
			showCommentsPanel: false,
			showComments: false,
			filters: {
				show1: true,
				show2: true,
				show3: true,
				all: true
			},
			limit: 8
		};

        $scope.startDate = new Date();
        $scope.appPrefix = 'actualites';
        $scope.currentThread = {};

        // View initialization
		template.open('threadsView', 'threads-view');
        template.open('comments', 'info-comments');
        template.open('infoEdit', 'info-edit');
        template.open('infoView', 'info-view');
		template.open('filters', 'filters');
		template.open('main', 'main');
    };

	$scope.checkMinExpirationDate = function(info) {
        if(!info.publication_date || !info.expiration_date)
            return;
        var publicationDateMin = moment(info.publication_date).add('day', 1)
        var expirationDate = moment(info.expiration_date)
        if(expirationDate.isBefore(publicationDateMin)){
            info.expiration_date = publicationDateMin.toISOString()
        }
	};

	$scope.sortByIsHeadline = function(info) {
		return info.is_headline;
	};

	$scope.increaseLimit = function(){
		$scope.display.limit += 5;
	}

    $scope.openMainPage = function(){
    	$location.path('/default');
	};

	$scope.allowForSelection = function(action){
		return _.filter(model.infos.selection(), function(info){
			return !info.allow(action);
		}).length === 0;
	};

	$scope.editInfo = function(info){
		model.infos.deselectAll();
		info.edit = true;
		info.expanded = true;
	};

    $scope.createInfo = function(info){
		$scope.currentInfo = new Info();
		template.open('createInfo', 'info-create');
    };

    $scope.showShareInfo = function(info) {
    	$scope.display.showInfoSharePanel = true;
    };

    $scope.cancelShareInfo = function() {
    	$scope.display.showInfoSharePanel = false;
    };

    $scope.saveDraft = function(){
		if($scope.currentInfo.save()){
			template.close('createInfo');
			$scope.currentInfo = new Info();
		}
    };

    $scope.saveSubmitted = function(){
		if($scope.currentInfo.createPending()){
			template.close('createInfo');
			$scope.currentInfo = new Info();
		}
    };

    $scope.savePublished = function(){
		if($scope.currentInfo.createPublished()){
			template.close('createInfo');
			$scope.currentInfo = new Info();
		}
    };

	$scope.cancelCreateInfo = function(){
		template.close('createInfo');
		$scope.currentInfo = new Info();
	};

	$scope.openThread = function(thread_id){
		$scope.threads.deselectAll();
		$scope.threads.findWhere({ _id: thread_id }).selected = true;
	};

	$scope.switchSselectThread = function(thread){
		thread.selected = !thread.selected;
		if(thread.selected){
			return;
		}
		model.infos.forEach(function(info){
			if(info.thread_id === thread._id){
				info.selected = false;
			}
		});
	};

    $scope.getState = function(info){
        if (info) {
            if (info.status === ACTUALITES_CONFIGURATION.infoStatus.PUBLISHED) {
                if (info.hasPublicationDate && moment().isBefore(getDateAsMoment(info.publication_date))) {
                    // label (A venir)
                    return "actualites.edition.status.4";
                }
                if (info.hasExpirationDate && moment().isAfter(getDateAsMoment(info.expiration_date).add(1, 'days'))) {
                    // label (Expiree)
                    return "actualites.edition.status.5";
                }
                if (info.owner !== model.me.userId) {
                    return "actualites.edition.status.empty";
                }
            }
            return "actualites.edition.status." + info.status;
        } else {
            return "";
        }
    };

	$scope.switchAll = function(){
		for(var filter in $scope.display.filters){
			$scope.display.filters[filter] = $scope.display.filters.all;
		}
	};

	$scope.checkAll = function(){
		$scope.display.filters.all = true;
		for(var filter in $scope.display.filters){
			$scope.display.filters.all = $scope.display.filters[filter] && $scope.display.filters.all;
		}
	};

	$scope.setFilter = function(state){
    	switch(state) {
			case ACTUALITES_CONFIGURATION.infoStatus.DRAFT:
				$scope.display.show1 = true;
				$scope.display.show2 = false;
				$scope.display.show3 = false;
				break;
			case ACTUALITES_CONFIGURATION.infoStatus.PENDING:
				$scope.display.show1 = false;
				$scope.display.show2 = true;
				$scope.display.show3 = false;
				break;
			case ACTUALITES_CONFIGURATION.infoStatus.PUBLISHED:
				$scope.display.show1 = false;
				$scope.display.show2 = false;
				$scope.display.show3 = true;
				break;
			default:
				$scope.display.show1 = true;
				$scope.display.show2 = true;
				$scope.display.show3 = true;
		}
    };

    /* Comments */
    $scope.hasInfoComments = function(info){
        return (info.comments !== undefined && info.comments.length > 0);
    };

    $scope.postInfoComment = function(info){
        if ((!_.isString(info.newComment.comment)) || (info.newComment.comment.trim() === "")) {
            return;
        }

        info.comment(info.newComment.comment);
        info.newComment = new Comment();

    };

    // Threads
    $scope.threadsView = function(){
		$location.path('/admin');
	};

	$scope.newThreadView = function(){
		$scope.currentThread = new Thread();
		template.open('main', 'thread-edit');
	};

	$scope.editSelectedThread = function(){
		$scope.currentThread = model.threads.selection()[0];
		model.threads.deselectAll();
		template.open('main', 'thread-edit');
	};

    $scope.saveThread = function(){
       	$scope.currentThread.save();
        template.open('main', 'threads-view');
		$scope.currentThread = undefined;
    };

    $scope.cancelEditThread = function(){
        $scope.currentThread = undefined;
		template.open('main', 'threads-view');
    };

    /* Util */
    $scope.formatDate = function(date){
    	var momentDate = getDateAsMoment(date);
		return moment(momentDate).calendar();
    };

	$scope.formatDateLocale = function(date){
		if(moment(date) > moment().add(-1, 'days').startOf('day') && moment(date) < moment().endOf('day'))
			return moment(date).calendar();

		if(moment(date) > moment().add(-7, 'days').startOf('day') && moment(date) < moment().endOf('day'))
			return moment(date).fromNow(); //this week

		return moment(date).format("L");
	};

	$scope.oneContribRight = function(){
		return model.threads.find(function(thread){
			return thread.myRights.contrib;
		});
	};

	//hack to avoid infinite digest
	var _threadsInSelection = [];
	$scope.threadsInSelection = function(){
		var selectionThreads = model.infos.map(function(info){
			return info.thread;
		});
		if(selectionThreads.length !== _threadsInSelection.length){
			_threadsInSelection = selectionThreads;
		}
		return _threadsInSelection;
	};

	$scope.filterByThreads = function(unpublished){
		return function(info){
			return info && ((unpublished && info.status <= 2) || (!unpublished && info.status > 2))
				&& ($scope.display.filters['show' + info.status || $scope.display.filters.all])
				&& _.findWhere($scope.threads.selection(), { _id: info.thread_id })
				&& info.allow('view');
		};
	};

    this.initialize();
}
<|endoftext|>


<commit_before>var test = require('tap').test
var fss = require('./')
var clone = require('clone')
var s = JSON.stringify

test('circular reference to root', function (assert) {
  var fixture = {name: 'Tywin Lannister'}
  fixture.circle = fixture
  var expected = s(
    {name: 'Tywin Lannister', circle: '[Circular]'}
  )
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('nested circular reference to root', function (assert) {
  var fixture = {name: 'Tywin Lannister'}
  fixture.id = {circle: fixture}
  var expected = s(
    {name: 'Tywin Lannister', id: {circle: '[Circular]'}}
  )
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('child circular reference', function (assert) {
  var fixture = {name: 'Tywin Lannister', child: {name: 'Tyrion Lannister'}}
  fixture.child.dinklage = fixture.child
  var expected = s({
    name: 'Tywin Lannister',
    child: {
      name: 'Tyrion Lannister', dinklage: '[Circular]'
    }
  })
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('nested child circular reference', function (assert) {
  var fixture = {name: 'Tywin Lannister', child: {name: 'Tyrion Lannister'}}
  fixture.child.actor = {dinklage: fixture.child}
  var expected = s({
    name: 'Tywin Lannister',
    child: {
      name: 'Tyrion Lannister', actor: {dinklage: '[Circular]'}
    }
  })
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('circular objects in an array', function (assert) {
  var fixture = {name: 'Tywin Lannister'}
  fixture.hand = [fixture, fixture]
  var expected = s({
    name: 'Tywin Lannister', hand: ['[Circular]', '[Circular]']
  })
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('nested circular references in an array', function (assert) {
  var fixture = {
    name: 'Tywin Lannister',
    offspring: [{name: 'Tyrion Lannister'}, {name: 'Cersei Lannister'}]
  }
  fixture.offspring[0].dinklage = fixture.offspring[0]
  fixture.offspring[1].headey = fixture.offspring[1]

  var expected = s({
    name: 'Tywin Lannister',
    offspring: [
      {name: 'Tyrion Lannister', dinklage: '[Circular]'},
      {name: 'Cersei Lannister', headey: '[Circular]'}
    ]
  })
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('circular arrays', function (assert) {
  var fixture = []
  fixture.push(fixture, fixture)
  var expected = s(['[Circular]', '[Circular]'])
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('nested circular arrays', function (assert) {
  var fixture = []
  fixture.push(
    {name: 'Jon Snow', bastards: fixture},
    {name: 'Ramsay Bolton', bastards: fixture}
  )
  var expected = s([
    {name: 'Jon Snow', bastards: '[Circular]'},
    {name: 'Ramsay Bolton', bastards: '[Circular]'}
  ])
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('repeated non-circular references in objects', function (assert) {
  var daenerys = {name: 'Daenerys Targaryen'}
  var fixture = {
    motherOfDragons: daenerys,
    queenOfMeereen: daenerys
  }
  var expected = s(fixture)
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('repeated non-circular references in arrays', function (assert) {
  var daenerys = {name: 'Daenerys Targaryen'}
  var fixture = [daenerys, daenerys]
  var expected = s(fixture)
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('double child circular reference', function (assert) {
  // create circular reference
  var child = {name: 'Tyrion Lannister'}
  child.dinklage = child

  // include it twice in the fixture
  var fixture = {name: 'Tywin Lannister', childA: child, childB: child}
  var cloned = clone(fixture)
  var expected = s({
    name: 'Tywin Lannister',
    childA: {
      name: 'Tyrion Lannister', dinklage: '[Circular]'
    },
    childB: {
      name: 'Tyrion Lannister', dinklage: '[Circular]'
    }
  })
  var actual = fss(fixture)
  assert.is(actual, expected)

  // check if the fixture has not been modified
  assert.deepEqual(fixture, cloned)
  assert.end()
})

test('child circular reference with toJSON', function (assert) {
  // Create a test object that has an overriden `toJSON` property
  TestObject.prototype.toJSON = function () { return { special: 'case' } }
  function TestObject (content) {}

  // Creating a simple circular object structure
  const parentObject = {}
  parentObject.childObject = new TestObject()
  parentObject.childObject.parentObject = parentObject

  // Creating a simple circular object structure
  const otherParentObject = new TestObject()
  otherParentObject.otherChildObject = {}
  otherParentObject.otherChildObject.otherParentObject = otherParentObject

  // Making sure our original tests work
  assert.deepEqual(parentObject.childObject.parentObject, parentObject)
  assert.deepEqual(otherParentObject.otherChildObject.otherParentObject, otherParentObject)

  // Should both be idempotent
  assert.equal(fss(parentObject), '{"childObject":{"special":"case"}}')
  assert.equal(fss(otherParentObject), '{"special":"case"}')

  // Therefore the following assertion should be `true`
  assert.deepEqual(parentObject.childObject.parentObject, parentObject)
  assert.deepEqual(otherParentObject.otherChildObject.otherParentObject, otherParentObject)

  assert.end()
})

test('null object', function (assert) {
  var expected = s(null)
  var actual = fss(null)
  assert.is(actual, expected)
  assert.end()
})

test('null property', function (assert) {
  var expected = s({ f: null })
  var actual = fss({ f: null })
  assert.is(actual, expected)
  assert.end()
})

test('nested child circular reference in toJSON', function (assert) {
  var b = {}
  var circle = { some: 'data' }
  circle.circle = circle
  var baz = { circle }
  var a = { b, baz }
  var o = {
    a,
    bar: a
  }
  b.toJSON = function () {
    a.b = 2
    return '[Redacted]'
  }
  baz.toJSON = function () {
    a.baz = circle
    return '[Redacted]'
  }
  baz.toJSON.forceDecirc = true

  var expected = s({
    a: {
      b: '[Redacted]',
      baz: '[Redacted]'
    },
    bar: {
      b: 2,
      baz: {
        some: 'data',
        circle: '[Circular]'
      }
    }
  })
  // fixture.child.actor[Symbol.for('forceDecirc')] = true
  var actual = fss(o)
  assert.is(actual, expected)
  assert.end()
})
<commit_msg>test: remove dead code<commit_after>var test = require('tap').test
var fss = require('./')
var clone = require('clone')
var s = JSON.stringify

test('circular reference to root', function (assert) {
  var fixture = {name: 'Tywin Lannister'}
  fixture.circle = fixture
  var expected = s(
    {name: 'Tywin Lannister', circle: '[Circular]'}
  )
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('nested circular reference to root', function (assert) {
  var fixture = {name: 'Tywin Lannister'}
  fixture.id = {circle: fixture}
  var expected = s(
    {name: 'Tywin Lannister', id: {circle: '[Circular]'}}
  )
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('child circular reference', function (assert) {
  var fixture = {name: 'Tywin Lannister', child: {name: 'Tyrion Lannister'}}
  fixture.child.dinklage = fixture.child
  var expected = s({
    name: 'Tywin Lannister',
    child: {
      name: 'Tyrion Lannister', dinklage: '[Circular]'
    }
  })
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('nested child circular reference', function (assert) {
  var fixture = {name: 'Tywin Lannister', child: {name: 'Tyrion Lannister'}}
  fixture.child.actor = {dinklage: fixture.child}
  var expected = s({
    name: 'Tywin Lannister',
    child: {
      name: 'Tyrion Lannister', actor: {dinklage: '[Circular]'}
    }
  })
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('circular objects in an array', function (assert) {
  var fixture = {name: 'Tywin Lannister'}
  fixture.hand = [fixture, fixture]
  var expected = s({
    name: 'Tywin Lannister', hand: ['[Circular]', '[Circular]']
  })
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('nested circular references in an array', function (assert) {
  var fixture = {
    name: 'Tywin Lannister',
    offspring: [{name: 'Tyrion Lannister'}, {name: 'Cersei Lannister'}]
  }
  fixture.offspring[0].dinklage = fixture.offspring[0]
  fixture.offspring[1].headey = fixture.offspring[1]

  var expected = s({
    name: 'Tywin Lannister',
    offspring: [
      {name: 'Tyrion Lannister', dinklage: '[Circular]'},
      {name: 'Cersei Lannister', headey: '[Circular]'}
    ]
  })
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('circular arrays', function (assert) {
  var fixture = []
  fixture.push(fixture, fixture)
  var expected = s(['[Circular]', '[Circular]'])
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('nested circular arrays', function (assert) {
  var fixture = []
  fixture.push(
    {name: 'Jon Snow', bastards: fixture},
    {name: 'Ramsay Bolton', bastards: fixture}
  )
  var expected = s([
    {name: 'Jon Snow', bastards: '[Circular]'},
    {name: 'Ramsay Bolton', bastards: '[Circular]'}
  ])
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('repeated non-circular references in objects', function (assert) {
  var daenerys = {name: 'Daenerys Targaryen'}
  var fixture = {
    motherOfDragons: daenerys,
    queenOfMeereen: daenerys
  }
  var expected = s(fixture)
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('repeated non-circular references in arrays', function (assert) {
  var daenerys = {name: 'Daenerys Targaryen'}
  var fixture = [daenerys, daenerys]
  var expected = s(fixture)
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('double child circular reference', function (assert) {
  // create circular reference
  var child = {name: 'Tyrion Lannister'}
  child.dinklage = child

  // include it twice in the fixture
  var fixture = {name: 'Tywin Lannister', childA: child, childB: child}
  var cloned = clone(fixture)
  var expected = s({
    name: 'Tywin Lannister',
    childA: {
      name: 'Tyrion Lannister', dinklage: '[Circular]'
    },
    childB: {
      name: 'Tyrion Lannister', dinklage: '[Circular]'
    }
  })
  var actual = fss(fixture)
  assert.is(actual, expected)

  // check if the fixture has not been modified
  assert.deepEqual(fixture, cloned)
  assert.end()
})

test('child circular reference with toJSON', function (assert) {
  // Create a test object that has an overriden `toJSON` property
  TestObject.prototype.toJSON = function () { return { special: 'case' } }
  function TestObject (content) {}

  // Creating a simple circular object structure
  const parentObject = {}
  parentObject.childObject = new TestObject()
  parentObject.childObject.parentObject = parentObject

  // Creating a simple circular object structure
  const otherParentObject = new TestObject()
  otherParentObject.otherChildObject = {}
  otherParentObject.otherChildObject.otherParentObject = otherParentObject

  // Making sure our original tests work
  assert.deepEqual(parentObject.childObject.parentObject, parentObject)
  assert.deepEqual(otherParentObject.otherChildObject.otherParentObject, otherParentObject)

  // Should both be idempotent
  assert.equal(fss(parentObject), '{"childObject":{"special":"case"}}')
  assert.equal(fss(otherParentObject), '{"special":"case"}')

  // Therefore the following assertion should be `true`
  assert.deepEqual(parentObject.childObject.parentObject, parentObject)
  assert.deepEqual(otherParentObject.otherChildObject.otherParentObject, otherParentObject)

  assert.end()
})

test('null object', function (assert) {
  var expected = s(null)
  var actual = fss(null)
  assert.is(actual, expected)
  assert.end()
})

test('null property', function (assert) {
  var expected = s({ f: null })
  var actual = fss({ f: null })
  assert.is(actual, expected)
  assert.end()
})

test('nested child circular reference in toJSON', function (assert) {
  var b = {}
  var circle = { some: 'data' }
  circle.circle = circle
  var baz = { circle }
  var a = { b, baz }
  var o = {
    a,
    bar: a
  }
  b.toJSON = function () {
    a.b = 2
    return '[Redacted]'
  }
  baz.toJSON = function () {
    a.baz = circle
    return '[Redacted]'
  }

  var expected = s({
    a: {
      b: '[Redacted]',
      baz: '[Redacted]'
    },
    bar: {
      b: 2,
      baz: {
        some: 'data',
        circle: '[Circular]'
      }
    }
  })
  var actual = fss(o)
  assert.is(actual, expected)
  assert.end()
})
<|endoftext|>


<commit_before>'use strict';
var test = require('ava');
var vkGot = require('./');

test('making requests', function (a) {
	return vkGot('users.get', {
		body: {
			userIds: 'sobo13v',
			v: '5.37'
		}
	}).then(function (res) {
		a.is(res.body.response[0].id, 15658953);
	});
});

test('accepting token', function (a) {
	return vkGot('users.get', {
		token: 'no token :('
	}).catch(function (err) {
		a.ok(err);
	});
});

test('requesting token', function (a) {
	return vkGot.token({
		body: {
			code: 'no code :(',
			clientId: 'nope',
			clientSecret: 'nope',
			redirectUri: 'http://localhost/code'
		}
	}).catch(function (err) {
		a.is(err.statusCode, 401);
	});
});
<commit_msg>100% coverage! :dizzy:<commit_after>'use strict';
var test = require('ava');
var vkGot = require('./');

test('cheking for method', function (a) {
	return vkGot().catch(function (err) {
		a.ok(err);
	});
});

test.serial('making requests', function (a) {
	return vkGot('users.get', {
		body: {
			userIds: 'sobo13v',
			v: '5.37'
		}
	}).then(function (res) {
		a.is(res.body.response[0].id, 15658953);
	});
});

test.serial('accepting token', function (a) {
	return vkGot('users.get', {
		token: 'no token :('
	}).catch(function (err) {
		a.ok(err);
	});
});

test.serial('requesting token', function (a) {
	return vkGot.token({
		body: {
			code: 'no code :(',
			clientId: 'nope',
			clientSecret: 'nope',
			redirectUri: 'http://localhost/code'
		}
	}).catch(function (err) {
		a.is(err.statusCode, 401);
	});
});
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-7-3 17:16:28<commit_after><|endoftext|>


<commit_before>var fs = require("fs");
var cs = require("colorplus").enable();
var crypto = require("crypto");

var file_system_tree = function()
{
	var r =
	{
		file_list:[],
		md5_map:[],
		show_scan_dir_flag:false,
		file_filter:undefined,
		default_filter:function(full_path, file_name)
		{
			if (!file_name.match(/.mp4$/)) return true;
			else return false;

		},
		scan_dir:function(target_dir)
		{
			this.file_list = [];
			this.md5_map = [];

			this.file_filter = this.default_filter;
			this.scan_dir_unit(target_dir);
			console.log(this.file_list.length);
		},
		scan_dir_unit:function(target_dir)
		{
			if (this.show_scan_dir_flag) console.log(("scan " + target_dir).bgred.yellow);
			var tmp_list = fs.readdirSync(target_dir);
			for (var key in tmp_list)
			{
				var r = {};
				r.file_name = tmp_list[key];
				r.full_path = target_dir + r.file_name;

				try
				{
					r.stat = fs.statSync(r.full_path);
				}
				catch (e)
				{
					console.log("Error".red);
					console.log(e);
					continue;
				}
				if (this.show_scan_dir_flag) console.log(full_path);
				if (r.stat.isDirectory())
				{
					if (this.show_scan_dir_flag) console.log("is dir".green);
					this.scan_dir_unit(r.full_path + "/");
				}
				else
				{

					if (this.show_scan_dir_flag) console.log("is not a dir".red);
					if (this.file_filter !== undefined)
					{
						if (this.file_filter(r.full_path, r.file_name))
						{
							console.log(r.file_name, "blocked by filter");
							continue;
						}
					}
					var hash = crypto.createHash('md5').update(r.full_path).digest("hex");
					console.log(hash);
					this.md5_map[hash] = this.file_list.length;
					r.md5 = hash;

					this.file_list.push(r);

				}
			}
		},
		query:function(query_in)
		{
			if (this.md5_map[query_in] !== undefined)
			{
				var at = this.md5_map[query_in];
				return this.file_list[at];
			}
			else return undefined;
		},

	}
	return r;
}

var PG = file_system_tree();
//PG.scan_dir("I:/sense/Anime/");
PG.scan_dir("/Users/PG/Dropbox/code/anime2/test_sample/src/");
//PG.scan_dir("");
var express = require('express');
var app = express();
var cons = require("consolidate");
app.engine("haml", cons.haml);
app.set("view engine", "haml");
app.set("views", __dirname + "/views");

app.get("/", function(req, res)
{
	console.log(req);
	res.send("Orihime (TM)");
});

app.get("/list", function(req, res)
{
	var output_buffer = "";
	for (var i = 0; i < PG.file_list.length; i++)
	{
		var file = PG.file_list[i];
		var tmp = "" + file.file_name + "
";
		output_buffer += tmp;
	}
	res.send(output_buffer);

});
app.get("/getfile/:file", function(req, res)
{

	var output_buffer = "";
	var query_result = PG.query(req.params["file"]);
	if (query_result !== undefined)
	{
		output_buffer += "
" + query_result.stat.size + "
";
		output_buffer += "
" + query_result.stat.atime + "
";
		output_buffer += "
" + query_result.stat.mtime + "
";
		output_buffer += "
" + query_result.stat.ctime + "
";
		output_buffer += query_result.file_name + "
";
		output_buffer += query_result.full_path + "
";
		output_buffer += "Yes
";
		output_buffer += " Download
";
	}
	else
	{
		output_buffer += req.params["file"] + "
";
		output_buffer += "No";
	}
	res.send(output_buffer);

});

app.get("/getfile/:file/go", function(req, res)
{

	var output_buffer = "";
	var query_result = PG.query(req.params["file"]);
	console.log(query_result);
	if (query_result !== undefined)
	{
		res.download(query_result.full_path);
	}
	else
	{
		res.send("Error");
	}

});

app.get("/haml", function(req, res)
{

	res.render("animecloud",
	{
		title:"test",
		title2:"t2",
		items:["1", "2", "3"],
		tmp123:"123123"

	});

});
app.use('/views', express.static(__dirname + '/views'));

app.listen(35101);<commit_msg>init function<commit_after>var fs = require("fs");
var cs = require("colorplus").enable();
var crypto = require("crypto");

var file_system_tree = function()
{
	var r =
	{
		file_list:[],
		md5_map:[],
		show_scan_dir_flag:true,
		file_filter:undefined,

		default_filter:function(full_path, file_name)
		{
			if (!file_name.match(/.mp4$/)) return true;
			else return false;
		},
		init:function()
		{
			this.file_list = [];
			this.md5_map = [];
			this.file_filter = this.default_filter;
		},
		scan_dir:function(target_dir)
		{
			this.scan_dir_unit(target_dir);
			console.log("scan_dir".green, this.file_list.length);
		},
		scan_dir_unit:function(target_dir)
		{
			if (this.show_scan_dir_flag) console.log(("scan " + target_dir).yellow);
			var tmp_list = fs.readdirSync(target_dir);
			for (var key in tmp_list)
			{
				var r = {};
				r.file_name = tmp_list[key];
				r.full_path = target_dir + r.file_name;

				try
				{
					r.stat = fs.statSync(r.full_path);
				}
				catch (e)
				{
					console.log("Error".red);
					console.log(e);
					continue;
				}
				if (r.stat.isDirectory())
				{
					this.scan_dir_unit(r.full_path + "/");
				}
				else
				{
					if (this.file_filter !== undefined)
					{
						if (this.file_filter(r.full_path, r.file_name))
						{
							//console.log(r.file_name, "blocked by filter");
							continue;
						}
					}
					var hash = crypto.createHash('md5').update(r.full_path).digest("hex");
					console.log(hash);
					this.md5_map[hash] = this.file_list.length;
					r.md5 = hash;

					this.file_list.push(r);

				}
			}
		},
		query:function(query_in)
		{
			if (this.md5_map[query_in] !== undefined)
			{
				var at = this.md5_map[query_in];
				return this.file_list[at];
			}
			else return undefined;
		},

	}
	return r;
}

var PG = file_system_tree();
//PG.scan_dir("I:/sense/Anime/");
PG.init();
PG.scan_dir("/Users/PG/Dropbox/code/anime2/test_sample/src/");

//PG.scan_dir("");
var express = require('express');
var app = express();
var cons = require("consolidate");
app.engine("haml", cons.haml);
app.set("view engine", "haml");
app.set("views", __dirname + "/views");

app.get("/", function(req, res)
{
	console.log(req);
	res.send("Orihime (TM)");
});

app.get("/list", function(req, res)
{
	var output_buffer = "";
	for (var i = 0; i < PG.file_list.length; i++)
	{
		var file = PG.file_list[i];
		var tmp = "" + file.file_name + "
";
		output_buffer += tmp;
	}
	res.send(output_buffer);

});
app.get("/getfile/:file", function(req, res)
{

	var output_buffer = "";
	var query_result = PG.query(req.params["file"]);
	if (query_result !== undefined)
	{
		output_buffer += "
" + query_result.stat.size + "
";
		output_buffer += "
" + query_result.stat.atime + "
";
		output_buffer += "
" + query_result.stat.mtime + "
";
		output_buffer += "
" + query_result.stat.ctime + "
";
		output_buffer += query_result.file_name + "
";
		output_buffer += query_result.full_path + "
";
		output_buffer += "Yes
";
		output_buffer += " Download
";
	}
	else
	{
		output_buffer += req.params["file"] + "
";
		output_buffer += "No";
	}
	res.send(output_buffer);

});

app.get("/getfile/:file/go", function(req, res)
{

	var output_buffer = "";
	var query_result = PG.query(req.params["file"]);
	console.log(query_result);
	if (query_result !== undefined)
	{
		res.download(query_result.full_path);
	}
	else
	{
		res.send("Error");
	}

});

app.get("/haml", function(req, res)
{

	res.render("animecloud",
	{
		title:"test",
		title2:"t2",
		items:["1", "2", "3"],
		tmp123:"123123"

	});

});
app.use('/views', express.static(__dirname + '/views'));

app.listen(35101);<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-7-24 01:49:25<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>var parse = require("./");

var t = parse("doo, *#foo > elem.bar[class$=bAz i]:not([ id *= \"2\" ])")({
	name: "elem",
	attribs: {class:"bar baz"},
	parent: {
		name: "elem",
		attribs: {id: "foo"}
	}
});
console.log("result:", !!t)<commit_msg>Restructured test, added performance test<commit_after>var parse = require("./"),
	testString = "doo, *#foo > elem.bar[class$=bAz i]:not([ id *= \"2\" ])",
	testDoc = {
		name: "elem",
		attribs: {class:"bar baz"},
		parent: {
			name: "elem",
			attribs: {id: "foo"}
		}
	};

console.log("result:", !!parse(testString)(testDoc))

try {
	console.log("Parsing took:", require("ben")(1e5, function(){parse(testString);})*1e3);
	parse = parse(testString);
	console.log("Executing took:", require("ben")(1e6, function(){parse(testDoc);})*1e3);
} catch(e){}<|endoftext|>


<commit_before>var assert = require('assert');
var five = require('./');

assert.equal(5, five(), 'Five should give you five');
assert.notEqual(6, five(), 'Five should not give you not five');

assert.equal(five.convertTo(5), 5);
assert.equal(five.convertTo(3), 3);
assert.equal(five.convertTo(665456), 665456);

assert.equal('⁵', five.upHigh(), 'An up high five should be a superscripted 5');
assert.equal('₅', five.downLow(), 'A down low five should be a subscripted 5');
assert.equal('V', five.roman(), 'A roman five should be a V');

assert.equal('خمسة', five.arabic(), 'A arabic five should be خمسة');
assert.equal('beş', five.azerbaijani(), 'A azerbaijani five should be beş');
assert.equal('bost', five.basque(), 'A basque five should be bost');
assert.equal('пяць', five.belarusian(), 'A belarusian five should be пяць');
assert.equal('pet', five.bosnian(), 'A bosnian five should be pet');
assert.equal('пет', five.bulgarian(), 'A bulgarian five should be пет');
assert.equal('cinc', five.catalan(), 'A catalan five should be cinc');
assert.equal('五', five.chinese(), 'A chinese five should be 五');
assert.equal('tahlapi', five.choctaw(), 'A choctaw five should be tahlapi');
assert.equal('pet', five.croatian(), 'A croatian five should be pet');
assert.equal('pět', five.czech(), 'A czech five should be pět');
assert.equal('mek', five.dothraki(), 'A dothraki five should be mek');
assert.equal('hen', five.dovah(), 'A dovah five should be hen');
assert.equal('vijf', five.dutch(), 'A dutch five should be vijf');
assert.equal('lempe', five.elvish(), 'A elvish five should be lempe');
assert.equal('five', five.english(), 'A english five should be five');
assert.equal('viis', five.estonian(), 'An estonian five should be viis');
assert.equal('viisi', five.finnish(), 'A finnish five should be viisi');
assert.equal('cinq', five.french(), 'A french five should be cinq');
assert.equal('fünf', five.german(), 'A german five should be fünf');
assert.equal('πέντε', five.greek(), 'A greek five should be πέντε');
assert.equal('חמש', five.hebrew(), 'A hebrew five should be חמש');
assert.equal('पांच', five.hindi(), 'A hindi five should be पांच');
assert.equal('öt', five.hungarian(), 'A hungarian five should be öt');
assert.equal('fimm', five.icelandic(), 'An icelandic five should be fimm');
assert.equal('lima', five.indonesian(), 'A indonesian five should be lima');
assert.equal('cúig', five.irish(), 'A irish five should be cúig');
assert.equal('cinque', five.italian(), 'A italian five should be cinque');
assert.equal('五', five.japanese(), 'A japanese five should be 五');
assert.equal('ಐದು', five.kannada(), 'A kannada five should be ಐದು');
assert.equal('vagh', five.klingon(), 'A klingon five should be vagh');
assert.equal('오', five.korean(), 'A korean five should be 오');
assert.equal('quinque', five.latin(), 'A latin five should be quinque');
assert.equal('pieci', five.latvian(), 'A latvian five should be pieci');
assert.equal('penki', five.lithuanian(), 'A lithuanian five should be penki');
assert.equal('таван', five.mongolian(), 'A mongolian five should be таван');
assert.equal('fem', five.norwegian(), 'A norwegian five should be fem');
assert.equal('پنج', five.persian(), 'A persian five should be پنج');
assert.equal('ivefay', five.piglatin(), 'A piglatin five should be ivefay');
assert.equal('pięć', five.polish(), 'A polish five should be pięć');
assert.equal('cinco', five.portuguese(), 'A portuguese five should be cinco');
assert.equal('cinci', five.romanian(), 'A romanian five should be cinci');
assert.equal('пять', five.russian(), 'A russian five should be пять');
assert.equal('pet', five.serbian(), 'A serbian five should be pet');
assert.equal('päť', five.slovakian(), 'A slovakian five should be päť');
assert.equal('pet', five.slovenian(), 'A slovenian five should be pet');
assert.equal('cinco', five.spanish(), 'A spanish five should be cinco');
assert.equal('fem', five.swedish(), 'A swedish five should be fem');
assert.equal('ஐந்து', five.tamil(), 'A tamil five should be ஐந்து');
assert.equal('ఐదు', five.telugu(), 'A telugu five should be ఐదు');
assert.equal('ห้า', five.thai(), 'A thai five should be ห้า');
assert.equal('beş', five.turkish(), 'A turkish five should be beş');
assert.equal('п’ять', five.ukrainian(), 'A ukrainian five should be п’ять');

assert.equal('.....', five.morseCode(), 'A five in morse code should be .....');
assert.equal('101', five.binary(), 'A binary five should be 101');
assert.equal('5', five.octal(), 'An octal five should be 5');
assert.equal('5', five.hex(), 'An hexadecimal five should be 5');
assert.equal('30056e1cab7a61d256fc8edd970d14f5', five.mdFive(), 'md5 checksum of "five" should be 30056e1cab7a61d256fc8edd970d14f5');

assert.equal('-5', five.negative(), 'A negative five should be -5');
assert.equal('FIVE', five.loud(), 'A loud five should be FIVE');
assert.equal('IVEFAY', five.loud('piglatin'), 'A loud five in Pig Latin should be IVEFAY');
assert.equal('ПЯТЬ', five.loud('russian'), 'A loud five in Russian should be ПЯТЬ');
assert.equal('S', five.smooth(), 'A smooth five should be S');

assert.equal('🕔', five.oclock(), 'A unicode symbol for five o\'clock should be U+1F554');

var now = new Date().valueOf();
var slowFive = five.tooSlow();
var finishes = new Date().valueOf();

assert.equal(5, slowFive, 'A too slow five should still be five');
assert.ok((finishes - now) > 500, 'A too slow five should take longer than 500 milliseconds to be returned, blocking execution and generally being a bad idea');

assert.equal(JSON.stringify(['Jackie','Tito','Jermaine','Marlon','Michael']), JSON.stringify(five.jackson()), 'A Jackson five should be the five members of the 70\'s pop family group the Jackson 5');

assert.equal(JSON.stringify(['Juwan Howard','Ray Jackson','Jimmy King','Jalen Rose','Chris Webber']), JSON.stringify(five.fab()), 'A fab five should be the 1991-1993 Michigan Mens Basketball Team');

assert.equal(true, five.isFive(five()));

assert.equal(JSON.stringify([5, 5]), JSON.stringify(five.filter([5, true, 5])));
assert.equal(JSON.stringify([5, 5, 5]), JSON.stringify(five.map([1, 2, 3])));
assert.equal(5, five.reduce([1, 2, 3]));

assert.equal('5678901234', five.rot('0123456789'), 'Numbers should be rotated');
assert.equal('fghijklmnopqrstuvwxyzabcde', five.rot('abcdefghijklmnopqrstuvwxyz'), 'Small letters should be rotated');
assert.equal('FGHIJKLMNOPQRSTUVWXYZABCDE', five.rot('ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 'Capital letters too');
assert.equal('$_$ -,- @.@?', five.rot('$_$ -,- @.@?'), 'Emoticons should not be rotated');

assert.equal(five * five, 25);
assert.equal(five + five, 10);
assert.equal(five / five, 1);
assert.equal(five - five, 0);
assert.equal((five / five) * (five), five);

var asyncTests = 1;
five.async(function(err, five) {
	assert.equal(err, null, 'Async should not result in an error.');
	assert.equal(five, 5, 'Async should pass 5 to callback.');
	asyncTests--;
});

setInterval(function() {
	if (!asyncTests) {
		process.exit(0);
	}
}, 100);
<commit_msg>added negative case for five.isFive<commit_after>var assert = require('assert');
var five = require('./');

assert.equal(5, five(), 'Five should give you five');
assert.notEqual(6, five(), 'Five should not give you not five');

assert.equal(five.convertTo(5), 5);
assert.equal(five.convertTo(3), 3);
assert.equal(five.convertTo(665456), 665456);

assert.equal('⁵', five.upHigh(), 'An up high five should be a superscripted 5');
assert.equal('₅', five.downLow(), 'A down low five should be a subscripted 5');
assert.equal('V', five.roman(), 'A roman five should be a V');

assert.equal('خمسة', five.arabic(), 'A arabic five should be خمسة');
assert.equal('beş', five.azerbaijani(), 'A azerbaijani five should be beş');
assert.equal('bost', five.basque(), 'A basque five should be bost');
assert.equal('пяць', five.belarusian(), 'A belarusian five should be пяць');
assert.equal('pet', five.bosnian(), 'A bosnian five should be pet');
assert.equal('пет', five.bulgarian(), 'A bulgarian five should be пет');
assert.equal('cinc', five.catalan(), 'A catalan five should be cinc');
assert.equal('五', five.chinese(), 'A chinese five should be 五');
assert.equal('tahlapi', five.choctaw(), 'A choctaw five should be tahlapi');
assert.equal('pet', five.croatian(), 'A croatian five should be pet');
assert.equal('pět', five.czech(), 'A czech five should be pět');
assert.equal('mek', five.dothraki(), 'A dothraki five should be mek');
assert.equal('hen', five.dovah(), 'A dovah five should be hen');
assert.equal('vijf', five.dutch(), 'A dutch five should be vijf');
assert.equal('lempe', five.elvish(), 'A elvish five should be lempe');
assert.equal('five', five.english(), 'A english five should be five');
assert.equal('viis', five.estonian(), 'An estonian five should be viis');
assert.equal('viisi', five.finnish(), 'A finnish five should be viisi');
assert.equal('cinq', five.french(), 'A french five should be cinq');
assert.equal('fünf', five.german(), 'A german five should be fünf');
assert.equal('πέντε', five.greek(), 'A greek five should be πέντε');
assert.equal('חמש', five.hebrew(), 'A hebrew five should be חמש');
assert.equal('पांच', five.hindi(), 'A hindi five should be पांच');
assert.equal('öt', five.hungarian(), 'A hungarian five should be öt');
assert.equal('fimm', five.icelandic(), 'An icelandic five should be fimm');
assert.equal('lima', five.indonesian(), 'A indonesian five should be lima');
assert.equal('cúig', five.irish(), 'A irish five should be cúig');
assert.equal('cinque', five.italian(), 'A italian five should be cinque');
assert.equal('五', five.japanese(), 'A japanese five should be 五');
assert.equal('ಐದು', five.kannada(), 'A kannada five should be ಐದು');
assert.equal('vagh', five.klingon(), 'A klingon five should be vagh');
assert.equal('오', five.korean(), 'A korean five should be 오');
assert.equal('quinque', five.latin(), 'A latin five should be quinque');
assert.equal('pieci', five.latvian(), 'A latvian five should be pieci');
assert.equal('penki', five.lithuanian(), 'A lithuanian five should be penki');
assert.equal('таван', five.mongolian(), 'A mongolian five should be таван');
assert.equal('fem', five.norwegian(), 'A norwegian five should be fem');
assert.equal('پنج', five.persian(), 'A persian five should be پنج');
assert.equal('ivefay', five.piglatin(), 'A piglatin five should be ivefay');
assert.equal('pięć', five.polish(), 'A polish five should be pięć');
assert.equal('cinco', five.portuguese(), 'A portuguese five should be cinco');
assert.equal('cinci', five.romanian(), 'A romanian five should be cinci');
assert.equal('пять', five.russian(), 'A russian five should be пять');
assert.equal('pet', five.serbian(), 'A serbian five should be pet');
assert.equal('päť', five.slovakian(), 'A slovakian five should be päť');
assert.equal('pet', five.slovenian(), 'A slovenian five should be pet');
assert.equal('cinco', five.spanish(), 'A spanish five should be cinco');
assert.equal('fem', five.swedish(), 'A swedish five should be fem');
assert.equal('ஐந்து', five.tamil(), 'A tamil five should be ஐந்து');
assert.equal('ఐదు', five.telugu(), 'A telugu five should be ఐదు');
assert.equal('ห้า', five.thai(), 'A thai five should be ห้า');
assert.equal('beş', five.turkish(), 'A turkish five should be beş');
assert.equal('п’ять', five.ukrainian(), 'A ukrainian five should be п’ять');

assert.equal('.....', five.morseCode(), 'A five in morse code should be .....');
assert.equal('101', five.binary(), 'A binary five should be 101');
assert.equal('5', five.octal(), 'An octal five should be 5');
assert.equal('5', five.hex(), 'An hexadecimal five should be 5');
assert.equal('30056e1cab7a61d256fc8edd970d14f5', five.mdFive(), 'md5 checksum of "five" should be 30056e1cab7a61d256fc8edd970d14f5');

assert.equal('-5', five.negative(), 'A negative five should be -5');
assert.equal('FIVE', five.loud(), 'A loud five should be FIVE');
assert.equal('IVEFAY', five.loud('piglatin'), 'A loud five in Pig Latin should be IVEFAY');
assert.equal('ПЯТЬ', five.loud('russian'), 'A loud five in Russian should be ПЯТЬ');
assert.equal('S', five.smooth(), 'A smooth five should be S');

assert.equal('🕔', five.oclock(), 'A unicode symbol for five o\'clock should be U+1F554');

var now = new Date().valueOf();
var slowFive = five.tooSlow();
var finishes = new Date().valueOf();

assert.equal(5, slowFive, 'A too slow five should still be five');
assert.ok((finishes - now) > 500, 'A too slow five should take longer than 500 milliseconds to be returned, blocking execution and generally being a bad idea');

assert.equal(JSON.stringify(['Jackie','Tito','Jermaine','Marlon','Michael']), JSON.stringify(five.jackson()), 'A Jackson five should be the five members of the 70\'s pop family group the Jackson 5');

assert.equal(JSON.stringify(['Juwan Howard','Ray Jackson','Jimmy King','Jalen Rose','Chris Webber']), JSON.stringify(five.fab()), 'A fab five should be the 1991-1993 Michigan Mens Basketball Team');

assert.equal(true, five.isFive(five()));
assert.equal(false, five.isFive(10));

assert.equal(JSON.stringify([5, 5]), JSON.stringify(five.filter([5, true, 5])));
assert.equal(JSON.stringify([5, 5, 5]), JSON.stringify(five.map([1, 2, 3])));
assert.equal(5, five.reduce([1, 2, 3]));

assert.equal('5678901234', five.rot('0123456789'), 'Numbers should be rotated');
assert.equal('fghijklmnopqrstuvwxyzabcde', five.rot('abcdefghijklmnopqrstuvwxyz'), 'Small letters should be rotated');
assert.equal('FGHIJKLMNOPQRSTUVWXYZABCDE', five.rot('ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 'Capital letters too');
assert.equal('$_$ -,- @.@?', five.rot('$_$ -,- @.@?'), 'Emoticons should not be rotated');

assert.equal(five * five, 25);
assert.equal(five + five, 10);
assert.equal(five / five, 1);
assert.equal(five - five, 0);
assert.equal((five / five) * (five), five);

var asyncTests = 1;
five.async(function(err, five) {
	assert.equal(err, null, 'Async should not result in an error.');
	assert.equal(five, 5, 'Async should pass 5 to callback.');
	asyncTests--;
});

setInterval(function() {
	if (!asyncTests) {
		process.exit(0);
	}
}, 100);
<|endoftext|>


<commit_before>var test = require('tape');
var Observable = require('./observer.js');
test('ObservableAddObserverTest', function(assert) {
	var observable = new Observable();
	var observer = function() {};

	observable.addObserver(observer);

	assert.equal(observer, observable.observers[0]);
	assert.end();
});

test('ObservableHasObserverTest', function(assert) {
	var observable = new Observable();
	var observer = function(){};
	observable.addObserver(observer);
	assert.ok(observable.hasObserver(observer));
	assert.end();
})

test('test should return false when no observers', function(assert) {
	var observable = new Observable();
	assert.notOk(observable.hasObserver(function(){}))
	assert.end();
})
<commit_msg>test should store functions passes<commit_after>var test = require('tape');
var Observable = require('./observer.js');
test('ObservableAddObserverTest', function(assert) {
	var observable = new Observable();
	var observer = function() {};

	observable.addObserver(observer);

	assert.equal(observer, observable.observers[0]);
	assert.end();
});

test('ObservableHasObserverTest', function(assert) {
	var observable = new Observable();
	var observer = function(){};
	observable.addObserver(observer);
	assert.ok(observable.hasObserver(observer));
	assert.end();
})

test('test should return false when no observers', function(assert) {
	var observable = new Observable();
	assert.notOk(observable.hasObserver(function(){}))
	assert.end();
})

test('test should store functions', function(assert) {
	var observable = new Observable();
	var observers = [function(){}, function(){}];

	observable.addObserver(observers[0]);
	observable.addObserver(observers[1]);

	assert.ok(observable.hasObserver(observers[0]));
	assert.ok(observable.hasObserver(observers[1]));

	assert.end();
})
<|endoftext|>


<commit_before>var browserify   = require('browserify');
var watchify     = require('watchify');
var bundleLogger = require('../util/bundle-logger');
var gulp         = require('gulp');
var handleErrors = require('../util/handle-errors');
var source       = require('vinyl-source-stream');
var streamify 	 = require('gulp-streamify');
var uglify			 = require('gulp-uglify');

gulp.task('browserify', function() {

	var bundleMethod = global.isWatching ? watchify : browserify;

	var bundler = bundleMethod({
		// Specify the entry point of your app
		entries: ['./src/app.js'],
		// Add file extentions to make optional in your requires
		extensions: ['.js', '.ractive'],
		debug: true
	});

	var bundle = function() {
		// Log when bundling starts
		bundleLogger.start();

		return bundler
			// Enable source maps!
			.bundle()
			// Report compile errors
			.on('error', handleErrors)
			// Use vinyl-source-stream to make the
			// stream gulp compatible. Specifiy the
			// desired output filename here.
			.pipe(source('app.js'))
			// Streamify + uglify, since gulp-uglify doesn't like streaming
			.pipe(streamify(uglify()))
			// Specify the output destination
			.pipe(gulp.dest('./public/js/'))
			// Log when bundling completes!
			.on('end', bundleLogger.end);
	};

	if(global.isWatching) {
		// Rebundle with watchify on changes.
		bundler.on('update', bundle);
	}

	return bundle();
});
<commit_msg>Tweaks to browserify task in hopes of fixing source map stupids<commit_after>var browserify   = require('browserify');
var watchify     = require('watchify');
var bundleLogger = require('../util/bundle-logger');
var gulp         = require('gulp');
var handleErrors = require('../util/handle-errors');
var source       = require('vinyl-source-stream');
var streamify 	 = require('gulp-streamify');
var uglify			 = require('gulp-uglify');

gulp.task('browserify', function() {

	var bundleMethod = global.isWatching ? watchify : browserify;

	var bundler = bundleMethod({
		// Specify the entry point of your app
		entries: ['./src/app.js'],
		// Add file extentions to make optional in your requires
		extensions: ['.js', '.ractive'],
		debug: true
	});

	var bundle = function() {
		// Log when bundling starts
		bundleLogger.start();

		return bundler
			.bundle()
			// Report compile errors
			.on('error', handleErrors)
			// Use vinyl-source-stream to make the
			// stream gulp compatible. Specifiy the
			// desired output filename here.
			.pipe(source('app.js'))
			// Streamify + uglify, since gulp-uglify doesn't like streaming
			.pipe(streamify(uglify({
				preserveComments: 'all'
			})))
			// Specify the output destination
			.pipe(gulp.dest('./public/js/'))
			// Log when bundling completes!
			.on('end', bundleLogger.end);
	};

	if(global.isWatching) {
		// Rebundle with watchify on changes.
		bundler.on('update', bundle);
	}

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


<commit_before>'use strict';
const jsonQuery = require('json-query')
const data = require('./data.js');
//sync request (even it is implemented with promises)
const  get_source_at = function(uri){
    var source;
      let request = require('request');
    request({ uri:uri}, function (error, response, body) {
        source = body;
        console.log(body);
    });
    while(source === undefined) {
      require('deasync').runLoopOnce();
    }
    return source;
};
// return parameteres
const get_parameters=function(){
    return jsonQuery('result.contexts[name=datakeeper]', {
          data: requestBody
      }).value.parameters
}
module.exports = {
  infographic_1(parameterscontextout,requestBody){

      // examples of query context
      let original_city=get_parameters().original_city;
     // use API (sync request) to get country for the original city

     let res=get_source_at('http://gd.geobytes.com/AutoCompleteCity?callback=?&q='+original_city)

    let countries=JSON.parse(res.substr(2).slice(0, -2));

    let country="";

    // check that country is not United State or Canada and country was not assign yet
    countries.forEach(function(element) {
        if(!element.includes("United States")){
            if(!element.includes("Canada")){
                if(country==""){
                    // extract just the country from the response
                    country=element.split(',')[element.split(',').length-1].substr(1);
                }
            }
        }
    })

    // get comperision data for this country
    let country_data=jsonQuery('body[Country='+country+']', {
        data: data.country_data
    }).value;

    parameterscontextout["Infographics"]={number:1,data:{country_data:country_data}};
  },
  infographic_2(parameterscontextout,requestBody){
      parameterscontextout["Infographics"]={number:2};
  },
  infographic_3(parameterscontextout,requestBody){
    let area_to_stay=get_parameters().area_to_stay;

    let area_data=jsonQuery('body[Name_of_area='+area_to_stay+']', {
        data: data.area_data
    }).value;

    parameterscontextout["Infographics"]={number:3,area_to_stay:area_data};
  },
   infographic_10(parameterscontextout,requestBody){

      // examples of query context
      let original_city=jsonQuery('result.contexts[name=datakeeper]', {
          data: requestBody
      }).value.parameters.original_city
      let area_to_stay=jsonQuery('result.contexts[name=datakeeper]', {
          data: requestBody
      }).value.parameters.area_to_stay[0]
      let flattype_to_stay=jsonQuery('result.contexts[name=datakeeper]', {
          data: requestBody
      }).value.parameters.flattype_to_stay[0]
      let TransportationType=jsonQuery('result.contexts[name=datakeeper]', {
          data: requestBody
      }).value.parameters.TransportationType[0]
      let TimesAWeek=jsonQuery('result.contexts[name=datakeeper]', {
          data: requestBody
      }).value.parameters.TimesAWeek

      let country_data=jsonQuery('body[Country=Netherlands]', {
          data: data.country_data
      }).value;

      parameterscontextout["Infographics"]={number:1,data:{country_data:country_data}};
  }

};

<commit_msg>automatic push<commit_after>'use strict';
const jsonQuery = require('json-query')
const data = require('./data.js');
//sync request (even it is implemented with promises)
const  get_source_at = function(uri){
    var source;
      let request = require('request');
    request({ uri:uri}, function (error, response, body) {
        source = body;
        console.log(body);
    });
    while(source === undefined) {
      require('deasync').runLoopOnce();
    }
    return source;
};
// return parameteres
const get_parameters=function(requestBody){
    return jsonQuery('result.contexts[name=datakeeper]', {
          data: requestBody
      }).value.parameters
}
module.exports = {
  infographic_1(parameterscontextout,requestBody){

      // examples of query context
      let original_city=get_parameters(requestBody).original_city;
     // use API (sync request) to get country for the original city

     let res=get_source_at('http://gd.geobytes.com/AutoCompleteCity?callback=?&q='+original_city)

    let countries=JSON.parse(res.substr(2).slice(0, -2));

    let country="";

    // check that country is not United State or Canada and country was not assign yet
    countries.forEach(function(element) {
        if(!element.includes("United States")){
            if(!element.includes("Canada")){
                if(country==""){
                    // extract just the country from the response
                    country=element.split(',')[element.split(',').length-1].substr(1);
                }
            }
        }
    })

    // get comperision data for this country
    let country_data=jsonQuery('body[Country='+country+']', {
        data: data.country_data
    }).value;

    parameterscontextout["Infographics"]={number:1,data:{country_data:country_data}};
  },
  infographic_2(parameterscontextout,requestBody){
      parameterscontextout["Infographics"]={number:2};
  },
  infographic_3(parameterscontextout,requestBody){
    let area_to_stay=get_parameters(requestBody).area_to_stay;

    let area_data=jsonQuery('body[Name_of_area='+area_to_stay+']', {
        data: data.area_data
    }).value;

    parameterscontextout["Infographics"]={number:3,area_to_stay:area_data};
  },
   infographic_10(parameterscontextout,requestBody){

      // examples of query context
      let original_city=jsonQuery('result.contexts[name=datakeeper]', {
          data: requestBody
      }).value.parameters.original_city
      let area_to_stay=jsonQuery('result.contexts[name=datakeeper]', {
          data: requestBody
      }).value.parameters.area_to_stay[0]
      let flattype_to_stay=jsonQuery('result.contexts[name=datakeeper]', {
          data: requestBody
      }).value.parameters.flattype_to_stay[0]
      let TransportationType=jsonQuery('result.contexts[name=datakeeper]', {
          data: requestBody
      }).value.parameters.TransportationType[0]
      let TimesAWeek=jsonQuery('result.contexts[name=datakeeper]', {
          data: requestBody
      }).value.parameters.TimesAWeek

      let country_data=jsonQuery('body[Country=Netherlands]', {
          data: data.country_data
      }).value;

      parameterscontextout["Infographics"]={number:1,data:{country_data:country_data}};
  }

};

<|endoftext|>


<commit_before>dojo.provide("dijit.tests.layout.module");

try{
	doh.registerUrl("dijit.tests.layout.ContentPane", dojo.moduleUrl("dijit", "tests/layout/ContentPane.html"), 30000);
	doh.registerUrl("dijit.tests.layout.ContentPaneLayout", dojo.moduleUrl("dijit", "tests/layout/ContentPaneLayout.html"), 30000);
	doh.registerUrl("dijit.tests.layout.AccordionContainer", dojo.moduleUrl("dijit", "tests/layout/AccordionContainer.html"), 30000);
	doh.registerUrl("dijit.tests.layout.TabContainer", dojo.moduleUrl("dijit", "tests/layout/TabContainer.html"), 30000);
	doh.registerUrl("dijit.tests.layout.robot.TabContainer_a11y", dojo.moduleUrl("dijit","tests/layout/robot/TabContainer_a11y.html"), 99999999);
	doh.registerUrl("dijit.tests.layout.robot.TabContainer_mouse", dojo.moduleUrl("dijit","tests/layout/robot/TabContainer_mouse.html"), 99999999);
	doh.registerUrl("dijit.tests.layout.StackContainer", dojo.moduleUrl("dijit", "tests/layout/nestedStack.html"));
}catch(e){
	doh.debug(e);
}
<commit_msg>!ContentPaneLayout.html needs more than 30s to run.  Refs #7681.<commit_after>dojo.provide("dijit.tests.layout.module");

try{
	doh.registerUrl("dijit.tests.layout.ContentPane", dojo.moduleUrl("dijit", "tests/layout/ContentPane.html"), 99999999);
	doh.registerUrl("dijit.tests.layout.ContentPaneLayout", dojo.moduleUrl("dijit", "tests/layout/ContentPaneLayout.html"), 99999999);
	doh.registerUrl("dijit.tests.layout.AccordionContainer", dojo.moduleUrl("dijit", "tests/layout/AccordionContainer.html"), 99999999);
	doh.registerUrl("dijit.tests.layout.TabContainer", dojo.moduleUrl("dijit", "tests/layout/TabContainer.html"), 99999999);
	doh.registerUrl("dijit.tests.layout.robot.TabContainer_a11y", dojo.moduleUrl("dijit","tests/layout/robot/TabContainer_a11y.html"), 99999999);
	doh.registerUrl("dijit.tests.layout.robot.TabContainer_mouse", dojo.moduleUrl("dijit","tests/layout/robot/TabContainer_mouse.html"), 99999999);
	doh.registerUrl("dijit.tests.layout.StackContainer", dojo.moduleUrl("dijit", "tests/layout/nestedStack.html"));
}catch(e){
	doh.debug(e);
}
<|endoftext|>


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

import style from '../../style/vanilla/css/footer.css';
import gridStyle from '../../style/vanilla/css/grid.css';

export default class Footer extends Component {

  backToTop(event) {
    event.preventDefault();
    document.body.scrollTo(0,0);
  }

  render() {
    return (
      <footer className={`${style['p-footer']} ${style['p-strip--light']} ${style['p-sticky-footer']}`}>

                    Back to top

              © 2019 Canonical Ltd.
 Ubuntu and Canonical are registered trademarks of Canonical Ltd.

              Powered by the Charmed Distribution of Kubernetes

              Join the forum, contribute to or report problems with
              {' '}
              snapd,
              {' '}
              Snapcraft,
              {' '}
              or
              {' '}
              this site.
              {' '}·{' '}

                  Legal information

                  Data privacy

                  Service status

                  Other functions

                  We’re hiring!

                Share on Twitter

                Share on Facebook

                Share on YouTube

    );
  }
}
<commit_msg>Removed CDK reference from the footer until further notice<commit_after>import React, { Component } from 'react';

import style from '../../style/vanilla/css/footer.css';
import gridStyle from '../../style/vanilla/css/grid.css';

export default class Footer extends Component {

  backToTop(event) {
    event.preventDefault();
    document.body.scrollTo(0,0);
  }

  render() {
    return (
      <footer className={`${style['p-footer']} ${style['p-strip--light']} ${style['p-sticky-footer']}`}>

                    Back to top

              © 2019 Canonical Ltd.
 Ubuntu and Canonical are registered trademarks of Canonical Ltd.

              Join the forum, contribute to or report problems with
              {' '}
              snapd,
              {' '}
              Snapcraft,
              {' '}
              or
              {' '}
              this site.
              {' '}·{' '}

                  Legal information

                  Data privacy

                  Service status

                  Other functions

                  We’re hiring!

                Share on Twitter

                Share on Facebook

                Share on YouTube

    );
  }
}
<|endoftext|>


<commit_before>var addSrc = require('gulp-add-src');
var cleancss = require('gulp-clean-css');
var customizer = require('../../customizer/lib');
var Vinyl = require('vinyl');
var fs = require('fs');
var gulp = require('gulp');
var If = require('gulp-if');
var path = require('path');
var Readable = require('stream').Readable;
var replace = require('gulp-replace');
var rename = require('gulp-rename');
var rimraf = require('rimraf');
var sass = require('gulp-sass');
var uglify = require('gulp-uglify');
var yaml = require('js-yaml').safeLoad;
var zip = require('gulp-zip');
var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer');
var webpackStream = require('webpack-stream');
var webpack = require('webpack');

var utils = require('../utils.js');
var processedArgv = utils.getProccessedArgv();

var FOUNDATION_VERSION = require('../../package.json').version;
var OUTPUT_DIR = processedArgv.values['--output'] || 'custom-build';
var CUSTOMIZER_CONFIG;
var MODULE_LIST;
var VARIABLE_LIST;

var WEBPACK_CONFIG = {
  mode: 'development',
  externals: utils.umdExternals({
    'jquery': 'jQuery'
  }),
  module: {
    rules: [
      {
        test: /.js$/,
        use: [
          {
            loader: 'babel-loader'
          }
        ]
      }
    ]
  },
  output: {
    libraryTarget: 'umd',
  }
};

// Load the configuration file for the customizer. It's a list of modules to load and Sass variables to override
gulp.task('customizer:loadConfig', function(done) {
  fs.readFile('customizer/config.yml', function(err, data) {
    var moduleListPath = processedArgv.values['--modules'] || '../../customizer/complete';
    var moduleList = require(moduleListPath);

    CUSTOMIZER_CONFIG = yaml(data.toString());
    MODULE_LIST = moduleList.modules;
    VARIABLE_LIST = moduleList.variables || {};
    done();
  });
});

// Prepare dependencies
gulp.task('customizer:prepareSassDeps', function() {
  return gulp.src([
      'node_modules/@(sassy-lists)/stylesheets/helpers/missing-dependencies',
      'node_modules/@(sassy-lists)/stylesheets/helpers/true',
      'node_modules/@(sassy-lists)/stylesheets/functions/contain',
      'node_modules/@(sassy-lists)/stylesheets/functions/purge',
      'node_modules/@(sassy-lists)/stylesheets/functions/remove',
      'node_modules/@(sassy-lists)/stylesheets/functions/replace',
      'node_modules/@(sassy-lists)/stylesheets/functions/to-list'
    ])
    .pipe(gulp.dest('_vendor'));
});

// Creates a Sass file from the module/variable list and creates foundation.css and foundation.min.css
gulp.task('customizer:sass', gulp.series('customizer:loadConfig', 'customizer:prepareSassDeps', function() {
  var sassFile = customizer.sass(CUSTOMIZER_CONFIG, MODULE_LIST, VARIABLE_LIST);
  var stream = createStream('foundation.scss', sassFile);

  return stream
    .pipe(sass({
      includePaths: [
        'scss',
        'node_modules/motion-ui/src'
      ]
    }))
    .pipe(postcss([autoprefixer()])) // uses ".browserslistrc"
    .pipe(gulp.dest(path.join(OUTPUT_DIR, 'css')))
    .pipe(cleancss({ compatibility: 'ie9' }))
    .pipe(rename('foundation.min.css'))
    .pipe(gulp.dest(path.join(OUTPUT_DIR, 'css')))
}));

// Creates a Foundation JavaScript file from the module list, and also copies dependencies (jQuery, what-input)
gulp.task('customizer:javascript-entry', gulp.series('customizer:loadConfig', function() {
  var entryFile = customizer.js(CUSTOMIZER_CONFIG, MODULE_LIST);
  // Create a stream with our entry file
  var stream = createStream('foundation.js', entryFile);

  return stream
    .pipe(gulp.dest(path.join(OUTPUT_DIR, 'js/vendor')));
}));

gulp.task('customizer:javascript', gulp.series('customizer:javascript-entry', function() {
  return gulp.src(path.join(OUTPUT_DIR, 'js/vendor/foundation.js'))
    .pipe(webpackStream(WEBPACK_CONFIG, webpack))
    .pipe(rename('foundation.js'))
    .pipe(gulp.dest(path.join(OUTPUT_DIR, 'js/vendor')))
    .pipe(uglify())
    .pipe(rename('foundation.min.js'))
    .pipe(addSrc([
      'node_modules/jquery/dist/jquery.js',
      'node_modules/what-input/dist/what-input.js'
    ]))
    .pipe(gulp.dest(path.join(OUTPUT_DIR, 'js/vendor')));
}));

// Copies the boilerplate index.html to the custom download folder
gulp.task('customizer:html', gulp.series('customizer:loadConfig', function() {
  var rtlEnabled = VARIABLE_LIST['global-text-direction'] && VARIABLE_LIST['global-text-direction'] === 'rtl';

  return gulp.src('customizer/index.html')
    .pipe(If(rtlEnabled, replace('ltr', 'rtl')))
    .pipe(gulp.dest(OUTPUT_DIR));
}));

// Add main CSS and JS files to the build directory and create a ZIP file from it.
gulp.task('customizer:zip', function (done) {
  var outputFolder = path.dirname(OUTPUT_DIR);
  var outputFileName = path.basename(OUTPUT_DIR);

  fs.closeSync(fs.openSync(path.join(OUTPUT_DIR, 'css/app.css', 'w')));
  fs.closeSync(fs.openSync(path.join(OUTPUT_DIR, 'js/app.js', 'w')));
  fs.writeFileSync(path.join(OUTPUT_DIR, 'js/app.js'), '$(document).foundation()\n');

  return gulp.src(path.join(OUTPUT_DIR, '/**/*'))
    .pipe(zip(path.basename(outputFileName) + '.zip'))
    .pipe(gulp.dest(outputFolder));
});

// Clean the build directory
gulp.task('customizer:clean', function(done) {
  rimraf(OUTPUT_DIR, done);
});

// Creates a custom build by:
//   - Generating a CSS file
//   - Generating a JS file
//   - Copying the index.html file
//   - Creating a blank app.css file
//   - Creating an app.js file with Foundation initialization code
gulp.task('customizer', gulp.series('customizer:sass', 'customizer:javascript', 'customizer:html', 'customizer:zip', 'customizer:clean'));

function createStream(name, content) {
  // Create a stream with our entry file
  var stream = new Readable({ objectMode: true });
  stream._read = function() {};
  stream.push(new Vinyl({
    path: name,
    contents: new Buffer(content)
  }));
  stream.push(null);
  return stream;
}
<commit_msg>Fix parameter position<commit_after>var addSrc = require('gulp-add-src');
var cleancss = require('gulp-clean-css');
var customizer = require('../../customizer/lib');
var Vinyl = require('vinyl');
var fs = require('fs');
var gulp = require('gulp');
var If = require('gulp-if');
var path = require('path');
var Readable = require('stream').Readable;
var replace = require('gulp-replace');
var rename = require('gulp-rename');
var rimraf = require('rimraf');
var sass = require('gulp-sass');
var uglify = require('gulp-uglify');
var yaml = require('js-yaml').safeLoad;
var zip = require('gulp-zip');
var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer');
var webpackStream = require('webpack-stream');
var webpack = require('webpack');

var utils = require('../utils.js');
var processedArgv = utils.getProccessedArgv();

var FOUNDATION_VERSION = require('../../package.json').version;
var OUTPUT_DIR = processedArgv.values['--output'] || 'custom-build';
var CUSTOMIZER_CONFIG;
var MODULE_LIST;
var VARIABLE_LIST;

var WEBPACK_CONFIG = {
  mode: 'development',
  externals: utils.umdExternals({
    'jquery': 'jQuery'
  }),
  module: {
    rules: [
      {
        test: /.js$/,
        use: [
          {
            loader: 'babel-loader'
          }
        ]
      }
    ]
  },
  output: {
    libraryTarget: 'umd',
  }
};

// Load the configuration file for the customizer. It's a list of modules to load and Sass variables to override
gulp.task('customizer:loadConfig', function(done) {
  fs.readFile('customizer/config.yml', function(err, data) {
    var moduleListPath = processedArgv.values['--modules'] || '../../customizer/complete';
    var moduleList = require(moduleListPath);

    CUSTOMIZER_CONFIG = yaml(data.toString());
    MODULE_LIST = moduleList.modules;
    VARIABLE_LIST = moduleList.variables || {};
    done();
  });
});

// Prepare dependencies
gulp.task('customizer:prepareSassDeps', function() {
  return gulp.src([
      'node_modules/@(sassy-lists)/stylesheets/helpers/missing-dependencies',
      'node_modules/@(sassy-lists)/stylesheets/helpers/true',
      'node_modules/@(sassy-lists)/stylesheets/functions/contain',
      'node_modules/@(sassy-lists)/stylesheets/functions/purge',
      'node_modules/@(sassy-lists)/stylesheets/functions/remove',
      'node_modules/@(sassy-lists)/stylesheets/functions/replace',
      'node_modules/@(sassy-lists)/stylesheets/functions/to-list'
    ])
    .pipe(gulp.dest('_vendor'));
});

// Creates a Sass file from the module/variable list and creates foundation.css and foundation.min.css
gulp.task('customizer:sass', gulp.series('customizer:loadConfig', 'customizer:prepareSassDeps', function() {
  var sassFile = customizer.sass(CUSTOMIZER_CONFIG, MODULE_LIST, VARIABLE_LIST);
  var stream = createStream('foundation.scss', sassFile);

  return stream
    .pipe(sass({
      includePaths: [
        'scss',
        'node_modules/motion-ui/src'
      ]
    }))
    .pipe(postcss([autoprefixer()])) // uses ".browserslistrc"
    .pipe(gulp.dest(path.join(OUTPUT_DIR, 'css')))
    .pipe(cleancss({ compatibility: 'ie9' }))
    .pipe(rename('foundation.min.css'))
    .pipe(gulp.dest(path.join(OUTPUT_DIR, 'css')))
}));

// Creates a Foundation JavaScript file from the module list, and also copies dependencies (jQuery, what-input)
gulp.task('customizer:javascript-entry', gulp.series('customizer:loadConfig', function() {
  var entryFile = customizer.js(CUSTOMIZER_CONFIG, MODULE_LIST);
  // Create a stream with our entry file
  var stream = createStream('foundation.js', entryFile);

  return stream
    .pipe(gulp.dest(path.join(OUTPUT_DIR, 'js/vendor')));
}));

gulp.task('customizer:javascript', gulp.series('customizer:javascript-entry', function() {
  return gulp.src(path.join(OUTPUT_DIR, 'js/vendor/foundation.js'))
    .pipe(webpackStream(WEBPACK_CONFIG, webpack))
    .pipe(rename('foundation.js'))
    .pipe(gulp.dest(path.join(OUTPUT_DIR, 'js/vendor')))
    .pipe(uglify())
    .pipe(rename('foundation.min.js'))
    .pipe(addSrc([
      'node_modules/jquery/dist/jquery.js',
      'node_modules/what-input/dist/what-input.js'
    ]))
    .pipe(gulp.dest(path.join(OUTPUT_DIR, 'js/vendor')));
}));

// Copies the boilerplate index.html to the custom download folder
gulp.task('customizer:html', gulp.series('customizer:loadConfig', function() {
  var rtlEnabled = VARIABLE_LIST['global-text-direction'] && VARIABLE_LIST['global-text-direction'] === 'rtl';

  return gulp.src('customizer/index.html')
    .pipe(If(rtlEnabled, replace('ltr', 'rtl')))
    .pipe(gulp.dest(OUTPUT_DIR));
}));

// Add main CSS and JS files to the build directory and create a ZIP file from it.
gulp.task('customizer:zip', function (done) {
  var outputFolder = path.dirname(OUTPUT_DIR);
  var outputFileName = path.basename(OUTPUT_DIR);

  fs.closeSync(fs.openSync(path.join(OUTPUT_DIR, 'css/app.css'), 'w'));
  fs.closeSync(fs.openSync(path.join(OUTPUT_DIR, 'js/app.js'), 'w'));
  fs.writeFileSync(path.join(OUTPUT_DIR, 'js/app.js'), '$(document).foundation()\n');

  return gulp.src(path.join(OUTPUT_DIR, '/**/*'))
    .pipe(zip(path.basename(outputFileName) + '.zip'))
    .pipe(gulp.dest(outputFolder));
});

// Clean the build directory
gulp.task('customizer:clean', function(done) {
  rimraf(OUTPUT_DIR, done);
});

// Creates a custom build by:
//   - Generating a CSS file
//   - Generating a JS file
//   - Copying the index.html file
//   - Creating a blank app.css file
//   - Creating an app.js file with Foundation initialization code
gulp.task('customizer', gulp.series('customizer:sass', 'customizer:javascript', 'customizer:html', 'customizer:zip', 'customizer:clean'));

function createStream(name, content) {
  // Create a stream with our entry file
  var stream = new Readable({ objectMode: true });
  stream._read = function() {};
  stream.push(new Vinyl({
    path: name,
    contents: new Buffer(content)
  }));
  stream.push(null);
  return stream;
}
<|endoftext|>


<commit_before>(function(){
	'use strict';
	QUnit.module('Thruster.Math.Vector2d');

	QUnit.test('Constructor', function(assert){
		// New from constructor.
		var vector = new Thruster.Math.Vector2d(3, 4);
		assert.equal(vector.x, 3, 'x value is set correctly.');
		assert.equal(vector.y, 4, 'y value is set correctly.');
	});

	QUnit.test('clone()', function(assert){
		// Clone from existing Vector2d.
		var vector = new Thruster.Math.Vector2d(3, 4);
		var clonedVector = vector.clone();
		assert.notEqual(clonedVector, vector, 'Returns a new separate object from the original.');
		assert.equal(clonedVector.x, vector.x, 'x value is the same as the original.');
		assert.equal(clonedVector.y, vector.y, 'y value is the same as the original.');
	});

	QUnit.test('fromComponents()', function(assert){
		// New Vector2d from angle and length.
		var vector = Thruster.Math.Vector2d.fromComponents(Math.PI / 6, 4);
		assert.equal(vector.x, 3.464101615137755, 'x value is set correctly.');
		assert.equal(vector.y, 1.9999999999999998, 'y value is set correctly.');
	});

	QUnit.test('add()', function(assert){
		// Add vector2 to vector1.
		var vector1 = new Thruster.Math.Vector2d(1, 2),
			vector2 = new Thruster.Math.Vector2d(3, 4);

		vector1.add(vector2);
		assert.propEqual(vector1, new Thruster.Math.Vector2d(4, 6), 'Vector has correct values after manipulation.');
	});

	QUnit.test('angle()', function(assert){
		// Get the angle of a vector.
		var vector = new Thruster.Math.Vector2d(3, 4);
		assert.equal(vector.angle(), 0.9272952180016122, 'Returned value is correct.')
	});

	QUnit.test('dot()', function(assert){
		// Calculate a dot product.
		var vector1 = new Thruster.Math.Vector2d(2, 3),
			vector2 = new Thruster.Math.Vector2d(4, 5);

		assert.equal(vector1.dot(vector2), 23, 'Returned value is correct.');
	});

	QUnit.test('length()', function(assert){
		// Get the length of a vector.
		var vector = new Thruster.Math.Vector2d(3, 4);
		assert.equal(vector.length(), 5, 'Returned value is correct.');
	});

	QUnit.test('multiply()', function(assert){
		// Multiply a vector by a scalar value.
		var vector = new Thruster.Math.Vector2d(3, 4);
		vector.multiply(5);
		assert.propEqual(vector, new Thruster.Math.Vector2d(15, 20), 'Vector has correct values after manipulation.');
	});

	QUnit.test('normalize()', function(assert){
		// Normalize a vector to length 1.
		var vector = new Thruster.Math.Vector2d(5, 12);
		var normalizedVector = vector.clone().normalize();

		assert.equal(normalizedVector.angle(), vector.angle(), 'Direction is preserved.');
		assert.equal(normalizedVector.length(), 1, 'Length of resulting vector is 1.');
	});

	QUnit.test('projection()', function(assert){
		// Find the vector projection of vector1 onto vector2
		var vector1 = new Thruster.Math.Vector2d(3, 4),
			vector2 = new Thruster.Math.Vector2d(1, 1);

		assert.propEqual(vector1.projection(vector2), new Thruster.Math.Vector2d(3.5, 3.5), 'Returned value is correct.');
	});

	QUnit.test('rejection()', function(assert){
		// Find the vector rejection of vector1 onto vector2
		var vector1 = new Thruster.Math.Vector2d(3, 4),
			vector2 = new Thruster.Math.Vector2d(1, 1);

		assert.propEqual(vector1.rejection(vector2), new Thruster.Math.Vector2d(-0.5, 0.5), 'Returned value is correct.');
	});

	QUnit.test('rotate()', function(assert){
		// Rotate a vector through 90 degrees (pi/2 radians).
		var vector = new Thruster.Math.Vector2d(8, 9);
		vector.rotate(Math.PI / 2);

		assert.propEqual(vector, new Thruster.Math.Vector2d(-9, 8), 'Vector has correct values after manipulation.');
	});

	QUnit.test('scalarProjection(), angle between vectors less than 90 degrees', function(assert){
		// Project vector1 onto vector2
		var vector1 = new Thruster.Math.Vector2d(2, 3),
			vector2 = new Thruster.Math.Vector2d(4, 5);

		assert.equal(vector1.scalarProjection(vector2), 3.5919965234379396, 'Returned value is correct.');
	});

	QUnit.test('scalarProjection(), angle between vectors is 90 degrees', function(assert){
		// Project vector1 onto vector2
		var vector1 = new Thruster.Math.Vector2d(1, 1),
			vector2 = new Thruster.Math.Vector2d(-1, 1);

		assert.equal(vector1.scalarProjection(vector2), 0, 'Returned value is correct.');
	});

	QUnit.test('scalarProjection(), angle between vectors more than 90 degrees', function(assert){
		// Project vector1 onto vector2
		var vector1 = new Thruster.Math.Vector2d(2, 3),
			vector2 = new Thruster.Math.Vector2d(-4, -5);

		assert.equal(vector1.scalarProjection(vector2), -3.5919965234379396, 'Returned value is correct.');
	});

	QUnit.test('subtract()', function(assert){
		// Subtract vector2 from vector1.
		var vector1 = new Thruster.Math.Vector2d(5, 5),
			vector2 = new Thruster.Math.Vector2d(1, 2);

		vector1.subtract(vector2);
		assert.propEqual(vector1, new Thruster.Math.Vector2d(4, 3), 'Vector has correct values after manipulation.');
	});
})();<commit_msg>Condensed Thruster,Math.Vector2d.scalarProjection() unit tests into one.<commit_after>(function(){
	'use strict';
	QUnit.module('Thruster.Math.Vector2d');

	QUnit.test('Constructor', function(assert){
		// New from constructor.
		var vector = new Thruster.Math.Vector2d(3, 4);
		assert.equal(vector.x, 3, 'x value is set correctly.');
		assert.equal(vector.y, 4, 'y value is set correctly.');
	});

	QUnit.test('clone()', function(assert){
		// Clone from existing Vector2d.
		var vector = new Thruster.Math.Vector2d(3, 4);
		var clonedVector = vector.clone();
		assert.notEqual(clonedVector, vector, 'Returns a new separate object from the original.');
		assert.equal(clonedVector.x, vector.x, 'x value is the same as the original.');
		assert.equal(clonedVector.y, vector.y, 'y value is the same as the original.');
	});

	QUnit.test('fromComponents()', function(assert){
		// New Vector2d from angle and length.
		var vector = Thruster.Math.Vector2d.fromComponents(Math.PI / 6, 4);
		assert.equal(vector.x, 3.464101615137755, 'x value is set correctly.');
		assert.equal(vector.y, 1.9999999999999998, 'y value is set correctly.');
	});

	QUnit.test('add()', function(assert){
		// Add vector2 to vector1.
		var vector1 = new Thruster.Math.Vector2d(1, 2),
			vector2 = new Thruster.Math.Vector2d(3, 4);

		vector1.add(vector2);
		assert.propEqual(vector1, new Thruster.Math.Vector2d(4, 6), 'Vector has correct values after manipulation.');
	});

	QUnit.test('angle()', function(assert){
		// Get the angle of a vector.
		var vector = new Thruster.Math.Vector2d(3, 4);
		assert.equal(vector.angle(), 0.9272952180016122, 'Returned value is correct.')
	});

	QUnit.test('dot()', function(assert){
		// Calculate a dot product.
		var vector1 = new Thruster.Math.Vector2d(2, 3),
			vector2 = new Thruster.Math.Vector2d(4, 5);

		assert.equal(vector1.dot(vector2), 23, 'Returned value is correct.');
	});

	QUnit.test('length()', function(assert){
		// Get the length of a vector.
		var vector = new Thruster.Math.Vector2d(3, 4);
		assert.equal(vector.length(), 5, 'Returned value is correct.');
	});

	QUnit.test('multiply()', function(assert){
		// Multiply a vector by a scalar value.
		var vector = new Thruster.Math.Vector2d(3, 4);
		vector.multiply(5);
		assert.propEqual(vector, new Thruster.Math.Vector2d(15, 20), 'Vector has correct values after manipulation.');
	});

	QUnit.test('normalize()', function(assert){
		// Normalize a vector to length 1.
		var vector = new Thruster.Math.Vector2d(5, 12);
		var normalizedVector = vector.clone().normalize();

		assert.equal(normalizedVector.angle(), vector.angle(), 'Direction is preserved.');
		assert.equal(normalizedVector.length(), 1, 'Length of resulting vector is 1.');
	});

	QUnit.test('projection()', function(assert){
		// Find the vector projection of vector1 onto vector2
		var vector1 = new Thruster.Math.Vector2d(3, 4),
			vector2 = new Thruster.Math.Vector2d(1, 1);

		assert.propEqual(vector1.projection(vector2), new Thruster.Math.Vector2d(3.5, 3.5), 'Returned value is correct.');
	});

	QUnit.test('rejection()', function(assert){
		// Find the vector rejection of vector1 onto vector2
		var vector1 = new Thruster.Math.Vector2d(3, 4),
			vector2 = new Thruster.Math.Vector2d(1, 1);

		assert.propEqual(vector1.rejection(vector2), new Thruster.Math.Vector2d(-0.5, 0.5), 'Returned value is correct.');
	});

	QUnit.test('rotate()', function(assert){
		// Rotate a vector through 90 degrees (pi/2 radians).
		var vector = new Thruster.Math.Vector2d(8, 9);
		vector.rotate(Math.PI / 2);

		assert.propEqual(vector, new Thruster.Math.Vector2d(-9, 8), 'Vector has correct values after manipulation.');
	});

	QUnit.test('scalarProjection()', function(assert){
		// Project vector1 onto vector2
		var vector1, vector2;

		vector1 = new Thruster.Math.Vector2d(2, 3),
		vector2 = new Thruster.Math.Vector2d(4, 5);
		assert.equal(vector1.scalarProjection(vector2), 3.5919965234379396, 'Correct result when angle between vectors is less than 90 degrees.');

		vector1 = new Thruster.Math.Vector2d(1, 1),
		vector2 = new Thruster.Math.Vector2d(-1, 1);
		assert.equal(vector1.scalarProjection(vector2), 0, 'Correct result when angle between vectors is exactly 90 degrees.');

		vector1 = new Thruster.Math.Vector2d(2, 3),
		vector2 = new Thruster.Math.Vector2d(-4, -5);
		assert.equal(vector1.scalarProjection(vector2), -3.5919965234379396, 'Correct result when angle between vectors is more than 90 degrees.');
	});

	QUnit.test('subtract()', function(assert){
		// Subtract vector2 from vector1.
		var vector1 = new Thruster.Math.Vector2d(5, 5),
			vector2 = new Thruster.Math.Vector2d(1, 2);

		vector1.subtract(vector2);
		assert.propEqual(vector1, new Thruster.Math.Vector2d(4, 3), 'Vector has correct values after manipulation.');
	});
})();<|endoftext|>