Something-driven development

Software development thoughts around Ubuntu, Python, Golang and other tools

Connecting android fragment events

leave a comment »

Android UI Fragments look like a great way to build re-usable elements within an app, but they don’t work exactly as expected out of the box (well, exactly is I expected – but that could be a lack of experience with android):

After defining an onClick event on a button within my fragment:

  <Button android:id="@+id/add_goal_button"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/button_create"
      android:onClick="addGoal" />

I’d expected this event to be routed directly to my fragment class without the containing Activity class needing to know about it – but instead, the addGoal() method is expected on the containing Activity instead.

To connect the fragment event directly to a click handler on the fragment class (so the view doesn’t need to be handling the fragment events, you can do the following instead (thanks Brill Pappin):

public class NewGoalFragment extends Fragment {
	
	...
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			                 Bundle savedInstanceState) {
		final View fragmentView = inflater.inflate(R.layout.fragment_new_goal,
							   container, false);
		...
		Button addGoalButton = (Button) fragmentView.findViewById(R.id.add_goal_button);
		addGoalButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(final View v) {
				// Pass the fragmentView through to the handler
				// so that findViewById can be used to get a handle on
				// the fragments own views.
				addGoal(fragmentView);
			}
		});
		return fragmentView;
	}
	
    public void addGoal(View view) {    	
    	EditText newGoal = (EditText) view.findViewById(R.id.new_goal);
	...
    }

Written by Michael

January 1, 2013 at 6:21 pm

Posted in android

A tour of Go – the web crawler exercise

with 5 comments

The last exercise in the Go Tour – parallelizing a web crawler – turned out to be quite a bit more interesting than I’d expected. If anyone has suggested improvements from which I can learn a bit more, or their own solutions posted, let me know – my exercise solution is on github. I’ve tried to stick to the tour content (ie. only using channels rather than the sync package for accessing shared data).

Spoiler Alert: If you are learning Golang and haven’t yet worked through the Go-Tour, go and do so now. If you get stuck, keep struggling, take a break, try again in a few days etc., before looking at other peoples’ solutions.

The solution I ended up with has a Crawl() function very similar to the original, just with two extra function parameters:

func Crawl(url string, depth int, fetcher Fetcher,
	startCrawl func(string) bool, crawlComplete chan string) {

	if depth <= 0 {
		crawlComplete <- url
 		return
	}

	body, urls, err := fetcher.Fetch(url)
	if err != nil {
		fmt.Println(err)
		crawlComplete <- url
 		return
	}

	fmt.Printf("found: %s %q\n", url, body)
	for _, u := range urls {
		if startCrawl(u) {
			go Crawl(u, depth-1, fetcher, startCrawl, crawlComplete)
		}
	}
	crawlComplete <- url
}

The two parameters are:

  • startCrawl func(url string) bool – used as a check before spawning a new ‘go Crawl(url)’ to ensure that we don’t crawl the same url twice.
  • crawlComplete chan string – used to signal that the Crawl function has fetched the page and finished spawning any child go-routines.

These two resources are created and passed in to the initial Crawl() call in the main() function:

func main() {
	startCrawl := make(chan StartCrawlData)
	crawlComplete := make(chan string)
	quitNow := make(chan bool)
	go processCrawls(startCrawl, crawlComplete, quitNow)

	// Returns whether a crawl should be started for a given
	// URL.
	startCrawlFn := func(url string) bool {
		resultChan := make(chan bool)
		startCrawl <- StartCrawlData{url, resultChan}
		return <-resultChan
	}

	Crawl("http://golang.org/", 4, fetcher, startCrawlFn,
		crawlComplete)

	<-quitNow
}

Access to the shared state of which urls have been crawled and when all Crawls() have finished etc., is managed via those channels in the processCrawls() go-routine, so that the main() can simply call the first Crawl() and then wait to quit. I want to check how cheap the temporary creation of a channel is (for the return value of the startCrawlFn above) – I think I saw this method on an earlier GoLang tutorial example, but otherwise I’m happy with the solution :-).

