Erick Ruiz de Chavez

Web Developer, Geek "to the bone", Happy husband.

Scaffolding a Basic AngularJS App

My most recent assignment is an AngularJS project. To be honest it took me a couple of weeks to get the whole AngularJS concept on my head, but once I got it I really liked it.

Since I truly believe that one of the keys to success relies on practice, I decided to scaffold an AngularJS project today using some of the tools I already use, like Express, RequireJS, a special version of Bootstrap for AngularJS and Bower.

It is worth to mention that, even tho this project could give you a nice start for a basic demo, I would not encourage you to use it for production as it lacks for testing and build tools. The aim of these is just to work as a start point for other practice examples/demos but nothing more than that.

The code of this example can be found at GitHub.

The directory layout

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|- public/                Our front-end code
|  |- css/                CSS style sheets
|  |- fonts/              Fonts
|  |- img/                Images
|  |- js/                 JavaScript code
|  |  |- app/             Our app code
|  |  |  |- modal/        Modal Module
|  |  |  |- templates/    App templates
|  |  |  |- welcome/      Welcome Module
|  |  |  |- app.js        Main Module
|  |  |  |- main.js       RequireJS' bootstrap file
|  |  |- lib/             Bower libraries are installed here
|  |- index.html          Main HTML file
|- routes/                Node.js routes
|  |- index.js            Basic route, currently only 1 fake service
|- .bowerrc               Bower configuration
|- .editorconfig          EditorConfig file
|- .jsbeatifyrc           JSBeautify configuration
|- .jshintrc              JSHint configuration
|- app.js                 Node.js App
|- bower.json             Bower dependencies
|- package.json           Node dependencies

A quick overview

First, to get this up and running you will need:

  • Node.js
  • Bower npm install -g bower

Once you grab the code, in the project folder you will need to install the dependencies by doing npm install && bower install. Finally the dependencies are installed, the project can be started by doing npm start.

Node.js

The code on app.js (the one at the top level) is mainly Express code to setup an Express application. The most “interesting” parts of it on this example are the lines with var routes = require('./routes') and routes(app). The first one will do a Node.js import of our module called “routes” and as you will see, it is a folder with an index.js file on it. This file will be our routing bootstrap as it will be including other route files the same way it is included and set up the routes so we do not end upt with a big mess of routes on a single file. An easy way to keep things clean on the urs is to set a baseUrl and pass it around to submodules avoiding having to hard-code the path everywhere.

Say you have your folder routes/ with an index.js on it. Also you may have a submodule users/ on it (with its respective index.js) and maybe also inside you also have a sub-submodule pets/ (with its respective index.js). From the URL you may want to have some RESTful URLS like /users and /users/pets. To accomplish this you may follow this pattern:

app.js

1
2
3
4
5
6
// ... express setup code here ...

var app = express(),
  routes = require('./routes');

routes(app, '/');

routes/index.js

1
2
3
4
5
6
var users = require('./users');
modules.exports = exports = function (app, baseUrl) {
  app.get(baseUrl, exports.index);
  users(app, baseUrl + 'users/');
}
// your code here...

routes/users/index.js

1
2
3
4
5
6
7
8
9
var pets = require('./pets');
modules.exports = exports = function (app, baseUrl) {
  app.get(baseUrl, exports.index);
  app.get(baseUrl + '/:id', exports.get);
  app.post(baseUrl, exports.create);
  // etc.
  pets(app, baseUrl + 'pets/');
}
// your users code here...

routes/users/pets/index.js

1
2
3
4
5
6
7
modules.exports = exports = function (app, baseUrl) {
  app.get(baseUrl, exports.index);
  app.get(baseUrl + '/:id', exports.get);
  app.post(baseUrl, exports.create);
  // etc.
}
// your pets code here...

RequireJS

The RequireJS code will be found on public/js/app/main.js. This file should contain only require.config and the dependencies to start up our application. The configuration will be filled mainly with paths to our libraries and shims for the code that have specific dependencies that cannot be loaded using modules. For more details about it you can always refer to RequireJS documentation.

AngularJS

Last but not least, the Angular part of this scaffolded code will make extensive use of RequireJS to manage file dependencies and lazy load them; this way we would not have to worry about loading them manually by adding script tags on the index.HTML file.

