Sunday, December 18, 2011

Majority Voting

I saw this one over at Programming Praxis. It's pretty simple with ruby, but there's one slightly interesting piece in there that might come in handy sometime. Here's the code ...


def majority(l)
h = Hash.new(0)
l.each { |v| h[v] += 1 }
max = h.max {|a,b| a[1] <=> b[1]}
max[1] >= l.length / 2.0 ? "#{max[0]} won with #{max[1]} out of #{l.length} total votes" : "No winner"
end

v1 = %w[A A A C C B B C C C B C C]
v2 = %w[A B C A B C A]

puts "v1 = #{majority(v1)}"
puts "v2 = #{majority(v2)}"


OK, so we create a Hash where the value in the key/value pair is initialized to 0 and we add one each time time we see a vote. Here's the cool part, we use the max function from Enumerable knowing that max itself uses each which will give us the key/value pair as a two element array. So, we set the function to compare the second element, the value, of the pair. The max that gets returned will also be a two element array and we use that to calculate whether there's a winner or not.

These types of problems are great for sharpening your programming skills in general and your ruby skills in particular. They're exactly the types of questions that end up on programming interview tests.

Let me know if you have questions or comments.

Monday, November 14, 2011

Centroids

Here's another one from my clustering code, slightly modified for explanatory purposes. This post was spurred by a conversation with a couple of friends when we were talking about programming, who said that programming languages mostly had the same things (i.e. everything old is new again). While I'm not completely in opposition to that, I think that some of the newer languages (read Ruby) do have a lot to offer when it comes to compactness.

Here the problem is to find the centroid of a number of points. Basically, we want the averages of all the first values of the points, the second values of the points, etc. Let's show an example ...

