Neural Networks and Unguided Machine Learning

Lately, I’ve been taking another look at my davebrain app, which is a simplified neural network. In the following post, I’ll talk first about the changes I’ve made to it since my last post and some challenges faced when building this kind of simulation. Secondly, I’ll talk about some interesting observations regarding the network’s behavior.

Building a Better Brain Part 1: Speed

One of the challenges in building a randomly-generated neural network with a potentially limitless number of neurons is, of course, optimization. After all, if each brain ‘cycle’ has 500+ neurons, with each neuron connected to 250 other neurons, we’re gonna need to focus pretty heavily on optimization if we want any generations to pass (and thus any learning to happen). The original setup used CSS, ng-repeats, and <div>s to actually draw the neurons. This looked pretty cool, and allowed us to do some neat things with 3D CSS, but man, was it slow! Instead, I’ve replaced this with HTML5 <canvas>, which allows a much faster drawing speed.

In addition, I’ve decided to fully remove the 3d-mode. The minor interesting graphical improvement this afforded (a 3D ‘brain’) was vastly offset by the huge detriment to performance.

These two changes serve to generally improve the speed of the app such that, at maximum speed, we can actually begin to see some emergent behavior now.

The other major changes made to the network are in the form of the actual behavior of the network itself, and are, in my opinion, more interesting.

Building a Better Brain Part 2: Sensing and Learning

The original goal of this project was to create a network that could learn given very minimal ‘rules’. The network then controls an ‘organism’ that attempts to seek out a prey item (and ‘consume’ it). While we could pretty easily directly program the organism to hunt down and find the organism directly, that would negate the purpose of the neural network (and thus the entire app). Instead, we need to determine simple rules that, in the lingo of evolutionary biology, act as both positive and negative environmental pressure to our organism1 . These are as follows, including both ‘reset’ scenarios as well as sensing and learning:

  • Hyperactivity (Seizure): If 90% or more of the neurons are ‘active’ (firing), then the organism’s brain has essentially experienced a lethal seizure. The organism is reset.
  • Hypoactivity (Brain Death): If no neurons are firing, the organism is essentially experiencing brain death. Again, the organism is reset.
  • Successful Hunt: If the organism ‘catches’ the prey (measured as the location of the prey and organism being within a certain threshold), then obviously it’s been successful. It’s reset, but a bonus is added to its ‘score’.
  • Energy Usage (Starvation): Finally, each neuron that fires uses up a certain percentage of a total energy amount. This is akin to metabolic energy that is used and must be replenished before an organism dies of starvation/exhaustion. If this energy is used up, then the organism resets.
  • Directional Tendency: As the organism moves, any movement towards the prey adds a point to the score. Any movement away from the prey subtracts a point. This is rule is actually the least ‘unguided’, as there should be nothing explicitly telling the organism that it needs to head towards the prey. I may remove this later.
  • Range Finding: In the original design, each ‘eyespot’ of the organism housed (or rather, was the geometric center of) one distance sensor that sensed the distance to the prey item. In this updated, new design, each eyespot actually now houses two sensors, one long distance and one short distance. As with regular neurons, the output of these is either binary. In the case of the distance sensors, this binary state is a random var, with the likelihood of the sensor being on going up the closer the organism is. The addition of two extra sensors affords the organism a little more specificity in locating the prey.
  • Scoreboard: The score, as well as a rolling average, is now graphed on a scoreboard so that you can more easily see the improvement (or lack of improvement!) over time.
  • Learning (Path Adjustment): Once a generation is complete - whether it’s successful or not - the network needs to be changed based on the score of that generation. This is done in a way that mimics biological learning: successful paths (measured as a score higher than the previous rolling average) are strengthened, while unsuccessful paths are weakened. The exact mathematical method of strengthening and weakening the paths depends on user choice:

    • If the user sets the Path Change Method to Multiplicative, the strength of successful paths is multiplied by 1.2 if successful, and 0.8 if unsuccessful.
    • If the user sets the Path Change Method to Additive, 0.02 is added to the path if successful, and 0.02 is subtracted if unsuccessful.

Building a Better Brain Part 3: Observations

  • The first, and most prevalent observation about this simulation is that it’s slow. Even if I do everything to optimize it, remember that this is a combination of evolution and learning simulator, and it tends to make mistakes just as often as it makes correct choices. In many cases, it needs to be run for a least a few hours before it shows any significant improvement.
  • In line with above, remember that this is a JavaScript app, and as with a lot of front-end stuff, will stop running when the tab it’s in is not focused. So run it on a machine you’re not using!
  • Interestingly, the overall pattern of scores tends to be sinusoidal. That is, a relatively successful generation is almost always followed by a relatively unsuccessful generation. This makes sense in the context of how the network learns.
  • For the (relatively simple) behavior that the organism needs to learn, a huge number of neurons doesn’t actually really improve it that much. This makes sense, as C. elegans has only 302 neurons at around an 8% connect rate (that is, each neuron is on average connected to around 8% of its fellow neurons).


1.I’ll note here that this simulation actually acts both as a learning simulator - that is, the organism tries to learn how to figure out how to achieve its goal - and as an evolution simulator, whereby the organism changes during each generation depending on the previous generation’s performance and an element of random mutation.

Simple Server in Node and Express

What This Is

The following is a brief explanation of how to set up (and run!) a server using NodeJS (from now on, called Node) and Node’s express module. You’ll learn how to install Node, as well as how to download and include (‘require’ packages). By the end of this, you’ll have a simple webserver running that can be extended into multiple projects:

Prior Knowledge

To get the most out of this tutorial, you’ll need to know a few things beforehand:

  • You’ll need to know basic HTML. While we won’t initially be doing anything on the front-end, we’ll eventually be sending some basic webpages forward.
  • You may want to know some basic CSS. While it’s not hugely necessary, I’d also recommend beginning developers learn HTML and CSS together.
  • You absolutely must know JavaScript. Since our server’s written in JavaScript, this tutorial will be largely useless/foreign to you if you don’t have a background in JavaScript.
  • You’ll probably want to already know AJAX and asynchronous JavaScript. While I’ll do a brief review of that below, I’d strongly suggest that, if you have never heard of these terms before, or never written a callback, you stop right now and go do that first.

All good? Then let’s continue with that aforementioned review of Async JavaScript.

Review of Asynchronous JavaScript

Synchronous JavaScript

JavaScript is single-threaded. That means that it can only, generally speaking, do one thing at a time. In more simple programs, this doesn’t matter as much, since modern computers can run JavaScript so quickly that it feels like everything’s happening at once. However… (you knew that was coming, didn’t you?)

Asynchronous JavaScript

Certain actions in JavaScript are such that you don’t know when they’ll finish. We call these actions ‘asynchronous’, because we’re not sure if they’ll happen immediately after we ask them to, or if they’ll take some time. Here’s a brief example:

var data = null;
function getStuff(){
    grabDataFromFarAway(function(data){
        console.log('Inside the callback, the data is',data)
    });
    console.log('Outside the callback, the data is',data);
}();
console.log('Outside everything, the data is',data);

When we run this, the getStuff() function is called. Now, imagine that this function grabs my favorite color (blue) from some external server. In normal, synchronous JavaScript, we’d expect the console to read

Inside the callback, the data is blue
Outside the callback, the data is blue
Outside everything, the data is blue

because that’s the order the lines are given in. However, JavaScript can’t know when the response from grabDataFromFarAway() will return. It may take picoseconds, or it make take centuries! So instead, JavaScript does the sensible thing and continues onto the next line. As such, we get the following:

Outside the callback, the data is null
Outside everything, the data is null
Inside the callback, the data is blue

If you’re wondering what this ‘callback’ thing is, that’s the function that’s ‘called’ when the response gets ‘back’ from the asynchronous request. In this case, it’s just an anonymous function that logs out "Inside the callback, the data is " plus the value of whatever we get back.

Async is Always Async!

If you’re using an asynchronous function, you can never expect it to run synchronously! Consider the following code:

console.log('one');
setTimeout(function(){
    console.log('two');
},0);
console.log('three');

Before we answer, note that setTimeout() is an asynchronous function that basically says “shove whatever’s in here aside, and run it after n seconds”. In this case, n is zero. The important thing about setTimeout() - and indeed all async functions - is that JavaScript does NOT wait for it to be done, but instead moves onto the next statement and does whatever the async function says to do when it’s ready. So, what does the above code print out to the console?

You may assume that, because the delay time is zero (i.e., no delay), it prints:

one
two
three

But unfortunately, because setTimeout() is an asynchronous function, JavaScript still says, “okay, I’ll deal with that later”, and moves onto the next line. So we get:

one
three
two

Moral of the story? Don’t expect even the briefest of async functions to run sequentially! Also, keep in mind that, in a series of nested functions, if one of the functions is asynchronous, all of its parent functions can be considered asynchronous.