Other solutions to learn from:

Written by Michael

November 14, 2012 at 12:32 pm

Posted in golang

Kanban for kids

with 8 comments

Facing the arrival of another child, I set out a few months ago to experiment with ways to help each other get things done together as a family without becoming a task-master of a father. A very simplified Kanban board seemed like a good fit for our kitchen wall, as it visualises what needs doing or other fun things that are planned, helps us to help each other when needed, and enables the kids to take part in the planning and organising of the day.

The photo of our board above is what we’ve ended up with after a few months. It is really a habit tracker – with most of the items on the board being things that we do daily, every few days, weekly or fortnightly. Some points that we’ve found helpful:

  • Items specific to the kids are colour coded (ie. we have a “Put clothes away” item for each child in their colour).
  • We have some incentives – each item has a number of associated “service points” [1]. For eg. 5 for putting away clothes, 15 for taking the dog out for a walk etc. (agreed with the kids and adjusted on feedback).
  • We have incentives to have fun doing items together – if you complete an item together with someone else, you get 50% extra service points, simply to encourage having fun doing things together (we put a magnet on the item to signify this).
  • We very rarely tell the kids to do something – in extreme circumstances I’ve told my daughter I need her to take the dog out now as I can’t do it myself, but it’s something we generally avoid, in fact…
  • The kids generally choose what item they want to do next and when they want to do it (ie. “You’d like to help daddy set the table for lunch? Shall we do it now or after playing Lego for a while?”).
  • Each item has a drawing and is laminated with a small magnet, so that we can stack certain items together (for eg, we have a stack of cards related to the dog which are done in order each day – dog breakfast, walk 7am-ish, Walk 11am-ish, etc).
  • We start each day by pulling things that we want to do into the backlog (in addition to the daily stuff). Some items are weekly, which we store in a stack for each day on the top-left. Other items are ad-hoc which we pull in from the mess on the bottom left.
  • We limit the number of cards in the TODO and Doing lanes to 4, to help us help each flow (or review whether we really want to do something).
  • We don’t put normal stuff like playing lego or dressups there – the kids can play whenever they want without feeling they need to have an item on the board 😛

So far it’s been a great help, but as always, a continual learning process. Each child is motivated by different things, and yet the end goal is that we’d all enjoy helping each other without extrinsic motivation. Interestingly, one of the most freeing things has been for the kids (and my wife) to get used to the fact that it’s OK to say, no, I don’t feel like doing that today, I’m just going to move the card over to Thursday for the moment. That is, the board is something we control – a helpful way to organise and communicate – it does not tell us what we have to do.

[1] Service points – The kids can use the service points at the end of the day in ways such as staying up a bit later (1minute per point, within reason), or going out on their own with mum or dad for an ice-cream desert (50 points). We haven’t yet found a good solution for left over points, and are currently converting to Euro-cents as pocket money at the end of the week which works well in terms of value, but I don’t like the direct connection of being paid money to do stuff around the house. Another option I’m trying at the moment is using saved service points as bargaining power for larger items that the kids need (like a new school bag). I’d be glad to hear of other ideas.

Written by Michael

October 3, 2012 at 11:08 am

Posted in Uncategorized

A DerbyJS version of the TodoMVC project

with 2 comments

I’ve spent a few evenings this week implementing a derbyjs version of the Todo spec for the TodoMVC project [1] – and it was a great way to learn more about the end-to-end framework, and appreciate how neat the model-view bindings really are. Here’s a 2 minute demo showing the normal TodoMVC functionality as well as the collaborative editing which Derby brings out of the box:

 

It’s amazing how simple Derby’s model-view bindings enable the code to be. It’s really just two files containing the functionality:

The other files are just setup (define which queries are allowed, define the express server, and some custom style on top of the base.css from TodoMVC). Well done Nate and Brian, and the DerbyJS community (which seems to be growing quite a bit over the last few weeks)!

