Category Archives: Uncategorized

Angular $http and 304 Not Modified

Angular has in issue with HTTP status codes: it believes only HTTP responses with a status code between 200 and 299 indicate a successful response. However, a common, successful HTTP response is 304 Not Modified. If $http receives a response with this status, the error closure is called. What’s worse is that there seems to be no way to get to the response data from this closure.

One way I’ve found to get around this problem is with cache busting – a technique normally reserved for ensuring you get the latest CSS file to the browser. Consider the following code.


$http.get('http://www.mydomain.com/my/endpoint')
.then(
    function(response){
        $scope.data = response.data;
    },
    function(error){
        // Here we get a 304 Not Modified but we can't do anything
    }
);

To get around this problem, try adding a timestamp to the endpoint.


$http.get('http://www.mydomain.com/my/endpoint' + '?t=' + (new Date()).getTime())
.then(
    function(response){
        $scope.data = response.data;
    },
    function(error){
        // Handle error
    }
);

Now we are sure to get a 200 OK response assuming the request was successful because the URL will be different for each request.

Handle exceptions with Dingo

Normally, when an uncaught exception is thrown in Laravel, the render method in app/Exceptions/Handler.php is called in. The exception object is passed in and you are able to respond to it in any way you please.

However, Dingo seems to tamper with this functionality causing the render method to never be called. It’s not even called when the exception is caused by a non-API route. To work around this, add the following to the boot method of you app/Providers/AppServiceProvider.php file.


public function boot()
{
    // Handle site-wide exceptions here
    app('Dingo\Api\Exception\Handler')->register(function (\Exception $ex) {
        // Handle Exception here
        // e.g. return view('errors.index');
    )};
}

To test for HTTP exception, such as a 404 error, add this use line to the top.


use Symfony\Component\HttpKernel\Exception\HttpException;

Now you can test for the 404 status code (or any other HTTP status code) like this.


use Symfony\Component\HttpKernel\Exception\HttpException;
public function boot()
{
    // Handle site-wide exceptions here
    app('Dingo\Api\Exception\Handler')->register(function (\Exception $ex) {
        if ($ex instanceof HttpException && $ex->getStatusCode() == 404){
            return view('errors.404-error');
        }else{
            return view('errors.general-error');
        }
        
    )};
}

Python’s assert statement

Python’s assert statement asserts that a value is True. If the value is not True, an AssertionError is raised.

Consider the following code.


assert True
assert False

The first line basically does nothing because the argument to assert is True. The second line will throw an AssertionError.

The assert statement is useful for explaining code. Let’s say I wrote a piece of code to explain how to add numbers in Python.


sum = 2 + 2
assert sum == 4

The assert line asserts that the variable sum must equal 4 – otherwise the code wouldn’t work. Without assert, the above code would have to be written like this.


sum = 2 + 2
# sum now equals 4

Having the assert statement makes it a little more eloquent to write about code.

Appending to and retrieving objects from commonpy entities

This tutorial will get you started subclassing the ‘entities’ class in commonpy to make array-like classes. Checkout version 1.1 to follow along.

First, let’s get some subclasses defined.


from entities import *
class gods(entities):
    pass

class god(entity):
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name

Here, our array-like class is gods since it inherits from entities. The second class, god inherits from entity. Instances of this class will will be elements of the gods. It doesn’t have to inherit from entity but it helps and one operations is impossible unless it does (we’ll see which one below).

Let’s create some gods and append them to the gods collection.


norse_pantheon = gods()
assert norse_pantheon.count == 0

thor = god('Thor')
odin = god('Odin')

norse_pantheon.append(thor)
norse_pantheon.append(odin)
assert norse_pantheon.count == 2

After instantiating our norse_pantheon collection, we can assert that its count property is 0 since we haven’t added any elements yet. Next we create thor and odin objects and append them to the norse_pantheon. Now the count property is 2.

The append method is only one way to add objects to our collection. Let’s clear the collection and try some other ways.


