jQuery time input plugin

After looking for ages for a  nice client side time entry  plugin, but without any result, I decided to write my own jQuery plugin.

My requirements:

  • Enter any amount of hours.
  • Be able to enter 12 hours and 30 minutes and display it like “12:30”.
  • Allow user to enter hours in two formats:  12:30 and 12,5 both meaning twelve hours and thirty minutes.
  • Easy retrieval of the entered value.

If you want to find out quickly if this plugin is what you are looking for, go to the demo page.

Usage:

1. Download the library from Github and add a reference to jQuery and the plugin script. In this example I use the Google CDN version of jQuery:

  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script src="jquery.timeinput-0.1.min.js"></script>

2. Create an input field in your html document:

<input id="timeInput" />

3. Call the plugin and attach a change eventhandler to have access to the total minutes entered by the user.

     $(document).ready(function () {
            var ti = $("#timeInput").timeInput();
            ti.on("change", function () {
                console.log("New input value: '" + ti.val() + "'. Minutes: " + ti.getTotalMinutes() + " (" + ti.getTotalHours() + " hours)");
            });
        });

Settings

The plugin accepts a settings object in the constructor. The available options are listed below.

Option Type Default value Description
maxMinutes Number 24 * 60 (one day) The maximum amount of minutes to enter.
minMinutes Number 0 The mimumum amount of minutes to enter.
defaultMinutes Number null If set to a numeric value, it will be displayed in the input field initially.
decimalSeparator String “,” The character used to enter values like “3,5”.
hourMinuteSeparator String “:” The character used to enter values like “3:30”.
roundToNearest Number 15 Round to the nearest 15, 30 or 60 minutes. Any other value will be ignored.

 

Here are some controls and plugins I checked out and why they don’t fit my needs:

  • Kendo timepicker: allows you to select a moment in time, but it’s not possible to select an amount of hours and minutes.
  • Kendo masked textbox: enables me to specify a format like HH:mm, but I cannot apply multiple masks.
  • Kendo numeric textbox: this one came close, but it is not possible to have a value of 3,75 but display 3:45 to the user.
  • jQuery time entry: great plugin, but only one input format accepted at a time.

Feed forward neural network in javascript

Introduction
A two year old child is able to do it, but it takes a cluster of no less than 16.000 computers to perform the task of recognizing a cat in a Youtube video. Somehow, our regular algorithms are simply not sophisticated enough to help us with this apparently easy task. The human brain however is very good at solving problems which involve a tremendous amount of input (video data) and recognizing a pattern (like a cat) in it.  Besides that, it is able to learn to recognize cats by looking at other videos or images of cats.
In this article, I’ll try to explain what a neural network is and what they can be used for without going into a lot of mathematical details. Hopefully, it’s just enough to get you started creating your own cool stuff like the examples I linked to at the bottom of this article.

Artificial neural networks
The answers to difficult problems are often found in nature. To solve problems similar to the recognize-a-cat problem, scientists are studying the inner workings of our brains for many years now.  They found out that the brain contains a huge collection of so called neurons which are wired together in a network structure. The anatomy of a single neuron looks like this:

neuron

 

Dendrites are the sensors of a neuron. They receive inputs from other neurons that will be processed in the soma. The soma then outputs some value through the axon. Because I’m not a biologist I don’t have a clue what really happens, but I’m sure there’s some pretty complex stuff going on in neural networks (NN).
The computer model that is based on this network is called an artificial neural network (ANN). It is not a resemblance of a real neural network, but it does use the same terminology.


Simple optical character recognition (OCR) in javascript
For this article I prepared a demo project written in javascript that makes use of an ANN. Some of the code I already wrote years ago (in Vb.Net), but I translated it to javascript & HTML5 because that makes it easier to display this demo on the web. To go to the demo page directly, click here. To view the source code of this page on Github, click here.

The demo project lets you draw a character (A, B or C) and displays it’s best guess:

ocr_demo

 

You can train the neural network with new characters or improve the recognition of existing characters using the Train methods as explained on the demo page.

The simplest form of an ANN is a so called feed forward neural network. The neurons in such a network are organized in layers. A neural network can have many layers, depending on the requirements.  In my OCR example, there are only two layers: input and output. The input layer is fed with the users drawing on the canvas. I downscaled the drawing to a 15 x 15 grid, so I now have 225 input values: a pixel is colored (1) or not (0). The network now calculates which character has the best match with the drawing.