Common Async Functions

The following are pretty much always run asynchronously:

  • HTTP Requests: These requests (get to ‘get’ information, post to send info to a server, as well as a few others) are generally used to bring external resources into a webpage or webserver. For example, when your favorite video sharing site plays a video, it might send out a request every few seconds to say “Hey, external resource! Can I get the next bit of video?”.
  • setTimeout() and setInterval(). These two sibling functions are asynchronous. As such, it’s important to remember that if you wanna use setTimeout() as a timer, you’ll need whatever you want to happen at the end of that time to be inside setTimeout()‘s callback.
  • User-triggered events, like window.onclick() and window.onkeydown(). As we can’t expect the user to hit a button exactly when we want, these actions are asynchronous. It’s not uncommon to see something like this:
window.onmousemove(function(e){
    //e is the mousemove event object
    console.log(e.x,e.y);//prints the current mouse coordinates
    //do something with those!
});

So now hopefully you at least have some idea of asynchronous JavaScript. Again, if this is your first introduction to it, I’d suggest you take a break and read up on it a bit. Because next, we’re gonna go in a completely different direction and code editors (hah, you didn’t see that coming, did you?).

Code Editors: What to Use

To make your life easier when writing JavaScript (or HTML, CSS, C#, Assembly… Whatever), you’re going to want an Integrated Development Environment, or IDE. An IDE this a special program that developers use to write code. Now, you might be thinking “I can write stuff in Notepad!”, and while that’s true, you’re gonna have a difficult time if your code ends up being longer than a few files. IDEs allow you to do cool things like:

  • Changing multiple lines at once
  • Selecting (and changing) all instances of a word or phrase
  • Having multiple files open at once for easy comparison
  • Auto-arranging text in particular languages for easy readability.

Notepad… doesn’t do this. Instead, you’ll have to keep track of everything yourself, which can get to be a nightmare with anything but the simplest projects.

You’ll also wanna make sure whatever you’re using saves your stuff in a plain-text format. Rich-text editors like Microsoft Word don’t do this. As an example, here’s an example of my (normally very readable!) resume opened in a plain-text editor:

f7da b146 98c7 2221 7c15 595f 1fef afa6
d648 69c4 1344 05c7 91f5 8295 753b 7f73
b39d f18c 2db0 3479 2363 c1d5 8cc5 91b5
d63a 9dd9 b68a d798 2175 2d52 cc4d 7029
2443 dafc 942b 9b21 f994 a557 b160 29d2
6441 28d1 2fb6 e738 a1b5 b311 9195 493e

That’s the result of the plain-text editor opening it and assuming it’s, well, just text. Most of this comes from extra formatting stuff, like font faces, font weights, etc. that are not part of what the text itself ‘says’.

Which IDE you choose is generally up to you, but I personally love Sublime Text for its extensibility. Webstorm and Atom are also very popular, as is Visual Studio.

For Sublime Text, go here to download it and install. Got an IDE? Great. Now let’s quit all this dilly-dallying and get into some Node!

Installing Node

Installing Node’s pretty easy. Just go to NodeJS.org. You’ll see two green buttons. The left-hand one, the LTS version, is the stable version (and is the one you should use!). It’s been tried and tested, and is relatively stable. The other version is the ‘bleeding-edge’ build, and may not be 100% stable. Unless you absolutely know what you’re doing, it’s better to stick with the well-tested version. Take note of that little bit that mentions NPM too!

So go ahead and download and install that LTS version. I’ll wait. Got it? Let’s make sure. Open a terminal/command prompt and type node. If everything worked out correctly, you should just be put on a blank new line. If you didn’t install it correctly, it’ll just tell you that it doesn’t know what ‘node’ is.

Congratulations! You’ve installed Node! Next, we’re gonna talk about Node ‘packages’, and how you organize a project in Node. Keep that command prompt/terminal open for now. As an aside, I’m gonna start just using the word ‘terminal’ for now, but if you’re on Windows, you’ll of course be using the command prompt.

Package.JSON: Node Packages and NPM

Node projects are organized by a special JSON file called ‘package.json’. This file contains info such as the project’s title, its author, and more importantly its dependencies (the stuff other people have written that you’re using in your project). So let’s not waste any more time and make our first NPM Project. Since this is eventually gonna be a server, we’ll call it myserver (names need to be all lowercase). For starters, we’ll create this package.json file using node’s package manager, NPM. If you’re wondering where you get NPM, don’t worry: it’s installed with Node.

Start by creating a new folder and cding into it: mkdir myServer && cd myServer. Then, make a package.json file by typing npm init in your terminal. You’ll be walked through creating a package.json file (it does say that, and NodeJS likes to be nice and honest with you). Some specific suggestions:

  • For version, I usually start out with 0.0.1 and follow Semantic Versioning, but that’s really up to you.
  • For the description, go ahead and give it a nice helpful description. Something like “This is my first Node and Express server”.
  • The ‘entry point’ is the file used if you decide to upload your package to npm so that others can use it. We’re not gonna do that, so you can just say “app.js” or something for now.
  • The remaining items can just be left blank.

In your myServer folder, you should now have a file labeled ‘package.json’. That’s your project file, and you can add packages to it using NPM. So let’s do that now, with chalk, which is a nice little package for making colored text in the terminal (it’s great for specific error or status messages). To install chalk, type the following:

npm install chalk --save

If you’re wondering (and you should be!), the --save tells NPM ‘record that to the package.json file’. Normally, when someone sends you a node project, they’re not gonna send you all the dependencies explicitly with it. Instead, they’ll just send you a list of the dependencies, and say “make sure you download those too!”.

Go ahead and check your ‘package.json’. You should notice a new property, “dependencies”, with one entry: chalk. If you’re wondering what the weird stuff after chalk is, that’s just the version of that package NPM is using. We don’t really need chalk for this project, so go ahead and run npm uninstall chalk to remove that dependency.

Next, let’s install some actually helpful packages. Start with Express, which is what we’ll use to write our routes. Remember, that’s npm install express --save. We’re also gonna want nodemon, which allows us to write a server that restarts whenever one of its files changes, and body-parser, which makes sure we can parse objects within POST requests. Got all those? Great. As a final step, go into your package.json file, and find the scripts object. Add the property "start", and give it the property of "nodemon app.js".

Next, we’ll talk about including modules within other modules: requiring!

What Dost Thou Require? require()

One of the great things about Node is the ability to include one file inside another by simply require()ing that included file. Those of you coming from other languages like C, Python, or Java might be familiar with this with things like Python’s Import. Those of you who are not coming from other languages can think of this like buying a brownie mix from the store and adding your own stuff, rather than making everthing from scratch. You’re require()ing the brownie mix, which means you don’t have to ‘code’ that part yourself.
For starters, make a new file in your ‘myServer’ folder called ‘app.js’. Open that file in your favorite code editor. For starters, we’re gonna include the Express module:

const express = require('express');

Again, that says “find the module named ‘express’, and include it”. Now we can use whatever functions and code Express has. Let’s add some more lines:

const http = require('http'),
    app = express(),
    routes = require('./routes'),
    path = require('path'),
    bodyParser = require('body-parser');

These lines are:

  • http: Allows HTTP requests (GET, POST, PUT, DELETE) on the back-end. This will actually serve (heh) as our server for this project. You might also notice that we never did npm install http --save. That’s because the http module is natively part of Node. We just gotta tell Node, yes, we do want that module.
  • app: Running the express module as a function creates an instance of express (it’s a constructor function). This will be our server.
  • routes: You can put all your routes (more on this in a bit!) in the app.js file. However, for sanity’s sake, you’ll probably wanna split them up into their own folder. Note the ‘./‘ here, which means we’re looking in a particular folder. In most cases, Node will assume that the first file in that folder called ‘index.js’ is the one you want. However, you could do ‘./routes/myRoutes.js’ instead. Go ahead and create a folder called ‘routes’, and put an index.js file in it.
  • bodyParser: Note the name format here: JavaScript variables are not allowed to have dashes in the middle. Remember that this module allows us to read the contents of POST requests.

Next, we’ll talk about configuring your server!

Setting Things Up. app.use() and middleware

Add the following lines to your app.js file:

app.use(bodyParser.urlencoded({ extended: false })); //allows your app to accept UTF-8 encoded stuff.
app.use(bodyParser.json()); //allow us to parse JSON (so we cand send data across!)
app.set('view engine', 'html'); //what KIND of files will we be displaying on the front end?
app.set('views', path.join(__dirname, 'views')); //and where are those files?

//Next, let's tell Node where to find the so-called front-end files.
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'views')));

//Finally, let's tell node to include that `routes` folder. 
app.use('/', routes);

And let’s go ahead and put some stuff in that index.js file inside your routes folder:

const express = require('express');
const router = express.Router();
const dog = {
    breed:'Tyrannosaur',
    name:'Fido'
};
//Routes will go on this line
module.exports=router;