norse_pantheon.clear()
assert norse_pantheon.count == 0
assert norse_pantheon.isempty

norse_pantheon += thor
norse_pantheon += odin
assert norse_pantheon.count == 2

The clear method method empties the collection. Now we can assert that the count proprety is 0 and norse_pantheon.isempty is True.

Next we append thor and oden to the collection again, this time using the += operator.

The append method and the += operator do the same thing here. I prefer += since it reduces the number of characters on the line. Once you get used to it, it’s easier to read.

There is one more method to append object to entities collection which is very useful in some circumstances.


norse_pantheon.clear()
norse_pantheon += thor + odin
assert norse_pantheon.count == 2

Here, thor and odin are added together to make an entities collection which is then append to the norse_pantheon collection. Convenient, but for this to work, thor and odin had to inherit from the entity class.

So far, we’ve added to the collection. Now, let’s explore ways to get the objects out of the collection. Here are three ways to do the same thing.


assert norse_pantheon[0] is thor
assert norse_pantheon[1] is odin

assert norse_pantheon['Thor'] is thor
assert norse_pantheon['Odin'] is odin

assert norse_pantheon.first is thor
assert norse_pantheon.second is odin

The first uses the collection indexer to to get the object out by it’s index number. The first object added to a collection will be indexed at 0, the second will be index at 1 and so on.

The second way is to use the name property as the index. Since we instantiated the god objects so their name properties would be ‘Thor’ and ‘Odin’ (see the constructor), we can obtain them by their name value.

The third way is to use the first and second properties. (There are also third, fourth and fifth properties. At the moment, there is no onehundredandseventyseventh property but I am looking in to a way to do that)

We can also iterate over the collection.


for g in norse_pantheon:
    print(g.name)

Since we added the __str__ method to the god class, we can do this and it will do the same as the above.


print(norse_pantheon)

Appending to and retrieving objects from Epiphany Py entities

This tutorial will get you started subclassing the ‘entities’ class in Epiphany Py to make array-like classes. Checkout version 1.1 to follow along.

First, let’s get some subclasses defined.


from entities import *
class gods(entities):
    pass

class god(entity):
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name

Here, our array-like class is gods since it inherits from entities. The second class, god inherits from entity. Instances of this class will will be elements of the gods. It doesn’t have to inherit from entity but it helps and one operations is impossible unless it does (we’ll see which one below).

Let’s create some gods and append them to the gods collection.


norse_pantheon = gods()
assert norse_pantheon.count == 0

thor = god('Thor')
odin = god('Odin')

norse_pantheon.append(thor)
norse_pantheon.append(odin)
assert norse_pantheon.count == 2

After instantiating our norse_pantheon collection, we can assert that its count property is 0 since we haven’t added any elements yet. Next we create thor and odin objects and append them to the norse_pantheon. Now the count property is 2.

The append method is only one way to add objects to our collection. Let’s clear the collection and try some other ways.


norse_pantheon.clear()
assert norse_pantheon.count == 0
assert norse_pantheon.isempty

norse_pantheon += thor
norse_pantheon += odin
assert norse_pantheon.count == 2

The clear method method empties the collection. Now we can assert that the count proprety is 0 and norse_pantheon.isempty is True.

Next we append thor and oden to the collection again, this time using the += operator.

The append method and the += operator do the same thing here. I prefer += since it reduces the number of characters on the line. Once you get used to it, it’s easier to read.

There is one more method to append object to entities collection which is very useful in some circumstances.


norse_pantheon.clear()
norse_pantheon += thor + odin
assert norse_pantheon.count == 2

Here, thor and odin are added together to make an entities collection which is then append to the norse_pantheon collection. Convenient, but for this to work, thor and odin had to inherit from the entity class.

So far, we’ve added to the collection. Now, let’s explore ways to get the objects out of the collection. Here are three ways to do the same thing.


