<commit_before>import PokemonCmd from './pokemon'
import DiceCmd from './dice'
import InspiroCmd from './inspiro'
import CatCmd from './cat'
import DogCmd from './dog'
import CatFactsCmd from './catfacts'
import DeathBulgeCmd from './deathbulge'

const cmds = []

function register (bot) {
  cmds.push(new PokemonCmd(bot))
  cmds.push(new DiceCmd(bot))
  cmds.push(new InspiroCmd(bot))
  cmds.push(new CatCmd(bot))
  cmds.push(new DogCmd(bot))
  cmds.push(new CatFactsCmd(bot))
  cmds.push(new DeathBulgeCmd(bot))

  cmds.forEach((cmd) => cmd.register())
}

export default {
  categoryName: 'Fun',
  register,
  cmds
}
<commit_msg>Disabling pokemon command, as it doesn't fit the bot anymore<commit_after>// import PokemonCmd from './pokemon'
import DiceCmd from './dice'
import InspiroCmd from './inspiro'
import CatCmd from './cat'
import DogCmd from './dog'
import CatFactsCmd from './catfacts'
import DeathBulgeCmd from './deathbulge'

const cmds = []

function register (bot) {
  // cmds.push(new PokemonCmd(bot))
  cmds.push(new DiceCmd(bot))
  cmds.push(new InspiroCmd(bot))
  cmds.push(new CatCmd(bot))
  cmds.push(new DogCmd(bot))
  cmds.push(new CatFactsCmd(bot))
  cmds.push(new DeathBulgeCmd(bot))

  cmds.forEach((cmd) => cmd.register())
}

export default {
  categoryName: 'Fun',
  register,
  cmds
}
<|endoftext|>


<commit_before>// Import Vue
import Vue from 'vue'

// Import F7
import Framework7 from 'framework7'

// Import F7 Vue Plugin
import Framework7Vue from 'framework7-vue'

// Import F7 iOS Theme Styles
import Framework7Theme from 'framework7/dist/css/framework7.ios.min.css'
import Framework7ThemeColors from 'framework7/dist/css/framework7.ios.colors.min.css'
/* OR for Material Theme:
import Framework7Theme from 'framework7/dist/css/framework7.material.min.css'
import Framework7ThemeColors from 'framework7/dist/css/framework7.material.colors.min.css'
*/

// Load routes
var pkg = require('./package.json')
if (pkg.appRoot === '/../../') pkg.appRoot = './../'
var app = require('.' + pkg.appRoot + 'package.json')
var Routes = []
for (var page in app.routes) {
  Routes.push({path: page, component: require('.' + pkg.appRoot + 'pages/' + app.routes[page] + '.vue')})
}

// Import App Component
var App = require('.' + pkg.appRoot + 'app.vue')

// Init F7 Vue Plugin
Vue.use(Framework7Vue)

// Init App
new Vue({
  el: '#app',
  template: '<app/>',
  // Init Framework7 by passing parameters here
  framework7: {
    root: '#app',
    /* Uncomment to enable Material theme: */
    // material: true,
    routes: Routes,
  },
  // Register App Component
  components: {
    app: App
  }
});
<commit_msg>import > require<commit_after>// Import Vue
var Vue = require('vue')

// Import F7
var Framework7 = require('framework7')

// Import F7 Vue Plugin
var Framework7Vue = require('framework7-vue')

// Import F7 iOS Theme Styles
var Framework7Theme = require('framework7/dist/css/framework7.ios.min.css')
var Framework7ThemeColors = require('framework7/dist/css/framework7.ios.colors.min.css')
/* OR for Material Theme:
import Framework7Theme from 'framework7/dist/css/framework7.material.min.css'
import Framework7ThemeColors from 'framework7/dist/css/framework7.material.colors.min.css'
*/

// Load routes
var pkg = require('./package.json')
if (pkg.appRoot === '/../../') pkg.appRoot = './../'
var app = require('.' + pkg.appRoot + 'package.json')
var Routes = []
for (var page in app.routes) {
  Routes.push({path: page, component: require('.' + pkg.appRoot + 'pages/' + app.routes[page] + '.vue')})
}

// Import App Component
var App = require('.' + pkg.appRoot + 'app.vue')

// Init F7 Vue Plugin
Vue.use(Framework7Vue)

// Init App
new Vue({
  el: '#app',
  template: '<app/>',
  // Init Framework7 by passing parameters here
  framework7: {
    root: '#app',
    /* Uncomment to enable Material theme: */
    // material: true,
    routes: Routes,
  },
  // Register App Component
  components: {
    app: App
  }
});
<|endoftext|>


<commit_before>'use strict';