Let’s take a look at what we just wrote. Firstly, we’re requiring Express again. Next, we access Express‘s Router() method, which allows us to construct routes. Routes tell a server how to respond when it receives a particular URL. I’ll talk about this more in the next section.
Finally, we tell Node that, if any external modules request access to this file, we’re gonna wanna let them have access to the router object. Note that, for example, the ‘dog’ object is not exported: if I require()d this module, I would not have access to the dog object!

Now that we’ve got our app’s routes file set up, let’s actually put some routes in!

Routes: Where do We Go From Here?

As I’ve mentioned, routes basically tell our server how to respond when a particular URL is requested. It’s important to note that they do not just tell the server where to go; they tell it how to answer. This is essential to remember since the response may occasionally not be a file. For example, I might have a particular route at ‘mySite.com/serverTime’ that simply asks the Node process to tell me the current system time on the server.

With that clarification out of the way, let’s get to routing! Remove the line in your ‘./routes/index.js’ file that says //Routes will go on this line, and replace it with the following:

router.get('/',function(req,res,next){
    res.sendFile('index.html',{"root":'./views'});
});

Let’s break this down. Firstly, it’s method on the router object we brought in via const router = express.Router(). It’s an HTTP GET method, which usually means it’s designed to, well, get information from the server while not giving a huge amount. Those of you familiar with the CRUD (Create, Read, Update, Delete) methodology of databases may note that this usually means it fits the ‘Read’ portion of that acronym. Next, we have the parameters that are sent to the .get() method. The first is the URL that we want this route to respond to. In this case, it’s just the root route; it’ll be activated when we go to ‘mysite.com’ without any other…stuff.

Finally, there’s the callback. Router callbacks in Express always have the same format:

  • It’s a callback function, so the entire thing’s a function. That means the usual function() and {}.
  • It has three parameters:
    • req: The Request object. In the case of GET requests, this can hold query string parameters as part of req.params. In the case of POST requests, this holds the body of the post request in, well… req.body.
    • res: The Response object. A response isn’t technically required, but not saying anything is a bad idea: how else does the front end know its information has been recieved? Remember that, under normal circumstances, a webserver can only send a response to the front end when requested! So if you don’t use this to respond, you may not be able to send that information. Also, note that a response can only be sent once per request!
    • next: Used for stuff like error-handling middleware. Often times, you’ll see something like if(errHappened) return next(err);, which basically says “If there’s an error, go ahead and continue to the next route (that’s specifically designed to deal with errors)”.
  • It uses that response object somehow. This can be done a number of ways:
    • res.send('Hiya!'):Send a simple response. Note that because most responses are gonna be viewed in a web browser, you can send HTML and stuff like that across.
    • res.sendFile('myFile.html'): This allows you to respond with a file (often HTML) when a particular route is used. For example, in the above route, you respond with the index.html file. Note the object here and its ‘roots’ property, which basically tells us where the file can be found.
    • res.json({some:'jsonObject'}): Send a specifically JSON response. Great if you’re requesting information of some sort.
    • res.end(): End the request without sending data.
    • res.download('./files/file.mp3'): Initiate a download (at the okay of the user, of course!). This includes a path to the file, and actually includes its own nested callback.
    • res.redirect('youreNotLoggedIn.html'): Allows you to respond by redirecting the client. Useful if, for example, you have a login service. In the event that a check for a logged-in status fails, you may wanna use this to redirect the client to a ‘hey, you need to login to view this!’ page.
    • res.render('jediProfile.ejs',{name:'Luke Skywalker'}): Used for so-called ‘template engines’ like EJS, Jade, etc. and can include stuff like template-specific variables. If you’re using HTML, don’t worry about this one.
    • res.status(418): Must be used with one of the other methods to actually respond, as all this does it determine the status code. Allows you to send a specific error code if an error occurs, rather than just 500 or 404 or something generic.

And yes, go ahead and create a ‘./views’ folder and put an index.html file in there. It doesn’t matter what it has in it, as long as it’s in the right place.

Next, let’s add two more routes, just to give us a little variety. Put these after your first route.:

router.get('/err',function(req,res,next){
    res.status(418).send('tea time!')
})
router.get('*',function(req,res,next){
    res.send('<span style="background:#090; color:#fff">Oh no!</span> I dont have a route for that!');
});

The first route responds with a specific error code. Open up your browser console and you should see something like [HTTP/1.1 418 I'm a teapot 8ms]. Yes, HTTP Error 418 is a real HTTP status code. The second route contains a wildcard, and basically means that if we go to any route, send this response.

You might ( == should) be wondering how the other routes get precedence over this ‘any’ route. When we go to ‘mysite.com/‘, for example, how does it know to trigger the index.html route instead? Well, remember that JavaScript is single-threaded, and so things happen, generally, in a sequence. Since the ‘/‘ route comes first, it gets precedence.

Now, go ahead and try to start your server. Type npm start in your terminal and press enter. You should see:

>nodemon app.js
[nodemon] 1.11.0
[nodemon] watching: *.*
[nodemon] starting `node app.js`, enter `rs`
[nodemon] clean exit - waiting for changes before restart

Well, it didn’t break, but clearly we’re missing something. That’s because while we’ve require()d the http module, we’ve yet to actually use it. Let’s do that now by passing our app into the http.Server() method. At the bottom of your app.js file, write const server = http.Server(app);.

Still not working. We need one more line, so go ahead and tell your server to start listening. Write: server.listen(process.env.PORT || 8080);

And that’s it! Go to ‘localhost.com:8080’ in your browser, and see that your server now works! Try a bunch of routes, including the ones we implemented before.

If you’re wondering, the parameter passed to the .listen() method basically says “Check our runtime environment for a port to run on, and if one exists, use it. Otherwise, use port 8080”. This is important to include (rather than simply doing server.listen(8080)) as certain webhosts like Heroku want to specify their own ports (and will actually crash if you try to specify one for them!). This just saves some headache later.

Further Exploration

Adding More

Adding more stuff is simply a matter of adding more routes. Let’s try using some dynamic routes. Add the following to your ‘./routes/index.js’, before the wildcard (‘*’) route:

router.get('/sayHi/:myName',function(req,res,next){
    res.send('Hello,'+req.params.myName+'! How are you today?')
});

Go to ‘localhost.com:8080/sayHi/Frodo’, and you’ll see it responds ‘Hello, Frodo! How are you today?’. GET parameters in Express are signified by a :. In this case, we’re sending along the property myName.

You can also send POST requests in a similar way. Assuming the route you send your post request to is ‘localhost.com:8080/sendInfo’, your route might look something like this:

router.post('/sendInfo',function(req,res,next){
    //assume that the post object you sent has a 'name' property and an 'age' property.
    if(req.body.age > 18){
        res.send('Hi '+req.body.name+'. You are an adult!')
    }else{
        res.send('Hi '+req.body.name+'. You are NOT an adult!')
    }
});

Front-End Files

One thing you may be wondering is where to put front-end JavaScript and CSS files. We’ve already discussed that HTML goes in the ‘./views’ folder, but what about making your website prettier (or more dynamic!)? Well, take a look back at the line in your ‘app.js’ that says app.use(express.static(path.join(__dirname, 'public')));. Basically, that tells us to make the ‘./public’ folder available to the front end.

Go ahead and create that folder, and stick a file called ‘main.js’ in it. Then, in your ‘index.html’, insert the line <script src="./main.js"></script> near the bottom. Note that since the ‘./public’ folder’s contents are now part of our front-end, we don’t need to include that as part of the path here: <script src="./public/main.js"></script> would be wrong.

Finally, let’s actually put a script in their. For now, we’ll just tell our user when the page was loaded. In that ‘main.js’ file you just made, write document.body.append('This file was loaded at: '+ new Date());. Reload the page (‘localhost.com:8080/‘), and you should notice it says when the page was loaded!

Conclusion

That’s it! Keep experimenting with routes, and have fun!

CSS in 3d

Contents:


Introduction

Cascading Style Sheets, or CSS, is often viewed as the bane of web design. While it’s relatively easy to learn - there’s generally only one pattern you need to learn, illustrated below - it’s notoriously difficult to master, and there are all sorts of finicky little gotchas that are sure to make you lose at least some of your hair. After all, how can this:

    #my-element{
        position:absolute;
        vertical-align:middle;
        text-align:center;
    }

not just simply do what it says on the box and, you know, put stuff in the middle of the page? The fact that simply typing vertical-align into Google brings up “vertical-align not working” as like the second or third suggestion should itself suggest how very many people have trouble with this little CSS rule 1.

One way of helping to alleviate this frustration is to remember that you’re a coder, and you love coding. So instead of beating your head against some really annoying, finicky CSS, why not try playing with it instead? Why not try making something in 3D, using only CSS?

Before we begin, I’m gonna do two review sections: one of the fundamentals of CSS inheritance, and one of the positioning system.


