Wednesday, July 13, 2016

Javascript Maps with UnderscoreJS

I'm continuing my discussion about UnderscoreJS, this time focusing on maps. This entry will be brief but hopefully it'll be useful.

I'm presuming that you installed NodeJS and you're familiar with RequireJS. If not, view those blogs that I linked. You'll also need some kind of editor; I recommend Sublime Text which is available for both Windows and Mac OS.

Create the following directory structure:

app\
js\lib\src\

Create this file, call it index.html, and save it in the root directory of your application.

<html>
   <head>
    <meta charset="utf-8">
    <title>RequireJS, Underscore, Arrays</title>
  </head>
  <body>
    <script src="http://requirejs.org/docs/release/2.2.0/comments/require.js" data-main="js/lib/src/config"></script>

    <h1>RequireJS, Underscore, Maps</h1>

    <div id="DISPLAY_MAPx"></div>
    <div id="KEYS"></div>
    <div id="VALUES"></div>
    <div id="SIZE"></div>
    <div id="LAST_NAME"></div>

  </body>
</html>

Create that config.js file under js/lib/src.

requirejs.config({

baseUrl: 'js/lib/src',
      paths: {
        'jquery': [
             '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min',
              '../lib/jquery-2.1.1.min'
        ],
        'underscore': 'http://underscorejs.org/underscore',
        'app': '../../../app'
      }
});

// Load the main app module to start the app
requirejs(["app/main"]);


Create a main.js file amd save it under the app directory. This is where we can demonstrate various UnderscoreJS Javascript functions for arrays.

require(['config', 'display'], function(config, display) {

var map = {
"FirstName": "Sandy",
"LastName": "Beach",
"Age": 21
};

    var keys = _.keys(map);
    var values = _.values(map);
    var size = _.size(map);

  var toString = "<br>";
    _.map(map, function(value,keyword){ toString = toString + keyword+":"+value+"<br>"; });

    var lastName = _.propertyOf(map)('LastName');

   display.showName("DISPLAY_MAP", toString);
   display.showName("KEYS", keys);
   display.showName("VALUES", values);
   display.showName("SIZE", size);
   display.showName("LAST_NAME", lastName);

})

Finally, create a file called display.js, and save it under js/lib/src. If you've read my blog on Javascript Arrays, you've seen this before.

define(['underscore', 'jquery'], function() {
     var showName = function(div, value) {
     
     
        value = '<b>' + div + ':</b> ' + value;
        div = '#' + div;
        $(div).html(value);
     
    };

    return {
           showName: showName
    };

});

Run your server and view the results. Go to the UnderscoreJS page to see all of the other useful functions. Remember: If there is a Javascript package that makes coding easier, use it!

Have fun!

Tuesday, July 12, 2016

Javascript Arrays - Don't Reinvent the Wheel

There are several Javascript packages out there and one of the extremely useful ones is called UnderscoreJS.

I'm presuming that you installed NodeJS and you're familiar with RequireJS. If not, view those blogs that I linked. You'll also need some kind of editor; I recommend Sublime Text which is available for both Windows and Mac OS.

Create the following directory structure:

app\
js\lib\src\

Create this file, call it index.html, and save it in the root directory of your application.

<html>
  <head>
    <meta charset="utf-8">
    <title>RequireJS, Underscore, Arrays</title>
  </head>
  <body>
    <script src="http://requirejs.org/docs/release/2.2.0/comments/require.js" data-main="js/lib/src/config"></script>

    <h1>RequireJS, Underscore, Arrays</h1>

    <div id="ARRAY"></div>
    <div id="FIRST"></div>
    <div id="LAST"></div>
    <div id="INDEXOF_B"></div>
    <div id="LAST_INDEXOF_B"></div>
    <div id="SIZE"></div>
    <div id="UNIQ"></div>
    <div id="ARRAY2"></div>
    <div id="UNION"></div>
    <div id="INTERSECTION"></div>

  </body>
</html>

Create that config.js file under js/lib/src.

requirejs.config({

baseUrl: 'js/lib/src',
      paths: {
        'jquery': [
             '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min',
              '../lib/jquery-2.1.1.min'
        ],
        'underscore': 'http://underscorejs.org/underscore',
        'app': '../../../app'
      }
});

// Load the main app module to start the app
requirejs(["app/main"]);