The output neurons (only 3 at this point) receive a zero or one from the input layer on their dendrites (the arrows in the image). Each arrow has a corresponding weight value which is used to determine how important the zero or one actually is. The weights can be changed by training the network, which I’ll show you later on. Every neuron generates an output value by simply adding up all the input values multiplied by their weight. That’s it. No complicated math involved!  The output neuron with the highest output value is the winner, because in this example it indicates the character that has the best match with the drawing.

The following image zooms in on the inner working of a single neuron:

artificial_neuron

The left part of this image represents the sum of all the dendrite values, multiplied by their weights. The right part represents the so called transformation function. This is, in my case, a function that will squeeze any input value to a value between 0 and 1:  sigmoid function. Doing this makes sure that each next neuron in the network can determine whether it will ‘activate’ or not. Some ANN’s are programmed to pass on the value (activate) only when it’s value is higher than some threshold,  e.g. 0.5. This is not applicable in the OCR demo project.

Here’s all the code of the Neuron class in Brain.js:

//a neuron is the calculation unit and is responsible for generating an output value.
var Neuron = (function () {

 //neuron constructor. They have names for easy retrieval.
 function Neuron(name) {
 this.Name = name;
 this.Dendrites = [];
 this.AxonValue = 0.5;
 }

 //generate an output value based on the input values multiplied by the corresponding weights.
 //the output value is always between 0 and 1 because of the sigmoid function (http://en.wikipedia.org/wiki/Sigmoid_function)
 Neuron.prototype.Think = function () {
 var sum = 0;
 if (this.Dendrites.length &gt; 0) {
 for (var i = 0; i &lt; this.Dendrites.length; i++) {
 sum += this.Dendrites[i].SourceNeuron.AxonValue * this.Dendrites[i].Weight;
 }

 //apply sigmoid function to transform the sum to a value between 0 and 1
 //AxonValue is just a sexy name.
 this.AxonValue = 1 / (1 + Math.exp(-sum));
 }
 };
 return Neuron;
}
)();

To kick off the networkon, all we have to do is call the Think() method of each Layer.

//make each layer in the network 'think' (generate output values)
    Brain.prototype.Think = function () {
        for (var i = 0; i < this.Layers.length; i++) {
            this.Layers[i].Think();
        }
    };

Each layer then calls the Neuron’s  Think() method.

 //make all neurons in the layer generate an output value
    Layer.prototype.Think = function () {
        for (var i = 0; i < this.Neurons.length; i++) {
            this.Neurons[i].Think();
        }
    };

In my humble opinion, the fun thing of this approach is that there’s isn’t any code  involved which has actually has anything to do with character recognition!

 

Training the network
The only thing left to explain is how the weights on the dendrites get their values. This refers to training the network which is a crucial part of an ANN: it’s ability to learn. Just like a human brain would have, the ANN first needs to have a good understanding of what is considered for example an “A” character. Therefore, the user needs to draw a few good A’s on the canvas first. In a training cycle, the network network will run as usual, but instead of showing the output to the user it calculates the difference (delta) between the output value and the input value. The delta or “error” value indicates how ‘wrong’ the dendrite’s weight is. To correct the weight, it will be increased by the product of the error value, the input value and a constant learning rate. The learning is only there to make sure that a training cycle doesn’t have too much impact at a time. In javascript, this looks like this:

//train an output neuron with some inputdata. The inputdata is considered a good example for the output neuron.
    Brain.prototype.Train = function (inputData, outputNeuron) {

        //no layers, no glory
        if (this.Layers.length === 0) {
            return;
        }

        //fill the first layer with input data to feed the network
        var inputLayer = this.Layers[0];
        for (var i = 0; i < inputData.length; i++) {
            inputLayer.Neurons[i].AxonValue = inputData[i];
        }

        //generate output for the given inputs
        this.Think();

        //adjust weights using the delta
        //the generated output is compared to the training input: the drawing in this case.
        //the subtraction is the error which will be corrected by adjusting the weight.
        var delta = 0;
        var learningRate = 0.01;
        for (var i = 0; i < outputNeuron.Dendrites.length; i++) {
            var dendrite = outputNeuron.Dendrites[i];
            delta = parseFloat(Math.max(inputData[i], 0) - outputNeuron.AxonValue);
            dendrite.Weight += parseFloat(Math.max(inputData[i], 0) * delta * learningRate);
        }

    }

Cool examples
You’ve made it to the end of this crash course in ANN’s. Now you’ve seen all the important aspects of ANN’s that you need to get started building your own mind blowing software ;-). Please take a look at the links below to see some nice examples of neural networks.

 

 

CSRF attacks for dummies

