Teaching an 8 year old to code with Ruby

Here’s a very simple Ruby script I put together this evening for my daughter. She’s just started a book called Computer Coding for Kids and the first little Python script in there is a game where you are being chased by a ghost and have to guess which door to open. If the door you open has no ghost behind it, you get to continue to the next room and go again. If there is a ghost, the game ends.

After she got the code working, we discussed how we could use the same idea, but have a different story line to the game. Because it’s Halloween, she thought it would be great to pretend we were trick or treating and have to guess what kind of treat she would get each time she rang on a doorbell.

I put this script together for her to copy. I think it’s a good starting point for kids who are already confident with technology and who have perhaps played with things like scratch before and maybe have some concept of syntax.

guess = nil
trick_or_treat = nil
puts "It's Halloween"
puts "."
puts "."
puts "."
puts "And you're out trick or treating."
3.times { puts "." }
until guess != trick_or_treat do
  puts "You walk toward a house with a pumpkin outside and ring the bell."
  puts "The door creaks open and you shout 'Trick Or Treat?'"
  puts "What type of treat will you get?"
  print "Enter 1 for lollipop, 2 for chocolate bar, 3 for toffee apple: "
  trick_or_treat = 1 + rand(2)
  guess = gets.chomp.to_i
  if guess == trick_or_treat
    puts "Yay! you guessed correctly. That's another sweet in the bag."
  end
end
puts "Bad luck, you you guessed wrong, time to go home."

There’s quite a few concepts in this script that I threw in there to sort of lead my daughter’s learning. She’s done some basic programming in a few visual programming languages and a little Logo. She’s also done some introductions at school where they explained what an algorithm is and they did some very simple logic like comparing two numbers and drawing out some if conditions.

Here are the interesting (at least to us) points of discussion. When I’m doing this sort of teaching, I generally try not to answer for her unless it’s clear that she really has no idea what’s going on. In that case, I’ll usually take a step back and try to explain the concept in a different way and come back to the actual question I’ve posed another time to see if it “clicks”. This usually makes the learning a little more fun. It’s a game of discovery. Though, of course, takes longer than just shoveling information in 🙂

Anyway, on to the questions (note she didn’t necessarily get all of these – one or two I listened to her reasoning and then shelved until another day – especially the points on nil and variable initialisation):

* How many ways were there in the code to print three full stops? Do you think there could be other ways? If you could make up a computer language, how would you make the computer print three full stops?
* What is `nil`? Why is it there? Why are those two lines there setting variables to nil?
* What are variables anyway?
* Given the way the code works, what does `!=` mean? Here I prompted her a bit more – tell me what the code does in your own words…..etc
* What do you think `gets` does? (we ignored `chomp` and `to_i` for today)
* Why are there two equals signs for comparison

Django REST Framework – Could not resolve URL for hyperlinked relationship using view name

django rest framework hyperlinked relationship error

Here’s an error that’s all too easy to stumble on if you are just hacking your way into an API using Django REST Framework

Could not resolve URL for hyperlinked relationship using view name “model-detail”. You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field

Recreating the error

I’ll assume you have, at least, a basic Django site up and running. Perhaps you are a little impatient (like me) and you skim the Django REST Framework’s homepage. You add the following in to settings.py:

REST_FRAMEWORK = {
    # Use hyperlinked styles by default.
    # Only used if the `serializer_class` attribute is not set on a view.
    'DEFAULT_MODEL_SERIALIZER_CLASS':
        'rest_framework.serializers.HyperlinkedModelSerializer',

    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ]
}

And then, somehow, you skip the rest of the tutorial and you end up with something like this:

class Pet(models.Model):
    name = models.CharField(max_length=250)
    date_of_birth = models.DateTimeField()

    def __unicode__(self):
        return self.name

## views.py:
from .models import Pet
from rest_framework.generics import(
    ListCreateAPIView
)

class PetAPIListCreateView(ListCreateAPIView):
    model = Pet


## urls.py:
from django.conf.urls import patterns, include, url
from .views import PetAPIListCreateView

urlpatterns = patterns('',
    url(r'^api/$', PetAPIListCreateView.as_view()),
)

Make sure you run your migration or sync your db.
Now you should be able to browse your api with the following url:

http://localhost:8000/pets/api