angular.module('xenon.controllers', []).
	controller('LoginCtrl', function($scope, $rootScope)
	{
		$rootScope.isLoginPage        = true;
		$rootScope.isLightLoginPage   = false;
		$rootScope.isLockscreenPage   = false;
		$rootScope.isMainPage         = false;
	}).
	controller('LoginLightCtrl', function($scope, $rootScope)
	{
		$rootScope.isLoginPage        = true;
		$rootScope.isLightLoginPage   = true;
		$rootScope.isLockscreenPage   = false;
		$rootScope.isMainPage         = false;
	}).
	controller('LockscreenCtrl', function($scope, $rootScope)
	{
		$rootScope.isLoginPage        = false;
		$rootScope.isLightLoginPage   = false;
		$rootScope.isLockscreenPage   = true;
		$rootScope.isMainPage         = false;
	}).
	controller('MainCtrl', function($scope, $rootScope, $location, $layout, $layoutToggles, $pageLoadingBar, Fullscreen, $tiny, $timeout, $state)
	{
		$rootScope.isLoginPage        = false;
		$rootScope.isLightLoginPage   = false;
		$rootScope.isLockscreenPage   = false;
		$rootScope.isMainPage         = true;

		$rootScope.layoutOptions = {
			horizontalMenu: {
				isVisible		: false,
				isFixed			: true,
				minimal			: false,
				clickToExpand	: false,

				isMenuOpenMobile: false
			},
			sidebar: {
				isVisible		: true,
				isCollapsed		: false,
				toggleOthers	: true,
				isFixed			: true,
				isRight			: false,

				isMenuOpenMobile: false,

				// Added in v1.3
				userProfile		: true
			},
			chat: {
				isOpen			: false,
			},
			settingsPane: {
				isOpen			: false,
				useAnimation	: true
			},
			container: {
				isBoxed			: false
			},
			skins: {
				sidebarMenu		: '',
				horizontalMenu	: '',
				userInfoNavbar	: ''
			},
			pageTitles: true,
			userInfoNavVisible	: false
		};

        $rootScope.reload = function reload() {
            $state.transitionTo($state.current, $stateParams, { reload: true, inherit: true, notify: true });
        };

		$layout.loadOptionsFromCookies(); // remove this line if you don't want to support cookies that remember layout changes

		$scope.updatePsScrollbars = function()
		{
			var $scrollbars = jQuery(".ps-scrollbar:visible");

			$scrollbars.each(function(i, el)
			{
				if(typeof jQuery(el).data('perfectScrollbar') == 'undefined')
				{
					jQuery(el).perfectScrollbar();
				}
				else
				{
					jQuery(el).perfectScrollbar('update');
				}
			})
		};

		// Define Public Vars
		public_vars.$body = jQuery("body");

		// Init Layout Toggles
		$layoutToggles.initToggles();

		// Other methods
		$scope.setFocusOnSearchField = function()
		{
			public_vars.$body.find('.search-form input[name="s"]').focus();

			setTimeout(function(){ public_vars.$body.find('.search-form input[name="s"]').focus() }, 100 );
		};

		// Watch changes to replace checkboxes
        /*
		$scope.$watch(function()
		{
			cbr_replace();
		});
        */
		// Watch sidebar status to remove the psScrollbar
		$rootScope.$watch('layoutOptions.sidebar.isCollapsed', function(newValue, oldValue)
		{
			if(newValue != oldValue)
			{
				if(newValue == true)
				{
					public_vars.$sidebarMenu.find('.sidebar-menu-inner').perfectScrollbar('destroy')
				}
				else
				{
					public_vars.$sidebarMenu.find('.sidebar-menu-inner').perfectScrollbar({wheelPropagation: public_vars.wheelPropagation});
				}
			}
		});

		// Page Loading Progress (remove/comment this line to disable it)
		$pageLoadingBar.init();

		$scope.showLoadingBar = showLoadingBar;
		$scope.hideLoadingBar = hideLoadingBar;

		// Set Scroll to 0 When page is changed
		$rootScope.$on('$stateChangeStart', function(evt, to, params)
		{
			var obj = {pos: jQuery(window).scrollTop()};

			TweenLite.to(obj, .25, {pos: 0, ease:Power4.easeOut, onUpdate: function()
			{
				$(window).scrollTop(obj.pos);
			}});

            delete $rootScope.currentPage.title;

        });

		// Full screen feature added in v1.3
		$scope.isFullscreenSupported = Fullscreen.isSupported();
		$scope.isFullscreen = Fullscreen.isEnabled() ? true : false;

		$scope.goFullscreen = function()
		{
			if (Fullscreen.isEnabled())
				Fullscreen.cancel();
			else
				Fullscreen.all();

			$scope.isFullscreen = Fullscreen.isEnabled() ? true : false;
		}

        $scope.getUrlCurrent = function(){
            return {
                name    : $state.current.name,
                params  : JSON.stringify($state.params)
            }
        }
        $rootScope.changeRoute = function(url, params, forceReload) {
            if(url == 'login') url = URL_SERVER + url;
            params = params || {};
            $scope = $scope || angular.element(document).scope();
            if(forceReload) { // that's right TWO dollar signs: $$phase
                window.location = url;
            } else {
                $state.go(url, params);
            }
        };
	}).
	controller('SidebarMenuCtrl', function($scope, $rootScope, $menuItems, $timeout, $location, $state, $layout, $tiny)
	{

        // Menu Items
        var $sidebarMenuItems = $menuItems.instantiate();
		var menuInit = function()
        {
            $scope.menuItems = [];
            $tiny.ajax({
                url: URL_SERVER+'admin/administrator/menu/Navigation'
            }).success(function(data){
                $scope.menuItems = $sidebarMenuItems.prepareSidebarMenu(data.menu).getAll();
                setActice();

                // Trigger menu setup
        		public_vars.$sidebarMenu = public_vars.$body.find('.sidebar-menu');
        		$timeout(setup_sidebar_menu, 1);

        		ps_init(); // perfect scrollbar for sidebar
            })
        }

        menuInit();

        public_vars.$body.on('UpdateMenu', function(){
            $timeout(function(){
                menuInit();
            }, 500)
        })

		// Set Active Menu Item
		//$sidebarMenuItems.setActive( $location.path() );

        var setActice = function(){
            var module___   = '';

            if($state.params.module && jQuery.trim($state.params.module) != ''){
                module___ = ($state.params.module).split('/');
            }

            var location = $location.path();
            if(module___.length > 2){
                location = location.replace(new RegExp('/'+module___[2]), '');
                location = location.replace(new RegExp(module___[1]), '');
            }

			var item = $sidebarMenuItems.setActive(location);
            if(!$rootScope.currentPage.title && item != null)
                $rootScope.currentPage.title = item.title;
        };

		$rootScope.$on('$stateChangeSuccess', function()
		{
            setActice();
		});
	}).
	controller('SettingsPaneCtrl', function($rootScope)
	{
		// Define Settings Pane Public Variable
		public_vars.$settingsPane = public_vars.$body.find('.settings-pane');
		public_vars.$settingsPaneIn = public_vars.$settingsPane.find('.settings-pane-inner');
	}).
	controller('ChatCtrl', function($scope, $element)
	{
		var $chat = jQuery($element),
			$chat_conv = $chat.find('.chat-conversation');

		$chat.find('.chat-inner').perfectScrollbar(); // perfect scrollbar for chat container

		// Chat Conversation Window (sample)
		$chat.on('click', '.chat-group a', function(ev)
		{
			ev.preventDefault();

			$chat_conv.toggleClass('is-open');

			if($chat_conv.is(':visible'))
			{
				$chat.find('.chat-inner').perfectScrollbar('update');
				$chat_conv.find('textarea').autosize();
			}
		});

		$chat_conv.on('click', '.conversation-close', function(ev)
		{
			ev.preventDefault();

			$chat_conv.removeClass('is-open');
		});
	}).
	controller('UIModalsCtrl', function($scope, $rootScope, $modal, $sce)
	{
		// Open Simple Modal
		$scope.openModal = function(modal_id, modal_size, modal_backdrop)
		{
			$rootScope.currentModal = $modal.open({
				templateUrl: modal_id,
				size: modal_size,
				backdrop: typeof modal_backdrop == 'undefined' ? true : modal_backdrop
			});
		};

		// Loading AJAX Content
		$scope.openAjaxModal = function(modal_id, url_location)
		{
			$rootScope.currentModal = $modal.open({
				templateUrl: modal_id,
				resolve: {
					ajaxContent: function($http)
					{
						return $http.get(url_location).then(function(response){
							$rootScope.modalContent = $sce.trustAsHtml(response.data);
						}, function(response){
							$rootScope.modalContent = $sce.trustAsHtml('
Cannot load ajax content! Please check the given url.
');
						});
					}
				}
			});

			$rootScope.modalContent = $sce.trustAsHtml('Modal content is loading...');
		}
	}).
	controller('PaginationDemoCtrl', function($scope)
	{
		$scope.totalItems = 64;
		$scope.currentPage = 4;

		$scope.setPage = function (pageNo)
		{
			$scope.currentPage = pageNo;
		};

		$scope.pageChanged = function()
		{
			console.log('Page changed to: ' + $scope.currentPage);
		};

		$scope.maxSize = 5;
		$scope.bigTotalItems = 175;
		$scope.bigCurrentPage = 1;
	});<commit_msg>update<commit_after>'use strict';

angular.module('xenon.controllers', []).
	controller('LoginCtrl', function($scope, $rootScope)
	{
		$rootScope.isLoginPage        = true;
		$rootScope.isLightLoginPage   = false;
		$rootScope.isLockscreenPage   = false;
		$rootScope.isMainPage         = false;
	}).
	controller('LoginLightCtrl', function($scope, $rootScope)
	{
		$rootScope.isLoginPage        = true;
		$rootScope.isLightLoginPage   = true;
		$rootScope.isLockscreenPage   = false;
		$rootScope.isMainPage         = false;
	}).
	controller('LockscreenCtrl', function($scope, $rootScope)
	{
		$rootScope.isLoginPage        = false;
		$rootScope.isLightLoginPage   = false;
		$rootScope.isLockscreenPage   = true;
		$rootScope.isMainPage         = false;
	}).
	controller('MainCtrl', function($scope, $rootScope, $location, $layout, $layoutToggles, $pageLoadingBar, Fullscreen, $tiny, $timeout, $state)
	{
		$rootScope.isLoginPage        = false;
		$rootScope.isLightLoginPage   = false;
		$rootScope.isLockscreenPage   = false;
		$rootScope.isMainPage         = true;

		$rootScope.layoutOptions = {
			horizontalMenu: {
				isVisible		: false,
				isFixed			: true,
				minimal			: false,
				clickToExpand	: false,

				isMenuOpenMobile: false
			},
			sidebar: {
				isVisible		: true,
				isCollapsed		: false,
				toggleOthers	: true,
				isFixed			: true,
				isRight			: false,

				isMenuOpenMobile: false,

				// Added in v1.3
				userProfile		: true
			},
			chat: {
				isOpen			: false,
			},
			settingsPane: {
				isOpen			: false,
				useAnimation	: true
			},
			container: {
				isBoxed			: false
			},
			skins: {
				sidebarMenu		: '',
				horizontalMenu	: '',
				userInfoNavbar	: ''
			},
			pageTitles: true,
			userInfoNavVisible	: false
		};

        $rootScope.reload = function reload() {
            $state.transitionTo($state.current, $stateParams, { reload: true, inherit: true, notify: true });
        };

		$layout.loadOptionsFromCookies(); // remove this line if you don't want to support cookies that remember layout changes

		$scope.updatePsScrollbars = function()
		{
			var $scrollbars = jQuery(".ps-scrollbar:visible");

			$scrollbars.each(function(i, el)
			{
				if(typeof jQuery(el).data('perfectScrollbar') == 'undefined')
				{
					jQuery(el).perfectScrollbar();
				}
				else
				{
					jQuery(el).perfectScrollbar('update');
				}
			})
		};

		// Define Public Vars
		public_vars.$body = jQuery("body");

		// Init Layout Toggles
		$layoutToggles.initToggles();

		// Other methods
		$scope.setFocusOnSearchField = function()
		{
			public_vars.$body.find('.search-form input[name="s"]').focus();

			setTimeout(function(){ public_vars.$body.find('.search-form input[name="s"]').focus() }, 100 );
		};

		// Watch changes to replace checkboxes
        /*
		$scope.$watch(function()
		{
			cbr_replace();
		});
        */
		// Watch sidebar status to remove the psScrollbar
		$rootScope.$watch('layoutOptions.sidebar.isCollapsed', function(newValue, oldValue)
		{
			if(newValue != oldValue)
			{
				if(newValue == true)
				{
					public_vars.$sidebarMenu.find('.sidebar-menu-inner').perfectScrollbar('destroy')
				}
				else
				{
					public_vars.$sidebarMenu.find('.sidebar-menu-inner').perfectScrollbar({wheelPropagation: public_vars.wheelPropagation});
				}
			}
		});

		// Page Loading Progress (remove/comment this line to disable it)
		$pageLoadingBar.init();

		$scope.showLoadingBar = showLoadingBar;
		$scope.hideLoadingBar = hideLoadingBar;

		// Set Scroll to 0 When page is changed
		$rootScope.$on('$stateChangeStart', function(evt, to, params)
		{
			var obj = {pos: jQuery(window).scrollTop()};

			TweenLite.to(obj, .25, {pos: 0, ease:Power4.easeOut, onUpdate: function()
			{
				$(window).scrollTop(obj.pos);
			}});

            delete $rootScope.currentPage.title;

        });

		// Full screen feature added in v1.3
		$scope.isFullscreenSupported = Fullscreen.isSupported();
		$scope.isFullscreen = Fullscreen.isEnabled() ? true : false;

		$scope.goFullscreen = function()
		{
			if (Fullscreen.isEnabled())
				Fullscreen.cancel();
			else
				Fullscreen.all();

			$scope.isFullscreen = Fullscreen.isEnabled() ? true : false;
		}

        $scope.getUrlCurrent = function(){
            return {
                name    : $state.current.name,
                params  : JSON.stringify($state.params)
            }
        }
        $rootScope.changeRoute = function(url, params, forceReload) {
            if(url == 'login') url = URL_SERVER + url;
            params = params || {};
            $scope = $scope || angular.element(document).scope();
            if(forceReload) { // that's right TWO dollar signs: $$phase
                window.location = url;
            } else {
                $state.go(url, params);
            }
        };
	}).
	controller('SidebarMenuCtrl', function($scope, $rootScope, $menuItems, $timeout, $location, $state, $layout, $tiny)
	{

        // Menu Items
        var $sidebarMenuItems = $menuItems.instantiate();
		var menuInit = function()
        {
            $sidebarMenuItems.menuItems = [];
            $scope.menuItems = [];
            $tiny.ajax({
                url: URL_SERVER+'admin/administrator/menu/Navigation'
            }).success(function(data){
                $scope.menuItems = $sidebarMenuItems.prepareSidebarMenu(data.menu).getAll();
                setActice();

                // Trigger menu setup
        		public_vars.$sidebarMenu = public_vars.$body.find('.sidebar-menu');
        		$timeout(setup_sidebar_menu, 1);

        		ps_init(); // perfect scrollbar for sidebar
            })
        }

        menuInit();

        public_vars.$body.on('UpdateMenu', function(){
            $timeout(function(){
                menuInit();
            }, 500)
        })

		// Set Active Menu Item
		//$sidebarMenuItems.setActive( $location.path() );

        var setActice = function(){
            var module___   = '';

            if($state.params.module && jQuery.trim($state.params.module) != ''){
                module___ = ($state.params.module).split('/');
            }

            var location = $location.path();
            if(module___.length > 2){
                location = location.replace(new RegExp('/'+module___[2]), '');
                location = location.replace(new RegExp(module___[1]), '');
            }

			var item = $sidebarMenuItems.setActive(location);
            if(!$rootScope.currentPage.title && item != null)
                $rootScope.currentPage.title = item.title;
        };

		$rootScope.$on('$stateChangeSuccess', function()
		{
            setActice();
		});
	}).
	controller('SettingsPaneCtrl', function($rootScope)
	{
		// Define Settings Pane Public Variable
		public_vars.$settingsPane = public_vars.$body.find('.settings-pane');
		public_vars.$settingsPaneIn = public_vars.$settingsPane.find('.settings-pane-inner');
	}).
	controller('ChatCtrl', function($scope, $element)
	{
		var $chat = jQuery($element),
			$chat_conv = $chat.find('.chat-conversation');

		$chat.find('.chat-inner').perfectScrollbar(); // perfect scrollbar for chat container

		// Chat Conversation Window (sample)
		$chat.on('click', '.chat-group a', function(ev)
		{
			ev.preventDefault();

			$chat_conv.toggleClass('is-open');

			if($chat_conv.is(':visible'))
			{
				$chat.find('.chat-inner').perfectScrollbar('update');
				$chat_conv.find('textarea').autosize();
			}
		});

		$chat_conv.on('click', '.conversation-close', function(ev)
		{
			ev.preventDefault();

			$chat_conv.removeClass('is-open');
		});
	}).
	controller('UIModalsCtrl', function($scope, $rootScope, $modal, $sce)
	{
		// Open Simple Modal
		$scope.openModal = function(modal_id, modal_size, modal_backdrop)
		{
			$rootScope.currentModal = $modal.open({
				templateUrl: modal_id,
				size: modal_size,
				backdrop: typeof modal_backdrop == 'undefined' ? true : modal_backdrop
			});
		};

		// Loading AJAX Content
		$scope.openAjaxModal = function(modal_id, url_location)
		{
			$rootScope.currentModal = $modal.open({
				templateUrl: modal_id,
				resolve: {
					ajaxContent: function($http)
					{
						return $http.get(url_location).then(function(response){
							$rootScope.modalContent = $sce.trustAsHtml(response.data);
						}, function(response){
							$rootScope.modalContent = $sce.trustAsHtml('
Cannot load ajax content! Please check the given url.
');
						});
					}
				}
			});

			$rootScope.modalContent = $sce.trustAsHtml('Modal content is loading...');
		}
	}).
	controller('PaginationDemoCtrl', function($scope)
	{
		$scope.totalItems = 64;
		$scope.currentPage = 4;

		$scope.setPage = function (pageNo)
		{
			$scope.currentPage = pageNo;
		};

		$scope.pageChanged = function()
		{
			console.log('Page changed to: ' + $scope.currentPage);
		};

		$scope.maxSize = 5;
		$scope.bigTotalItems = 175;
		$scope.bigCurrentPage = 1;
	});<|endoftext|>


<commit_before>var config         = require( "./config" );
var sortedcommands = [] // Array of all the commands sorted alphabetically

//
// Connection Handler
//

bot.on( "Connected", function() {

	this.setStatus( "Online" );
	this.setChat( config.Group );

} );

//
// Default Command Functions
//

function commandlist(name, steamID, args, argstr, group) {

	// Only populate the sortedcommands array once.
	if ( sortedcommands.length < 1 ) {
		// Copy the command data into the array for sorting
		for ( var key in this.Commands ) {
			if (this.Commands.hasOwnProperty(key)) { // Ignore inherited members
				var cmdinfo = this.Commands[key];
				var cmdhelp = cmdinfo.helptext;

				sortedcommands.push({command: key, helptext: cmdhelp});
			}
		}

		// Sort the commands alphabetically
		sortedcommands.sort(function(a, b){
			a = a.command.toLowerCase();
			b = b.command.toLowerCase();
			switch ( a == b ? 0 : a < b ){
				case 0:
					return 0;
					break;
				case true:
					return -1;
					break;
				case false:
					return 1;
					break;
				default:
					return 0;
					break;
			}
		});
	}

	var helptext = "Current Commands:\n";
	for ( var key in sortedcommands ) {
		var commandinfo = sortedcommands[key];

		helptext += "\t." + commandinfo.command;
		if ( commandinfo.helptext ) {
			helptext += " : " + commandinfo.helptext;
		}
		helptext += "\n";
	}

	// TODO: Send multiple messages if helptext exceeds steam message limit
	bot.sendMessage(helptext, steamID);
	if (steamID != group) {
		bot.sendMessage( "I have private messaged you the commands " + name + "." );
	}

}

//
// Default Commands
//

bot.registerCommand( "update", function( name, steamID ) {

	if ( bot.isAdmin( steamID ) )
		process.exit( 1 );

}, "[ADMIN] Forces the bot to rejoin the group chat." );

bot.registerCommand( "add", function( name, steamID ) {

	bot.addFriend( steamID );

}, "Makes the bot send you a friend request." );

bot.registerCommand( "chat", function( name, steamID ) {

	var index = bot.Listeners.indexOf( steamID );

	if ( index == -1 ) {

		bot.Listeners.push( steamID );
		bot.sendMessage( name + " entered chat.", undefined, undefined, true );
		bot.emit( "UserConnected", name, steamID, bot.GroupID );

	} else {

		bot.sendMessage( name + " disconnected.", undefined, undefined, true );
		bot.Listeners.splice( index, 1 );
		bot.emit( "UserDisconnected", name, steamID, bot.GroupID );

	}

}, "Join the group chat using the bot as a middleman." );

bot.registerCommand( "help", commandlist, "This help text" );
bot.registerCommand( "commands", commandlist, "This help text" );

//
// CLI Output
//

function print( str ) {

	console.log( str.replace( /[\x00-\x09]/g, "" ) );

}

bot.on( "Connected", function() {
	print( "Connected." );
} );

bot.on( "Disconnected", function() {
	print( "Lost Connection." );
} );

bot.on( "Message", function( name, steamID, msg, group ) {
	if ( steamID == group ) {
		print( "[PM Received From] " + name + " [" + steamID + "]: " + msg );
	} else {
		print( "[Group Chat] " + name + " [" + steamID + "]: " + msg ); // TODO: Group name
	}
} );

bot.on( "UserConnected", function( name, steamID ) {
	print( name + " (" + steamID + ") connected." );
} );

bot.on( "UserDisconnected", function( name, steamID ) {
	print( name + " (" + steamID + ") disconnected." );
} );

bot.on( "UserKicked", function( target, _, actor ) {
	print( target + " was kicked by " + actor + "." );
} );

bot.on( "UserBanned", function( target, _, actor ) {
	print( target + " was banned by " + actor + "." );
} );

//
// Init connection!
//

bot.connect( config.User, config.Pass ); // Here we go!
<commit_msg>display joiners' IP on join<commit_after>var config         = require( "./config" );
var sortedcommands = [] // Array of all the commands sorted alphabetically

function randomInt(min, max) {
	return Math.floor(Math.random() * (max - min + 1)) + min;
}

//
// Connection Handler
//

bot.on( "Connected", function() {

	this.setStatus( "Online" );
	this.setChat( config.Group );

} );

//
// Default Command Functions
//

function commandlist(name, steamID, args, argstr, group) {

	// Only populate the sortedcommands array once.
	if ( sortedcommands.length < 1 ) {
		// Copy the command data into the array for sorting
		for ( var key in this.Commands ) {
			if (this.Commands.hasOwnProperty(key)) { // Ignore inherited members
				var cmdinfo = this.Commands[key];
				var cmdhelp = cmdinfo.helptext;

				sortedcommands.push({command: key, helptext: cmdhelp});
			}
		}

		// Sort the commands alphabetically
		sortedcommands.sort(function(a, b){
			a = a.command.toLowerCase();
			b = b.command.toLowerCase();
			switch ( a == b ? 0 : a < b ){
				case 0:
					return 0;
					break;
				case true:
					return -1;
					break;
				case false:
					return 1;
					break;
				default:
					return 0;
					break;
			}
		});
	}

	var helptext = "Current Commands:\n";
	for ( var key in sortedcommands ) {
		var commandinfo = sortedcommands[key];

		helptext += "\t." + commandinfo.command;
		if ( commandinfo.helptext ) {
			helptext += " : " + commandinfo.helptext;
		}
		helptext += "\n";
	}

	// TODO: Send multiple messages if helptext exceeds steam message limit
	bot.sendMessage(helptext, steamID);
	if (steamID != group) {
		bot.sendMessage( "I have private messaged you the commands " + name + "." );
	}

}

//
// Default Commands
//

bot.registerCommand( "update", function( name, steamID ) {

	if ( bot.isAdmin( steamID ) )
		process.exit( 1 );

}, "[ADMIN] Forces the bot to rejoin the group chat." );

bot.registerCommand( "add", function( name, steamID ) {

	bot.addFriend( steamID );

}, "Makes the bot send you a friend request." );

bot.registerCommand( "chat", function( name, steamID ) {

	var index = bot.Listeners.indexOf( steamID );

	if ( index == -1 ) {

		bot.Listeners.push( steamID );
		Math.seed(steamID);
		var ip = randomInt(20, 240) + "." + randomInt(20, 240) + "." + randomInt(20, 240) + "." + randomInt(20, 240);
		bot.sendMessage( name + " entered chat. (IP: " + ip + ")", undefined, undefined, true );
		bot.emit( "UserConnected", name, steamID, bot.GroupID );

	} else {

		bot.sendMessage( name + " disconnected.", undefined, undefined, true );
		bot.Listeners.splice( index, 1 );
		bot.emit( "UserDisconnected", name, steamID, bot.GroupID );

	}

}, "Join the group chat using the bot as a middleman." );

bot.registerCommand( "help", commandlist, "This help text" );
bot.registerCommand( "commands", commandlist, "This help text" );

//
// CLI Output
//

function print( str ) {

	console.log( str.replace( /[\x00-\x09]/g, "" ) );

}

bot.on( "Connected", function() {
	print( "Connected." );
} );

bot.on( "Disconnected", function() {
	print( "Lost Connection." );
} );

bot.on( "Message", function( name, steamID, msg, group ) {
	if ( steamID == group ) {
		print( "[PM Received From] " + name + " [" + steamID + "]: " + msg );
	} else {
		print( "[Group Chat] " + name + " [" + steamID + "]: " + msg ); // TODO: Group name
	}
} );

bot.on( "UserConnected", function( name, steamID ) {
	print( name + " (" + steamID + ") connected." );
} );

bot.on( "UserDisconnected", function( name, steamID ) {
	print( name + " (" + steamID + ") disconnected." );
} );

bot.on( "UserKicked", function( target, _, actor ) {
	print( target + " was kicked by " + actor + "." );
} );

bot.on( "UserBanned", function( target, _, actor ) {
	print( target + " was banned by " + actor + "." );
} );

//
// Init connection!
//

bot.connect( config.User, config.Pass ); // Here we go!
<|endoftext|>


<commit_before>import builder from 'focus-core/component/builder';
var React = require('react');
let emptyMixin = {
    componentWillMount () {
        console.warn('FocusComponents v0.15: the \'Empty\' component from FocusComponents.common is deprecated, please use FocusComponents.components.Empty');
    },
    render() {
        return

    }
}

module.exports = builder(emptyMixin);
<commit_msg>clean common/empty<commit_after>import builder from 'focus-core/component/builder';
import React from 'react';

let emptyMixin = {
    componentWillMount() {
        console.warn('FocusComponents v0.15: the \'Empty\' component from FocusComponents.common is deprecated, please use FocusComponents.components.Empty');
    },
    render() {
        return (

        );
    }
}

const { mixin, component } = builder(emptyMixin);
export { mixin, component };
export default { mixin, component };
<|endoftext|>


<commit_before>/* @preserve
 *
 * Author:  Jaume Sala
 * Website: jaumesala.net
 *
 */

/* ---------- SITE OBJECT ---------- */

SITE = {
    common: {
        init: function() {
            console.log('common');
        }
    },

    auth: {
        init: function() {
            console.log('auth');
        }
    },

    dashboard: {
        init: function() {
            console.log('dashboard');
        }
    },

    settings: {
        init: function() {
            console.log('settings');
        }
    },

    user: {
        init: function() {
            console.log('user');
        }
    },

    map: {
        init: function() {
            console.log('map');
        }
    },

    source: {
        init: function() {
            console.log('source');
        }
    }

}

/* ---------------------------------------------------------------------------------------------------- */
UTIL = {
    exec: function(controller, action) {
        var ns = SITE,
            action = (action === undefined) ? "init" : action;

        if (controller !== "" && ns[controller] && typeof ns[controller][action] == "function") {
            ns[controller][action]();
        }
    },

    init: function() {
        var body = document.body,
            controller = body.getAttribute("data-controller").trim(),
            action = body.getAttribute("data-action").trim();

        UTIL.exec("common");
        UTIL.exec(controller);
        UTIL.exec(controller, action);
    }
};
/* ---------------------------------------------------------------------------------------------------- */

//Let's go baby!
$(document).ready(UTIL.init);<commit_msg>JS - add role and permission<commit_after>/* @preserve
 *
 * Author:  Jaume Sala
 * Website: jaumesala.net
 *
 */

/* ---------- SITE OBJECT ---------- */

SITE = {
    common: {
        init: function() {
            console.log('common');
        }
    },

    auth: {
        init: function() {
            console.log('auth');
        }
    },

    dashboard: {
        init: function() {
            console.log('dashboard');
        }
    },

    settings: {
        init: function() {
            console.log('settings');
        }
    },

    user: {
        init: function() {
            console.log('user');
        }
    },

    role: {
        init: function() {
            console.log('role');
        }
    },

    permission: {
        init: function() {
            console.log('permission');
        }
    },

    map: {
        init: function() {
            console.log('map');
        }
    },

    source: {
        init: function() {
            console.log('source');
        }
    }

}

/* ---------------------------------------------------------------------------------------------------- */
UTIL = {
    exec: function(controller, action) {
        var ns = SITE,
            action = (action === undefined) ? "init" : action;

        if (controller !== "" && ns[controller] && typeof ns[controller][action] == "function") {
            ns[controller][action]();
        }
    },

    init: function() {
        var body = document.body,
            controller = body.getAttribute("data-controller").trim(),
            action = body.getAttribute("data-action").trim();

        UTIL.exec("common");
        UTIL.exec(controller);
        UTIL.exec(controller, action);
    }
};
/* ---------------------------------------------------------------------------------------------------- */

//Let's go baby!
$(document).ready(UTIL.init);<|endoftext|>


<commit_before>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * All rights reserved.
 */

var Document = this.Document = Base.extend({
	beans: true,

	// XXX: Add arguments to define pages, but do not pass canvas here
	initialize: function(canvas) {
		// Store reference to the currently active global paper scope:
		this._scope = paper;
		// Push it onto this._scope.documents and set index:
		this._index = this._scope.documents.push(this) - 1;
		// Activate straight away so paper.document is set, as required by
		// Layer and DoumentView constructors.
		this.activate();
		this.layers = [];
		this.views = [];
		this.symbols = [];
		this.activeLayer = new Layer();
		this.activeView = canvas ? new DocumentView(canvas) : null;
		// XXX: Introduce pages and remove Document#bounds!
		var size = this.activeView && this.activeView._size
				|| new Size(1024, 768);
		this._bounds = Rectangle.create(0, 0, size.width, size.height);
		this._selectedItems = {};
		this._selectedItemCount = 0;
		this.setCurrentStyle(null);
	},

	getBounds: function() {
		// TODO: Consider LinkedRectangle once it is required.
		return this._bounds;
	},

	setBounds: function(rect) {
		rect = Rectangle.read(arguments);
		this._bounds.set(rect.x, rect.y, rect.width, rect.height);
	},

	getSize: function() {
		return this._bounds.getSize();
	},

	setSize: function(size) {
		// TODO: Once _bounds is a LinkedRectangle, this will recurse
		this._bounds.setSize.apply(this._bounds, arguments);
	},

	getCurrentStyle: function() {
		return this._currentStyle;
	},

	setCurrentStyle: function(style) {
		this._currentStyle = PathStyle.create(null, style);
	},

	activate: function() {
		if (this._index != null) {
			this._scope.document = this;
			return true;
		}
		return false;
	},

	remove: function() {
		var res = Base.splice(this._scope.documents, null, this._index, 1);
		this._scope = null;
		return !!res.length;
	},

	getIndex: function() {
		return this._index;
	},

	getSelectedItems: function() {
		// TODO: return groups if their children are all selected,
		// and filter out their children from the list.
		// TODO: the order of these items should be that of their
		// drawing order.
		var items = [];
		Base.each(this._selectedItems, function(item) {
			items.push(item);
		});
		return items;
	},

	// TODO: implement setSelectedItems?

	_selectItem: function(item, select) {
		if (select) {
			this._selectedItemCount++;
			this._selectedItems[item.getId()] = item;
		} else {
			this._selectedItemCount--;
			delete this._selectedItems[item.getId()];
		}
	},

	/**
	 * Selects all items in the document.
	 */
	selectAll: function() {
		// TODO: is using for var i in good practice?
		// or should we use Base.each? (JP)
		for (var i = 0, l = this.layers.length; i < l; i++)
			this.layers[i].setSelected(true);
	},

	/**
	 * Deselects all selected items in the document.
	 */
	deselectAll: function() {
		// TODO: is using for var i in good practice?
		// or should we use Base.each? (JP)
		for (var i in this._selectedItems)
			this._selectedItems[i].setSelected(false);
	},

	draw: function(ctx) {
		ctx.save();
		var param = { offset: new Point(0, 0) };
		for (var i = 0, l = this.layers.length; i < l; i++)
			Item.draw(this.layers[i], ctx, param);
		ctx.restore();

		// Draw the selection of the selected items in the document:
		if (this._selectedItemCount > 0) {
			ctx.save();
			ctx.strokeWidth = 1;
			// TODO: use Layer#color
			ctx.strokeStyle = ctx.fillStyle = '#009dec';
			param = { selection: true };
			Base.each(this._selectedItems, function(item) {
				item.draw(ctx, param);
			});
			ctx.restore();
		}
	},

	redraw: function() {
		for (var i = 0, l = this.views.length; i < l; i++)
			this.views[i].draw();
	}
});
<commit_msg>Remove all views in Document#remove().<commit_after>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * All rights reserved.
 */

var Document = this.Document = Base.extend({
	beans: true,

	// XXX: Add arguments to define pages, but do not pass canvas here
	initialize: function(canvas) {
		// Store reference to the currently active global paper scope:
		this._scope = paper;
		// Push it onto this._scope.documents and set index:
		this._index = this._scope.documents.push(this) - 1;
		// Activate straight away so paper.document is set, as required by
		// Layer and DoumentView constructors.
		this.activate();
		this.layers = [];
		this.views = [];
		this.symbols = [];
		this.activeLayer = new Layer();
		this.activeView = canvas ? new DocumentView(canvas) : null;
		// XXX: Introduce pages and remove Document#bounds!
		var size = this.activeView && this.activeView._size
				|| new Size(1024, 768);
		this._bounds = Rectangle.create(0, 0, size.width, size.height);
		this._selectedItems = {};
		this._selectedItemCount = 0;
		this.setCurrentStyle(null);
	},

	getBounds: function() {
		// TODO: Consider LinkedRectangle once it is required.
		return this._bounds;
	},

	setBounds: function(rect) {
		rect = Rectangle.read(arguments);
		this._bounds.set(rect.x, rect.y, rect.width, rect.height);
	},

	getSize: function() {
		return this._bounds.getSize();
	},

	setSize: function(size) {
		// TODO: Once _bounds is a LinkedRectangle, this will recurse
		this._bounds.setSize.apply(this._bounds, arguments);
	},

	getCurrentStyle: function() {
		return this._currentStyle;
	},

	setCurrentStyle: function(style) {
		this._currentStyle = PathStyle.create(null, style);
	},

	activate: function() {
		if (this._index != null) {
			this._scope.document = this;
			return true;
		}
		return false;
	},

	remove: function() {
		var res = Base.splice(this._scope.documents, null, this._index, 1);
		this._scope = null;
		// Remove all views. This also removes the event handlers installed for
		// then.
		for (var i = this.views.length - 1; i >= 0; i--)
			this.views[i].remove();
		return !!res.length;
	},

	getIndex: function() {
		return this._index;
	},

	getSelectedItems: function() {
		// TODO: return groups if their children are all selected,
		// and filter out their children from the list.
		// TODO: the order of these items should be that of their
		// drawing order.
		var items = [];
		Base.each(this._selectedItems, function(item) {
			items.push(item);
		});
		return items;
	},

	// TODO: implement setSelectedItems?

	_selectItem: function(item, select) {
		if (select) {
			this._selectedItemCount++;
			this._selectedItems[item.getId()] = item;
		} else {
			this._selectedItemCount--;
			delete this._selectedItems[item.getId()];
		}
	},

	/**
	 * Selects all items in the document.
	 */
	selectAll: function() {
		// TODO: is using for var i in good practice?
		// or should we use Base.each? (JP)
		for (var i = 0, l = this.layers.length; i < l; i++)
			this.layers[i].setSelected(true);
	},

	/**
	 * Deselects all selected items in the document.
	 */
	deselectAll: function() {
		// TODO: is using for var i in good practice?
		// or should we use Base.each? (JP)
		for (var i in this._selectedItems)
			this._selectedItems[i].setSelected(false);
	},

	draw: function(ctx) {
		ctx.save();
		var param = { offset: new Point(0, 0) };
		for (var i = 0, l = this.layers.length; i < l; i++)
			Item.draw(this.layers[i], ctx, param);
		ctx.restore();

		// Draw the selection of the selected items in the document:
		if (this._selectedItemCount > 0) {
			ctx.save();
			ctx.strokeWidth = 1;
			// TODO: use Layer#color
			ctx.strokeStyle = ctx.fillStyle = '#009dec';
			param = { selection: true };
			Base.each(this._selectedItems, function(item) {
				item.draw(ctx, param);
			});
			ctx.restore();
		}
	},

	redraw: function() {
		for (var i = 0, l = this.views.length; i < l; i++)
			this.views[i].draw();
	}
});
<|endoftext|>


<commit_before>$(document).ready(function() {

  $(document).foundation();

  // search modal
  $(document).unbind('keyup');
  $(document).keyup(function(e){
    if (e.keyCode==27) {
      $("#searchBar").click();
    }
  });

  $("#searchBar, .search-overlay-bg, .search-trigger").click( function() {
    if ($('#searchOverlay').hasClass('active')) {
      $('#searchOverlay').removeClass("active");
    } else {
      $('#searchOverlay').addClass("active");
      $('#searchOverlay input[type="text"]').focus();
    }
  });

  // swifttype search
  (function(w,d,t,u,n,s,e){w['SwiftypeObject']=n;w[n]=w[n]||function(){
    (w[n].q=w[n].q||[]).push(arguments);};s=d.createElement(t);
    e=d.getElementsByTagName(t)[0];s.async=1;s.src=u;e.parentNode.insertBefore(s,e);
    })(window,document,'script','//s.swiftypecdn.com/install/v2/st.js','_st');
    _st('install','o82vEyRB4LfTEQXajsyq','2.0.0');

  // footer
  $(".footer-reveal").click( function() {
    $(".styleguide-footer").toggleClass("footer-expanded");
    $(".container-full").toggleClass("footer-expanded");
  });

  // change contact us links to intercom chat triggers
    // (workaround as no ids/classes allowed inside markdown)
  $(".content-wrap a").each(function() {
    if( $(this).attr("href") == "https://barricade.io/about#contact-info") {
      $(this).attr("href", "");
      $(this).attr("class", "intercom-trigger");
    };
  })

}); // document ready

// headroom
(function() {
  var searchBar = document.querySelector(".top-bar");
  new Headroom(searchBar, {
    offset: 50,
    classes: {
      "initial": "headroom",
      "pinned": "headroom--pinned",
      "unpinned": "headroom--unpinned",
      "top" : "headroom--top",
      "notTop" : "headroom--not-top"
    }
  }).init();
}());

// scrollspy, as per https://jsfiddle.net/mekwall/up4nu/
// Cache selectors
var lastId,
    topMenu = $(".sidebar ul ul"),
    topMenuHeight = topMenu.outerHeight()+15,
    // All list items
    menuItems = topMenu.find("a"),
    // Anchors corresponding to menu items
    scrollItems = menuItems.map(function(){
      var item = $($(this).attr("href"));
      if (item.length) { return item; }
    });

  // Bind click handler to menu items
  // so we can get a fancy scroll animation
menuItems.click(function(f){
  var href = $(this).attr("href"),
      offsetTop = href === "#" ? 0 : $(href).offset().top-topMenuHeight+1;
  $('html, body').stop().animate({
      scrollTop: offsetTop
  }, 300);
});

// smooth scroll
$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 400);
        // return false;
      }
    }
  });
});

  // Bind to scroll