Create a main.js file amd save it under the app directory. This is where we can demonstrate various UnderscoreJS Javascript functions for arrays.

require(['config', 'display'], function(config, display) {
    var array = ['A', 'B', 'C', 'D', 'E', 'B', 'F'];
    var first = _.first(array);
    var last = _.last(array);
    var indexOf = _.indexOf(array,'B');
    var lastIndexOf = _.lastIndexOf(array,'B');
    var size = _.size(array);
    var uniq = _.uniq(array);

    var array2 =  ['F', 'A', 'C', 'T', 'S'];
    var union = _.union(array, array2);
    var intersection = _.intersection(array, array2);

        display.showName("ARRAY", array);
    display.showName("FIRST", first);
    display.showName("LAST", last);
    display.showName("INDEXOF_B", indexOf);
    display.showName("LAST_INDEXOF_B", lastIndexOf);
    display.showName("SIZE", size);
    display.showName("UNIQ", uniq);
    display.showName("ARRAY2", array2);
    display.showName("UNION", union);
    display.showName("INTERSECTION", intersection);
})

Finally, create a file called display.js, and save it under js/lib/src.

define(['underscore', 'jquery'], function() {
     var showName = function(div, value) {
       
     
        value = '<b>' + div + ':</b> ' + value;
        div = '#' + div;
        $(div).html(value);
     
    };

    return {
           showName: showName
    };

});

Run your server and view the results. Go to the UnderscoreJS page to see all of the other useful functions. Remember: If there is a Javascript package that makes coding easier, use it!

Have fun!

Monday, July 11, 2016

Fuzzy Logic Air Combat

There are a lot of news on the Artificial Intelligence front today. One which peaked my interest is actually a local story. A UC grad student built an "intelligent foe" for pilots to fight and train against. Nick Ernest worked with the Air Force to create Alpha, an artificial intelligence system that controls the flights of military drones in realistic combat simulations. Gene Lee, a retired U.S. Air Force colonel with decades of experience as a fighter pilot and aerial combat instructor, fought against this foe and was shot down EVERY TIME.

Alpha approaches modern air combat situations the way a human would. It analyzes data from the field and decides what moves to make. It uses a fuzzy-logic tree to make those decisions. A fuzzy-logic tree is a set of IF-THEN statements with one or more inputs and an output. 

How Does Fuzzy Logic Work?

Conventional logic that a computer can understand takes precise input and produces a definite output as TRUE or FALSE.  Fuzzy logic works on the levels of possibilities of input to achieve the definite output.

Fuzzy logic is made up of four components:

The Fuzzification Module which splits input signals into one of five values: LP (x is a large positive number), MP (x is a medium large positive number), S (x is a small number), MN (x is a medium large negative number), LN (x is a large negative number).
The Knowledge Base which is the large IF-THEN database put together by experts in the subject.
The Inference Engine which simulates human thinking by making fuzzy inferences of the IF-THEN rules.
The Defuzzification Module which transforms the fuzzy set from the Inference Engine and returns a crisp result.

For example, let's consider an Artificially Intelligent air conditioner. The Fuzzification Module contains the various temperature values: very cold, cold, warm, very warm, and hot. Then you construct the Knowledge Base by creating various rules such as: if the room is very warm or hot and you want the room to be cool, blow cold air. This can be translated to:

     IF (hot OR very-warm) AND (target-temperature == cold) THEN output Cold. 

The Inference Engine uses the rules and determines what to do, applying the fuzzy value. Finally, the Defuzzification Module returns the value for Cold.

Back to Air Combat

In the case of the air combat "intelligent foe", there could be hundreds or maybe even thousands of variables. Altitude of the plane, location of the plane, is the plane ascending/descending, what is topology around the area, and so on. These values are put into thousands of IF-THEN statements, and a result determines what to do.

So, is there anything that fuzzy logic could do to help the general public? Consider medical diagnosis which is not very simple or straight forward. There are several different conditions that share some of the same symptoms. Based on these symptoms, there may be several possible diagnoses. This uncertainty could prompt the program to ask additional questions; questions the doctor may have not considered relevant, that could result in determining that the patient has a very rare condition that maybe only one in a hundred thousand people have.  