An AngularJS module can be completely on a single .js file containing all its directives, filters, services, etc. or it can also be split into multiple files and then loaded as required, again, using RequireJS.

An example of this can be as follows:

test.js

1
2
3
define(['angular'], function (angular) {
  angular.module('test', []);
});

testftry.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
define(['angular', 'test'], function (angular) {
  angular.module('test').factory('testFactory', function ($http, $q) {
    return {
      getSomething: function () {
        var deferred = $q.defer();
        $http
          .get('/something')
          .success(function (data) {
            deferred.resolve(data);
          })
          .error(function (data) {
            deferred.reject(data);
          });
        return deferred.promise;
      }
    }
  });
});

testctrl.js

1
2
3
4
5
6
7
8
9
10
11
define(['angular', 'test', 'testftry'], function (angular) {
  angular.module('test').controller('testController', function ($scope, testFactory) {
    $scope.data = [];

    $scope.getSomething = fucntion() {
      testFactory.getSomething().then(function (data) {
        $scope.data = data;
      });
    }
  });
});

test.html

1
<button data-ng-click="getSomething()">Click me!</button>

testdir.js

1
2
3
4
5
6
7
8
9
define(['angular', 'text!test.html', 'test', 'testctrl'], function (angular, html) {
  angular.module('test').directive('test', function () {
    return {
      restrict: 'A',
      template: html,
      controller: 'testController'
    }
  });
});

And finally, somewhere on your javascript (like on your main.js or app.js) when the directive is required as a dependency, the complete chain of dependencies is loaded “automagically”.

What is next

As I said at the beginning of the post, this code is only intended for learning purposes and it is far of being production ready. There are several things to be added like a Grunt file for building or a testing framework to mention some.

Do not hesitate in contact me if you have any questions regarding this example, the code snippets or anything related, I’ll be more than happy to help you.

RPN (Postfix) Calculator

Today’s programming exercise is an RPN (Postfix) Calculator. From Wikipedia:

Reverse Polish notation (RPN) is a mathematical notation in which every operator follows all of its operands, in contrast to Polish notation, which puts the operator in the prefix position. It is also known as postfix notation and is parenthesis-free as long as operator arities are fixed. The description “Polish” refers to the nationality of logician Jan Łukasiewicz, who invented (prefix) Polish notation in the 1920s. Source

The requirement

Implement an RPN calculator that takes an expression like 19 2.14 + 4.5 2 4.3 / – * which is usually expressed as (19 + 2.14) * (4.5 – 2 / 4.3) and responds with 85.2974. The program should read expressions from standard input and print the top of the stack to standard output when a newline is encountered. The program should retain the state of the operand stack between expressions. Source

My solution in Node.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
var readline = require('readline'),
  rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  }),
  operators = {
    '+': function (a, b) {
      return a + b;
    },
    '-': function (a, b) {
      return a - b;
    },
    '*': function (a, b) {
      return a * b;
    },
    '/': function (a, b) {
      return a / b;
    }
  },
  ops = Object.keys(operators),
  stack = [],
  tokens, a, b;

console.log('Enter a Postfix expression and hit enter to get result or just hit enter to exit');
rl.setPrompt('> ');
rl.prompt();

rl.on('line', function (line) {
  line = line.trim();

  if (!line) {
    return process.exit();
  }

  tokens = line.split(' ');
  tokens.forEach(function(token) {
    if (ops.indexOf(token) >= 0) {
      if (stack.length < 2) {
        console.log('Error: Incorrect input, missing operands');
        return process.exit(1);
      }
      b = stack.pop();
      a = stack.pop();
      stack.push(operators[token](a, b));
    } else {
      stack.push(Number(token));
    }
  });

  if (stack.length !== 1) {
    console.log('Error: Incorrect input, missing operators');
    return process.exit(2);
  }

  console.log(stack.pop());
  rl.prompt();
});

What I learned

While solving this exercise I learned the following concepts in Node.js:

Bingo!

Today’s programming exercise is about Bingo!

The requirement

Bingo is a children’s game of chance, sometimes played by adults for fun or money. Each player has a card of numbers arranged in a five-by-five grid with five randomly-chosen numbers from 1 to 15 in the first column, from 16 to 30 in the second column, 31 to 45 in the third column, 46 to 60 in the fourth column, and 61 to 75 in the fifth column; the central space is “free” and is considered to be occupied. Then a caller randomly calls numbers from 1 to 75 without replacement, each player marking the corresponding number, if it is present on their card, as occupied. The first player to have five occupied numbers in a row horizontally, in a column vertically, or along either of the two major diagonals is the winner.