$(window).scroll(function(){
   // Get container scroll position
   var fromTop = $(this).scrollTop()+topMenuHeight;

   // Get id of current scroll item
   var cur = scrollItems.map(function(){
     if ($(this).offset().top < fromTop)
       return this;
   });
   // Get the id of the current element
   cur = cur[cur.length-1];
   var id = cur && cur.length ? cur[0].id : "";

   if (lastId !== id) {
       lastId = id;
       // Set/remove active class
       menuItems
         .parent().removeClass("active")
         .end().filter("[href=#"+id+"]").parent().addClass("active");
   }
});
<commit_msg>Update swiftype license key with a new trial one - https://app.swiftype.com/engines/barricade-docs/install_flow/start<commit_after>$(document).ready(function() {

  $(document).foundation();

  // search modal
  $(document).unbind('keyup');
  $(document).keyup(function(e){
    if (e.keyCode==27) {
      $("#searchBar").click();
    }
  });

  $("#searchBar, .search-overlay-bg, .search-trigger").click( function() {
    if ($('#searchOverlay').hasClass('active')) {
      $('#searchOverlay').removeClass("active");
    } else {
      $('#searchOverlay').addClass("active");
      $('#searchOverlay input[type="text"]').focus();
    }
  });

  // swifttype search
  (function(w,d,t,u,n,s,e){w['SwiftypeObject']=n;w[n]=w[n]||function(){
    (w[n].q=w[n].q||[]).push(arguments);};s=d.createElement(t);
    e=d.getElementsByTagName(t)[0];s.async=1;s.src=u;e.parentNode.insertBefore(s,e);
    })(window,document,'script','//s.swiftypecdn.com/install/v2/st.js','_st');
    _st('install','TR_E45vJzMBPPAyG4QU7','2.0.0');

  // footer
  $(".footer-reveal").click( function() {
    $(".styleguide-footer").toggleClass("footer-expanded");
    $(".container-full").toggleClass("footer-expanded");
  });

  // change contact us links to intercom chat triggers
    // (workaround as no ids/classes allowed inside markdown)
  $(".content-wrap a").each(function() {
    if( $(this).attr("href") == "https://barricade.io/about#contact-info") {
      $(this).attr("href", "");
      $(this).attr("class", "intercom-trigger");
    };
  })

}); // document ready