Every web developer out there knows there is a good chance that his or her web application will become the target of someone trying to do harm to your website or its users. If you built a popular website, it seems  like hackers are willing to spend lots of hours to find even the smallest hole in your digital walls.  Sadly, it isn’t enough to simply keep your site out of the Moz top 500 to remain safe. That’s because low traffic sites might also be stumbled upon by one of the zillion robots scanning these sites for vulnerabilities.

The Open Web Application Security Project (OWASP) publishes a list with the most common threats every year. Here’s last year’s list:

If any of these make you scratch your head you should probably take some time to read about them first. Injection attacks and XSS vulnerabilities are very well known and most webdevelopers take at least some measures to prevent them. This article is about another common but many times overlooked threat on this list: the cross-site request forgery (CSRF).

How the internet works
When someone visits a webpage, the browser composes a HTTP request and sends it to the webserver. The webserver then responds accordingly. The response might contain a webpage (html), a PDF document, an image or whatever you requested. After the response is sent back, the webserver has completed its task and can now close the connection. In most cases it is perfectly acceptable that the webserver has forgotten all about you at this point. 

Browser: hey server, I would like to see “nice_page.html”
Server: let me look for that file…oh here it is, catch! I’m going to sleep now.

Sometimes it’s necessary that the server remembers you for subsequent requests. A typical example is when someone logs in and browses to a protected page. This is usually accomplished by passing around a secret token called a session ID. The server generates the session ID as soon as the first request is received and usually remembers it for the next 20 minutes. The session ID is sent back to the browser during the first response. When the next request is composed, the browser automatically sends the token along with the request.

Browser: hey server, I would like to see “protected_page.html”. My Session ID is ‘12345’
Server: Hi ‘12345’, let me check if I have seen you in the last couple of minutes…yes, I still remember you! You are allowed to view ‘protected_page.html’, so here you go.

Even though the server correctly verified the session ID, it cannot know for sure where the request originated from. It trusts the browser because it was able to give a session ID for a user that is allowed to view the requested page. This simple fact is exploited during a CSRF attack.

The target page
Take a look at  a document called change_password.html with the following markup:

<h1>Change your password</h1>
<form method=’post’>
New password: <input type=’password’ name=’newpassword’/>
<input type= ‘submit’ value= ‘Change password’>
</form>

This renders to a pretty page like this, hosted on our imaginary domain: http://www.greatdomainname.com/change_password.html

change_password

When a logged in user hits the submit button, the browser knows it has to post the new password to greatdomainname.com. By convention, it will send the session ID along with the post request as explained earlier. The server can now process the password change request for the user.

The attackers page
Now here’s a slightly different version of the html that an attacker can host anywhere on the internet.

<h1>Free ice cream!</h1>
<form method="post" action="http://www.greatdomainname.com/change_password.html">
    <img src="icecream.jpg" />
    <input type="hidden" name="newpassword" value="h4ck3d!" /><br />
    <br />
    <input type="submit" value="Click here for your free ice cream!" />
</form>

Which renders to something like this:

free_ice_cream

Notice that the attacker has instructed the form to submit to another domain then it is hosted on.

When a user is logged in at greatdomainname.com and later on visits the evildomain.com, he/she might be tempted by the delicious free ice cream and therefore clicks the button. What will happen now, is that the browser composes a request with a valid session ID, but the attacker has chosen his own password by using a hidden input field with the same name!

In general terms, to make a CSRF  attack succeed there are two prerequisites:

  • The user must be logged in at the trusted domain – thanks to single sign on lots of popular sites, this is often true.
  • The browser must be triggered to submit the malicious form. It isn’t always as obvious as the free ice cream sample. In fact, the whole Ice cream page isn’t event necessary, since the attacker could post the form directly in the onload event of the document with some javascript. In most cases, an attacker uses another exploit like XSS to inject the form into another website. The victim couldn’t possibly have a clue of what’s going on.

Ok, you scared me. What can I do to prevent CSRF ?

Depending on the platform you’re using there are pretty good solutions available. The key is to add an extra (hidden) input field to the form, which value is set to a value that only the server knows about. By checking this field when the request is received, the server is able to check the origin of the request.

Here are some platform related links regarding this subject:

ASP.NET MVC: http://www.asp.net/mvc/overview/security/xsrfcsrf-prevention-in-aspnet-mvc-and-web-pages
PHP: http://www.wikihow.com/Prevent-Cross-Site-Request-Forgery-(CSRF)-Attacks-in-PHP
Ruby: http://ruby.about.com/od/security/a/forgeryprotect.htm
Java: http://java.dzone.com/articles/preventing-csrf-java-web-apps