Review of CSS Inheritance

CSS is so-called cascading because of the way in which elements inherit particular CSS rules. The most general rules are ‘obeyed’, unless there are more specific rules. Just so we know what I’m talking about later on, let’s make a quick list of the order of inheritance. First, we’ll look at where the rules are coming from:

  • None: While it’s pretty much impossible to ‘use’ this, as the user-agent stylesheet takes precedence over it, we could argue that the most basic style is simply no style.
  • User-Agent stylesheet: The most general ruleset in use is the user-agent stylesheet, which is defined by the browser itself. This is why, for example, input elements look different in different browsers. Worth remember, if you need very specific styles.
  • External stylesheets: If we load an external sheet, via a <link> tag, that stylesheet takes precedence over the user-agent sheet.
  • Inline <style> declaration: It’s usually frowned upon (separation of concerns and all that), but if you’re a rebel and choose to include inline <style> elements, these will win over external stylesheets.
  • Inline, in-element declarations: These are the most specific, generally speaking. While they were traditionally frowned upon, as they have the same issue as inline <style> declarations in terms of lack of separation of concerns, they’ve become slightly more popular with dynamically generated views, from stuff like AngularJS or ReactJS.

Within each of these style categories, there are also rules determining what element(s) is/are selected:

  • ‘*’ selector: The ‘everything’ selector. * is a generic wildcard for ‘any element’. Useful if you wanna make very broad changes
  • <tag> selector: This selects every element with a particular tag name. For example, if you said span{ background:#f00; }, every <span> element would now have a bright red background. Note two things here: firstly, making all your span elements have a red background is a surefire way to make people hate you. Second, the actual selector here is just the tag’s name, *not the name plus the < and > symbols.
  • ‘.class’ selector: This selects everything with a particular class. So if we apply a style to class ‘my-class’, then that’d affect <div class='my-class'>, <span class='my-class'>, and <input class='my-class'>, but not <div class='your-class'>. The class selector (almost!) always wins over the tag selector.
  • ‘#id’ selector: The ID selector is the most specific of the general element selectors. Baring any other hierarchy considerations, the ID selector always wins over the class selector.

There are also pseudo-classes, pseudo-selectors, and other miscellanous bits, which can be applied to any of the above four selector types:

  • :hover: Applies a style only when an element has the mouse over it. An example might be something like #my-btn:hover{font-size:larger}, which would make your (presumably button) element with the id my-btn have a larger font-size when hovered over.
  • :focus: Usually used for input elements, this is used when an element has focus. That is, for example, if I’m typing, and the stuff I’m typing is currently going in this particular text input, then this style will affect that element.
  • :active: Don’t ignore this one just because it’s there for such a brief time! The :active pseudo-class applies while an element is being actually used. So if it’s a link, this’ll be active while the mouse is down on it.
  • :visited: Remember the old alink, link and vlink attributes of HTML4 and previous? This is sorta like that old vlink: it changes the style of links, but only if they’ve been visited.
  • ::before: Allows you to create what is essentially a separate element (complete with its own style!) that’s ‘attached’ to the parent element. Note that you’ll usually need to use content:''; to actually give the element something to ‘show’. traditionally goes before the element (that is, above or to the left of)
  • ::after: Same as above, but traditionally goes, well, after the element.
  • !important: Not a pseudo-selector, but I thought it important to include it here anyway. The infamous !important declaration goes on a particular rule, and basically overrides any other heirarchy rules:
  #my-id{
      background-color:#f00;
  }
  .my-class{
      background-color:#0f0!important;
  }

Assuming we have element with both the class ‘my-class’ and the id ‘my-id’, the background color of this element would be green, despite the fact that ID selectors normally take precedence over class selectors. Because it basically overwrites any normally more-specific rulesets, this is frowned upon as a bit of a sledgehammer-to-crack-a-nut approach: it’s far better to rewrite your code so that you don’t have to use this than to use it. 2


Review of CSS Positioning

If you ever wanna position anything with CSS, you’ll need to know about the four different types of positioning, via the eponymous position property.

  • position:static;: This value is very rarely explicitly used, as it’s basically the default value. This basically means that the element ignores all ‘custom’ positioning rules. So if you said:
     #my-div{
         position:static;
         left:100px;
     }

Your element would stubbornly refuse to move right 100 pixels. How rude. Instead, elements with a static declaration will be positioned as per ‘normal’ layout.

  • position:absolute;: In this case, the element is positioned relative to the first parent (going up its DOM heirarchy tree) that itself has a position value of something other than static. As the name implies, it’s useful for positioning elements absolutely.
  • position:relative;: This allows you to position elements relative to their ‘normal’ position. So if you say:
     #my-div{
         position:relative;
         left:10px;
     }

then your element would be 10px to the right of where it ‘normally’ is. 3

  • position:fixed;: This one’s a bit odd: instead of positioning an element relative to a parent, or to its original position, it positions the element relative to the browser window. The cool thing about this affect is that if you position an element as so:
     #my-div{
         position:fixed;
         left:10px;
         top:10px;
     }

and then scroll the window, the element will stay ‘glued’ to the same position. Really useful for stuff like menus.

Note that fixed and absolute also tell the browser not to leave space for the element. That is, if we have three spans, and the middle one has position:fixed;, then the first and third span will be smack up against each other.

You’ll also, however, need to know about the various display property values:

  • display:none;: Does pretty much what it says on the can: doesn’t show anything. Often used behind the scenes with various dynamic view things like AngularJS’s ng-show attribute.
  • display:inline;: Basically only takes up as much with as the element needs. Does not force a new line (akin to <br>) after or before the element. inline also tends to ignore certain positioning rules (as well as width and height), so when in doubt, probably best to choose one of the other rules if you need specific positioning.
  • display:block;: On the contrary, this by default takes up the whole width of the page, and does force a new before and after. Also, does pay attention to positioning rules. Pretty useful, but for elements that aren’t supposed to take up the entire page, the blank space can get kinda annoying.
  • display:inline-block;: The best of both worlds! Doesn’t force annoying linebreaks that create nasty blank space, but also allows you to specify widths and heights. Great for things like menus!
  • display:flex;: I won’t go into this much here, but suffice it to say that flex, part of CSS3’s Flexbox setup, is very useful, and well worth the research.

The Magic: transform-style:preserve-3d; and perspective;

The transform-style property declares how elements are displayed in 3-space. Normally, its default value of flat means that while you can rotate and move elements in 3-space, they’ll be ‘flattened’ against the element with this declaration. That is, if you attempt to dynamically rotate them (via an onmousemove event or something similar), they’ll still appear as part of a flat, z-axis-less plane.

Instead, we need to use the magic rule transform-style:preserve-3d;, which says that any child elements of this element will keep their z-axis (and thus stay 3D!). It’s worth repeating that this does not affect this element itself, but only its children!


How to 3d

After you’ve declared a parent element with a transform-style property of preserve-3d, you just simply have to use the various transform property values to position your element in 3-space. Be aware that while you can rotate and move an element in the third, Z-axis dimension, there is no depth property. That is, you cannot construct a box by doing:

    .my-box{
        width:100px;
        height:100px;
        depth:100px;
    }

instead, you’d have to construct the ‘walls’ of the box by rotating and positioning the individual faces.


Performance

There are generally three pieces of advice useful for doing CSS-3d:

  1. When possible, don’t. Yes, I love doing CSS 3d, but even the best computer/browser is gonna find it a strain.
  2. When possible, use 3d transforms. The reason for this is that, especially with modern browsers, simply using a 3d-transform (even something like transform:rotateZ(30deg), which is visually no different than transform:rotate(30deg)) forces the browser to use hardware accelerated graphics, if available. Since most computer’s graphics cards are better at, well, doing graphics than simple software rendering, this can make stuff much more performant.
  3. Cross-browser testing is important! Depending on exactly what you’re doing, you’re gonna be using some pretty fancy and cutting-edge tech here. Certain browsers (hello again, IE/Edge) haven’t quite kept up with that, so you may run into issues rendering stuff in 3d in those environments.

Alternatives and When to Use

As I mention in point 1 of the previous section, most browsers find this a particular strain, since it’s forcing the browser to make relatively complex calculations. A much faster method would be to use JavaScript and Canvas, which are explicitly designed for graphics.
However, for demonstration purposes, very simple UI effects, and a few other use cases, CSS 3d is fine to use.