Let's consider another application. Facial recognition. The input images may not be clear and the person won't be standing still facing forward. So, how could a computer program use a moving image to pair up with thousands of potential faces? Again, using various rules of height, hair length, eye color, scars/tattoos and so on, various potential faces can be eliminated until a very small fraction of candidates can be returned. Similarly, you can isolate someone's voice in an audio file and filter out all of the background noises using fuzzy logic.

Another plus with fuzzy logic is that it's easy to add additional rules as the expert learns more about the topic at hand and quite possibly, you could have the system generate its own rules based on the inputs known at the time and the result it witnesses. Returning back full circle, this is how a system can learn how a pilot thinks.


Monday, July 4, 2016

RequireJS For Beginners

First you'll need to download Nodejs and create a simple localhost server. See my blog post on how to do that. You'll need to download a decent text editor for this as well. I recommend Sublime Text which is available for both Windows and Mac OS. You can easily see your directory structure and edit your files in it!


Create the following directory structure:

app\
js\lib\src\

We're going to create a very simple webpage that tells the browser that we're using RequireJS and we'll add a div tag. Call this file index.html and save it in the root directory of your application.

<html>
  <head>
    <meta charset="utf-8">
    <title>RequireJS</title>
  </head>
  <body>
    <script src="http://requirejs.org/docs/release/2.2.0/comments/require.js" data-main="js/lib/src/config"></script>

    <div id="NAME"></div>

  </body>
</html>

Every RequireJS application needs a config file. That is what we're telling the web browser via that data-main section. Let's create that config.js file under js/lib/src.

requirejs.config({

baseUrl: 'js/lib/src',
      paths: {
        'jquery': [
             '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min',
              '../lib/jquery-2.1.1.min'
        ],
        'underscore': 'http://underscorejs.org/underscore',
        'app': '../../../app'
      }
});

// Load the main app module to start the app
requirejs(["app/main"]);