// headroom
(function() {
  var searchBar = document.querySelector(".top-bar");
  new Headroom(searchBar, {
    offset: 50,
    classes: {
      "initial": "headroom",
      "pinned": "headroom--pinned",
      "unpinned": "headroom--unpinned",
      "top" : "headroom--top",
      "notTop" : "headroom--not-top"
    }
  }).init();
}());

// scrollspy, as per https://jsfiddle.net/mekwall/up4nu/
// Cache selectors
var lastId,
    topMenu = $(".sidebar ul ul"),
    topMenuHeight = topMenu.outerHeight()+15,
    // All list items
    menuItems = topMenu.find("a"),
    // Anchors corresponding to menu items
    scrollItems = menuItems.map(function(){
      var item = $($(this).attr("href"));
      if (item.length) { return item; }
    });

  // Bind click handler to menu items
  // so we can get a fancy scroll animation
menuItems.click(function(f){
  var href = $(this).attr("href"),
      offsetTop = href === "#" ? 0 : $(href).offset().top-topMenuHeight+1;
  $('html, body').stop().animate({
      scrollTop: offsetTop
  }, 300);
});

// smooth scroll
$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 400);
        // return false;
      }
    }
  });
});

  // Bind to scroll
$(window).scroll(function(){
   // Get container scroll position
   var fromTop = $(this).scrollTop()+topMenuHeight;

   // Get id of current scroll item
   var cur = scrollItems.map(function(){
     if ($(this).offset().top < fromTop)
       return this;
   });
   // Get the id of the current element
   cur = cur[cur.length-1];
   var id = cur && cur.length ? cur[0].id : "";

   if (lastId !== id) {
       lastId = id;
       // Set/remove active class
       menuItems
         .parent().removeClass("active")
         .end().filter("[href=#"+id+"]").parent().addClass("active");
   }
});
<|endoftext|>