Notes:

  1. If you’re wondering why this doesn’t work, it has to do with the fact that the height of a webpage is very rarely explictly defined. Because they’re designed to scroll vertically, webpages basically function on the “if I need more space, just add more vertical height” mantra. For this reason, telling something to be positioned vertically, especially by something like a percent or relative value (rather than, say, an absolute one like “500px”) just won’t work. Take a look at the following example:

        html,body{
            background:#000;//black background;
        }
        .my-div{
            position:absolute;
            width:98%;
            left:1%;
            top:1%;
            height:98%;
            background:#ddf;
        }
    

    This, demonstrably, doesn’t work. If you inspect it, you’ll find a div with the correct width (98% of the total window width), but a height of zero! Instead, we need to explicitly define the height of the document as 100%:

        html,body{
            height:100%;
            width:100%;
            background:#000;//black background;
        }
    
  2. Furthermore, using multiple !important declarations can make your CSS incredibly difficult to debug!

  3. Here’s a perhaps better example. Imagine we have a bunch of <span> elements in a row, contained within a div that has its property set to absolute. If we apply the rule position:relative to the spans, and then add left:0px;, the elements will be positioned as if they had no position styling at all. If we changed that left to say, 5px, the elements would now all be shifted right by 5 pixels from their original locations. Similarly, if we change position:relative to position:absolute, the elements would now all be stacked on top of each, 5 pixels from the left border of the container div.

Exploring JavaScript Functions

Contents:


Introduction

Functions in programming, including JavaScript, are the verbs of code. They are the doers, without which our code would be boring at best, and long-winded at worst. Functions allow us to package our code and deliver it in those nice little packages to whatever might need to use it. Before we begin, let’s look at the anatomy of one particular type of function, known as an anonymous function:

function(userName){
    alert('Hello there,'+userName);
}

Firstly, we simply use the reserved function keyword to designate a function. The word used here depends on the language - Python uses the def keyword, for example - but the underlying structure of functions is pretty similar all over.

Next, we have a list of arguments. In this case, it’s just one argument - userName - but we could potentially pass more. I’ll talk more about this - as well as some cool things you can do in the latest version of JavaScript - in the Function Arity section below.

Finally, we have the meat of the function, known in programming as a ‘block’. Wikipedia defines ‘block’ as, quite unhelpfully and simply, ‘a lexical structure of source code which is grouped together’. Basically, that just says that all the stuff between those two curly brackets is what the function does. If we changed it to say:

{
callMom();
}

Our function would now, presumably, call Mom.

Finally, note that nested functions are a thing. While this can be a bad thing (if, for example, you call recursive functions or allow them to call themselves), this also allows us to do funky things like this: Math.floor(Math.random()*9999).toString(32). Here, we first take a random decimal from 0 to 1. We then multiply that by 9999. Next, we take the floor of that number - that is, the next integer lower than or equal to that decimal - and convert it to a base-32 string. All in all, this allows us to easily spit out a random string of letters and numbers; great if you need a random ID for something!

In the remainder of this post, I’ll look at some various types of functions, as well as a specific feature of ES6/7 that makes functions more adaptable and fun.


Function Expressions vs Function Declarations

There are, generally speaking, two ways of writing a function.

The first is known as the function declaration:

function myFunc(breed){
    console.log('My dog is a ',breed,'!')
}

The second is the function expression:

var myFunc = function(breed){
    console.log('My dog is a ',breed,'!')
};

So… what’s the difference? Well, in this case, none. But remember JavaScript hoisting?

Hoist the functions!

While the function expression’s variable (var myFunc) is hoisted, the actual value of that variable - the function body - isn’t! And that means that if you have the following code:

myFunc('Dave');
var myFunc = function(name){
    console.log('In case you didnt know, your name is',name)
};

you’ll get the following error (in Chrome; other browsers will have different versions of this error):

Uncaught TypeError: myFunc is not a function

because while the fact that the variable myFunc exists (is ‘defined’) is hoisted, the contents of it aren’t. So by the time we call the function with myFunc('Dave');, JavaScript thinks that we’re trying to run something that’s not a function! Remember that if neither the contents nor the declaration were hoisted, we’d simply get: Uncaught ReferenceError: myFunc is not defined.

So… why wouldn’t you wanna use function declarations? Would that just make everything easier? Well, yes, and that can actually be a problem. By using function expressions, functions are defined exactly when they need to be. As such, you can much more easily debug your awesome new app, because you know exactly where to look in the code based on where the functions are failing.


Synchronous vs Asynchronous

In any application that will eventually require some sort of communication with a non-immediately-local resource, you’re gonna have some unpredictability over when that resource will finally get there. Anyone who’s planned a party (or even been to a party) has experienced this issue: when do you start the party so that people don’t get bored waiting, but so that there’s enough, say, cake for the late-comers? The Asynchronous methodology adopts the “when-it’s-ready approach”: You serve people cake when they arrive.

While this approach is pretty obvious in every life, it’s perhaps not so obvious to the beginning programmer whose code, up until now, has been doing things exactly when he tells it to. Let’s look at a synchronous example first, with some pseudo-pseudocode:

var animalList = ['cat','fish','dog','monkey','hippo','apatosaurus']
var myFunc = function(){
    //it's a function expression!
    var theAnimal = syncGetAnAnimal(animalList);//pretend this returns 'dog'
    console.log('The animal we picked is:',theAnimal);
};
myFunc();//run function!

Works great! We pick a random animal (in this case, a dog), and spit out “The animal we picked is: dog”. The code within the function basically just runs from top to bottom.

But what if our list of animals is not part of our app? What if it’s somewhere else on the computer, or worse, somewhere else on some other computer? Again, the pseudo-pseudocode:

var myFunc = function(){
    //it's a function expression!
    var theAnimal = asyncGetAnAnimal('davesawesomeanimalsite.com');
    console.log('The animal we picked is:',theAnimal);
};
myFunc();

Same thing, right? Al I’ve done is changed the function a bit.

Well… no. You should probably be used to blogs doing that by now, since going “Ah, but wait!” seems to make us devs feel clever or something. Anyway, this function, instead of spitting out what you’d expect - and want! - it to, will just spit out: “The animal we picked is: undefined”. This is because while the asyncGetAnAnimal() function needs an indeterminate amount of time to get its particular resource, the JavaScript interpreter just keeps going. So while asyncGetAnAnimal() is off getting its act together, console.log(...) is already running! It runs before we even have an animal. Now, you may be wondering what happens if we ‘know’ that our delay is extremely small. For example, the setTimeout() function runs a particular bit of code after a specified delay. It’s great for creating JavaScript alarm clocks to piss off your co-workers. That specified delay can be any number, including zero! So what happens if we run this code?:

console.log('one');
setTimeout(function(){
    console.log('two')
},0);//
console.log('three');

Since it’s a delay of zero milliseconds, JavaScript should be fine with that, right? It should just print ‘one’, then ‘two’, then ‘three’! Yeh, you guessed it: Nope. Since setTimeout() is an asynchronous function, JavaScript basically says “Okay, that’s async. I’ll do it later” - no matter how long the delay is!

Instead, we need to use what’s called a ‘callback’, which essentially is a way for an asynchronous operation to run when it’s ready to. So if our asyncGetAnAnimal() function from above takes a year to run, our callback would run when that year’s up. If it takes a millisecond, it’ll run in a millisecond. Many callbacks take the form of arguments passed to their ‘parent’ async function:

myAsyncFunc(function aCallBack(r){
    console.log('Response is',r);
});

So… what determines whether a function is synchronous or asynchronous? Well, in short, if any of the function’s components - the stuff it calls, etc. - is async, then the function itself is async.

Finally, some common (uses of) async functions:

  • Getting data from external resources. Most commonly, using two methods:
    • GET method if you basically just want data, and don’t wanna provide a huge amount of data to the external resource
    • POST method if you need to provide a lot of data from your side, usually via a POJO (Plain-Old-JavaScript-Object);
  • The timer functions setInterval() and setTimeout(). Remember as per above that these are always asynchronous, even WITH a timer delay of zero!
  • User Interface (UI) functions, such as window.onclick(). In this case, the function callback is triggered whenever the user does something. Note that a lot of these functions pass an event parameter to their callback:

    window.onmousemove = function(e){
      console.log('mouse is at position',e.offsetX,e.offsetY)
    };
    

Implicit vs Explicit Return

One thing functions in any programming language - especially an object-oriented-capable one like JavaScript - are useful for is stringing together various operations. So, for example:

mixDryIngreds().mixWetIngreds().addChocolate().pourInCakePan().bake();

In order for a function’s work to be used by something else, that function needs to return something, using an optional ( gasp! ) return statement. If it’s not included, the function returns an implied undefined:

function checkIfDave(name){
    if(name==='Dave'){
        return true;
    }
}

If the value of the string name passed to the checkIfDave() function isn’t ‘Dave’, we obviously aren’t gonna trigger the return true; bit. Instead, the function will implicitly return undefined. Since that undefined is falsey, we can use this to implied return value a conditional!


Pure vs Impure

It sounds like some horrible term for JavaScript eugenics. Either that, or impure functions sound like something that little kids should be shielded from.

Hide your eyes, kids!

However, pure with regards to functions is simply a term for functions that, given the same specific, explicit arguments each time, will spit out the same result each time. The function Math.floor() is always going to return the 4, if given the same input 4.3.

