Pair program with me! profile for carousel at Stack Overflow, Q&A for professional and enthusiast programmers

10/22/2013

REST cheat sheet

I created a simple cheasheet table, like every day reminder for creating beautifull rest API-s. So, if you have experience with old PHP routing style in the form of:
"http://host/resource /?id=some_id"

it is time to refresh your skills by moving to more modern approach. Fortunately, REST (Representational state transfer) is supported in all new frameworks like ExpressJS or PHP Laravel.
So this table can help because it can be sometimes confusing to remember which verb belongs to which path.

Here it is:


Thanks for visiting my blog.
Miro

10/21/2013

How to properly understand Javascript language PART 1 ?

Hello;

My first programming language was Javascript. Learning JS without previos knowledge of programming theory ( paradigms, history and language background ) was a very painful process, full of pitfalls and roaming in the dark.  As I can see, a lot of people had a same experience. From my point of view it is because  in JS it is relatively  easy to write applications that looks like a real applications - with the help of large number of  libraries that provides usefull abstractions in the form of their "easy to learn" API.  Canonical example is jQeury - with a minimal code you can have reference to DOM object, without knowing what is happening in the back:

    //
    var elem = $("div")
    //

I am not saying that abstractions are evil, and that we should avoid them. It should be a nightmare to write code without them. After all with the help of abstractions, we are not writing assemby anymore, or in the case of jQuery, cool animations. I want to say that when learning language  starting with libraries like jQuery can cause  unnecessary confusion, which is hard to correct.

This is even more the case with JS, because of it‘s weird combinations of paradigms and idioms. For example, concept of closure  has become trademark of a language, that is very hard to pick without a knowledge about its context, root and origin. To proof, term closure is one of the most searched programming term online, with blogs and even whole sites dedicated to it.
People are really having problem to digest closure. It is not a surprise, because it is one of the hardest programming concept that exist.

After years of struggling with JS I created my mental model about what is Javascript. Of course, it is not just a theory. I am a programmer and the whole point of this post is to better understand Javascript so I can express my self with code.

So lets examine some of the main bulding blocks of JS.

I‘ll start with syntax, since it is very natural to start with when learning new language. Javascript belongs to so called "curly-braces" family of languages, which is mostly influenced by C.
Take a look at the following examples:
    //
    var i;
    for ( i = 0; i < 5, i++){
          console.log("hello");
    };
    int i;
    for ( i = 0; i < 5, i++){
          printf("%s\n","hello");
    };
    //

These two examples are identical, except one cosmetic difference. To write to output, Javascript uses console.log method, which is specific to browser environment, and C uses printf. Their syntatic similarity can also be seen  through code formating that I use in this blog. Both loops are formatted using same pre tag ( <pre class = "brush:js">), which is JS specific. But the output is still well formed, except some minor color differences.  Looking deeper in the languages syntax, there is very, very close relationship between them. I don't want to spend too much time dealing with that topic, since it is covered in more details on other places. To start with syntax comparison read a great Wiki articles: Comparison of programming languages syntax and List of programming languages by type.

The main takeaway from this is: Take some to learn basis of C programming language.  There are tons of great resources and tutorials online. You'll be surprised how much is Javascript influenced by C. In the beginning that influence can be seen as only syntatical, but with experience you'll see how much  have you missed. I became enlightened after learning C.

And that is just a beginning. In the future posts I'll cover other important Javascript  paradigms - first object and then functional.

Miro.


9/16/2013

Linux system calls - fork,exec and pipes.

These days I am passionate about network programming concepts, in order to fully understand Nodejs stack.
I created a small program to demonstrate canonical usage of basic linux system calls - fork, exec and pipes. These calls are used in most network applications and servers. It is heavily commented. Sorry for the code formatting, it is syntax highlighter issue.

#include
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 


// canonical example of fork,pipe and exec.
// it is heavily commented

// main program
int main (int argc, char ** args)
{
    // pipe
    int p[2];
    char buf[5]="\0";
    int pid;

    // do we have a fork ?
    if (!fork()){
        // write to one end of pipe
        write(p[1],"Child writes to pipe\n",22);

        // open a file
        int fd = open("one.js",O_RDWR);
        // read from that file
        read(fd,buf,70);

        //close file descriptor
        close(1);
        // replicate closed descriptro
        int i = dup(0);
        // print usefull message
        printf("Value of fd is: %d\n",i);

        // open new program, and provide some arguments
        execlp("./one","one",buf,NULL);

        // don't forget to exit child process and close open file descriptor
        exit(0);
        close(fd);
    }else{
        printf("Parent reading pipe");
        // read from a pipe
        read(p[0],buf,5);
        // print a pipe content
        printf("%s\n",buf);
        // wait for a child to exit
        wait(NULL);
    }
   return 0;
}
//

Thanx for visiting my blog
Happy Coding :)

9/05/2013

Network programming with sockets

I have to admit, I've moved away from Javascript , and I am spending most of my time in C/C++ together with Unix/Linux programming.
One of awesome things in compiled land :) are native kernel support for socket interface. In case you don't know what are sockets check out this link. Sockets are the basis of Internet, and It is very usefull to become familiar with them. Socket header files are written in C, but there are implementations for all modern languages. Sockets represents low level layer of network stack.
This is my simple implementation of server socket, written in C:

//
#include 
#include 
#include 
#include 
#include 
#include 
#include 