If we have [[x0, y0, z0], [x1, y1, z1], ... [xn, yn, zn]] as our points then the centroid would be the point given by [sum(x's) / n, sum(y's)/n, sum(z's) / n] (and here I'm too lazy to figure out how to create the capital Sigma for sum). Think about how you might solve this in your favorite programming language. In C/C++ anyway, you'd need to know in advance how many points and how many dimensions (the example above uses three, but it could be more or less). In Java, you don't need that, but I don't think you could do something like this ...



def centroid(x)
x[0].zip(*x[1..x.length-1]).map { |v| v.inject(:+) / v.length.to_f }
end


OK, so what's going on here? First up we're going to take the first element of the array (above the [x0, y0, z0]) and zip it with the rest of the array with *x[1..x.length-1]. This should give us, once again from the example above [[x0, x1, ...xn], [y0, y1, ... yn], [z0, z1 ... zn]]. So basically, a new array with all the x's gathered together, the y's, etc. Now comes map. Here, we'll take each element, which is itself an array and then use inject to run through each of the items, say [x0, x1, ... xn] and sum them together. Finally, we'll divide by the length of the element to get an average. If it's hard to see this, break it into pieces and then run it through using irb. It should be a bit easier to see there.

So, what's the point here. Well, essentially you could this in any programming language or in fact any Turing machine, but the language itself can make it easier freeing you to do other things or harder.

Let me know if you have any questions or comments.

Friday, November 11, 2011

Monty Hall Problem

A friend of mine got asked this question in an interview yesterday and I thought it'd make an interesting programming problem. It goes something like this ... Suppose you're on a game show and are offered the choice of one of three doors. Behind one of the doors is a car and behind the other two are goats. Let's say you choose door number three (see Jimmy Buffet song). At this point Monty Hall shows you that behind door number one is a goat and offers to let you switch to door number two. The question is, should you do it? The easy (and incorrect answer) is that it doesn't matter. The correct answer is that, yes you should. Why? I'll let you look it up or you can just run the following program ...


possible_doors = [:goat, :goat, :car].permutation.to_a
bad_choice = 0
tries = 100000
1.upto tries do |mc|
test_doors = possible_doors[Random.rand(possible_doors.length)]
bad_choice += 1 if test_doors[Random.rand(test_doors.length)] == :car
end
puts "bad_choice percent = #{bad_choice.to_f / tries.to_f * 100} good_choice percent = #{100.0 - (bad_choice.to_f / tries.to_f * 100)}"


First up, we get a list of all the possible ways the doors could be arranged and set the number of times that switching would be a bad choice to 0. We'll run this 100000 times in a Monte (not Monty) Carlo loop. In the loop we get one of the possible arrangements of test doors randomly selected and then increment the bad_choice variable if the door we pick contains the car (in other words switching from where we are would be a "bad choice"). When we run this program we see that switching is a bad choice only about 33% of the time and a good choice about 66% of the time (one might guess that these are really 33.333333...% and 66.6666666%). So, then answer in this case is that yes you should switch.

Let me know if you have questions or comments.

Tuesday, November 1, 2011

Ruby Distance Calculation

I was just looking at a clustering algorithm and needed a distance calculation between two points in n-dimensional space. If you remember your high school geometry (or even earlier) the distance between two points in the xy plane is the sqrt((x1 - x2)**2 + (y1-y2)**2). Where the two points are represented by (x1, y1) and (x2, y2). For more dimensions, just add values inside the sqrt as in (z1-z2)**2 for a third dimension. Given that here's a one line function that I came up with


def distance(a, b)
Math.sqrt(a.zip(b).inject(0) { |d, c| d + (c[0] - c[1]) ** 2 })
end


It's a bit tricky, so let's go through it. First we have the Math.sqrt which will just take the square root of whatever is inside it. Next the a.zip(b) will take two arrays (here the input parameters) and take the first values of each of the arrays, create a new array from them and then add that to the output array (see also this post for more information on zip). Same with the second values of the arrays and so on. For example if we have [x1, y1, z1].zip([x2, y2, z2]) this will return [[x1, x2], [y1, y2], [z1, z2]] (hopefully, this looks like something we can use to you). Next we're going to use inject to run through this array with a starting value of 0 (d) and add to it the square of the difference of the two values in the array. Finally as noted before, take the square root and return.

If you have any problems with this, break it up into multiple lines and check the intermediate values. As always, let me know if you have any questions.

Wednesday, October 5, 2011

Heaps

I noted in my last post that I had a technical phone interview. When it was scheduled, the HR person told me that it would include "data structures, algorithms, and architecture". I decided that it wouldn't be a bad idea to review a bit and so I got a copy of Steven Skiena's "The Algorithm Design Manual" and started rummaging through it.

One of the data structures that I came across was a heap (as in heapsort if you've forgotten). A heap is a binary tree data structure that has the property that the parent is smaller for a min-heap or larger for a max-heap than its children. They can be used for priority queues as the minimum or maximum is always at the top of the heap or for sorting assuming that you a) take the top element and then b) recalculate the tree.

The code here follows Skiena's pretty closely excepting he starts his array at 1 and I use the more natural (for me anyway) 0 start. This code also implements only a min-heap, but you should take a bit of time to see if you can figure out how to make it either a min-heap or a max-heap as an initialization parameter. A couple of other things aren't that pretty (extract_min! in particular bugs me), but mostly it's not bad and is straight forward.

So ... here's the code


class Heap
def initialize(a)
@q = []
a.each { |v| insert(v) } if a
end

def parent(n)
n == 0 ? -1 : (n-1) / 2
end

def young_child(n)
(2 * n) + 1
end

def insert(v)
@q << v
bubble_up(@q.size-1)
end

def bubble_up(n)
return if parent(n) == -1 # Root of heap, no parent
if @q[parent(n)] > @q[n]
swap(n, parent(n))
bubble_up(parent(n))
end
end

def swap(n, pn)
@q[n], @q[pn] = @q[pn], @q[n]
end

def min
@q.first
end

def extract_min!
m, @q[0] = @q.first, @q.last
@q.pop
bubble_down(0)
m
end

def bubble_down(n)
c = young_child(n)
min_index = n

0.upto(1) { |i| min_index = c+i if ((c+i) <= @q.size-1) &&(@q[min_index] > @q[c+i]) }

if (min_index != n)
swap(n, min_index)
bubble_down(min_index)
end
end

def sort!
a = []
while v = extract_min! do a << v end
a
end
end

h = Heap.new([12, 14, 6, 10, 8, 27, 1, 4, 9])
puts "extract_min! = #{h.extract_min!}"
puts "extract_min! = #{h.extract_min!}"
puts "extract_min! = #{h.extract_min!}"
puts "extract_min! = #{h.extract_min!}"
puts "min = #{h.min}"
puts "min = #{h.min}"
puts "sort! = #{h.sort!}"


Let me know if you have any questions or comments and if you make improvements, post those too.

Tuesday, October 4, 2011

Phone Interview - 1

I had a phone interview with a great company yesterday and thought I'd share some of the questions, my answers, what I think might have been better answers, and some additional potential questions that might have been asked. First, this was for a manager position and the fact that they're asking technical questions as part of the interview process and as the first interview really impressed me. It shows that they value technical abilities and respect their engineers and developers enough to hire managers that are technically capable as a top priority. We started out, as is usually the case with a bit of small talk about myself, the interviewer, and the company. Nothing too interesting there. I don't recall the actual order of the questions, but I think I got them all.

1. What are horizontal and vertical scaling? Here I knew what horizontal scaling was, but I don't believe I've heard the term vertical scaling. Horizontal scaling means adding more servers to give more processing power while vertical scaling (as I learned when I looked it up) is beefing up the capabilities of an existing server by adding say memory, CPUs, or CPU power. A reasonable follow up to this would have been to discuss the advantages and disadvantages to each.

2. What is object oriented programming? Here I discussed encapsulation and inheritance. I probably should have mentioned polymorphism and message passing. The Wikipedia article is pretty decent and wouldn't be a bad place to do a high level review for this sort of question. I was a little surprised that I didn't get a question on a specific problem. I always would as someone to list out objects and methods for a card game or for a file system (stolen I believe from Steve Yegge if I remember correctly).

3. Given an unsorted list, how would you find a duplicate element. This one was interesting because it had recently appeared on Programming Praxis. I solved it there and used a hash table. The idea is to run through each element of the list and put it on the hash table. If when you go to put it on the hash table, there's something already there, then you've found the duplicate and should return it.

4. In the above question, what's the complexity using Big O notation. Here, since we're running through the list just once, it should be O(n) where n is the size of the list.

5. How does a hash table work or how is it implemented "under the hood"? There are actually a couple of ways of implementing hash tables. I gave the answer of an array of linked lists. You have an array of size n and then use the element that you're going to put on the table to generate a hash value using a hash function. Then use this mod n and add it to the linked list that's at that element.

6. How would you count the number of 1's in an integer? This is pretty classic. Probably the easiest is to use a shift/and technique. You would "and" the value with "1" and if it's non-zero (actually it'll be 1) then add one to the bit count. Shift right and repeat until the value is 0.

7. The final question was about Design Patterns and whether I knew about them and why they're useful. My response was that they're useful in that they give us a way to discuss our designs with a common language. People were using design patterns before the GoF book, but they codified the patterns and gave them names. This makes it much easier to talk about these things.

I think that was all of the questions. We then talked a bit about the position and the company in general. As I said, I was very impressed with them and their "corporate culture".

So ... what sorts of things do you ask or have you been asked in technical phone interviews? Anything interesting or unique? Let us know in the comments.

Tuesday, September 13, 2011

Tetrahedral Numbers

Here's another one from Programming Praxis this one on tetrahedral numbers. I'll leave you to read the description and just jump straight into the ruby solution. The interesting thing here is to use a lambda to create a method that we can pass around. Here's the entire program ...



def linear(target, f)
n = 1
while ( f.call(n) != target)
n = n + 1
end
n
end

def binary(target, f)
low, high = 1, 2
while (f.call(high) < target) do high = high*2 end
mid = (high + low) / 2
while (fmid = f.call(mid)) != target do
fmid < target ? (low, mid = mid, (mid + high) / 2) : (high, mid = mid, (low + mid) / 2)
end
mid
end


tetrahedral = lambda { |n| n * (n + 1) * (n + 2) / 6 }

1.upto(10) { |i| puts tetrahedral.call(i) }

puts linear(169179692512835000, tetrahedral)
puts binary(169179692512835000, tetrahedral)


We start out with two methods linear and binary which are pretty straightforward with the exception that both take a function (in this case f) as a parameter. For linear, we start at 1 and continue calling f until the value of f(n) is the same as target. binary is similar, but here we keep doubling the high value until we're above the target and then we calculate the fmid and use it as a high or low value until we converge.

The tetrahedral function itself is created with a lambda so that we can pass it to the other two methods. The next lines are simply tests. Note how much longer the linear method takes than the binary.

As always, let me know if you have questions or comments.

Saturday, September 3, 2011

Two String Exercise via Programming Praxis

Here's another one (or two rather) from Programming Praxis. Let's take a look at the second one first as it's trivial in ruby. If we're given a string, how do we replace multiple spaces with single spaces. F/or example the string "a b c" would become "a b c". For both of these, we're going to monkey patch the string class. Here's the code ...


class String
def remove_consecutive_spaces
self.gsub(/ +/, " ")
end
end


All we do is do a global substitution of one or more spaces with a single space. This would be quite a bit trickier in C say which is why it ends up in interview questions.

The second (or first) problem is to remove duplicate characters from a string. For example, "aaaabbbb" becomes "ab" and "abcbd" becomes "abcd". This one is a bit trickier but shows another good example of how useful inject() can be. Here's the code ...


class String
def remove_duplicate_characters
self.split(//).inject([]) { |a, c| a << c if !a.include?(c); a }.join
end
end


Going through it from left to right, we have first the split(//) which will turn the array into a string of characters. With that string of characters we do an inject([]) which a) initializes a new empty array (sometimes called the "memo") and then runs through the character array adding a character "c" to the array "a" if it's not already there include?. The ; a returns the current array back to the inject. Finally, we recreate the string by doing a join on the character string array.

Let me know if you have questions or comments.

Thursday, August 11, 2011

Hett's Problem

Sorry for not writing for a while, I've been busy looking for a new job. If you've got one, you can contact me here or at slabounty at large search company that starts with "g".

Anyway ... over at Programming Praxis there's a problem via PrologSite concerning lists. Here's the problem statement ...
1.28 (**) Sorting a list of lists according to length of sublists
a) We suppose that a list (InList) contains elements that are lists themselves. The objective is to sort the elements of InList according to their length. E.g. short lists first, longer lists later, or vice versa.

Example:
?- lsort([[a,b,c],[d,e],[f,g,h],[d,e],[i,j,k,l],[m,n],[o]],L).
L = [[o], [d, e], [d, e], [m, n], [a, b, c], [f, g, h], [i, j, k, l]]

b) Again, we suppose that a list (InList) contains elements that are lists themselves. But this time the objective is to sort the elements of InList according to their length frequency; i.e. in the default, where sorting is done ascendingly, lists with rare lengths are placed first, others with a more frequent length come later.

Example:
?- lfsort([[a,b,c],[d,e],[f,g,h],[d,e],[i,j,k,l],[m,n],[o]],L).
L = [[i, j, k, l], [o], [a, b, c], [f, g, h], [d, e], [d, e], [m, n]]

Note that in the above example, the first two lists in the result L have length 4 and 1, both lengths appear just once. The third and forth list have length 3; there are two list of this length. And finally, the last three lists have length 2. This is the most frequent length.


So how can we solve these two problems in Ruby? The first one is pretty much trivial. Here's the code ...


list = [%w[a, b, c], %w[d], %w[e, f], %w[g, h, i, j, k], %w[l], %w[m, n, o]]
list_sort_length = list.sort {|a, b| a.length <=> b.length}
p list_sort_length


All we're going to do is use the option to sort that takes a block. The block will get two values and instead of the default, we're going to use the values length. Run this and you should see ...
[["l"], ["d"], ["e,", "f"], ["a,", "b,", "c"], ["m,", "n,", "o"], ["g,", "h,", "i,", "j,", "k"]].

The next piece is a bit trickier. Here, we can't do just a one-liner (that I could see anyway). Here's the code ...


hist = Hash.new{|h, k| h[k] = []}
list.each { |l| hist[l.length] << l }
list_sort_hist = []
hist.sort {|a,b| a.length <=> b.length}.each { |key, value| value.each {|e| list_sort_hist << e } }
p list_sort_hist


We start out creating the histogram hash and passing a block so that each element is initialized with an empty array. Then, we work through the list and add each element to an array at the appropriate histogram hash location. Next, create the empty sorted histogram array. Finally, we're going to sort the histogram the same way that we did in the earlier problem (we can do this because they both are Enumerable. We take the result of that and do and each for every item in the histogram. For each of the values (which remember are arrays), we add them to the list_sort_hist array. Finally, we print that out. If it makes it easier to see, split that long line in two. First create a sorted histogram array and then for each value loop through the value and add it to the list_sort_hist array.

Let me know if you have any comments, questions, or jobs.

Saturday, May 28, 2011

Array.zip() and Upside Up Numbers

I've known about the zip method for arrays but have never really found much of a use for it. I was working a problem on Programming Praxis the other day and saw some Python solutions that used it, so I decided to give it a try in my solution. Let's start out with how it works.

In the simplest case, we have an array and we zip it with an array of the same size. Here's what it looks like ...


a = [1, 2, 3]
b = [4, 5, 6]
a.zip(b) => [[1,4], [2,5], [3,6]]


We can see that we end up with an array that's the same size as the original arrays made up of elements of each of the arrays. We can also zip multiple arrays ...


a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]
d = %w[a, b, c]
a.zip(b, c, d) => [[1, 4, 7, "a,"], [2, 5, 8, "b,"], [3, 6, 9, "c"]]


With that here's the documented code for the upside_up program including, at the beginning, the original requirements from Programming Praxis ...


# An “upside up” number is a number that reads the same when it is rotated
# 180°. For instance, 689 and 1961 are upside up numbers.

# Your task is to find the next upside up number greater than 1961, and to
# count the number of upside up numbers less than ten thousand. When you are
# finished, you are welcome to read or run a suggested solution, or to post
# your own solution or discuss the exercise in the comments below.
#
# Create an array of pairs that can match. We should end up with
# UPSIDE_DICT = [[0, 0], [1, 1], [6, 9], [8, 8], [9, 6]]
UPSIDE_DICT = %w[0 1 6 8 9].zip(%w[0 1 9 8 6])

# Open the Integer class and add the upside_up? method that returns true/false
# based on whether the integer is an upside number or not.
# Let's take this a piece at a time:
# 1) self.to_s.split(//) will give us an array of characters for the given number
# such as [1, 9, 6, 1]
# 2) zip this array with
# 3) self.to_s.split(//).reverse will give us the array above reversed ...
# [1, 6, 9, 1]
# 4) and zipping the two together should give us something like ...
# [[1, 1], [9, 6], [6, 9], [1, 1]]
# 5) Now, we'll loop through the above zipped array using inject and make sure that every pair
# in it is also in the UPSIDE_DICT array. If all of them are, then we'll return
# true otherwise the inject() will return false.
class Integer
def upside_up?
self.to_s.split(//).zip(self.to_s.split(//).reverse).inject(true) { |r,v| r && UPSIDE_DICT.include?(v) }
end
end

# Find all the upside values up to 10000 and print them.
(1..10000).each do |v|
puts "#{v} is an upside number" if v.upside_up?
end


Be sure to let me know if you have questions or comments.

Wednesday, May 18, 2011

Interviewing

I had a young person come in for an internship interview a couple of days ago and it made me realize that I've never posted anything outside the programming world. I'm going to try to do a few different posts on the subject of interviews and resumes to hopefully help give some perspective to the hiring process from someone who actually hires rather than someone who tries to get you hired (head hunter). Is my perspective better than theirs? No probably not, but it may be a bit different.

With any interview there are going to be both soft questions and hard questions. By this I don't mean easy and hard but personality questions and technical questions. Let's start by looking at some of the soft questions you might get and why they're asked in the first place. The first thing to remember here is that you're going to be part of a group (as an aside, I hate the term "team" unless you're all dressed the same). Because of this, the hiring manager is going to want to know how you're going to fit in with the rest of the group and the soft questions will be used to try to ascertain that.

One question that seems to get asked is "Tell me about yourself". This is where you should discuss your interests related to the job. Since the interviewer is most likely going to ask about job related items later, now is a good time to bring up any outside projects that might relate. Open source projects that you've done or contributed to or a blog that you write (programming/technical related) are things that will get the interviewer's attention. Just about anything technically related is a good thing to bring up.

You're also almost certain to get a question on a group project that you worked on. Here, it won't matter if you're a developer with 20 years experience or a new grad, you'll probably have to talk about working with other people. The question may be as straight forward as "Tell me about a project that you worked on with other people." or it may be more subtle "Tell me about your last project" with the expectation that this involved other people. As you talk about this project, you may get follow on questions such as "Were there any personal issues between people in the group?" or "Was there anyone in the group who didn't pull their weight?". Then these will be followed up with "How did these issues get resolved?". All of these questions are geared towards finding out how well you will fit in in a group situation. And, as a subtext, the interviewer will be looking for your "leadership" capabilities. All of these questions are a chance for you to show that you will work well in a group and not just work well but make the whole group work better. In the example of someone not pulling their weight, stating that you noticed that Fred wasn't doing what was expected, you could tell how you talked with Fred and let him know that you'd noticed his work wasn't as good as it had been and then worked with him to get him back up to speed. In the case of personality issues, discuss how in a meeting where things were getting tense, you played the peacemaker by making sure that both sides got heard and then working through the issues.

There's probably more, but these are the types of questions that I'll usually pursue, these (or similar ones) and then follow ons based on the responses I receive. The thing to remember though is that all of these soft questions are designed for better or worse to figure out if you will fit in the group structure. Try to approach them in this way and you should do fine.

As always, let me know if you have questions or comments.

Wednesday, April 20, 2011

All True

I was working a problem on Programming Praxis yesterday and ended up writing a little piece of code that returned true if every element in a hash was true. It used inject and I thought it would be worth posting a generalized version here.


module Enumerable
def all_true
self.inject(true) { |r, v| r && (yield v) }
end
end


We start by monkey patching the Enumerable module which will make it available for Arrays, Hashes, etc., basically anything that includes Enumerable. Next, we define the method all_true. The only line in the method is an inject which we initialize with true and then give it a block with two parameters, the r(esult) and the v(alue). We then and/&& the r(esult) with whatever the yield of the v(alue) returns.

You can test it with the following code ...


puts "#{[2, 4, 6, 8].all_true { |n| n%2 == 0 }}"
puts "#{[2, 4, 7, 8].all_true { |n| n%2 == 0 }}"

puts "#{{ 2=>2, 4=>4, 6=>6, 8=>8}.all_true { |n| n[0]%2 == 0 && n[1]%2 == 0 }}"
puts "#{{ 2=>2, 4=>4, 7=>7, 8=>8}.all_true { |n| n[0]%2 == 0 && n[1]%2 == 0 }}"


The first two of each set will return true, the second false.

As I've been doing the Programming Praxis problems, I've found myself using inject and its close relative map/collect more and more. I think this is partly because of the types of problems posted there and the influence of the solutions that are generated which tend to be functional programming based. At any rate, having a good understanding of both inject and map/collect will serve you well and simplify many of your day to day programming tasks.

Let me know if you have questions or comments.

Tuesday, March 29, 2011

Nanoc and No Compiling or Routing

Here's a short post on using nanoc with files that you just want copied from the content directory to the output directory unchanged. For these types of files, it's best if you have them in their own subdirectory (say images or css). Let's say we have some images (.jpg, .png, etc.). First just put them in an images directory under content. Then we need to add a couple of rules to our Rules files ...


compile '/images/*/' do
# Leave everything in the images directory as is.
end


and then a bit later on in the routing section ...


route '/images/*/' do
# Make sure that /images/some_image/ is routed to
# /images/some_image.jpg or /images/some_image.png or so
item.identifier.chop + '.' + item[:extension]
end


I didn't do an actual project and put it up on GitHub for this one, but if this isn't clear, then let me know and I can do that too.

Friday, March 25, 2011

Nanoc and Multiple Layout Templates

A while back we took a quick look at nanoc for generating static web sites. I've been using it a bit both experimenting and for a simple web site for an author friend of mine. I'm going to do a few short articles on using it, documenting what I've learned in much the same way I've tried to do with Ramaze.

Let's start with some simple code that uses multiple layout templates. You have this often with web sites where there's a home page that uses a different layout than the rest of the pages of the site. Let's start with creating a new site. We do that the same way we did last time with ...

nanoc create_site multiple_templates

and let's add a couple of pages to go along with them ...

nanoc create_item page1
nanoc create_item page2

We didn't really talk about the Rules in the last post and I'm only going to touch on them now. You should take a few minutes and read a bit about them here. We'll discuss them a bit more as we go through future posts.

Now, we need to modify the Rules file to tell it to use an alternate layout for the content/page[12].html files. I'm not going to show the entire file, just the compile rule for these ...


compile '/page*/' do
filter :erb
layout 'page'
end


What this rule says is that when we "compile" files in our content/ directory, we should first run them through the erb (embedded ruby) and then use the page template in the layouts directory.

Here's the default which will get use by everything else (essentially our main page at content/index.html).


compile '*' do
filter :erb
layout 'default'
end


This along with the code for all of this up on github should be enough to get you started. As always though, let me know if you have questions or comments.

Tuesday, March 1, 2011

Inkscape

This one is going to be short since I'm not a designer. I've been reading "Web Design for Developers" by Brian P. Hogan and he recommends using Illustrator for parts of his book. Since the cost was a bit umm... prohibitive for learning purposes, I started looking around for a suitable alternative. What I found was Inkscape. This is a nice little program for generating SVG (Scalable Vector Graphics) files. You can use it for generating files for say logos or banners on websites. While I won't say it's simple to use (and this probably says more about me than the program), with the tutorials available, you shouldn't have too much problem getting it to work. Additionally, there's a book on it that's reviewed on Slashdot. I haven't read the book yet but do have it on order and if it seems worthwhile, I'll post here about it.

To install ...

sudo apt-get install inkscape

and you should have an inkscape selection Applications/Graphics or at least on Ubuntu.

Once again, I'm not sure how much I'll be able to help, but if you have questions, be sure and let me know.

Friday, January 28, 2011

Nanoc and Static Web Sites

A few days ago we looked at Webby for generating static web sites. I had a couple of issues with it, including the fact that it didn't work with ruby 1.9.2 and it hasn't been updated for a couple of years now. Someone on the Ramaze email list suggested that I should take a look at nanoc too. It seems to have many of the same features as webby, but is actively maintained and runs on ruby 1.9.2. So let's take a look at getting it up, running, and generating a site. First, we'll need to add a few gems ...


gem install nanoc
gem install kramdown
gem install adsf


Here we're installing nanoc itself, kramdown, which is a Markdown converter, and adsf, which is used as a web server for showing the site.

With that out of the way, let's go ahead and create a new site ...

nanoc create_site my_site

This should create a new site in the directory my_site that has a few different files and directories. Go ahead and cd into the directory and then

nanoc compile

which should "compile" the site. In this case, compile will create an output directory where the resulting HTML files will reside. OK, now we can start a web server with

nanoc view

and then point our browser at http://localhost:3000. At this point you should see the default site for nanoc. For viewing, you could also use

nanoc autocompile

which will also compile a file when changes are made to the site automatically. For "real" work, this is probably the option to use.

OK, let's take a look at the content directory. This is where nanoc will keep the files that will get compiled and moved to the output directory. Go ahead and open up content/index.html in your favorite text editor and make a few changes. Go back to the browser, reload, and you should see your changes there. Now, take a look at layout/default.html. If you make a change in there, say adding an h1 tag before the h2 Documentation tag, it will appear in all the pages that are generated.

Finally, we're going to need to add new pages if this is going to be useful. Try this ...

nanoc create_item test

This will create a test.htnml in the content directory and when it gets compiled, you should be able to go to http://localhost:3000/test/ (don't forget the final "/") and see the page. A couple of things to note here. In the output directory, this will be output/test/index.html.

This should be enough to get you started. Definitely check out the nanoc site for more information. I'm going to use this to generate a personal site, so I'll let you know how it goes and what good/bad things I see.

Let me know if you have questions or comments.

Tuesday, January 25, 2011

Ruby and Rational Numbers

Here's a problem over on Programming Praxis that for whatever reason I wasn't having much luck posting there. Their loss, your gain ;-). Here's the code ...


class Fraction

attr_reader :n, :d

def initialize(n, d)
raise "Can't have zero denominator." if d == 0

n, d = -n, -d if d < 0

g = n.gcd(d)
if g == 1
@n = n
@d = d
else
@n = n / g
@d = n / g
end
end

def plus(f)
Fraction.new((@n*f.d)+(@d*f.n), @d*f.d)
end

def minus(f)
Fraction.new((@n*f.d)-(@d*f.n), @d*f.d)
end

def times(f)
Fraction.new(@n*f.n, @d*f.d)
end

def divide(f)
Fraction.new(@n*f.d, @d*f.n)
end

def to_s
"#{@n}/#{@d}"
end
end

f1 = Fraction.new(1, 3)
f2 = Fraction.new(-1, 7)
puts "#{f1} + #{f2} = #{f1.plus(f2)}"
puts "#{f1} + #{f2} = #{f1.minus(f2)}"
puts "#{f1} + #{f2} = #{f1.times(f2)}"
puts "#{f1} + #{f2} = #{f1.divide(f2)}"


Nothing too awfully complex here, but if you have questions, let me know.

Monday, January 24, 2011

Webby and Static Web Sites

I was trying to figure out recently how to build a static site with Ramaze and didn't really come up with anything, but someone pointed me in the direction of Webby that's designed with just this use case in mind. It seems pretty cool, so I thought I'd document how to get it up and running on Ubuntu.

First I tried just doing a gem install, but that didn't work because I'm using ruby 1.9.2 so ...

rvm install 1.8.7

to get the right ruby (assuming you're using rvm to manage this). Then, you'll need to set the correct ruby with

rvm 1.8.7

to add the following gems for ruby 1.8.7


gem install webby
gem install RedCloth


The RedCloth gem is needed for the default, but if you decide to use a different templating system, you don't need to install it.

OK, let's create a web site now.

webby-gen website my_site

There should now be a directory called my_site with a few different directories. Now you can

cd my_site
webby


and this should create a new directory called output with some HTML files and the css for the site. If you modify the file index.txt in the content directory, and then rerun the webby command, you should see the output/index.html change.

Since you've been reading this blog, you probably have a pretty good idea of how templating works, so there really shouldn't be too much here that you haven't seen in general even if you haven't looked at the RedCloth templating. webby also supports a number of other templating systems that you can use by setting a filter in the content file. This is documented in the User Manual.

To be honest, I just started looking at this today, so I'm not sure how much help I'm going to be with questions, but let me know if you have any and I'll give them a shot.