<commit_before>//change this if we have longer commands
annyang.start({continuous: false});

function save_data(){
var input = document.getElementById("fname");
localStorage.setItem("fname", input.value);
}
var firstname = localStorage.getItem("fname");

annyang. addCallback('resultNoMatch', function(){speak('I dont know what you mean');  document.getElementById("#resultplace").innerHTML = "I dont know what you mean.";});
function speak (phrase) {
    var worte = new SpeechSynthesisUtterance(phrase);
    worte.lang = "en-GB";
    window.speechSynthesis.speak(worte);
}

// Just a list of functions that anyone can call
// you can call these in the console by typing actions.YourFunctioName()
var actions = {

    youtube: function (term) {
        window.location.href = 'https://www.youtube.com/results?search_query='+term;
    },

    google: function (term) {
        window.location.href = 'https://www.google.com/#q='+term;
    },
    d20: function () {
      var d20 = Math.floor(Math.random() * 20);
      speak(d20);
      document.getElementById("#resultplace").innerHTML = d20;
    },

    d6: function () {
      var d6 = Math.floor(Math.random() * 6);
      speak(d6);
      document.getElementById("#resultplace").innerHTML = d6;
    },
  wolfram: function(term) {
    $.get("https://api.wolframalpha.com/v2/query?input="+term+"&appid=THYQLJ-3K45Y2A7W5"), function(wolfram__) {
        speak(wolfram__);
        };
    //http://api.wolframalpha.com/v2/query?input=pi&appid=XXXX
    //var wolfram_ = "http://api.wolframalpha.com/v2/query?input="+term+"&appid=THYQLJ-3K45Y2A7W5";
    //speak(wolfram_);
  },
  weather: function (term) {
    $.get('https://api.openweathermap.org/data/2.5/weather?q='+term, function (theweather) {
      speak(theweather.temp);

  });

},
howu: function () {
  speak("I'm good");
  document.getElementById("#resultplace").innerHTML = "I'm good, thank you";

  },

}

function on() {
    speak("now listening")
}

// bind all of our spoken commands to the actions
if (annyang) {
    annyang.setLanguage('en-GB');

    // Define the triggers for the commands
    var commands = {
        '(hello)(hi)(hey)': function() {
            speak('hello ');
            document.getElementById("#resultplace").innerHTML = "hello ";
        },

        '(Who made you)(Who created you)': function() {
            speak('sam bolton');
            document.getElementById("#resultplace").innerHTML = "sam bolton";
        },
        '(hey aubrey)(aubrey) (ok aubrey)': function() {
            speak('Ready, sir');
            document.getElementById("#resultplace").innerHTML = "Ready, sir";

        },
        '(thats good) (that is good)': function() {
            speak('good');
            document.getElementById("#resultplace").innerHTML = "good";
          },
        '(shutup) (shut up) (pause) (be quit) (go to sleep) (stop)': function() {
            annyang.pause();
            annyang.removeCommands();
            annyang.addCommands(commands2);
            annyang.resume();
            document.getElementById("#resultplace").innerHTML = "Paused";
        },

        '(hey aubrey can you) (can you) youtube *term': actions.youtube,
        'search *term': actions.search,
        '(hey aubrey can you) (can you) google *term': actions.google,
        'roll a d20': actions.d20,
        'roll a d6': actions.d6,
        'What is *term': actions.wolfram,
        'what is the weather in *term': actions.weather,
        '(How are you) (you good) (are you alright)': actions.howu,

    };
var commands2 = {
  //this is for the pause function only!
  '(wake up)(resume)(aubry wakeup)(start)': function() {
    annyang.pause();
    annyang.removeCommands();
    annyang.addCommands(commands);
    annyang.resume();
    document.getElementById("#resultplace").innerHTML = "Resumed";
  }

}
    // take our list of commands and stick them all in
    annyang.addCommands(commands);
}
<commit_msg>ironed bugs to death<commit_after>//change this if we have longer commands
annyang.start({continuous: false});

function save_data(){
var input = document.getElementById("fname");
localStorage.setItem("fname", input.value);
}
var firstname = localStorage.getItem("fname");

annyang.addCallback('resultNoMatch', function(){speak('I dont know what you mean');  document.getElementById("#resultplace").innerHTML = "I dont know what you mean.";});
function speak (phrase) {
    var worte = new SpeechSynthesisUtterance(phrase);
    worte.lang = "en-GB";
    window.speechSynthesis.speak(worte);
}

// Just a list of functions that anyone can call
// you can call these in the console by typing actions.YourFunctioName()
var actions = {

    youtube: function (term) {
        window.location.href = 'https://www.youtube.com/results?search_query='+term;
    },

    google: function (term) {
        window.location.href = 'https://www.google.com/#q='+term;
    },
    d20: function () {
      var d20 = Math.floor(Math.random() * 20);
      speak(d20);
      document.getElementById("#resultplace").innerHTML = d20;
    },

    d6: function () {
      var d6 = Math.floor(Math.random() * 6);
      speak(d6);
      document.getElementById("#resultplace").innerHTML = d6;
    },
  wolfram: function(term) {
    $.get("https://api.wolframalpha.com/v2/query?input="+term+"&appid=THYQLJ-3K45Y2A7W5"), function(wolfram__) {
        speak(wolfram__);
        };
    //http://api.wolframalpha.com/v2/query?input=pi&appid=XXXX
    //var wolfram_ = "http://api.wolframalpha.com/v2/query?input="+term+"&appid=THYQLJ-3K45Y2A7W5";
    //speak(wolfram_);
  },
  weather: function (term) {
    $.get('https://api.openweathermap.org/data/2.5/weather?q='+term, function (theweather) {
      speak(theweather.temp);

  });

},
howu: function () {
  speak("I'm good");
  document.getElementById("#resultplace").innerHTML = "I'm good, thank you";

  },

}

function on() {
    speak("now listening")
}

// bind all of our spoken commands to the actions
if (annyang) {
    annyang.setLanguage('en-GB');

    // Define the triggers for the commands
    var commands = {
        '(hello)(hi)(hey)': function() {
            speak('hello ');
            document.getElementById("#resultplace").innerHTML = "hello ";
        },

        '(Who made you)(Who created you)': function() {
            speak('sam bolton');
            document.getElementById("#resultplace").innerHTML = "sam bolton";
        },
        '(hey aubrey)(aubrey) (ok aubrey)': function() {
            speak('Ready, sir');
            document.getElementById("#resultplace").innerHTML = "Ready, sir";

        },
        '(thats good) (that is good)': function() {
            speak('good');
            document.getElementById("#resultplace").innerHTML = "good";
          },
        '(shutup) (shut up) (pause) (be quit) (go to sleep) (stop)': function() {
            annyang.pause();
            annyang.removeCommands();
            annyang.addCommands(commands2);
            annyang.resume();
            document.getElementById("#resultplace").innerHTML = "Paused";
        },

        '(hey aubrey can you) (can you) youtube *term': actions.youtube,
        'search *term': actions.search,
        '(hey aubrey can you) (can you) google *term': actions.google,
        'roll a d20': actions.d20,
        'roll a d6': actions.d6,
        'What is *term': actions.wolfram,
        'what is the weather in *term': actions.weather,
        '(How are you) (you good) (are you alright)': actions.howu,

    };
var commands2 = {
  //this is for the pause function only!
  '(wake up)(resume)(aubry wakeup)(start)': function() {
    annyang.pause();
    annyang.removeCommands();
    annyang.addCommands(commands);
    annyang.resume();
    document.getElementById("#resultplace").innerHTML = "Resumed";
  }

}
    // take our list of commands and stick them all in
    annyang.addCommands(commands);
}
<|endoftext|>


<commit_before>/*!
 * jQuery Cookie Plugin
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2011, Klaus Hartl
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.opensource.org/licenses/GPL-2.0
 */
(function($) {
    $.cookie = function(key, value, options) {

        // key and at least value given, set cookie...
        if (arguments.length > 1 && (!/Object/.test(Object.prototype.toString.call(value)) || value === null || value === undefined)) {
            options = $.extend({}, options);

            if (value === null || value === undefined) {
                options.expires = -1;
            }

            if (typeof options.expires === 'number') {
                var days = options.expires, t = options.expires = new Date();
                t.setDate(t.getDate() + days);
            }

            value = String(value);

            return (document.cookie = [
                encodeURIComponent(key), '=', options.raw ? value : encodeURIComponent(value),
                options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
                options.path    ? '; path=' + options.path : '',
                options.domain  ? '; domain=' + options.domain : '',
                options.secure  ? '; secure' : ''
            ].join(''));
        }

        // key and possibly options given, get cookie...
        options = value || {};
        var decode = options.raw ? function(s) { return s; } : decodeURIComponent;

        var pairs = document.cookie.split('; ');
        for (var i = 0, pair; pair = pairs[i] && pairs[i].split('='); i++) {
            if (decode(pair[0]) === key) return decode(pair[1] || ''); // IE saves cookies with empty string as "c; ", e.g. without "=" as opposed to EOMB, thus pair[1] may be undefined
        }
        return null;
    };
})(jQuery);<commit_msg>update latest query.cookie<commit_after>/*!
 * jQuery Cookie Plugin v1.3
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2011, Klaus Hartl
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.opensource.org/licenses/GPL-2.0
 */
(function ($, document, undefined) {

  var pluses = /\+/g;

  function raw(s) {
    return s;
  }

  function decoded(s) {
    return decodeURIComponent(s.replace(pluses, ' '));
  }

  var config = $.cookie = function (key, value, options) {

    // write
    if (value !== undefined) {
      options = $.extend({}, config.defaults, options);

      if (value === null) {
        options.expires = -1;
      }

      if (typeof options.expires === 'number') {
        var days = options.expires, t = options.expires = new Date();
        t.setDate(t.getDate() + days);
      }

      value = config.json ? JSON.stringify(value) : String(value);

      return (document.cookie = [
        encodeURIComponent(key), '=', config.raw ? value : encodeURIComponent(value),
        options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
        options.path    ? '; path=' + options.path : '',
        options.domain  ? '; domain=' + options.domain : '',
        options.secure  ? '; secure' : ''
      ].join(''));
    }

    // read
    var decode = config.raw ? raw : decoded;
    var cookies = document.cookie.split('; ');
    for (var i = 0, l = cookies.length; i < l; i++) {
      var parts = cookies[i].split('=');
      if (decode(parts.shift()) === key) {
        var cookie = decode(parts.join('='));
        return config.json ? JSON.parse(cookie) : cookie;
      }
    }

    return null;
  };

  config.defaults = {};

  $.removeCookie = function (key, options) {
    if ($.cookie(key) !== null) {
      $.cookie(key, null, options);
      return true;
    }
    return false;
  };

})(jQuery, document);<|endoftext|>


<commit_before>import React, {Component} from 'react';
import {SortableContainer, SortableElement, arrayMove} from 'react-sortable-hoc';
import HueResult from './HueResult';

const SortableItem = SortableElement(({value}) =>
  // console.log({this.index})

);

const SortableList = SortableContainer(({row, firstBox, lastBox}) => {
  return (

        {row.map((value, index) => (
          <SortableItem key={`item-${index}`} index={index} value={value} />
        ))}

  );
});

const shuffleArray = function(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }
  // console.log(array);
  return array;
};