In contrast, an impure function is one that mutates or produces different outputs depending on external resources (and may itself change those external resources):

var pickCat = false;
function likesPet(name){
    if(pickCat){
        console.log(name,'prefers cats!');
    }else{
        console.log(name,'prefers dogs!')
    }
}

While this function does include an input of name, which by itself would leave the function pure, its output also depends on the value of an external variable pickCat. As Eric Elliot says, “pure functions produce no side effects”.


Function Arity

Function Arity is, simply put, the number of arguments that a function can take. In a lot of programming languages, we can do what’s called ‘overloading’ functions by specifying a bunch of identically named functions, all with different numbers of arguments. When the code’s run, the computer will ‘pick’ the appropriate function. However, we can’t do this with JavaScript. Because it’s a scripting language, subsequently defined ‘bodies’ for a particular function would replace previously-defined ones. So if we write:

myFunc(name){...}

and then later on write

myFunc(name,date){...}

the single-argument version of myFunc would no longer exist!

So how do we deal with JavaScript functions with an unknown number of arguments? Traditionally (pre ES2015/ES6), we’ve had to write functions expecting the maximum number of arguments, and then either allow the un-passed arguments to be undefined, or explicitly define them (if undefined!) within the body of the function. So, my example from above:

var myFunc = function(name,date){
    if(!name){
        name = 'An unknown person';
    }
    if(!date){
        date = 'an unknown date';
    }
    console.log(name,'called myFunc on',date);
}

This is fine if we have a maximum number of arguments that could possibly go in the function. However, what if we dont know the number of arguments?

Enter the ES2015 spread operator, which in addition to making your functions look slightly passive-aggressive, allows you to pass in any number of arguments!

var doIt = function(...fine){
    console.log('You inputted',fine.join(','),'. Not like I wanted to run anyway.');
}

Basically, the arguments inputted in this doIt function get converted to an array. And yes, it’s a real array (unlike, say, the results of document.getElementsByTagName(), which returns an array-like HTMLCollection that doesn’t have inherent access to a lot of the Array prototype functions), so you can then do normal array-things to it, like forEach(), or map().

What about arity with NodeJS? Well, it’s relatively easy to pass arguments into a NodeJS module’s function by appending them as flags to the command-line arguments. So:

$node pickAnimalModule

could become

$node pickAnimalModule -onlyMammals

You’d then access these arguments in Node via process.argv, which is, you guessed it, an array. There are, however, two very important distinctions/caveats here:

  1. First, the first two items in the array (positions 0 and 1, respectively), are the name/location of the process running your Node stuff (that is, Node itself), and the location of the JavaScript file being run.
  2. Second, the arguments are passed as strings. This means if you want to, say, pass a config object to your Node function, you’ll need to run JSON.parse on it at some point.

Finally, while the spread operator and process.argv solve the problem of how many arguments there are, it doesn’t help with determing what kind of arguments they are. In other words, let’s say we have a function ageGreeting(name,age) that accepts two arguments - name and age - and outputs some sort of greeting based on that age. So if the user inputs Dave and 300, it might say “Hi Dave! You’re very old!”. Now, let’s say that, for whatever reason, we need to pass age in as an object such as:

{years:300}

How would we prevent the user from inputting the arguments in the wrong order? As it’s written, our function wants a string first (name), and then an object (age). Feeding these in the wrong order will generate an error. One way to fix this is by using the arguments parameter, which is part of every JavaScript function, and is simply an array of the arguments given. We can then do some relatively simple type-checking on the items in this arguments array:

    var ageGreetings = function(name,age){
        var actualName,
            actualAge;
        arguments.forEach(function(arg){
            if (typeof arg=='string'){
                //this is probably the name!
                actualName=arg;
            }else if(typeof arg=='object' && arg.age){
                actualAge=arg;
            }
        })
        //do stuff with the info
    }

Functions as First-Class Objects

One of the most popular statements used as an explanation of JavaScript is that “functions are first-class objects”. But what does this mean? Does it mean that JavaScript functions sit in the front of the plane, drinking Martinis? Does it mean they’re richer than other functions?

Of course not. It means that, first and foremost, JavaScript functions follow another very famous JavaScript mantra: (almost) Everything is an object.

What this means in terms of functions is two-fold: firstly, functions are, as with any other objects, created with their own constructor. This Function constructor actually can be called explicitly (i.e., new Function(args)), but is usually implicitly called via simply writing a function declaration or function expression.

The second result of functions being objects stems from JavaScript’s prototypical inheritance model. Remember from high school biology how organisms are grouped based on similarities, and organisms that share a common group also share common traits? Well, the same’s true for JavaScript ‘groups’ (we call these classes): all members of the Function class can be ‘called’, all members of the Object class can have their properties listed via Object.getOwnPropertyNames(), and so on. So what does this mean in terms of the statement “functions are first-class objects”? It just means that functions in JavaScript are objects. You can pass them around like objects. You can ask for their property names.

Mad Science

Explorations with Coding


Contents:


Introduction:

Recently, I’ve been exploring a lot of biological - and specifically ecological - concepts via coding. As much of ecology is based on the behavior of large systems, it’s a field that naturally lends itself to modeling by computers. Be it evolutionary development, neurology, or just basic ecology, it’s both relatively easy - and rather interesting - to model various systems via something as simple as vanilla JavaScript. Below, I’ll talk about a few of the projects I’ve been playing with recently.


Neural Network:

Link

According to wikipedia, a neural network is “a computational approach which is based on a large collection of neural units loosely modeling the way a biological brain solves problems with large clusters of biological neurons connected by axons (Wikipedia: Artificial neural network)”.
What?
Well, put simply, it’s a virtual brain created in a computer. The neurons in the ‘brain’ are, just as in a biological brain, seperate simple subunits, and they’re connected by connections of differing ‘strength’. These differing strengths then determine the path that a particular signal will take through the ‘brain’, much like the neural signal in a real brain.
I created a relatively simple neural network simulation in JavaScript and Angular. As with most neural networks, this one needed to have a goal (otherwise, it’ll just sit there and ponder virtual philosophy or something). In this case, the brain attempts to steer a predator organism to catch a prey organism.
The neural network also needs to be able to react with its environment. In a biolgoical sense, this’d be like your eyes and ears, and your muscles. The network needs eyes and ears to get its current state, and muscles to adjust its state. In the case of my simulation, I have a pair of distance sensors which simply read the distance to the target, and a set of out ‘states’ that move the organism up, down, left, or right.
One interesting facet of this experiment is that, besides the initial goal and input/output of the organism, the initial network is not ‘programmable’. Instead, the network attempts to program itself, obeying the following rules:

  • The network runs until one of five conditions are met:

    • The network runs out of time. This is essentially starvation, in a biological sense
    • The network leaves the play area. This is a predator wandering out of its prey area
    • The network has no active nodes. This constitutes random brain death.
    • The network has an overwhelming majority of active nodes. This constitutes something like a seizure
    • The organism successfully catches the prey item.
  • Each run, the network gets a score, based on two parameters (with lower being better):

    • The final distance to the prey item
    • The amount of time taken
  • During each run, the paths taken are recorded. At the end of a run, if the current score is better than a moving average, that path is strengthened. If the current score is worse, the path is weakened.

Over time, these relatively simple rules produce a learned behavior. Interestingly, the more nodes you have the better (as would be expected).


Lunar Lander Evolution

Link

Note: The title of the above page refers to this as a neural network. It’s not!

One interesting biological simulation that can be done with code is that of simulated evolution. By giving some sort of ‘survival’ conditions, and a pseudo-randomly mutating spaceship with its own genome, we can produce some basic evolutionary trends.
In this example, I’ve created something similar to those ubiquitous lunar lander games that you (used to?) see everywhere: you land on some object with your little spacecraft. This time, however, you have absolutely no control over the spacecraft. Instead, two spacecrafts are generated, each with its own assortment of thrusters, each of which in turn has its own start time, end time, angle, and power settings.
Each generation, two spacecraft exist. Except for the initial condition, one of these is an older, ‘parent’ spacecraft, and the other is a mutation off of that parent. The spaceships again have the goal of reaching the target object (the ‘moon’), but this time control is given by an artificial genome that controls the number and stats of each engine.
After each generation is complete - i.e., after either one spaceship has landed, one has left the play area, or one has sat with no engines firing for more than 20 seconds - the scores of both spaceships is determined as, again, a combination of distance and time taken. The spaceship with the better score is kept, and the worse-scoring spaceship is discarded. The better spaceship is then duplicated, with a very small chance of mutations. This repeats until the user gets sick of staring at a bunch of circles moving around.
Some interesting observations about the behavior of this system:

  • Like the Neural Network simulation above, this simulation is not explicitly programmed. That is, while there is ostensibly a success condition (and multiple failure ones!), the spaceship itself doesn’t actually know about this condition. Instead, each generation is rated as an isolated event, and only the emergent behavior of multiple generations leads to any changes.
  • This, in turn, means that you might observe very little (if any!) progress in the first 30-60 generations or so. This actually makes complete sense, biologically, and is an example of the late Stephen Jay Gould’s Punctuated Equilibrium, whereby evolution generally occurs very slowly except for the occasional sudden burst of progress. For example, while life is generally agreed to have appeared 3600 million years ago, it took until about 7-800 million years ago (2800 years at least!) for life to figure out that bunching multiple cells together was a good idea. Pretty soon after that, however, we get an enormous number of diverse new evolutionary experiments as part of the Ediacaran fauna and the famous ‘Cambrian Explosion’.
  • The simulation may reach a plateau, beyond which very little if any improvement occurs. This makes a lot of sense too, as while natural selection is goal-driven - that is, better organisms survive more - evolution itself really isn’t. We might refer to pre-avian dinosauria as trying to ‘figure out’ how to fly, for example, but this is really a combination of a colloquialism and hindsight: We can see that, over time, evolutionary pressures were driving certain organisms towards developing flight. However, neither the birds in this example nor the spaceships in this simulation are individually striving towards any particular goal.