const char message[] = "Yuhuuuuu. Hello From The Server\n";
int main(int argc, char *argv[]) {

    int simpleSocket = 0;
    int simplePort = 0;
    int returnStatus = 0;
    struct sockaddr_in simpleServer;

    if (2 != argc) {

        fprintf(stderr, "Usage: %s \n", argv[0]);
        exit(1);

    }

    printf("%s\%s\n","Listening of port: ",argv[1]);

    simpleSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    if (simpleSocket == -1) {

        fprintf(stderr, "Could not create a socket!\n");
        exit(1);

    }
    else {
     fprintf(stderr, "Socket created!\n");
    }

    /* retrieve the port number for listening */
    simplePort = atoi(argv[1]);

    /* setup the address structure */
    /* use INADDR_ANY to bind to all local addresses  */
    bzero(&simpleServer, sizeof(simpleServer));
    simpleServer.sin_family = AF_INET;
    simpleServer.sin_addr.s_addr = htonl(INADDR_ANY);
    simpleServer.sin_port = htons(simplePort);

    /*  bind to the address and port with our socket  */
    returnStatus = bind(simpleSocket,(struct sockaddr *)&simpleServer,sizeof(simpleServer));

    if (returnStatus == 0) {
     fprintf(stderr, "Bind completed!\n");
    }
    else {
        fprintf(stderr, "Could not bind to address!\n");
 close(simpleSocket);
 exit(1);
    }

    /* lets listen on the socket for connections      */
    returnStatus = listen(simpleSocket, 5);

    if (returnStatus == -1) {
        fprintf(stderr, "Cannot listen on socket!\n");
 close(simpleSocket);
        exit(1);
    }

    while (1)

    {

        struct sockaddr_in clientName = { 0 };
 int simpleChildSocket = 0;
 int clientNameLength = sizeof(clientName);

 /* wait here */

        simpleChildSocket = accept(simpleSocket,(struct sockaddr *)&clientName, &clientNameLength);

 if (simpleChildSocket == -1) {

            fprintf(stderr, "Cannot accept connections!\n");
     close(simpleSocket);
     exit(1);

 }

        /* handle the new connection request  */
 /* write out our message to the client */
 write(simpleChildSocket, message, strlen(message));
        close(simpleChildSocket);

    }

    close(simpleSocket);
    return 0;
}
//
Happy Coding.

8/17/2013

Bootstrap data with Jade templating engine

Jade is templating engine closely related to expressjs. It is not a surprise, since jade is created by a same author. Jade is heavily influenced by syntax of Ruby and Haml.
There are lot of great features in Jade, that makes dealing with compex views on server side really  smooth. One of them is ability to transfer data directly to html ( jade file ), without additional request.
Let me explain that more. We know that HTTP request are expensive. So it is a good pattern to initially load as more content as possible,  so we don't have to make new requests to server. That is  a winning paradigm that  makes single page web applications so powerful on the client side.  On the client, simply load all the view once and make Ajax request for data if needed.  Since Jade is rendered on the server, this approach is especially useful when application needs data from database for the first load.

With Jade we can easily bootstrap data like this:

//
//here data is plain js object
var data = { "name": "myApp","version":0.0.0,"db":"mongodb"};

// now just render existing view, with data object attached   
app.get("/",function(req,res){
    res.render("home",{obj:data}) 
//

In the previous example data object  was local, contained in the same file as main app file. When we want  to bootstrap data from database, we take same approach when rendering jade template.
Again, data is attached to Jade template. The only difference is that we have to have access to database.

Here is example:
//
exports.queryDB = function (req,res) {
    db.collection("jazz",function (err,collection) {
        collection.find().toArray(function (err,collection) {
            res.render("jazz",{giants:collection});
        });
    });
};
//

Database example is a function that asynchronously query data, due to nature af nodejs native mongodb driver. But when we have data, we can manipulate with it with Jade syntax. For example, to iterate over data object and insert it in the html we can do this:

    // 
    ul
        each giant in giants
            li
                a(href="#{giant["name"]}") #{giant["name"]}
    //


Now we have nice list of jazz giants on our page, bootstrapped on first request.

Thanks for visiting my blog.

8/12/2013

Mongodb and underscorejs - the mean stack

I found a way to combine two very powerful toys that I am playing with :

Mongodb - noSQL database that is shaping web these days and Underscorejs  - which make me fell in love with functional programming.

If you don't know already, mongo is using document/oriented key/value way of storing data in JSON format ( BSON - binary JSON under the hood ).
Underscore has a tons of functions that works with literals like plain JS objects and arrays ( which are basic building blocks of mongo collection ). Also, underscore is environment agnostic. That means that it is not dependent on interfaces like DOM. It is important just to execute underscore functions under Javascripot interpreter. Mongo shell is actually javascript shell, so underscore fits great.

To import JS code in mongo, open your .mongorc.js file, that is located in /home/ directory ( Linux/MacOSx), and place any script inside. It can be whole library, like underscore. Now, from terminal, open mongo shell, and type load (".mongorc.js"). Now all code inside that file is avaliable to mongo documents.

Play yourself and have fun.

Thanks for visiting my blog.


8/11/2013

Design patterns refactored

I did some cleaning and refactoring of my implementations of classic design patterns in coffeescript.
Also I included some variations of existing patterns ( adapter, composite ). There is always more than one way in which we can do same thing ( especially with JS ).

Code is  here

Thanks for visiting my blog.