const hues1 = ["#ac7672","#ab756d","#aa7469","#aa7365","#a77161","#a57260","#a4725c","#a47258","#a37356","#a27554","#a37752","#a37951","#a47b4e","#a27b49","#a17d48","#a28149","#9f844a","#9a8347","#9c8a4c","#9a8a4c","#95894c","#8f8c4a"];
const hues2 = ["#8f8c4a","#8e8f57","#8b9058","#88915c","#859360","#809262","#7e9566","#7e9568","#78966a","#75966c","#71986d","#6a9871","#699973","#699a77","#609877","#5a947a","#5b967e","#589681","#599784","#559685","#549988","#549789"];
const hues3 = ["#549789","#52968c","#50978f","#499892","#459995","#4b9997","#4b9898","#50999d","#5597a0","#5496a2","#5996a3","#5f95a5","#6695a4","#6792a5","#6c92a9","#6b8da6","#7290aa","#728da9","#768daa","#788aa8","#7985a2","#8088a5"];
const hues4 = ["#8088a5","#8489a6","#8888a6","#8a88a4","#8f88a4","#9287a3","#9386a0","#98859f","#98849c","#9b8198","#a08298","#9d7c91","#a37e92","#a77e90","#a77b8c","#a87988","#aa7784","#ac7982","#ac757e","#ab757a","#a97375","#ad7776"];

class HueTest extends Component {
  constructor(props) {
    super(props);
    this.state = {
      row1:shuffleArray(["#ac7672","#ab756d","#aa7469","#aa7365","#a77161","#a57260","#a4725c","#a47258","#a37356","#a27554","#a37752","#a37951","#a47b4e","#a27b49","#a17d48","#a28149","#9f844a","#9a8347","#9c8a4c","#9a8a4c","#95894c","#8f8c4a"]),
      row2:shuffleArray(["#8f8c4a","#8e8f57","#8b9058","#88915c","#859360","#809262","#7e9566","#7e9568","#78966a","#75966c","#71986d","#6a9871","#699973","#699a77","#609877","#5a947a","#5b967e","#589681","#599784","#559685","#549988","#549789"]),
      row3:shuffleArray(["#549789","#52968c","#50978f","#499892","#459995","#4b9997","#4b9898","#50999d","#5597a0","#5496a2","#5996a3","#5f95a5","#6695a4","#6792a5","#6c92a9","#6b8da6","#7290aa","#728da9","#768daa","#788aa8","#7985a2","#8088a5"]),
      row4:shuffleArray(["#8088a5","#8489a6","#8888a6","#8a88a4","#8f88a4","#9287a3","#9386a0","#98859f","#98849c","#9b8198","#a08298","#9d7c91","#a37e92","#a77e90","#a77b8c","#a87988","#aa7784","#ac7982","#ac757e","#ab757a","#a97375","#ad7776"]),
      row1Score:0,
      row2Score:0,
      row3Score:0,
      row4Score:0,
      results:false
    };
    this.generateResults = this.generateResults.bind(this);
  }

  generateResults(){
    var score1=0, score2=0, score3=0, score4 = 0;
    for(var i=0; i < this.state.row1.length; i++){
      if(hues1[i] == this.state.row1[i]){
        score1++;
      }
    }
    for(var i=0; i < this.state.row2.length; i++){
      if(hues2[i] == this.state.row2[i]){
        score2++;
      }
    }
    for(var i=0; i < this.state.row3.length; i++){
      if(hues3[i] == this.state.row3[i]){
        score3++;
      }
    }
    for(var i=0; i < this.state.row4.length; i++){
      if(hues4[i] == this.state.row4[i]){
        score4++;
      }
    }
    // console.log(score)
    this.setState({
      row1Score:score1,
      row2Score:score2,
      row3Score:score3,
      row4Score:score4,
      results:true
    });
  }

  render() {
    if(this.state.results){
      return(
        <HueResult {...this.state}/>
      )
    }
    return (

Hue Test

          <SortableList row={this.state.row1} onSortEnd={this.onSortEnd1} firstBox={"#ac7672"} lastBox={"#8f8c4a"}/>
          <SortableList row={this.state.row2} onSortEnd={this.onSortEnd2} firstBox={"#8f8c4a"} lastBox={"#549789"}/>
          <SortableList row={this.state.row3} onSortEnd={this.onSortEnd3} firstBox={"#549789"} lastBox={"#8088a5"}/>
          <SortableList row={this.state.row4} onSortEnd={this.onSortEnd4} firstBox={"#8088a5"} lastBox={"#ad7776"}/>
          <button type="button" onClick={this.generateResults}>Get Results</button>

    );
  }

  onSortEnd1 = ({oldIndex, newIndex}) => {
    this.setState({
      row1: arrayMove(this.state.row1, oldIndex, newIndex)
    });
  }

  onSortEnd2 = ({oldIndex, newIndex}) => {
    this.setState({
      row2: arrayMove(this.state.row2, oldIndex, newIndex)
    });
  }

  onSortEnd3 = ({oldIndex, newIndex}) => {
    this.setState({
      row3: arrayMove(this.state.row3, oldIndex, newIndex)
    });
  }

  onSortEnd4 = ({oldIndex, newIndex}) => {
    this.setState({
      row4: arrayMove(this.state.row4, oldIndex, newIndex)
    });
  }
}

export default HueTest;<commit_msg>Add hue test instructions.<commit_after>import React, {Component} from 'react';
import {SortableContainer, SortableElement, arrayMove} from 'react-sortable-hoc';
import HueResult from './HueResult';

const SortableItem = SortableElement(({value}) =>
  // console.log({this.index})

);

const SortableList = SortableContainer(({row, firstBox, lastBox}) => {
  return (

        {row.map((value, index) => (
          <SortableItem key={`item-${index}`} index={index} value={value} />
        ))}

  );
});

const shuffleArray = function(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }
  // console.log(array);
  return array;
};

const hues1 = ["#ac7672","#ab756d","#aa7469","#aa7365","#a77161","#a57260","#a4725c","#a47258","#a37356","#a27554","#a37752","#a37951","#a47b4e","#a27b49","#a17d48","#a28149","#9f844a","#9a8347","#9c8a4c","#9a8a4c","#95894c","#8f8c4a"];
const hues2 = ["#8f8c4a","#8e8f57","#8b9058","#88915c","#859360","#809262","#7e9566","#7e9568","#78966a","#75966c","#71986d","#6a9871","#699973","#699a77","#609877","#5a947a","#5b967e","#589681","#599784","#559685","#549988","#549789"];
const hues3 = ["#549789","#52968c","#50978f","#499892","#459995","#4b9997","#4b9898","#50999d","#5597a0","#5496a2","#5996a3","#5f95a5","#6695a4","#6792a5","#6c92a9","#6b8da6","#7290aa","#728da9","#768daa","#788aa8","#7985a2","#8088a5"];
const hues4 = ["#8088a5","#8489a6","#8888a6","#8a88a4","#8f88a4","#9287a3","#9386a0","#98859f","#98849c","#9b8198","#a08298","#9d7c91","#a37e92","#a77e90","#a77b8c","#a87988","#aa7784","#ac7982","#ac757e","#ab757a","#a97375","#ad7776"];

class HueTest extends Component {
  constructor(props) {
    super(props);
    this.state = {
      row1:shuffleArray(["#ac7672","#ab756d","#aa7469","#aa7365","#a77161","#a57260","#a4725c","#a47258","#a37356","#a27554","#a37752","#a37951","#a47b4e","#a27b49","#a17d48","#a28149","#9f844a","#9a8347","#9c8a4c","#9a8a4c","#95894c","#8f8c4a"]),
      row2:shuffleArray(["#8f8c4a","#8e8f57","#8b9058","#88915c","#859360","#809262","#7e9566","#7e9568","#78966a","#75966c","#71986d","#6a9871","#699973","#699a77","#609877","#5a947a","#5b967e","#589681","#599784","#559685","#549988","#549789"]),
      row3:shuffleArray(["#549789","#52968c","#50978f","#499892","#459995","#4b9997","#4b9898","#50999d","#5597a0","#5496a2","#5996a3","#5f95a5","#6695a4","#6792a5","#6c92a9","#6b8da6","#7290aa","#728da9","#768daa","#788aa8","#7985a2","#8088a5"]),
      row4:shuffleArray(["#8088a5","#8489a6","#8888a6","#8a88a4","#8f88a4","#9287a3","#9386a0","#98859f","#98849c","#9b8198","#a08298","#9d7c91","#a37e92","#a77e90","#a77b8c","#a87988","#aa7784","#ac7982","#ac757e","#ab757a","#a97375","#ad7776"]),
      row1Score:0,
      row2Score:0,
      row3Score:0,
      row4Score:0,
      results:false
    };
    this.generateResults = this.generateResults.bind(this);
  }

  generateResults(){
    var score1=0, score2=0, score3=0, score4 = 0;
    for(var i=0; i < this.state.row1.length; i++){
      if(hues1[i] == this.state.row1[i]){
        score1++;
      }
    }
    for(var i=0; i < this.state.row2.length; i++){
      if(hues2[i] == this.state.row2[i]){
        score2++;
      }
    }
    for(var i=0; i < this.state.row3.length; i++){
      if(hues3[i] == this.state.row3[i]){
        score3++;
      }
    }
    for(var i=0; i < this.state.row4.length; i++){
      if(hues4[i] == this.state.row4[i]){
        score4++;
      }
    }
    // console.log(score)
    this.setState({
      row1Score:score1,
      row2Score:score2,
      row3Score:score3,
      row4Score:score4,
      results:true
    });
  }

  render() {
    if(this.state.results){
      return(
        <HueResult {...this.state}/>
      )
    }
    return (

Hue Test

Instructions:

Sort all chips in each colum by color hue.

The top and bottom chips are fixed.

Click "Done" once you finish sorting.

        <SortableList row={this.state.row1} onSortEnd={this.onSortEnd1} firstBox={"#ac7672"} lastBox={"#8f8c4a"}/>
        <SortableList row={this.state.row2} onSortEnd={this.onSortEnd2} firstBox={"#8f8c4a"} lastBox={"#549789"}/>
        <SortableList row={this.state.row3} onSortEnd={this.onSortEnd3} firstBox={"#549789"} lastBox={"#8088a5"}/>
        <SortableList row={this.state.row4} onSortEnd={this.onSortEnd4} firstBox={"#8088a5"} lastBox={"#ad7776"}/>
        <button type="button" onClick={this.generateResults}>Done</button>

    );
  }

  onSortEnd1 = ({oldIndex, newIndex}) => {
    this.setState({
      row1: arrayMove(this.state.row1, oldIndex, newIndex)
    });
  }

  onSortEnd2 = ({oldIndex, newIndex}) => {
    this.setState({
      row2: arrayMove(this.state.row2, oldIndex, newIndex)
    });
  }

  onSortEnd3 = ({oldIndex, newIndex}) => {
    this.setState({
      row3: arrayMove(this.state.row3, oldIndex, newIndex)
    });
  }

  onSortEnd4 = ({oldIndex, newIndex}) => {
    this.setState({
      row4: arrayMove(this.state.row4, oldIndex, newIndex)
    });
  }
}

export default HueTest;<|endoftext|>


<commit_before>//Modules
var modSpawning = require('module.spawning');
var modCommon = require('module.common');
var modUtil = require('module.utility');
var modStructures = require('module.structures');
var modMemory = require('module.memory');
var modAssist = require('module.assist');
var modConstants = require('module.constants');

//Function to remove 'dead' creeps from the memory to conserve space
function clearDead(){
  for(var i in Memory.creeps) {
    if(!Game.creeps[i]) {
      var job = Memory.creeps[i].role;
      var roomName = Memory.creeps[i].room;
      if(roomName){
        modUtil.decrementCreepNum(job,roomName);
        modSpawning.enqueuByJob(job,roomName,false);
      }
      delete Memory.creeps[i];
      console.log("Removed creep "+i+" (a "+job+") from memory");
    }
  }
}