Taxonomy Database

Link

This example is perhaps the simplest of the bunch, and is still somewhat a work-in-progress. It’s basically just a taxonomy database. Current features:

  • Add a taxon by entering its info in the box.
  • Remove a taxon by going to davetaxonomy.herokuapp.com/remove/ plus the name of your taxon. So to remove a taxon called ‘myTaxa’, you’d go to davetaxonomy.herokuapp.com/remove/myTaxa.
  • Draw a tree by picking a taxon and then clicking the ‘draw tree’ button.
  • Get info on any particular taxon by going to davetaxonomy.herokuapp.com/info/ plus the name of your taxon. Case sensitive. Example for Bilateria

Upcoming features:

  • Right now, you can only delete taxa via a specific url (davetaxonomy.herokuapp.com/remove/<nameOfTaxon>). Eventually I’ll make this part of the UI.
  • While synapomorphies are entered as part of the taxon creation process, they’re never actually displayed after this. I’ll change that.

Ecology Simulation

Link

This one is, so far, the most complex. It’s basically a food web/ecology simulation, in which there are a number of organisms with specific ‘diets’. The simulation follows these rules:

  • Except for plants, which operate by their own rules (they’re hipsters like that), all organisms have a specific list of organisms that they like to eat.
  • Organisms constantly lose health, and replenish this whenever they feed. This acts a starvation mechanic.
  • Interactions between organisms fall into a number of categories:

    • Predation: a predator organism ‘tags’ a prey organism, and attempts to feed on it. If successful, the predator organism gains health.
    • Intraspecific competition: Usually does not result in death, but may result in one of the organisms being injured (i.e., losing health).
    • Interspecific, non-predatory competition: this can result in the death of one of the two organisms. However, it does not ever result in one of the organisms gaining health.
    • Mating: a male and female of the same species have a good time together.
    • Nothing: Finally, if two organisms have no particular interaction set between them (i.e., a wolf and a tree), then nothing happens: the two just go about their business
  • Both mating and predation have a certain chance of success. Mating success simply determines whether an offspring is produced or not. Predation, if successful, kills the prey organism and heals the predator. If unsuccessful, the predator takes damage.
  • To prevent ‘sticking’ (i.e., predator A continuously following prey item B until it makes a successful kill), organisms have a cooldown timer on things like predation and mating. While this actually isn’t as important for predation, as the predator might equally well end up killing itself, this is quite important for mating, where two ‘stuck together’ organism may continously mate, leading to intense overpopulation.
  • newborn organisms have a slightly increased chance of winning predation event if they are the prey item.
  • organisms have a few timers:
    • a starvation timer. As mentioned above. This prevents organisms from just sitting there and doing nothing.
    • a maturity timer. Basically, newborn organisms must wait a certain amount of time (dependent on species) before they themselves can mate.
    • a gestation timer. This actually doesn’t determine how long after mating before a newborn is produced. This happens immediately. Instead, this misnamed timer acts as a time-between matings deally, preventing organisms from mating too many times. This is also based on real-world species-specific data
    • a predation timer. Prevents an organism from eating too often
  • The decision on what an organism is doing (i.e., is it just wandering, seeking prey, or seeking a mate) is determined by how recently each of the relevant events occured.
  • Finally, the organisms, if not actively interacting, attempt to stay within a certain distance from each other as part of an underlying flocking simulation. A simplified version of this flocking sim can be seen by clicking the [Old Version] button.

Setup basically just consists of setting the number of organisms. Click each organism to see what eats. Note that the dragon basically acts as an apex predator, and its particular timers are based on estimates of Tyrannosaur data.

Finally, please note that the simulation is still buggy, and you may find that organisms tend to fall off the screen more often than not.

Teaching and Programming

Opposing Forces

I’ve been thinking a bit about the teaching of programming. Like any technically intense subject, there’s a necessary balance between two (somewhat) opposing forces. These are:

  • Dumping1 as much information as possible on the students, so that they can successfully navigate the labyrinthe that is whatever topic you’re trying to teach them.
  • Actually effectively teaching them anything.

The important point here is that, while you can get a bunch of students to memorize a bunch code snippets, the difference between call() and apply() and bind(), or all of the standard methods on the String prototype2, this does NOT constitute teaching. In this post, I’m gonna examine the ways in which we can first ineffectively and then (hopefully!) effectively hit both marks.

How Not To Do It

A.K.A., the Look At What I Can Do method

There’s an old, famous adage in teaching: Show, don’t tell. Basically, teachers shouldn’t just tell students that an idea is true, but rather demonstrate it. Obviously, there are limits to this. For example, all of euclidean geometry is based off of the unprovable assumption that, simply put, a point is a point, a line is a line, and a plane is a plane3.

Unfortunately, a lot of ineffective teaching stems from the assumption that because you tell students something, they’ll learn it. I could go into a completely separate tangent about Howard Gardener’s multiple intelligences, and how verbal learning is only one of at least seven separate styles, but suffice it to say that this is almost never an effective pedagogical method.

What’s worse, this lack of absorption is often compounded by severe information overload. Here’s an example:

  1. You’re teaching JavaScript, and you have a class of completely beginner programmers. They know how2computer, but they’ve never touched code in their lives.
  2. You show them the following script:

    var myName = ‘Dave’;
    myName = prompt(‘Enter a name please.’);
    function sayHi(n){
    alert(‘Hello ‘+n+’!’);
    }
    sayHi(myName);

    Fig 1: A “simple” code example

Simple, right? It just asks for their name and then says hello! Great way to introduce a simple bit of JavaScript, right?

Wrong! Remember, you’re (most likely) looking at this from the perspective of a relatively seasoned programmer. You know what we mean when we have a word followed by parentheses (i.e., myFunction(thing)). You know what variables are. So you look at this example and automatically know what it does. But imagine someone who’s never seen a programming function, or worse, has yet to go through high-school algebra (i.e., does not know what a variable is). For that person, the concept of changing variables4 may be still foreign to them.

This is an example (albeit a comparatively simple one) of a case of telling and not showing. In this case, our hypothetical teacher (you) assumes that because you already have the knowledge, it’ll be easy for your students to learn. The teacher fails to make the cognitive prediction between amount of knowledge that the students need to gain before they’re competent and the cognitive “leaps” that they can effectively take to get to that knowledge

Worse still, the student may not realized that they haven’t learned the material effectively until too late (i.e., the exam, or when they need to use this knowledge in a real-world scenario). This stems from the copy-and-paste programming education that this “tell” style of teaching lends itself to. Imagine that you’re a student in the above class. You’re told to copy and paste the above code, but you can (for now) change whatever’s between the quotes. You write:


var myName = ‘Bob’;
myName = prompt(‘Who are you?!’);
function sayHi(n){
alert(‘Greetings, ‘+n+’!’);
}
sayHi(myName);

Fig 2: The student writes some code

So you run your code, and hey, it works! It says something different now, so that must mean you know what you’re doing. Right?

Well, no. It means you’ve copied some code directly. While this is fine later on (hello, Stack Overflow), this doesn’t teach you anything except how to type. Your teacher introduced at least 7 different concepts here5. Because these are relatively fundamental concepts, your teacher assumed that they’d be basal enough that anyone would either know them, or immediately “get” them.

Instead, we need to ask what the most fundamental pieces of these scripts are, and how we can break them down into (still functioning!) pieces that teach only a few concepts at a time.

The Pillars of Programming

A.K.A., What’s Actually Important

So what are these fundamental pieces? Well, to answer that, perhaps we’d better start by asking what’s common to all (or at least, most) languages6. This’ll help us see what particular pieces we may wrongly assume everyone already knows. Here’s my list (feel free to skip this section if you want):