[1] I’ve still got a few things todo before I can submit a pull-request to get this added to TodoMVC.

Written by Michael

August 9, 2012 at 9:28 am

Posted in javascript

Tagged with ,

6 things I’m loving about derbyjs

with one comment

Over the last week or so I’ve spent a few hours learning a bit about DerbyJS – an all-in-one app framework for developing collaborative apps for the web [1]. You can read more about DerbyJS itself at derbyjs.com, but here are six highlights that I’m excited about (text version below the video):

 

1. The browser reflects dev changes immediately. While developing, derbyjs automatically reflects any changes you make to styles, templates (and scripts?) as soon as you save. No need to switch windows and refresh, instead they’re pushed out to your browser(s).

2. Separation of templates (views) and controllers. Derbyjs provides a model-view-controller framework that we’ve come to expect, with Handlebars-like templates and trivial binding to any event handlers defined in your controller. Derby also provides standard conventions for file locations and bundles your files for you.

3. Model data is bound to the view – derbyjs automatically updates other parts of your templates that refer to any data which the user changes, but that’s not all…

4. Model data is synced real-time (as you type/edit) – updating the data you are changing in all browsers viewing the same page. The data just synchronises (and resolves conflicts) without me caring how. (OK, well I really do care how, but I don’t *need* to care).

5. The same code runs on both the (node) server and the browser. The code that renders a page after a server request (great for initial page load and search indexing) is one and the same code that renders pages in the browser without (necessarily) hitting the server.

6. My app works offline out of the box. That’s right – as per the demo – any changes made while offline are automatically synced back to the server and pushed out to other clients as soon as a connection is re-established.

It’s still early days for DerbyJS, but it looks very promising – opening up the doors to loads of people with great ideas for collaborative apps who don’t have the time to implement their own socket.io real-time communication or conflict resolution. Hats off to the DerbyJS team and community!

[1] After doing similar experiments in other JS frameworks (see here and here), and being faced with the work of implementing all the server-sync, sockets, authentication etc. myself, I went looking and found both meteorjs and derbyjs. You can read a good comparison of meteorjs and derbyjs by the derbyjs folk (Note: both are now MIT licensed).

Written by Michael

July 27, 2012 at 5:59 pm

Posted in javascript

My Ubuntu HTML5 App development environment

leave a comment »

After experimenting recently with the YUI 3.5.0 Application framework, I wanted to take a bit of time to see what other HTML5 app development setups were offering while answering the question: “How can I make HTML5 app development more fun on Ubuntu” – and perhaps bring some of this back to my YUI 3.5 setup.

I’m quite happy with the initial result – here’s a brief (3 minute) video overview highlighting:

  • Tests running not only in a browser but also automatically on file save without even a headless browser (with pretty Ubuntu notifications)
  • Modular code in separate files (including html templates, via requirejs and its plugins)

 

 