//main loop
module.exports.loop = function () {

  //Only initialize if it hasnt been done (or it was manually set to false)
  if(Memory.initialized!==true){
    modMemory.init();
  }

  //Loop to check each room that is visible to the script
  for(var roomName in Memory.rooms){
    var room = Game.rooms[roomName];

    //Creep lists in each room, comparing lengths shows if there are 'others'
    var allCreepList = room.find(FIND_CREEPS);
    var myCreepList = _.filter(allCreepList, (creep) => (creep.owner && creep.owner.username ==="PCarton"));
    var enemyPresent = allCreepList.length>myCreepList.length;

    //Al the structures in the room that are controlled by the player
    var allStructs = room.find(FIND_MY_STRUCTURES);
    var allConstruct = room.find(FIND_MY_CONSTRUCTION_SITES);
    var towers = _.filter(allStructs, (struct) => struct.structureType === STRUCTURE_TOWER);
    var links = _.filter(allStructs, (struct) => struct.structureType === STRUCTURE_LINK);

    if(allStructs.length <=0 && allConstruct.length<=0){
      //Find the nearest room to this new one and spawn an assist builder and upgrader test
      var dist = -1;
      var otherRoom = null;
      for(var roomNameClose in Game.rooms){
        if(roomNameClose !== roomName){
          var tempDist = Game.map.getResourceType(roomName, roomNameClose);
          if(dist === -1 || tempDist < dist){
            dist = tempDist;
            otherRoom = roomNameClose;
          }
        }
      }
      if(otherRoom !== null){
        modSpawning.enqueueAssist(otherRoom, 'builder', roomName);
        modSpawning.enqueueAssist(otherRoom, 'upgrader', roomName);
      }
    }

    for(var tower in towers){
      if(!Memory.rooms[roomName].towers[tower.id]){
        modMemory.initTower(towers[tower]);
      }
    }

    for(var link in links){
      if(!Memory.rooms[roomName].links[link.id]){
        modMemory.initLink(links[link]);
      }
    }

    //Clear dead creeps from memory
    clearDead();

    //assign the right run method to each creep based on its role
    for(var name in myCreepList) {
        var creep = myCreepList[name];

        //Has the non-military creeps retreat
        //Mining creeps are considered military - like the supply line
        if(!room.controller.safeMode && enemyPresent && creep.memory.military !== true){
          modCommon.retreat(creep);
        }
        if(creep.ticksToLive == 1){
          creep.say("Goodbye, cruel world!",false);
        }
        //if the creep is to assist
        else if(creep.memory.assist){
          modAssist.run(creep);
        }
        //If there are no enemies, run the appropriate role method
        else{
          modUtil.runCreep(creep);
        }
    }

    //determine if new creeps need to be spawned and pick an appropriate spawner
    //Spawn logic is in a seperate module
    if(Memory.rooms[roomName].roles.numCreeps < modSpawning.maxCreeps){
      if(Game.time%modConstants.spawnFrequency===0)
        modSpawning.enqueueAllNeeded(roomName);
      modSpawning.spawn(roomName);
    }

    var control = room.controller;
    var enemy = modCommon.playerAttack(allCreepList);

    if(enemyPresent && enemy){
      if((!control.safeMode && !control.safeModeCooldown) &&  (control.safeModeAvailable > 0 )){
        control.activateSafeMode();
        Game.notify(modCommon.linkRoomAtTick(room,Game.time,"Activated Safe Mode(Player Attack by:"+enemy+")"),0);
      }else{
        Game.notify(modCommon.linkRoomAtTick(room,Game.time,"Player Attack by:"+enemy),0);
      }
    }

    var newEnemy = true;

    for(var towerId in Memory.rooms[roomName].towers){
      if(Memory.rooms[roomName].towers[towerId].mode === "attack")
        newEnemy = false;
      var towerObj = Game.getObjectById(towerId);
      if(enemyPresent){
        Memory.rooms[roomName].towers[towerId].mode = "attack";
        var targetID =   Memory.rooms[roomName].towers[towerId].target;
        var target = null;
        try{
          target = Game.getObjectById(targetID);
        }catch(err){
          console.log(err.name + "\n" + err.message);
        }
        if(!target){
          modStructures.pickTargets(Game.getObjectById(towerId), allCreepList);
        }
      }else{ //TODO check for injured creeps and set to heal, maybe room variable that triggers on hit
        Memory.rooms[roomName].towers[towerId].mode = "repair";
      }
      modStructures.runTower(towerObj,allCreepList);
    }

    for(var linkID in Memory.rooms[roomName].links){
      var linkMemObj = Memory.rooms[roomName].links[linkID];
      var linkObj = Game.getObjectById(linkID);
      if(linkMemObj.load && linkObj.energy == linkObj.energyCapacity){
        var notLoads = _.filter(links, (obj) => obj.id != linkID && obj.energy <= 100 );
        if(notLoads.length && linkObj.cooldown === 0){
          linkObj.transferEnergy(notLoads[0]);
        }
      }
    }

    if(enemyPresent && newEnemy)
      Game.notify(modCommon.linkRoomAtTick(room, Game.time, "EnemyFound"),60);
  }
};
<commit_msg>removed the buffer from other links<commit_after>//Modules
var modSpawning = require('module.spawning');
var modCommon = require('module.common');
var modUtil = require('module.utility');
var modStructures = require('module.structures');
var modMemory = require('module.memory');
var modAssist = require('module.assist');
var modConstants = require('module.constants');

//Function to remove 'dead' creeps from the memory to conserve space
function clearDead(){
  for(var i in Memory.creeps) {
    if(!Game.creeps[i]) {
      var job = Memory.creeps[i].role;
      var roomName = Memory.creeps[i].room;
      if(roomName){
        modUtil.decrementCreepNum(job,roomName);
        modSpawning.enqueuByJob(job,roomName,false);
      }
      delete Memory.creeps[i];
      console.log("Removed creep "+i+" (a "+job+") from memory");
    }
  }
}

//main loop
module.exports.loop = function () {

  //Only initialize if it hasnt been done (or it was manually set to false)
  if(Memory.initialized!==true){
    modMemory.init();
  }

  //Loop to check each room that is visible to the script
  for(var roomName in Memory.rooms){
    var room = Game.rooms[roomName];

    //Creep lists in each room, comparing lengths shows if there are 'others'
    var allCreepList = room.find(FIND_CREEPS);
    var myCreepList = _.filter(allCreepList, (creep) => (creep.owner && creep.owner.username ==="PCarton"));
    var enemyPresent = allCreepList.length>myCreepList.length;

    //Al the structures in the room that are controlled by the player
    var allStructs = room.find(FIND_MY_STRUCTURES);
    var allConstruct = room.find(FIND_MY_CONSTRUCTION_SITES);
    var towers = _.filter(allStructs, (struct) => struct.structureType === STRUCTURE_TOWER);
    var links = _.filter(allStructs, (struct) => struct.structureType === STRUCTURE_LINK);

    if(allStructs.length <=0 && allConstruct.length<=0){
      //Find the nearest room to this new one and spawn an assist builder and upgrader test
      var dist = -1;
      var otherRoom = null;
      for(var roomNameClose in Game.rooms){
        if(roomNameClose !== roomName){
          var tempDist = Game.map.getResourceType(roomName, roomNameClose);
          if(dist === -1 || tempDist < dist){
            dist = tempDist;
            otherRoom = roomNameClose;
          }
        }
      }
      if(otherRoom !== null){
        modSpawning.enqueueAssist(otherRoom, 'builder', roomName);
        modSpawning.enqueueAssist(otherRoom, 'upgrader', roomName);
      }
    }

    for(var tower in towers){
      if(!Memory.rooms[roomName].towers[tower.id]){
        modMemory.initTower(towers[tower]);
      }
    }

    for(var link in links){
      if(!Memory.rooms[roomName].links[link.id]){
        modMemory.initLink(links[link]);
      }
    }

    //Clear dead creeps from memory
    clearDead();

    //assign the right run method to each creep based on its role
    for(var name in myCreepList) {
        var creep = myCreepList[name];

        //Has the non-military creeps retreat
        //Mining creeps are considered military - like the supply line
        if(!room.controller.safeMode && enemyPresent && creep.memory.military !== true){
          modCommon.retreat(creep);
        }
        if(creep.ticksToLive == 1){
          creep.say("Goodbye, cruel world!",false);
        }
        //if the creep is to assist
        else if(creep.memory.assist){
          modAssist.run(creep);
        }
        //If there are no enemies, run the appropriate role method
        else{
          modUtil.runCreep(creep);
        }
    }

    //determine if new creeps need to be spawned and pick an appropriate spawner
    //Spawn logic is in a seperate module
    if(Memory.rooms[roomName].roles.numCreeps < modSpawning.maxCreeps){
      if(Game.time%modConstants.spawnFrequency===0)
        modSpawning.enqueueAllNeeded(roomName);
      modSpawning.spawn(roomName);
    }

    var control = room.controller;
    var enemy = modCommon.playerAttack(allCreepList);

    if(enemyPresent && enemy){
      if((!control.safeMode && !control.safeModeCooldown) &&  (control.safeModeAvailable > 0 )){
        control.activateSafeMode();
        Game.notify(modCommon.linkRoomAtTick(room,Game.time,"Activated Safe Mode(Player Attack by:"+enemy+")"),0);
      }else{
        Game.notify(modCommon.linkRoomAtTick(room,Game.time,"Player Attack by:"+enemy),0);
      }
    }

    var newEnemy = true;

    for(var towerId in Memory.rooms[roomName].towers){
      if(Memory.rooms[roomName].towers[towerId].mode === "attack")
        newEnemy = false;
      var towerObj = Game.getObjectById(towerId);
      if(enemyPresent){
        Memory.rooms[roomName].towers[towerId].mode = "attack";
        var targetID =   Memory.rooms[roomName].towers[towerId].target;
        var target = null;
        try{
          target = Game.getObjectById(targetID);
        }catch(err){
          console.log(err.name + "\n" + err.message);
        }
        if(!target){
          modStructures.pickTargets(Game.getObjectById(towerId), allCreepList);
        }
      }else{ //TODO check for injured creeps and set to heal, maybe room variable that triggers on hit
        Memory.rooms[roomName].towers[towerId].mode = "repair";
      }
      modStructures.runTower(towerObj,allCreepList);
    }

    for(var linkID in Memory.rooms[roomName].links){
      var linkMemObj = Memory.rooms[roomName].links[linkID];
      var linkObj = Game.getObjectById(linkID);
      if(linkMemObj.load && linkObj.energy == linkObj.energyCapacity){
        var notLoads = _.filter(links, (obj) => obj.id != linkID && obj.energy === 0 );
        if(notLoads.length && linkObj.cooldown === 0){
          linkObj.transferEnergy(notLoads[0]);
        }
      }
    }

    if(enemyPresent && newEnemy)
      Game.notify(modCommon.linkRoomAtTick(room, Game.time, "EnemyFound"),60);
  }
};
<|endoftext|>


<commit_before>actions.craft = function (params, successCallback, errorCallback) {
    checkParams(0, params);
    var craftAction = getAreaAction('craft', null);
    if (!craftAction) {
        throw new ProgrammingError("You cannot craft here.");
    }
    successCallback();
}
actions.enchant = function (params, successCallback, errorCallback) {
    checkParams(0, params);
    var enchantAction = getAreaAction('enchant', null);
    if (!enchantAction) {
        throw new ProgrammingError("You cannot craft enchantments here.");
    }
    successCallback();
}
actions.make = function (params, successCallback, errorCallback) {
    checkParams(1, params);
    var recipeKey = params[0];
    var recipe = allRecipes[recipeKey];
    if (!recipe || (recipe.type == 'crafting' && recipe.level > player.craftingSkill) || (recipe.type == 'enchanting' && recipe.level > player.enchantingSkill)) {
        throw new ProgrammingError("There is no unlocked recipe called '" + recipeKey+"'.");
    }
    if (recipe.type == 'crafting') {
        var craftAction = getAreaAction('craft', null);
        if (!craftAction) {
            throw new ProgrammingError("You cannot craft here.");
        }
    } else if (recipe.type == 'enchanting') {
        var enchantAction = getAreaAction('enchant', null);
        if (!enchantAction) {
            throw new ProgrammingError("You cannot enchant here.");
        }
    }
    if (!canCraft(recipe)) {
        throw new ProgrammingError("You don't have the necessary ingredients to craft '" + recipeKey+"'.");
    }
    craftRecipe(recipe);
    successCallback();
}

function CraftAction(slot) {
    this.actionName = "craft";
    this.getDiv = function () {
        return $div('action slot' + slot, $div('box', 'Craft')).attr('helpText', 'Craft items from the ingredients you have bought or collected. Learn more Craft skills in the skill tree to unlock new recipes.');
    };
    this.perform = function () {
        displyCraftingPage($('.js-craftContainer'), player.craftingSkill, craftingRecipes);
        recordAction(this.actionName, this.actionTarget);
    };
}
function EnchantAction(slot) {
    this.actionName = "enchant";
    this.getDiv = function () {
        return $div('action slot' + slot, $div('box', 'Enchant')).attr('helpText', 'Craft enchantments that can be used later to power up the gear you are wearing. Enchantments are lost when the enchanted item is unequiped or when you rest. Learn more Enchantment skills in the skill tree to unlock new recipes.');
    };
    this.perform = function () {
        displyCraftingPage($('.js-enchantContainer'), player.enchantingSkill, enchantingRecipes);
        recordAction(this.actionName, this.actionTarget);
    };
};