What is the average number of calls required before a single card achieves bingo? In a large game with five hundred cards in play, what is the average number of calls required before any card achieves bingo? Source

My solution

I found that when the number of cards increase in one game, the number of turns required to win is reduced. I some tests, running 1000 games with 1 card, it took always more than 60 turns, but when increasing the number of cards playing to, say 500, the number of turns required to find a winner is usually less than 16.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#!/usr/bin/env python
# BINGO Game simulator.
import random
import argparse

# This is the layout for each card.
"""
 0  5 10 15 20
 1  6 11 16 21
 2  7 12 17 22
 3  8 13 18 23
 4  9 14 19 24
"""

# The list of possible winning positions
winners = [(0,1,2,3,4),(5,6,7,8,9),(10,11,12,13,14),(15,16,17,18,19),(20,21,22,23,24),(0,5,10,15,20),(1,6,11,16,21),(2,7,12,17,22),(3,8,13,18,23),(4,9,14,19,24),(0,6,12,18,24),(4,8,12,16,20)]

# The range of values that can be assigned per column
ranges = [(1, 15), (16, 30), (31, 45), (46, 60), (61, 75)]

def gen_card():
  """
  Generates a random card.
  """
  card = []
  for r in ranges:
    used = []
    for i in range(5):
      number = random.randint(r[0], r[1])
      while number in used:
        number = random.randint(r[0], r[1])
      card.append((number, False))
      used.append(number)
  card[12] = (card[12][0], True)
  return card

def gen_cards(qty):
  """
  Generates 'qty' cards for a game
  """
  cards = []
  for i in range(qty):
    cards.append(gen_card())
  return cards

def is_winner(card):
  """
  Check if the provided card is in a winning state
  """
  winner = False
  option = 0
  options = len(winners)
  while not winner and option < options:
    winner = card[winners[option][0]][1] and card[winners[option][1]][1] and card[winners[option][2]][1] and card[winners[option][3]][1] and card[winners[option][4]][1]
    option += 1
  return winner

def print_card(card):
  """
  Basic card printing, shows the marked positions
  """
  print(' B   I   N   G   O!')
  row = []
  for i in range(5):
    col = []
    for j in range(0, 25, 5):
      if card[i + j][1]:
        col.append('X'.center(3))
      else:
        col.append('   ')
    row.append('|'.join(col))
  print('\n-------------------\n'.join(row))

def play(cards):
  """
  Play a BINGO game with the provided cards
  """
  used = []
  number = 0
  winner = None
  while not winner:
    number = random.randint(1, 75)
    used.append(number)
    for card in cards:
      index = False
      try:
        index = card.index((number, False))
      except Exception:
        pass
      if index:
        card[index] = (number, True)
      if is_winner(card):
        winner = card
        break
  return card, len(used)


if __name__ == '__main__':
  parser = argparse.ArgumentParser('')
  parser.add_argument('--cards', type=int, default=10)
  parser.add_argument('--games', type=int, default=10)
  args = parser.parse_args()

  results = []
  for i in range(args.games):
    cards = gen_cards(args.cards)
    winner = play(cards)
    results.append(winner[1])
    print('Wiiner Play a BINGO game with the provided cards for game %i' % (i + 1))
    print_card(winner[0])

  average = sum(results)/len(results)
  print('After playing %d games with %d cards each, it took an average of %d turns to win' % (args.games, args.cards, average))

What I learned

While solving this exercise I learned the following concepts in Python:

Sieve of Eratosthenes

Today’s programming exercise is the Sieve of Eratosthenes. From Wikipedia:

In mathematics, the sieve of Eratosthenes (Greek: κόσκινον Ἐρατοσθένους), one of a number of prime number sieves, is a simple, ancient algorithm for finding all prime numbers up to any given limit. It does so by iteratively marking as composite (i.e. not prime) the multiples of each prime, starting with the multiples of 2. Source

The requirement

Write a function that takes a single argument n and returns a list of prime numbers less than or equal to n using the optimized sieving algorithm described above. Apply the function to the argument 15485863 and count the number of primes returned. Source

My solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/usr/bin/env python
import math

def primes(number):
  # Create a list of all the odd numbers less than or equal to 'number'
  numbers = range(3, number + 1, 2)

  # The last number to be tested is the square root of 'number'
  max = int(math.sqrt(number))

  # For each number in the range
  for curr in numbers:
    # If the current number is not already removed and the current number is less
    # than or equals to the square root of our biggest possible prime
    if curr and curr <= max:
      # We will start at curr ^ 2
      start = curr ** 2
      # since this is a list of odd numbers, positions are not continuous
      index = (start - 3) / 2
      while index < len(numbers):
        # Remove the current number as it is a multiply value of curr and therefore
        # it is not a prime number
        numbers[index] = None

        # Move to the next multiply of curr that is an odd number
        value = index * 2 + 3
        value += curr
        while (value % 2 == 0):
          value += curr

        # Get next number's index
        index = (value - 3) / 2

  # Remove all None values from the range
  numbers = [n for n in numbers if n is not None]

  # Even numbers are not on the list but 2 is a prime, so add it to the list
  numbers.insert(0, 2)

  return numbers

if __name__ == '__main__':
  number = int(raw_input('> '))
  print(primes(number))

What I learned

While solving this exercise I learned the following concepts in Python:

RPN (Postfix) Calculator

Today’s programming exercise is an RPN (Postfix) Calculator. From Wikipedia:

Reverse Polish notation (RPN) is a mathematical notation in which every operator follows all of its operands, in contrast to Polish notation, which puts the operator in the prefix position. It is also known as postfix notation and is parenthesis-free as long as operator arities are fixed. The description “Polish” refers to the nationality of logician Jan Łukasiewicz, who invented (prefix) Polish notation in the 1920s. Source

The requirement

Implement an RPN calculator that takes an expression like 19 2.14 + 4.5 2 4.3 / – * which is usually expressed as (19 + 2.14) * (4.5 – 2 / 4.3) and responds with 85.2974. The program should read expressions from standard input and print the top of the stack to standard output when a newline is encountered. The program should retain the state of the operand stack between expressions. Source

My solution in Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/usr/bin/env python
import operator

stack = []
operations = {
  '+': operator.add,
  '-': operator.sub,
  '*': operator.mul,
  '/': operator.div
}

def rpn(inputs):
  for item in inputs.split(' '):
    if item not in operations.keys():
      number = float(item)
      stack.append(number)
    else:
      if len(stack) >= 2:
        b = stack.pop()
        a = stack.pop()
        stack.append(operations[item](a, b))

  return stack.pop()

print('Enter a Postfix expression and hit enter to get result or just hit enter to exit')

inputs = True
while inputs:
  inputs = raw_input('> ')
  if inputs:
    print(rpn(inputs))

What I learned

While solving this exercise and looking for a couple of finished codes (after I finished my own version) I learned the following concepts in Python:

New Year Resolutions 2014

An we are starting a new year, and with it, the tradition to have new year resolutions which most of the times are only followed for a couple of months and then forgot. But this year I am making some of them public, so I have a better commitment. I’ll update them if I get new resolutions to follow up along the year, but at least for the present time these are my new year resolutions:

  1. Read (at least) 1 book each month and/or 12 books in these year, whatever fits better my schedule.
  2. Do a daily programming exercise on python or other programming language that is not my current one.

For resolution number 1 there is no need to do a lot of details. I am just willing to read a lot this year.

Resolution number 2 is more focused on 2 things, the first one, I feel I have felt on my comfort zone and I only do my day to day tasks without exercising my general problem solving abilities. I am too focused on common use cases that when I am prompted to do something different my head freezes. I am also doing some Python practicing, so, what best way to do more practice for both, my head and my Python skills that push myself to do at least 5 exercises per week (mon-fri). At the present I will be using programmingpraxis.com, my plan is to follow those in chronological order, but I may skip some of them.

Do you have any suggestions? Would you like to share your resolutions? Do not be shy! Leave me a comment!

My Start With AngularJS

Some weeks ago I was required to start working on a side project with high visibility and aggressive deadline. This time I was not leading the project itself but we are all sharing architectural choices as well as coding responsibilities.