This is telling the browser that we will be using the jquery and underscore javascript libraries reverenced at these URLs. It also tells the browser, when we say "app", reference it off of the app root (that's three directories before the baseUrl and then in the directory app).

The main.js file is the one that calls and references all of the other javascript files. So it tells the web browser that this code requires certain files: the configuration file (shown above) and your script. We'll make a simple script that shows "Hello" followed by a name. Create a file called main.js and put it under the app directory.

require(['config', 'hello'], function(config, hello) {
   hello.showName("NAME", "Bob");
})

This tells the web browser, in the javascript file called hello.js, run the showName function and pass it the parameters "NAME" and "Bob". Let's write that script and save it under js/lib/src.

define(['underscore', 'jquery'], function() {
     var showName = function(div, value) {
        
        value = '<b>Hello ' + value + '!</b> ';
         div = '#' + div;
        $(div).html(value);
       
     };

      return {
           showName: showName
      };

});

This javascript file uses the jquery and underscore javascript files we referenced in the config file. It creates some html text that says "Hello (name)" in bold. This is written in div section. So, looking back at the app.js, we will be writing "Hello Bob!" in the div section NAME (see index.html).

Run your server and view the results.

Okay Now What?

Let's prove to ourselves that we know what we are doing. Let's add a second div in the index.html:

<div id="NAME2"></div>

And add another call in the app.js  file.

hello.showName("NAME2","Mary");

View the file and you should see:
Hello Bob!
Hello Mary!

Now, to show how we would access ANOTHER javascript file, make a copy of hello.js and call it goodbye.js. Change the word "Hello" to "Goodbye". Keep the function name the same. We're going to PROVE that we're using the second script.

Update the app.js file.

require(['config', 'hello', 'goodbye'], function(config, hello, goodbye) {
   hello.showName("NAME", "Bob");
   hello.showName("NAME2", "Mary");
   goodbye.showName("GNAME", "Bob");
   goodbye.showName("GNAME2", "Mary"); })


Now update the index.html file:

<html>
  <head>
    <meta charset="utf-8">
    <title>RequireJS</title>
  </head>
  <body>
    <script src="http://requirejs.org/docs/release/2.2.0/comments/require.js" data-main="js/lib/src/config"></script>

    <div id="NAME"></div>
    <div id="NAME2"></div>
    <div id="GNAME"></div>
    <div id="GNAME2"></div>

   </body>
</html>

We we view the page, we will see:

Hello Bob!
Hello Mary!
Goodbye Bob!
Goodbye Mary!

So, there we go, we made a javascript file that referenced two different javascript files!

A Short Fun Project

Let's have some fun with this now. We will make a simple webpage that generates the six stats for an AD&D character: Strength, Dexterity, Constitution, Intelligence, Wisdom and Charisma. We will do a simple 3D6 calculation (roll 3 six-sided dice and add the numbers).

We will update the index.html page as follows:

<html>
  <head>
    <meta charset="utf-8">
    <title>RequireJS</title>
  </head>
  <body>
    <script src="http://requirejs.org/docs/release/2.2.0/comments/require.js" data-main="js/lib/src/config"></script>

    <div id="STR"></div>
    <div id="DEX"></div>
    <div id="CON"></div>
    <div id="INT"></div>
    <div id="WIS"></div>
    <div id="CHA"></div>
   </body>
</html>

Now we will update the main.js to call a different javascript file called character. We'll pass in the name of the stat (which matches the div id in the webpage).

require(['config', 'character'], function(config, character) {
   character.showStat("STR");
   character.showStat("DEX");
   character.showStat("CON");
   character.showStat("INT");
   character.showStat("WIS");
   character.showStat("CHA");
})

We'll create the character.js file and save it under js/lib/src. We'll create a roll function and a showStat function:

define(['underscore', 'jquery'], function() {

    var roll = function() {
         return Math.floor(Math.random()*6+1) + Math.floor(Math.random()*6+1) +
            Math.floor(Math.random()*6+1);        
     };

    var showValue = function(div) {
       var value = roll();
       var stat = '<b>' + div + ' </b> ' + value;

       div = '#' + div;
       $(div).html(stat);
    };

     return {
           showValue: showValue,
           getBonus: getBonus,
           roll: roll
     };
});

When we view the page, we will see the stat followed by the value rolled. Refreshing the file will generate a new character.  That's fine, but what if we wanted to use those values somewhere else? We can update the main.js to call the roll function and pass the value to showValue and have showValue use that value:

require(['config', 'character'], function(config, character) {
      var strength = character.roll();
      character.showValue('STR',strength);

      var dexterity = character.roll();
      character.showValue('DEX',dexterity);

      var constitution = character.roll();
      character.showValue('CON',constitution);

      var intelligence = character.roll();
      character.showValue('INT',intelligence);

      var wisdom = character.roll();
      character.showValue('WIS',wisdom);

      var charisma = character.roll();
      character.showValue('CHA',charisma);
})

Then we update the character.js showValue function as follows:

    var showValue = function(div, value) {
       
        var stat = '<b>' + div + ' </b> ' + value;
        div = '#' + div;
        $(div).html(stat);
      
     };

      return {
           showValue: showValue,          
           roll: roll
      };

There you go, a simple AD&D character generator using RequireJS!

A Simple Localhost Server

Supports:
Windows and Mac OS

Step 1:
Download and install Nodejs.

Step 2:
Write the Javascript shown below in your favorite editor. I recommend Sublime Text. Save the file in a  folder where your javascript/html files will reside. Call the file server.js.

/**
 *A simple localhost web server.
 */
var http = require('http');
var fs = require('fs');
var url = require('url');


// Create a server
http.createServer( function (request, response) { 
   // Parse the request containing file name
   var pathname = url.parse(request.url).pathname;
  
   // Print the name of the file for which request is made.
   console.log("Request for " + pathname + " received.");
  
   // Read the requested file content from file system
   fs.readFile(pathname.substr(1), function (err, data) {
      if (err) {
         console.log(err);
         // HTTP Status: 404 : NOT FOUND
         // Content Type: text/plain
         response.writeHead(404, {'Content-Type': 'text/html'});
      }else{   
         //Page found     
         // HTTP Status: 200 : OK
         // Content Type: text/plain
         response.writeHead(200, {'Content-Type': 'text/html'});   
        
         // Write the content of the file to response body
         response.write(data.toString());       
      }
      // Send the response body
      response.end();
   });  
}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');

Step 3:
Go to your command prompt.
Windows: Start > run> cmd
Mac: Finder > Applications > Utilities > Terminal

Step 4:
Go to that directory and run:
node server.js 

Step 5:
If you haven't put any other files in this directory, put a simple index.html file with some text in it just to verify that this works. 

Step 6:
Launch your favorite browser and go to: http://127.0.0.1:8081/index.html