Monthly Archives: October 2016

Fast development in Pantheon

Developing on Pantheon can be slow

Pantheon provides a convenient environment for developing and hosting WordPress and Drupal sites. For each Pantheon site, you are provided with a development, test and live (production) environment. The development environment offers a convenient method for testing code changes.

pantheon

However, on first glance, deploying code changes to the development environment may seem terribly inconvenient. So much so, I imagine most developers set up a local development environment for developing on. Of course, this relegates Pantheon’s development environment to being a mere gateway for getting your code into the test and live environments.

The reason developing in Pantheon environment is inconvenient is because it uses SFTP and Git as the means to upload your code modifications to the development environment. That means, every time you make code modifications which you would like to test, you must save them in your IDE locally, then use an SFTP or Git client to upload your (likely small) changes to the development environment. Using Git for this seems out of the question, since it would mean a commit for each minor modification you make during development, but a conventional SFTP client would be to slow because every time you save your changes, you would have to switch to your SFTP client, select and upload the changed files, wait for the transmission to complete, then test the changes.

Luckily, there is a faster way.

SSHFS allows you to mount an SFTP site just like you would mount any other drive. You can install it using the following.


sudo apt-get install sshfs

Instruction for installing on Mac and Windows can be found at here.

Mounting

Get you SFTP connection information by going to your development site’s Pantheon Dashboard and click on the Connection Info button.

Create a directory for the mount.


mkdir ~/mnt/dev-jesse-hogan.com

Now mount the SFTP site,


sshfs <user-name-from-dashboard>@<host-name-from-dashboard>: ~/mnt/dev-jesse-hogan.com -p 

sshfs will request the SFTP password which is also obtainable from the Pantheon Dashboard.

If all goes well, you should be able to enter that mount directory and begin editing your source files.


$ sshfs <username>@<hostname>: ~/mnt/jesse-hogan.com/ -p 2222 
<username>@<hostname>'s password:
$ cd ~/mnt/jesse-hogan.com/
$ ls
bin  cache  certs  chef.stamp  code  files  fusedav.conf  htpasswd  includes  logs  metadata.json  mime.types  nginx.conf  php  php-fpm.conf  php.ini  run  stunnel  tmp
$ cd code
$ ls
index.php    readme.html  wp-activate.php  wp-blog-header.php    wp-config.php         wp-content   wp-includes        wp-load.php   wp-mail.php      wp-signup.php     xmlrpc.php
license.txt  README.md    wp-admin         wp-comments-post.php  wp-config-sample.php  wp-cron.php  wp-links-opml.php  wp-login.php  wp-settings.php  wp-trackback.php

As you can see above, when you first enter the mount, there are no WordPress file presented – only config files, logs for the web server’s environment. You must go into the code/ directory to view the WordPress files (not sure about Drupal). From here, you can edit your WordPress themes and plugins as if you were on the development site itself.

How to paste in Vim from the outside

When using Vim in a dummy terminal, pasting text into Vim can be result in indentations which get progressively longer as the screen fills up. This vexed me for quite some time until I discovered that there is a simple fix for it. When you want to paste into Vim, just type following into Vim’s command-line.


set paste

Now pasting will work as expected.

When you’re done pasting, be sure to turn pasting off by issuing the following command. Otherwise, you’ll notice strange behavior when editing – such as autoindent not working.


set nopaste

Submitting a form using XHR and jQuery

jQuery’s serialize() method offers a convenient way to turn an HTML form’s data into a text string in standard URL-encoded notation. Consider the following code


$('form').on('submit', function(e) {
    $.ajax({
        type: 'POST',
        url:  '/my/endpoint',
        data: $('form').serialize(),
        dataType: 'json',
        success: function(data){
            // Success Code
        },
        error: function(jqXHR, strStatus, strErrorThrown){
            // Error Code
        }
    });
});

This serializes the form data in $(‘form’) and sends it to /my/endpoint.

Note that the JSON will contain keys for all the input elements regardless of whether or not they contain data except for inputs of type “radio” or “checkbox”. They must be clicked, then their key and value will be present in the JSON.

The following PHP code will take the serialized form data and convert it into a standard PHP array.


$qry = file_get_contents("php://input");
parse_str($qry, $qry_array);

$qry_array will contain the form’s data.

Pretty printing JSON in Vim

Command Line

First, your going to want to get a good command line tool to pretty print JSON. Unfortunately, you can’t just do this.


apt-get install ppjson

However, to create `ppjson`, you can just do the following.


sudo sh -c 'echo python -mjson.tool  > /usr/local/bin/ppjson'
sudo chmod 755 /usr/local/bin/ppjson

Now you have a JSON pretty printer called `ppjson`. Just pipe some JSON into it and watch it go to work.


jhogan@abe:$ echo '{"b":2, "a":1}' | ppjson
{
    "a": 1,
    "b": 2
}

Doing it in Vim

Vim has a very nice feature that lets you pipe text from a Vim buffer into a filter (i.e., command). Lets say your Vim buffer is filled with unformatted JSON text – but nothing more. Just issue the following command-line in Vim’s command mode.

%!ppjson

The buffer will now be filled with nicely formatted JSON.

On the other hand, if only a portion of the Vim buffer contains JSON, use CTRL-V to select the JSON, then, while still in normal mode, type !ppjson. In Vim’s command line, you will see:


:'<,'>!json

Hit ENTER and the unformatted JSON will be replaced by formatted JSON.

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 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)

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)