Things are looking good, job done? Not so fast……spend a moment inserting a record into the Pet table – create a fixture, write some raw sql, whatever floats your boat. Refresh your api endpoint and you’ll get a glorious error:

“Could not resolve URL for hyperlinked relationship using view name “pet-detail”. You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field.”

How do you dig yourself out of this one?

Two methods – the first (possibly simplest) is to cut the following out of settings.py (commented out so you don’t skim my post and add it in again):

#REST_FRAMEWORK = {
#    # Use hyperlinked styles by default.
#    # Only used if the `serializer_class` attribute is not set on a view.
#    'DEFAULT_MODEL_SERIALIZER_CLASS':
#        'rest_framework.serializers.HyperlinkedModelSerializer',
#
#    # Use Django's standard `django.contrib.auth` permissions,
#    # or allow read-only access for unauthenticated users.
#    'DEFAULT_PERMISSION_CLASSES': [
#        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
#    ]
#}

In actual fact, removing just the following two lines will fix it for you:

    #'DEFAULT_MODEL_SERIALIZER_CLASS':
        #'rest_framework.serializers.HyperlinkedModelSerializer',

The second is to create a serializers.py class like so:

from rest_framework import serializers
from .models import Pet

class PetSerializer(serializers.ModelSerializer):
    class Meta:
        model=Pet
        fields =('id','name','date_of_birth')

and update your views.py as follows:

from .models import Pet
from .serializers import PetSerializer

from rest_framework.generics import(
    ListCreateAPIView
)

class PetAPIListCreateView(ListCreateAPIView):
    queryset = Pet.objects.all()
    serializer_class = PetSerializer

and you will be back in the land of the living.

Why does this happen?

Well, the key lies in the Default Model Serializer Class – when it is set to HyperlinkedModelSerializer, the rest framework needs a serializer to work with.

Kvetch

The error message here is really, really unhelpful for a anyone not familiar with the Django Rest Framework.

Could not resolve URL for hyperlinked relationship using view name “pet-detail”

made me start questioning my sanity – I had neither a detail suffix view defined, nor any sort of relationship with another model – both things I thought would be obvious causes of the error.

The added annoyance of the bug on rearing its head when data is populated also irked me somewhat because as part of my bug exploration, I created a new stripped down project (as above) to test the damn thing out. I didn’t include any fixtures in my test project, so initially, it looked like it worked and spent a hunk of time back in my original application looking for bugs in “my” code rather than default settings of the REST framework itself.

Ultimately the lesson is: RTFM? Well yes and no. I do think that projects should have an “at a glance” page, and I erroneously thought the Django REST Framework’s homepage would be it – you know “whack this in your app and you’ll have a basic json response going” type of thing. Of course this is a case where I should have read just a little bit more to save myself a headache.

Aah well, live and learn.

An ASP.NET MVC3 implementation of the cancerous Node.js Fibonacci code

I like to tinker with Node.js. Ted Dziuba doesn’t anymore. He thinks node.js is a cancer.
Obviously, a few people disagree – Joshua Kehn and Brian Beck. Ignoring all issues of relevance or flaimbait…and even ignoring all issues of original intent of the article, I was curious to see how C# under ASP.NET MVC3 fared in this little shootout.

I set up a simple MVC application. One controller. It looks like this:

public class HomeController : Controller
    {
        private int Fib(int? n){
            if (n < 2)
            {
                return 1;
            }
            else
            {
                return Fib(n - 2) + Fib(n - 1);
            }
        }

        public string Index(int? n)
        {
            if (string.IsNullOrEmpty(n.ToString()))
            {
                n = 2;
            }
            return Fib(n).ToString();
        }
    }

I ran it on an instance of IIS6.

$ time curl http://localhost/?n=40
default
real    0m0.343s
user    0m0.015s
sys     0m0.015s

Not too bad really. Haskell, however, is super duper fast – as Mathias Biilmann shows.

There’s a little fun for a Tuesday morning.

Principles not techniques

I like to think of coding in terms of principles vs techniques. I’ve met tons of good coders with lots of technique. Good technique. Rote technique. I’ve met very few coders who have good principles. A principle will let you look at anything code related…..and understand it….and if need be troubleshoot it.
Continue reading Principles not techniques