Things that I really like about this setup:

  • requirejs – YUI-like module definitions and dependency specification makes for very clear code. It’s an implementation of the Asynchronous Module Definition “standard” which allows me to require dependencies on my own terms, like this:
    require(["underscore", "backbone"], function(_, Backbone) {
        // In here the underscore and backbone modules are loaded and
        // assigned to _ and Backbone respectively.
    })

    There’s some indication that YUI may also implement AMD in its loader also. RequireJS also has a built in optimiser to combine and minify all your required JS during your build step. With two plugins for RequireJS I can also use CoffeeScript instead of Javascript, and load my separate HTML templates as resources into my modules (no more stuffing them all into your index.html.

  • mocha tests running on nodejs or in the browser – as shown in the above screencast. Once configured, this made it pretty trivial to add a `make watch` command to my project which runs tests automatically (using nodejs’ V8 engine) when files change, displaying the results using Ubuntu’s built-in notification system. (Mocha already has built in growl support for Mac users, it’d be great to get similar OSD notifications built in too).

The setup wasn’t without its difficulties [1], but the effort was worth it as now I have a fun environment to start building my dream app (we’ve all got one right?) and continue learning. I think it should also be possible for me to go back and re-create this nodejs dev environment using YUI also – which I’m keen to try if someone hasn’t already done something similar – or even possibly without needing nodejs? I think the challenge for YUI will be if and when most other modules can be loaded via AMD why, as an app developer, would I want to commit to one monolithic framework release when I can cleanly pick-n-chose the specific versions of small tightly-focused modules that I need (assuming my tests pass). Or perhaps YUI will join in and begin versioning modules (and module dependencies) rather than the one complete framework so that they were available via any AMD loader – that would rock!

Thanks to James Burke (author of RequireJS) and the brunch team for their help!

[1] For those interested, things that were difficult getting this setup were:

  • Many JS libraries are not yet AMD ready (or yet giving support), which means adding shims to load them correctly (or using the use plugin in some cases). And sometimes this gets complicated (as it did for me with expect.js). I don’t know if AMD will get widespread adoption, who knows? A result of this is that many JS libraries are designed to work within the browser or node only (ie. they assume that either window or module/exports will be available globally).
  • Using the coffeescript plugin is great for looking at the code, but the errors displayed when running tests that result from  coffeescript parse errors are often hard to decipher (although I could probably use an editor plugin to check the code on save and highlight errors).
  • A recent nodejs version isn’t yet available in the ubuntu archives for Precise. It wasn’t difficult, but I had to install Node 0.6.12 to my home directory and put its bin directory on my path before I could get started.

If you want to try it out or look at the code, just make sure NodeJS 0.6.12 is available on your path and do:

tmp$ bzr branch lp:~michael.nelson/open-goal-tracker/backbone-test/
Branched 42 revisions. 
tmp$ cd backbone-test/
backbone-test$ make
[snip]
backbone-test$ make test
...........
✔ 12 tests complete (47ms)

Written by Michael

March 8, 2012 at 12:59 pm

Open goal tracker with jquery-mobile

with 2 comments

I had a few hours recently to try updating my Open Goal Tracker javascript client prototype to use jQuery Mobile for the UI… and wow – it is so nice, as a developer with an idea, not having to think about certain UI issues (such as a touch interface, or just basic widget design). I can see now how ugly my previous play-prototype looked. Here’s a brief demo of the jQueryMobile version (sorry for the mumbling):

 

That’s using jQuery Mobile 1.01 for the UI and YUI 3.5.0PR2 for the MVC client-side framework, although I’m tempted to move over to backbone.js (which is what the YUI application framework is based on, it seems). Backbone.js has beautifully annotated source and a book – Developing backbone applications – which so far seems like very worthwhile reading material.

The prototype can be played with at http://opengoaltracker.org/prototype_fun/

Written by Michael

February 13, 2012 at 2:56 pm

More YUI and html5 fun

with 2 comments

Continuing on my YUI MVC experiment, I got to spend a bit of time last week playing with my prototype for Open Goal Tracker, and was blown away by the simplicity of two new html attributes: x-webkit-speech (just ‘speech’ when standardised) and contenteditable. Here’s a 2min video showing how I might use both of them in practise (in dire need of styling as usual):

 

 

Behind the scenes I’m still loving Yahoo User Interfaces application framework together with the unit-test api, which allow me to create tests like “creating the view should render stats for existing goals”.

Next week I hope to start implementing the server-sync and investigating integration with Ubuntu’s notification system. Once I’ve sorted out the application-cache and build/packaging etc. for both Ubuntu and Android, I want to do a initial dummy release and then start iterating the features that will make Open Goal Tracker actually useful for facilitating social-yet-individual learning, both within and without of classrooms.

You can play with the little open-goal-tracker prototype (I’ve only tried webkit so far) or run the tests yourself.

Written by Michael

November 29, 2011 at 11:16 am

Posted in Uncategorized

A generic juju charm for Django apps

with 4 comments

After experimenting with juju and puppet the other week, I wanted to see if it was possible to create a generic juju charm for deploying any Django apps using Apache+mod_wsgi together with puppet manifests wherever possible. The resulting apache-django-wsgi charm is ready to demo (thanks to lots of support from the #juju team), but still needs a few more configuration options. The charm currently:

  1. Enables the user to specify a branch of a Python package containing the Django app/project for deploy. This python package will be `python setup.py install`’d on the instance, but it also
  2. Enables you to configure extra debian packages to be installed first so that your requirements can be installed in a more reliable/trusted manner, along with the standard required packages (apache2, libapache2-mod-wsgi etc.). Here’s the example charm config used for apps.ubuntu.com,
  3. Creates a django.wsgi and httpd.conf ready to serve your app, automatically collecting all the static content of your installed Django apps to be served separately from the same Apache virtual host,
  4. When it receives a database relation change, it creates some local settings, overriding the database settings of your branch, sync’s and migrates the database (a noop if it’s the second unit) and restarts apache (See the database_settings.pp manifest for more details).

Here’s a quick demo which puts up a postgresql unit and two app servers with these commands:

$ juju deploy --repository ~/charms local:postgresql
$ juju deploy --config ubuntu-app-dir.yaml --repository ~/apache-django-wsgi/ local:apache-django-wsgi
$ juju add-relation postgresql:db apache-django-wsgi
$ juju add-unit apache-django-wsgi

Things that I think need to be improved or I’m uncertain about:

  1. `gem install puppet-module` is included in the install hook (a 3rd way of installing something on the system :/). I wanted to use the vcsrepo puppet module to define bzr resource types and puppet-module-tool seems to be the way to install 3rd-party puppet modules. Using this resource-type enables a simple initial_state.pp manifest. Of course, it’d be great to have ‘necessary’ tools like that in the archive instead.
  2. The initial_state.pp manifest pulls the django app package to /home/ubuntu/django-app-branch and then pip installs it on the system. Requiring the app to be a valid python package seemed sensible (in terms of ensuring it is correctly installed with its requirements satisfied) while still allowing the user to go one step further if they like and provide a debian package instead of a python package in a branch (which I assume we would do ultimately for production deploys?)
  3. Currently it’s just a very simple apache setup. I think ideally the static file serving should be done by a separate unit in the charm (ie. an instance running a stripped down apache2 or lighttpd). Also, I would have liked to have used an ‘official’ or ‘blessed’ puppet apache module to benefit from someone else’s experience, but I couldn’t see one that stood out as such.
  4. Currently the charm assumes that your project contains the configuration info (ie. a settings.py, urls.py etc.), of which the database settings can be simply overridden for deploy. There should be an additional option to specify a configuration branch (and it shouldn’t assume that you’re using django-configglue), as well as other options like django_debug, static_url etc.
  5. The charm should also export an interface (?) that can be used by a load balancer charm.

Written by Michael

November 22, 2011 at 5:59 pm

Posted in django, juju

Experimenting with YUI application framework

with one comment

I’ve been playing around wit h YUI’s new application framework over the past few weeks, basically building on the ToDo list example app, extending it for a basic interface for the Open Goal Tracker project. Here’s a 2 min demo:

I’m loving the MVC separation in the client code, separation of templates, ability to use real links for navigating within the client (which will also work when copy-n-pasted to hit the server) etc.

If anyone is interested, you can play with the code yourself:

$ bzr branch lp:~michael.nelson/open-goal-tracker/html5-client-play
$ cd html5-client-play
$ fab test

which will setup the dev environment and run the django tests… followed by

$ fab runserver

To play with the demo html5 client: http://localhost:8000/static/index.html
To run the javascript unit tests: http://localhost:8000/static/app/tests/test_models.html

or find out more about the purpose of the app with the first 2 mins of this video from a year ago outlining where i hope to go with the application: http://www.youtube.com/watch?v=OT7P-u-86sM (when time permits :)).

Written by Michael

November 11, 2011 at 12:17 pm

Posted in javascript, yui