assert norse_pantheon[0] is thor
assert norse_pantheon[1] is odin

assert norse_pantheon['Thor'] is thor
assert norse_pantheon['Odin'] is odin

assert norse_pantheon.first is thor
assert norse_pantheon.second is odin

The first uses the collection indexer to to get the object out by it’s index number. The first object added to a collection will be indexed at 0, the second will be index at 1 and so on.

The second way is to use the name property as the index. Since we instantiated the god objects so their name properties would be ‘Thor’ and ‘Odin’ (see the constructor), we can obtain them by their name value.

The third way is to use the first and second properties. (There are also third, fourth and fifth properties. At the moment, there is no onehundredandseventyseventh property but I am looking in to a way to do that)

We can also iterate over the collection.


for g in norse_pantheon:
    print(g.name)

Since we added the __str__ method to the god class, we can do this and it will do the same as the above.


print(norse_pantheon)

Committing select parts of a file in Git

Have you ever made changes to a file and wanted to commit only some of those changes. Perhaps, along with with your modifications, you’ve also added a lot of instrumentation code to a source file which really shouldn’t be part of the commit. Or maybe you’ve worked on two features in one source file, each of which deserving of their own commit, but you forgot to commit the first feature, so now it appears you have to put the two features in one commit.

Well it turns out Git has a solution to this problem and it’s quite easy to learn how to use it. It’s also very much worth your while to learn it. Plus it helps to explain why Git has an index, unlike most other VCS’s.

So lets say you have a file called helloworld.c which has some changes you would like to commit and some you would rather not. Add it to the index by using the familiar git add command, but this time pas in the --patch option (or -p for short).


git add --patch helloworld.c

Git will then present you with “hunks” of helloworld.c and prompt you to indicate whether or not you want the hunk to be staged. Use y to indicate that you want to stage the hunk, and n to indicate you don’t want to stage the hunk.

Here is a complete list of the options:

  • y stage this hunk for the next commit
  • n do not stage this hunk for the next commit
  • q quit; do not stage this hunk or any of the remaining hunks
  • a stage this hunk and all later hunks in the file
  • d do not stage this hunk or any of the later hunks in the file
  • g select a hunk to go to
  • / search for a hunk matching the given regex
  • j leave this hunk undecided, see next undecided hunk
  • J leave this hunk undecided, see next hunk
  • k leave this hunk undecided, see previous undecided hunk
  • K leave this hunk undecided, see previous hunk
  • s split the current hunk into smaller hunks
  • e manually edit the current hunk
  • ? print hunk help

Now you can check what has been staged by diffing the index:


git diff --cached

If you noticed that you’ve staged a change that you don’t want, you can reverse the operation with this command:


git reset HEAD -p

This will do exactly what git add -p, except in reverse.

Once you have everything staged the way you want it, you can commit you changes like normal


git commit

Rubber Duck Debugging

duck
Today I helped a colleague solve an issue she was having simply by listening. By giving her an opportunity to discuss the topic with me, she was able to work out the solution herself. Before I had even fully understood the problem, she thanked me for the help.

This technique of problem solving even has a name: “Rubber Duck Debugging“. The term comes from a story in the book The Pragmatic Programmer.

The idea is to obtain a rubber ducky, keep it at your desk, and explain your code
to it whenever you are stuck on a problem – though you can use a human in place of the duck, if you prefer. The human doesn’t need to programmer. The technique is based on the idea that teaching a subject forces an evaluation from a different perspective allowing for a deeper insight into the problem.

Epiphany Py released

I’ve released version 1.0 of Epiphany Py today. Epiphany Py is a collection of libraries that would prove useful in any Python project. Currently it contains a base-class similar to the .NET CollectionBase class. You can use it to make your Python objects behave like super powerful arrays. It also comes with a useful unit testing framework called Tester.

I’ve enjoyed using these base classes in my other projects and have achieved a high degree of reusability and terseness from them. In future posts, I will provide demonstrations on how to use them.