As usual with any new library, frameworks, technologies, etc. we started by sharing previous experiences and both on-line and off-line resources so we could all be on the same level of understanding. The choices were Node.js as back and middle end and AngularJS for the front end. The front end choice was actually very interesting for me due to the fact that none of my projects uses it and there are only a couple of other experiences on the rest of the team.

Some of the main reasons I found this specially interesting were:

  1. As you may know, I am a big Backbone.js fan. I have spent at least 2 years learning about it, defining projects, improving them, abstracting components and code on top of it.
  2. AngularJS is made and sponsored by [Google][google]. If they are using it, it should have a good foundation; also, it is making a lot of noise lately just like Backbone.js used to do it.

I started by reading the core concepts of AngularJS on its documentation page and spending some time watching some good introductory videos but I didn’t feel I was moving on the right direction as these were either too good or too basic for my current knowledge.

After doing some struggling with my initial code and spending some time reviewing it withe the project leader, he pointed some interesting points and also shared an excellent resource to get better understanding of AngularJS: EggHead. If you are starting with AngularJS you must go trough these videos, and, if you are already familiar with AngularJS you should also take a look at them, you might find something interesting you didn’t know.

As the time went on and my code was evolving my brain slowly started changing my jQuery/Backbone-ish mindset into a more flexible one. During the days the team shared a couple of links that also really helped me to finally make the mindset switch. Now, I can say that AngularJS finally “clicked” on my head.

I am still far from feeling completely comfortable on AngularJS but I am indeed now immersed on its core concepts and I can now think fast on how to solve my problems and my requirements. My next step once I have more time to learn is to dive deeper on the guts of AngularJS and understand clearly its internal flow so I can do better choices on my future coding.

Now on GitHub Pages!

And, after a bit more than a year I decided to shutdown my AWS instance, which BTW I recently upgraded from a Micro to a Mini one.

Why?

I originally decided to move to AWS to have enough flexibility to basically do whatever the hell I wanted with my server leaving behind the classic shared hosting. I was indeed a little more expensive but not comparable with a VPS.

Initially the site was running a WordPress instance but recently I decided to move into OctoPress. Such change also opened a new chance: Move to a completely free environment by using GitHub Pages. After some thinking I finally decided to make the move, and to be honest it didn’t took more than 30 mins.

How?

The hardest part so far was to change my DNS settings and I mean “hardest” cause it was on my registrar page and not on my command line. Another task I had to do and maybe (just because I have still some level of ignorance of how OctoPress internals work) was to clone a brand new install of OctoPress, set it up as a GitHub blog and then move my files over it. Everything else was just straight commits and pushes to GitHub.

And then?

The only remaining task was to setup the job I created to repost my old posts which was initially running on a set of cron jobs. Since this was so far the only reason so far to have shell access on the server so I could setup my cron jobs my decision was to instead use AppFog’s cloud service and do some updates to my reposter to support running with its own “cron -like” job. The change was in fact simple as well, I just had to modify the original code replacing my option to run the process every X seconds with a node module called “cron” and then just detect if there is (or not) a cron string to use. Some extra things I had to do was to include a couple of extra files to shim CoffeeScript command line for AppFog and create a simple “status” server to verify the app is actually running and it has the right parameters. If you want to check out the changes you can do so on its GitHub repo.

Reposting Old Posts - Node.js, CoffeeScript

Since the blog is now statically generated with Octopress, there is nothing dynamic on it at the server level. I was using WordPress with some plugins, most of them just for render and presentation functionality BUT there was 1 plugin I was starting to miss: Tweet Old Post. The idea behind Tweet Old Post is to allow you to share automatically your old posts on Twitter allowing you to share content you already published some time ago and expose it again to new followers on different times.

Since I am a developer and also I’ve being playing lately with CoffeeScript, I decided to do a simple script that reads my Blog’s Feed, discards posts from a blacklist and publish one of them to my Twitter account. After some coding and the corresponding testing I now have a script that works perfectly and it is also an open source project in case you are interested.

In a nutshell the script:

  • Reads the Blog Feed
  • Translates it into a JavaScript Object and extracts post URLs and Titles
  • Reads a couple of files from the file system (blacklist and last tweeted post)
  • Finds the next post to tweet
  • Tweets the post with post title and link
  • Stores the tweeted URL on a file for later
  • If instructed, waits N milliseconds and triggers itself again