Variables: var myVar = 'chocolate'

In order to store information, your program needs little boxes in which to store that stuff. Just like you might label a box in your closet “shoes”, or a drawer “silverware”, we might label a ‘box’ in our code as myVar. We could then store in this box your favorite flavor of ice cream. In some languages, different variables can store different kinds of information. Your cardboard shoebox can store shoes, but you’d probably not wanna store last night’s chicken stew in there.

Arrays/Lists: var simpsons = ['Lisa','Bart','Maggie','Marge','Homer']

Remember how we said different variables can store different stuff? Well, some variables are designed to hold multiple bits of information. In the example above, the variable simpsons stores all of the (human) members of the Simpsons’ family. Just a useful way of organizing information!

Conditionals: if(condition) then actionIfTrue else actionIfFalse

Programs are famous for making complex decisions. It was, generally, why the first programs are written. Conditionals allow a program to interpret different input and change depending on what that input says. For example, let’s say you write code for a robot to sort your house out. It inspects each container in your house and then puts the appropriate item in there. You might have something like the following


if (box_for_shoes==true) then
Put_Shoes_In
else if (box_for_tupperware==true) then
Put_Stew_In
else
Yell “I don’t know what to do!”
end

Fig 3: Example of a conditional7

Your robot inspects the box, and first asks “Is it a shoebox?”. If yes, it sticks shoes in there. If no, it then asks if the container is tupperware. If so, it sticks stew in there. Finally, if neither of these is true, it screams at you in frustration.

Loops: while (thing is true) then do something

Imagine your house-sorting robot needs to sort 1000 boxes (you really need to do something about your boxes, dude). You could write the above conditional 1000 times. Or, you could not drive yourself completely insane, and use a loop! Note that, for the example below, we’re pretending that “sort_a_box“ just tells the robot to, well, sort that box.


var num_boxes = 1000
while (num_boxes>0) do
sort_a_box
num_boxes = num_boxes - 1
end

Fig 4: Example of a while() loop

So we start out with 1000 boxes. Then we have a loop, where each time it asks “Is the number of boxes greater than zero?” If so, it continues. Otherwise, it stops. Finally, we subtract 1 from the number of boxes, so that our robot essentially ticks one box off as being ‘done’ each time. Note that there’s no “false” condition for this loop: there’s no while (thing is true) then do_something otherwise do_other_thing

Another incredibly useful type of loop is the for loop. This loop basically runs a set number of times. So if you wanted to say “Hi!” 10 times, you could do:


say “Hi!”
say “Hi!”
say “Hi!”
say “Hi!”
say “Hi!”
say “Hi!”
say “Hi!”
say “Hi!”
say “Hi!”
say “Hi!”

Fig 5: Code repetition

Pretty repetitive, right? Alternatively, you could do the following:


var i = 0;
for i,i<10,i+=1 do
say “Hi!”
end


Fig 6: for() Loop

So much more compact! This loop tells us to start by making a variable named i, and setting it to zero. We then start our loop. During each iteration of the loop, we look at i and ask whether it’s still less than 10. If it is, we increment i by one and do another iteration. Otherwise, we stop.

Functions/Methods: function myFunc(name) do say "Hello, "+name endFunc

Loops are pretty great at making our code more efficient, but what if we have bigger blocks of code that we wanna pass around? Or, worse, what if we don’t know the order in which we want our code to run? This is where functions (also known as methods in some areas) come in. Functions allow us to write blocks of reusable code that we can pass around for different areas of the code to “borrow”.
Let’s stick our conditional example from above in a function


function shoe_or_stew(box_for_shoes,box_for_tupperware) do
if (box_for_shoes==true) then
Put_Shoes_In
else if (box_for_tupperware==true) then
Put_Stew_In
else
Yell “I don’t know what to do!”
end

Fig 7: My First Function

The bits between the parentheses are called arguments. They basically allow us to pass in information for our function for each ‘run’ of that function. So each time our robot gets a new box, it runs this function. If the value passed in for box_for_shoes is true, then it’s a shoebox. If the value for box_for_tupperware is true, it’s a tupperware container. And if neither is true, yell in frustration.

Blocks: do some_stuff end

You may have noticed in the past few examples the words do and end. These sit on the ends of sometjing in programming called a block. Wikipedia defines a “code block [as] a section of code which is grouped together” (Wikipedia:Block Programming). We can then do things with those blocks, like use them as the result of a conditional, or the contents of a function.
In some languages, the blocks are denoted by curly brackets ({ and }).



1 I deliberately use the term “dumping” here, for reasons I’ll explain later.

2 Can ya tell what language I’m using here? I’m totally not a JavaScript fanboy or anything. Nope.
3 This is actually not exactly what the postulate says, but it’s close enough.
4 Variable variables?
5 Variables, functions, strings, function arguments, the alert() method, programming blocks ({...}), and calling functions.
6 Of course I mean programming languages here, but interestingly enough, there are common features to spoken/human languages as well that basically allow us to learn other languages. These include things like verbs, nouns, descriptive words, and some sort of system for distinguishing what words play which “role” (i.e., subject vs. object).
7 We would, of course, at some point also want to mention why we use == vs =.

What Influenced and Inspired Me to Learn Code

Why Program?

Of Screens and Stereotypes

Why be a programmer? Well, before I answer that question, perhaps we should look at why that even is a question. Why do we still need to justify our decisions to sit behind computer screens, presumably wear pocket protectors and thick-rimmed glasses, and speak in nasally voices? Because let’s face it: that’s exactly what the stereotype of ‘the programmer’ has been for decades. My answer to that question is a multiple part one, and it begins with my love of building things back when I was but a wee lad.

The History of Dave

I have had many what one might ostensibly call ‘career ideas’ in my school career, but what they’ve all centered around is the desire to construct and to present information to others.
As I’ve mentioned, my school career is diverse. In 2009, I graduated from Lafayette college with a degree in biology, which any scientist will tell you has about as little to do with programming (or indeed, math in general) as anything that’s still in the field of ‘science’ possibly could do. Biologists love dealing in fuzzy logic (or fuzzy creatures), and the only math the traditional biologist is ‘comfortable’ with is the relatively tame world of statistics. I mention this because it’ll help me explain later why I translated into programming eventually. I wasn’t the traditional biologist, and I would often observe particular pieces of the natural world – the structure of DNA and its relation to RNA, protein, and even binary code; the ecological interaction of different levels of a trophic web, and the ‘self balancing’ nature of a mature ecosystem, for example. So it was only natural that I started to apply myself to some basic coding techniques to try to emulate these systems. I learned JavaScript, and dug up my old memories of HTML and CSS (I’d pretty much stopped learning anything web-related back when the font tag was still in vogue!).

Teaching

Meanwhile, in my non-computer-related life, I took up the pursuit of teaching. I studied at Drexel University, graduating in 2011 with a Masters’ degree in science education at a secondary level. Again, dear reader, you may be wondering “Dave, what the heck? You were just talking about biology vs. programming, and now you’re onto teaching? Get your mind on track!”. But bear with me. My love of understanding how to model natural systems, how to build, and, let’s just face it, programming in general, extended to the world of teaching. It was all very well and good if I could build a website to translate DNA to RNA and protein, but unless the site could explain why this translation worked, it was useless. Paradoxically, this meant designing a program that could both explain the biological, chemical-related world of transcription and translation – mRNA, tRNA, codons, and all those good buzzwords high schoolers hate – and the oft more strict world of programming. Here’s a brief example:
1.DNA is a chemical code comprised of differing combinations of A (Adenine), T (Thymine), C (Cytosine), and G (Guanine).
2.Its counterpart RNA (the mid-step to conversion into a protein) basically copies that code (think of DNA as the master blueprint, and RNA as the copy of the blueprint taken to the job site).
3.But wait, there’s more! Unlike DNA, RNA has no “T” (that’s thymine, folks). Instead, it uses Uracil (U).
4.So in a very simple programming exercise, I needed to replace every instance of ‘T’ in the input string with ‘U’.

So What?

So in short, I guess what made me want to program was both a love of web design (and hey, let’s face it, the ‘tricks’ you can do with it’) as well as a desire to take advantage of yet another medium to help in the education of science.

Another Observation

Perhaps not directly related to the question itself, but here’s a bit of an interesting observation: DNA is a full-fledged programming language, in the same way any other programming language is. It’s reactive, in that the ‘programs’ it generates are reactive to their environment (we call these programs “living things”). It is moderately self-correcting, containing error-proofing mechanisms that any programmer should be jealous of. The major two differences stylistically between DNA and, say, JavaScript are:

DNA is based on a quaternary (four-part) code, while computer programming languages are at some level influencing a binary system.
Its development cycle is a bit slow, on the order of centuries, millennia, or eons. Waiting for the next program update to come out is not advised.