function displyCraftingPage($container, skillLevel, recipeList) {
    closeAll();
    $container.addClass('open');
    $('.js-inventoryContainer').addClass('open');
    $('.js-inventoryPanel').removeClass('selected');
    $('.js-inventoryPanel.js-items').addClass('selected');
    $container.find('.js-body').empty();
    for (var i = 0; i < recipeList.length && i <= skillLevel; i++) {
        $('.js-enchantContainer .js-body').append($div('heading', 'Level ' + i));
        $.each(recipeList[i], function (key, recipe) {
            //{'result': 'fur', 'ingredients': {'furScrap': 5}},
            var item = allItems[recipe.result];
            var $recipe = $container.find('.js-baseRecipe').clone().removeClass('js-baseRecipe').show();
            $recipe.find('.js-result').html(getItemName(item)).attr('helpText', getItemHelpTextWithEnchantments(item));
            var canCraft = true;
            var $ingredient = $recipe.find('.js-ingredient').remove();
            $.each(recipe.ingredients, function (key, amount) {
                amount = ingredientAmount(amount);
                $ingredient = $ingredient.clone();
                var ingredient = allItems[key];
                var amountOwned = player.inventory[ingredient.slot][key];
                $ingredient.find('.js-current').text(amountOwned);
                $ingredient.find('.js-cost').text(amount);
                $ingredient.find('.js-name').html(getItemName(ingredient));
                $ingredient.data('ingredient', ingredient);
                $ingredient.data('amount', amount);
                $recipe.append($ingredient);
                $ingredient.toggleClass('enoughOwned', amountOwned >= amount);
                canCraft = canCraft && (amountOwned >= amount);
            });
            $recipe.toggleClass('canCraft', canCraft);
            $recipe.data('recipe', recipe);
            $container.find('.js-body').append($recipe);
        });
    }
}

function ingredientAmount(baseAmount) {
    //the 'care' skill reduces crafting costs by 25%
    return Math.max(1, Math.round(baseAmount * (player.specialSkills.care ? .75 : 1)));
}

function setupCrafting() {
    $('.js-craftContainer').on('click', '.js-craft', function () {
        //get the amount to make sure it can be sold
        var recipe = $(this).closest('.js-recipe').data('recipe');
        craftRecipe(recipe);
    });
    $('.js-enchantContainer').on('click', '.js-enchant', function () {
        //get the amount to make sure it can be sold
        var recipe = $(this).closest('.js-recipe').data('recipe');
        craftRecipe(recipe);
    });
}

function craftRecipe(recipe) {
    if (!canCraft(recipe)) {
        return;
    }
    var item = allItems[recipe.result];
    player.inventory[item.slot][item.key]++;
    //copy duplicates items you craft
    if (player.specialSkills.copy) {
        player.inventory[item.slot][item.key]++;
    }
    $.each(recipe.ingredients, function (key, amount) {
        amount = ingredientAmount(amount);
        var ingredient = allItems[key];
        player.inventory[ingredient.slot][ingredient.key] -= amount;
    });
    uiNeedsUpdate.inventory = true;
    //show the inventory page that the item was added to
    $('.js-inventoryPanel').removeClass('selected');
    $('.js-inventoryPanel.js-' + item.slot).addClass('selected');
    //update buy buttons now that you have less gold
    uiNeedsUpdate.craft = true;
    uiNeedsUpdate.enchant = true;
    recordAction('make', recipe.key);
}

function updateCrafting($container) {
    $container.find('.js-body .js-recipe').each(function () {
        var $recipe = $(this);
        var canCraft = true;
        $recipe.find('.js-ingredient').each(function () {
            var $ingredient = $(this);
            var ingredient = $ingredient.data('ingredient');
            var amount = $ingredient.data('amount');
            var amountOwned = player.inventory[ingredient.slot][ingredient.key];
            canCraft = canCraft && (amountOwned >= amount);
            $ingredient.find('.js-current').text(amountOwned);
        });
        $recipe.toggleClass('canCraft', canCraft);
    });
}

function canCraft(recipe) {
    if ((recipe.type == 'crafting' && recipe.level > player.craftingSkill) || (recipe.type == 'enchanting' && recipe.level > player.enchantingSkill) ) {
        return false;
    }
    var canCraft = true;
    $.each(recipe.ingredients, function (key, amount) {
        amount = ingredientAmount(amount);
        var ingredient = allItems[key];
        var amountOwned = player.inventory[ingredient.slot][ingredient.key];
        if (amountOwned < amount) {
            canCraft = false;
            return false;
        }
        return true;
    });
    return canCraft;
}
<commit_msg>Fix ingredient colors weren't changing in the crafting screen as the amounts change.<commit_after>actions.craft = function (params, successCallback, errorCallback) {
    checkParams(0, params);
    var craftAction = getAreaAction('craft', null);
    if (!craftAction) {
        throw new ProgrammingError("You cannot craft here.");
    }
    successCallback();
}
actions.enchant = function (params, successCallback, errorCallback) {
    checkParams(0, params);
    var enchantAction = getAreaAction('enchant', null);
    if (!enchantAction) {
        throw new ProgrammingError("You cannot craft enchantments here.");
    }
    successCallback();
}
actions.make = function (params, successCallback, errorCallback) {
    checkParams(1, params);
    var recipeKey = params[0];
    var recipe = allRecipes[recipeKey];
    if (!recipe || (recipe.type == 'crafting' && recipe.level > player.craftingSkill) || (recipe.type == 'enchanting' && recipe.level > player.enchantingSkill)) {
        throw new ProgrammingError("There is no unlocked recipe called '" + recipeKey+"'.");
    }
    if (recipe.type == 'crafting') {
        var craftAction = getAreaAction('craft', null);
        if (!craftAction) {
            throw new ProgrammingError("You cannot craft here.");
        }
    } else if (recipe.type == 'enchanting') {
        var enchantAction = getAreaAction('enchant', null);
        if (!enchantAction) {
            throw new ProgrammingError("You cannot enchant here.");
        }
    }
    if (!canCraft(recipe)) {
        throw new ProgrammingError("You don't have the necessary ingredients to craft '" + recipeKey+"'.");
    }
    craftRecipe(recipe);
    successCallback();
}

function CraftAction(slot) {
    this.actionName = "craft";
    this.getDiv = function () {
        return $div('action slot' + slot, $div('box', 'Craft')).attr('helpText', 'Craft items from the ingredients you have bought or collected. Learn more Craft skills in the skill tree to unlock new recipes.');
    };
    this.perform = function () {
        displyCraftingPage($('.js-craftContainer'), player.craftingSkill, craftingRecipes);
        recordAction(this.actionName, this.actionTarget);
    };
}
function EnchantAction(slot) {
    this.actionName = "enchant";
    this.getDiv = function () {
        return $div('action slot' + slot, $div('box', 'Enchant')).attr('helpText', 'Craft enchantments that can be used later to power up the gear you are wearing. Enchantments are lost when the enchanted item is unequiped or when you rest. Learn more Enchantment skills in the skill tree to unlock new recipes.');
    };
    this.perform = function () {
        displyCraftingPage($('.js-enchantContainer'), player.enchantingSkill, enchantingRecipes);
        recordAction(this.actionName, this.actionTarget);
    };
};

function displyCraftingPage($container, skillLevel, recipeList) {
    closeAll();
    $container.addClass('open');
    $('.js-inventoryContainer').addClass('open');
    $('.js-inventoryPanel').removeClass('selected');
    $('.js-inventoryPanel.js-items').addClass('selected');
    $container.find('.js-body').empty();
    for (var i = 0; i < recipeList.length && i <= skillLevel; i++) {
        $('.js-enchantContainer .js-body').append($div('heading', 'Level ' + i));
        $.each(recipeList[i], function (key, recipe) {
            //{'result': 'fur', 'ingredients': {'furScrap': 5}},
            var item = allItems[recipe.result];
            var $recipe = $container.find('.js-baseRecipe').clone().removeClass('js-baseRecipe').show();
            $recipe.find('.js-result').html(getItemName(item)).attr('helpText', getItemHelpTextWithEnchantments(item));
            var canCraft = true;
            var $ingredient = $recipe.find('.js-ingredient').remove();
            $.each(recipe.ingredients, function (key, amount) {
                amount = ingredientAmount(amount);
                $ingredient = $ingredient.clone();
                var ingredient = allItems[key];
                var amountOwned = player.inventory[ingredient.slot][key];
                $ingredient.find('.js-current').text(amountOwned);
                $ingredient.find('.js-cost').text(amount);
                $ingredient.find('.js-name').html(getItemName(ingredient));
                $ingredient.data('ingredient', ingredient);
                $ingredient.data('amount', amount);
                $recipe.append($ingredient);
                $ingredient.toggleClass('enoughOwned', amountOwned >= amount);
                canCraft = canCraft && (amountOwned >= amount);
            });
            $recipe.toggleClass('canCraft', canCraft);
            $recipe.data('recipe', recipe);
            $container.find('.js-body').append($recipe);
        });
    }
}

function ingredientAmount(baseAmount) {
    //the 'care' skill reduces crafting costs by 25%
    return Math.max(1, Math.round(baseAmount * (player.specialSkills.care ? .75 : 1)));
}

function setupCrafting() {
    $('.js-craftContainer').on('click', '.js-craft', function () {
        //get the amount to make sure it can be sold
        var recipe = $(this).closest('.js-recipe').data('recipe');
        craftRecipe(recipe);
    });
    $('.js-enchantContainer').on('click', '.js-enchant', function () {
        //get the amount to make sure it can be sold
        var recipe = $(this).closest('.js-recipe').data('recipe');
        craftRecipe(recipe);
    });
}

function craftRecipe(recipe) {
    if (!canCraft(recipe)) {
        return;
    }
    var item = allItems[recipe.result];
    player.inventory[item.slot][item.key]++;
    //copy duplicates items you craft
    if (player.specialSkills.copy) {
        player.inventory[item.slot][item.key]++;
    }
    $.each(recipe.ingredients, function (key, amount) {
        amount = ingredientAmount(amount);
        var ingredient = allItems[key];
        player.inventory[ingredient.slot][ingredient.key] -= amount;
    });
    uiNeedsUpdate.inventory = true;
    //show the inventory page that the item was added to
    $('.js-inventoryPanel').removeClass('selected');
    $('.js-inventoryPanel.js-' + item.slot).addClass('selected');
    //update buy buttons now that you have less gold
    uiNeedsUpdate.craft = true;
    uiNeedsUpdate.enchant = true;
    recordAction('make', recipe.key);
}

function updateCrafting($container) {
    $container.find('.js-body .js-recipe').each(function () {
        var $recipe = $(this);
        var canCraft = true;
        $recipe.find('.js-ingredient').each(function () {
            var $ingredient = $(this);
            var ingredient = $ingredient.data('ingredient');
            var amount = $ingredient.data('amount');
            var amountOwned = player.inventory[ingredient.slot][ingredient.key];
            canCraft = canCraft && (amountOwned >= amount);
            $ingredient.toggleClass('enoughOwned', amountOwned >= amount);
            $ingredient.find('.js-current').text(amountOwned);
        });
        $recipe.toggleClass('canCraft', canCraft);
    });
}

function canCraft(recipe) {
    if ((recipe.type == 'crafting' && recipe.level > player.craftingSkill) || (recipe.type == 'enchanting' && recipe.level > player.enchantingSkill) ) {
        return false;
    }
    var canCraft = true;
    $.each(recipe.ingredients, function (key, amount) {
        amount = ingredientAmount(amount);
        var ingredient = allItems[key];
        var amountOwned = player.inventory[ingredient.slot][ingredient.key];
        if (amountOwned < amount) {
            canCraft = false;
            return false;
        }
        return true;
    });
    return canCraft;
}
<|endoftext|>