Letter loungin’

DSC_2187

Yesterday, I put on an event with Claire Medcalf from Glovepuppet, and a few friends, called the letter lounge. As you'd expect from the name, we started it to help people get round to actually writing more letters to distant friends and relatives, and take the time to reflect and generally slow down somewhat, as a way of clawing back some tranquility and respite against the whirl of tweets, emails facebook messages and IM chats that punctuate our lives.

And suffice to say, I'm really happy with how it turned out -turnout was high enough to be encouraging, and low enough to mean Claire and I could take the time to write to people instead of playing host the whole day.

However, without a doubt, the highlight of the day, apart from seeing Claire's entourage waiting outside the hub with a full on toy postbox for us to use, was hearing from one of the visitors, telling me that because of this event, she finally wrote her first physical letter in 15 years - how cool?

Made my day, and pretty much sealed the deal for us to running another Letter Lounge as soon as we have a chance.

If you want to hear more about the letter lounge... yes it's on twitter - @letterlounge, and now we've run one of these events and have an idea of how to do them, we're going to make it much easier to find out about future ones so we start building some momentum with this idea.

But first, sleep...

  • Share/Bookmark
Posted in Journal | Tagged , , , , | Leave a comment

Tea, Arduino and Dynamic Demand

It’s the next HomeCamp tomorrow. And in a spectacular feat of bad calendaring, I’ve managed to organise the Letter Lounge to take place on the day I’ve been looking forward to for the last few months are coming away from the initial HomeCamp, utterly inspired by what I saw there.

So to make up for not being able to attend, the least I can do is finally get round to writing about the Tealight, a fun, Homecampy little project James Gardner and I built one evening in the Hub recently.

We did it partly to learn about the Arduino platform, and partly to explore how to make something as complex as demand response intelligible to people who don’t think about this for a living, and well here it is, in all it’s janky, low budget hackish glory:

This green orb constantly polls the national power grid to see how it’s keeping up with demand from everyone watching The Apprentice, and subsequently whether your next cuppa will be a particularly carbon intensive one.

If there’s spare capacity on the grid, the tealight will glows green, it’s basically saying:

‘Go ahead! Make some tea! Knock yourself out!’

If there isn’t, the colour shifts to red, saying:

“Now’s not the best time for that cuppa, give it a little while.”

The main idea here is that you can glance at the globe from across an office or co-working space, to get an idea about whether making that cup of tea is a good idea right now, without having to think too hard about it.

Think of it as national grid load balancing, using people, and hot beverages.

How we made this

This is thing is almost embarrassingly simple.

On the software side, we’re basically polling the api for caniturniton.com a website which scrapes the national grid for power usage data every minute or so, and depending on if the figure returned is higher or lower than the baseline of 50hz, we call a function to tell the BlinkM to change the colour of it’s LED accordingly.

Here’s the shopping list of hardware we used:

The fact that we could even make this, with me generally not being big on writing in any languages that feel like C, and with James being almost completely new to the platform is a testament to how lego-like the Arduino ecosystem is getting now.

When we take the shade off the lamp, it’s quite a bit easier to see how it all works:

Tealight working without the globe

The orange cable is a ethernet cable, and the grey one is the usb power, running off a spare iPod I had lying around.

The code has largely been a messy cut and paste job spliced from number of sources, but mostly from this thread in the arduino forums, and the string parsing code example is from a post by Jeff Tanner here on the daniweb forums.

This isn’t really big enough to be considered a project on github, so I’m just chucking a gist up for now:

Isn’t this massively oversimplifying and trivialising the whole concept of demand smoothing?

You could argue so, yes.

But placing it in a relatively high traffic co-working space, full of people working in totally unrelated fields is a great opportunity to speak to them about the ideas inspiring this little toy, and get lots of interesting feedback, and see how best to communicate on issues related to climate change and how massively energy intensive our life styles are.

But why tea?

A number of reasons:

  • they provide a recognisable power spike for comparing against national averages, and also for graphing against national load averages too. It makes it easier to see if behaviour is changing.

  • there’s a pattern to making hot beverages at work, but it’s pretty easy to timeshift it, without getting into emotive issues like calling people utter carbon bastards for flying to Spain on holiday.

  • it’s a usefully mundane , which makes explaining why changing behaviour here could work to smooth out demand on the national grid, meaning the oldest, dirtiest power stations don’t need to be powered up just so everyone can have a cup of tea at the same time.

  • because a good pun is its own reword.

This builds on ideas and hacks developed by Nick O'Leary at IBM, Tom Dyson at Torchbox Joe Short from Demand Logic, and presented at the last Homecamp. I really wish I was going, but I have a day of letter writing ahead of me instead for Saturday.

Which after this weekend, will be the subject of another post.

  • Share/Bookmark
Posted in Journal | Tagged , , , , , , | Leave a comment

Happy Ada Day!

I read about Ada Lovelace while at uni, studying the cultural roots of digital media, so I'm really happy to see Suw working to give this woman the recognition she deserves.

She's generally seen as the first person to write about the idea of using computation machines for creative purposes, like creating music, and she was doing this before Charles Babbage had even built his first Difference Engine; she was the prototypical art-code alpha geek of her day.

225px-becky_hoggeMy Ada day pick - Becky Hogge

As I pledged to, I'm going to write about a woman in tech who admire, and at the risk of embarassing her something rotten, I'd have to say Becky Hogge's, ex-executive director of the Open Rights Group us my choice.

I started my internship at ORG round not long after she had just begun in the job; she had some pretty big shoes to fill after Suw, day to day responsibility over an NGO with a ridiculously wide remit, and not much in the way of a budget to accomplish a clutch of heady, heady goals.

And in the two years she was there, she did an amazing job, and she's been one of the professionals my industry who I've often looked to for a sense of perspective about my own working life.

Through shadowing her at the Demos thinktank, over the course of my internship, and even after it had ended, she always impressed me with how eloquently she communicated abstract issues like copyright term extension, digital privacy, e-voting reform and many more to both lay people and experts alike.

She moved on early this year to concentrate on writing, something she does incredibly well, and I'm really looking forward to seeing what she does next.

A lot of my own views about professional integrity and working with technology have come out my time with her, and partly as a result of this came my decision to start a company with a friend working solely on web projects we believe in.

She also shared with me a wonderful line* that I use whenever I'm working on something that isn't immediately lucrative, but feels good, true and plain right:

"Our cause is just, and we must prevail!"

She's my choice for Ada Day because if there's one thing the tech industry would needs more of, it's fiercely intelligent women who can communicate clearly about complex issues, and Becky clearly is one of these rare breeds.

  • She doesn't claim ownership of this line, but a cursory googling of the phrase doesn't bring up the name of the original owner of this utterance.
  • Share/Bookmark
Posted in Journal | Leave a comment

Looking for a green host #2

In my last post I described I gave a primer outlining the differences between using shared hosting, having a full fat dedicated server to run your website on. I also explained why Virtual Private servers represent the best of these two worlds, and how finding a good affordable green host  was much harder than it really needs to be.

In this post, I'm going to outline what I'm looking for in a hosting company - to give an idea of what my priorities are when finding a host, and the reasons for my critieria. In the next post, I should have enough data back to share my final results.

The ideal host I'm looking for would:

1) Be based in the UK, or alternatively, the EU.

There are two main reasons for this:

1) Support -

Having someone speak the same language as you makes life much simpler when you have support questions. Having them exist in the same time zone also helps.

2) Data protection

Personal data is essentially radioactive - fairly harmless in small amounts, but when you collect and store it carelessly, losing track of it is increasingly dangerous, expensive. There is a strong temptation to store data with cheap hosting companies in the US, but in the EU data protection laws are far more stringent, with far more restrictions on what information can be passed on to third parties, so by storing data closer to home, you can argue that you are voluntarily subscribing to a much more rigorous legal framework than if you were choosing to store all your data in a region where privacy laws were weaker.

However, if you are storing your data in the US, you should be aware of the Safe Harbour agreement. You can think of as set of principles designed to emulate the EU data protection laws, which should provide some public statement of intent for the care you take with people's data. The thing is, organisations gain this status by self-certifying as Safe Harbour complaint, with no legal obligation for a third party to audit this status, so you're effectively asked to just take a company's word that they voluntarily take the same care with data as would be required by law over here in the EU. 

2) Source its power responsibly

The best case scenario for our hypothetical data centre is one that sources its power exclusively from renewable sources. By doing business with the company, we're helping grow the market for renewable energy, which desperately needs to happen. Sadly, there are very few companies who source their energy like this, b) there simply isn't much capacity in the UK right now. a) mainly because the idea of buying your power from the most expensive source possible when it's usually the single biggest cost of your company is financially quite a painful decision to make.

In this case, offsets to cancel out the unavoidable leftover emissions are basically unavoidable. Where they are used, offsets that go towards investing in renewable power are more attractive option, because they stop more coal fired power stations being built, so the carbon is saved straight away, compared to than simply planting trees in the hope that over the next 20 or so years, they'll eventually make up for the carbon dioxide that was pumped into the atmosphere today.

3) Uses the power that it does suck off the grid as efficiently as possible.

This isn't such a huge ask for a supplier; and the costs of power are simply so high, and the savings available are so obvious (40-50% savings in power aren't uncommon) that this step is happening by default. The degree that companies are doing so, and their willingness to openly discuss what steps they are taken are good indicators of how seriously they take this, and how well communication flows inside the company.

As a rule, if the company can coherently communicate internally about their own processes so that the customer facing staff can talk about what steps the company is taking on this, then they're likely to be able to provide support effectively too.

4) Use Open Source Software and actively support its use.

In 2009, when most of the web has been built on open standards and runs on open source software, I shouldn't really need to say why open source is generally a Good Thing. But when a hosting company actively invests and uses open source software themselves, they're much more likely to be able to provide meaningful support if something breaks, and have useful expertise on hand to troubleshoot. Finally, the other advantage of open source is that stops lock-in - if you aren't happy with service, you can simply move to another supplier, rather than being stuck using a proprietary product that can't be replicated elsewhere. This tends to mean suppliers compete on price, and customer service or sustainability, which are also Good Things.

Now that I've outlined what I'm looking for in a host, I can explain in the next post who we think is the best fit for these criteria, to spare some other poor soul of 3-4 weeks of research and emails.

  • Share/Bookmark
Posted in Journal | 4 Comments

Looking for a green host.

renewable-energy

For the last two weeks, I’ve been looking for a good reliable, green, well priced hosting company that offers virtual servers in or around the UK, and it’s been largely a fruitless, frustrating endeavor. But in order to really explain why I’m doing this in the first place, it helps to give a summary of what kinds of hosting is available.

A brief primer on web hosting

Up until fairly recently, there were two main kinds of web hosting you could buy to put a website on: shared hosting, or dedicated servers.

Shared Hosting

If you have your own personal website, the chances pretty high that you’re running on shared hosting.

When you bought shared hosting, what you did was effectively rent space on a computer that had loads of user accounts sharing it like, in the same way you might have a few different user accounts on a laptop that multiple people share. It’s a pretty cheap way of having use of a computer, but is has a few drawbacks, namely:

  • You can’t treat it like your computer

    If some arbitrary IT security policy put on a computer by someone else has stopped you doing something you want to on a computer, you’ll know how frustrating this can be. In the days of simple html, this wasn’t so much of a problem; you just put html on a server, and that was about it. When you wanted to update the site, you would pay someone to write new code.

    However, it’s understandable to want to update your own website these days, and this frequently involves putting software on the server itself, like Wordpress or Drupal, which dynamically create html to feed to browsers. It’s common to bump up against limits to stop you using more than your fair share of the server’s processing power, which usually results in your programs being killed off halfway through doing something, or your users’ unable to do more processor intensive things like attach large files.

    Also, if you’re looking to something slightly non-standard, like use a new web framework like Django or Ruby on Rails, these limits will stop you dead in your tracks.

  • Everyone on the server shares the same limited resources.

    Conversely with shared hosting, when some other bright spark decides to something slightly non-standard, like use a new web framework like Django or Ruby on Rails, when they crash their program it can bring down your website too. Not great.

    Finally, if your host crams too many people onto a single server you end up with a ridiculously slow website, because you’re all fighting over the same resources. You’ll often have this on hosting offers than seem ridiculously cheap.

    Fees for shared hosting tend tend to correlate with how many people are being crammed onto each server, how much space is being offered, and what kind of bandwidth the sites use up, starting at less than a pound, and scaling upto around £25 per month. Companies know for bring shared hosting providers are Dreamhost, 1and1.co.uk, http://fasthosts.co.uk

Dedicated Servers

Dedicated, or private servers are servers that are totally dedicated for your use alone.

As you’d expect, they carry none of the problems that sharing have, but they’re usually much more expensive, and in many cases a pretty wasteful way of hosting a site unless you really need one. If you need one of these, you either can afford to pay someone to look after it for you, or you’ve been ripped off, or your website is so successful that there is nothing I could tell you that you don’t already know.

Prices for these start range from around £60, upwards.

The third way - the wonders of the VPS

In the last few years, companies like Slicehost and Linode have made a name form themselves by specialising in offering virtual private servers to customers. In a nutshell, a virtual private server offers you the benefits of control, and predictability of a dedicated server, but at a cost much closer to that of shared hosting.

When you rent a virtual private server, you share a physical server like with shared hosting, but each virtual machine runs in it’s own isolated sandbox, to stop what everyone gets upto on their machines affecting each other. This has a few advantages:

  • Predictability

    That sandbox gives a reassuring degree of reliability, and fair minimum expectation of performance. Someone else being dugg or slasheddotted won’t affect your site.

  • Control

    Because you have control over your environment, running slightly more exotic software like Rails or Django, or using a source control system like Git, is much much simpler. While these can sometimes be done with shared hosting, any long running processes that might run in the background will usually be killed off on shared hosting.

  • Elasticity

    Virtual machines are no longer physical machines, but simply digital containers talking to hardware in an abstract sense, they take on a protean nature, that means they can be copied, resized, backed up and generally fiddled with in ways that you can’t with physical machines. If your site gets popular, you can resize the the server to make it respond to increased demand, and conversely, in a datacentre full of virtual machines, throttling back energy usage when demand drops is also possible.

  • Portability

    The same qualities that make virtual machines elastic, also make them portable, and this has me really interested right now; it helps with testing, as you can have a container on your local machine, but also helps safeguard against being locked into one hosting company if you’re not happy with what they offer and makes it easier to move hosts more easily. This makes it possible to allow website owners to choose hosts based on factors like customer service, or how sustainably they are run, rather than worrying about if they’ll install the right version of Perl for you.

The starting rate virtual machines is around the £15 mark, scaling up depending on how much power you need.

Back to the point - where are the reliable green virtual private servers?

This post should have worked as halfway decent primer for explaining why virtual private servers are so desirable. In the next post, I’ll build on this to share the results of my trying to find a good green virtual hosting company in the UK, as I know I’m not the only one who’s looking around for this.

  • Share/Bookmark
Posted in Journal | Leave a comment

On computer games and pushups

featuredoverviewpushupfu

If you own an iPhone or iPod touch, you're curious about just how creative developers on the AppStore can be, you really should try out PushupFu - it's a great example of successfully applying computer game thinking to transform an existing, somewhat dull, if largely good for you activity, into a great little casual game.

Pushupfu seems to be loosely based on the the One hundred pushups program, helping you get fitter and stronger, by beginning a course of pushups every other day, where you start out with very gentle sets of 3 or 2 pushups, and increase these sets in intensity and duration, working your way up to the finale, where you end up cranking 100 pushups in one go, in an eye bulging, vein popping testosterone soaked display of machismo and sheer masculine potency, that make the Spartans from 300 look like total girls.

It's fair to say, that I'm not there yet.

But, I am enjoying the journey very much, and I think I have a few good ideas why. It's offering me plenty of the following game mechanisms that make doing a fairly mindless exercise much more appealing to the easily bored:

Instant feedback

You can see when you're doing well, straight away here. If you're on bad form, the app reprimand your for cheating, when you don't do a full pushup, or try to do it too fast - every time you do a pushup correctly, the electronic voice from the iphone counts up further - it's a little thing, but the constant feedback makes it much easier to stay motivated. Also, it stops you cheating yourself - when your body starts feeling heavy, it doesn't matter - you still have to keep form or you won't make it to the next milestone.

Tracking progression

Which brings us nicely to the next step - having something track your progress automatically is a godsend - it effectively turns the game into an RPG of sorts, with regular level ups. Having that sense of acheivemen, and grading each stage means that you're less keen on breaking the line, and even if you aren't able to crank out the pushups you need to make the next stage, there's always room for improvement for coming back again. The levelling system is also great for...

Competition

This seems to be one of the biggest selling points, and the thing that turns this from a training aid to a computer game - you can challenge people around the world to pushup battles, and whoever can do more pushups in one session walks away with bragging rights, climbing further up the public leaderboard, visible on GymFu. It's a nice idea, and well executed - displaying everyone's stats publicly puts adds an extra element of outside pressure that works as an excellent motivator!

More training needed

However, there are a few things with the app that do leave me wanting - the progression up the stages seems rather uneven, I've been able to breeze through the first four stages, but there's a massive spike in difficulty on the following stage, making it almost discouragingly hard.

Also, challenging people until recently had a really tight window to answer them with no outside notification. Thankfully this has been largely fixed now, and challenges end up in your email inbox as well now.

Finally, scrapping an accelerometer to your arm to measure pushups can sometimes give strange readings, especially when halfway through a set of pushups it starts to come loose; this ends up giving frustrating false positives. 

Finally, accidentally pressing the Apple home button gets you out of the app without saving any kind of progress - hitting this at the end of a set basically means you have to start from scratch again. Annoying, but not a deal breaker.

One of the nicer things about the App Store is how cheap the little apps are - trying out PushupFu costs about the same as a decent espresso, and I've got far more enjoyment out of PushupFu and most espresso's I've tried.

If you have an iPhone or iPod touch, I really recommend giving it a go.

  • Share/Bookmark
Posted in Journal | 3 Comments

SockMonkeys and um, …things that rhyme with sock monkeys

Some people are naturally talented when it comes to making things with their hands.

Sadly, I'm not one of them. I'm a terrible sketcher, and making actual real things that you can drop on your foot is something that is largely alien to me - I don't usually have the patience to persevere after about 90 seconds, and usually give up straight afterwards. As you'd imagine, is a bit of a barrier when it comes to making stuff.

But something amazing happened this weekend - I actually made something physical, and I now know the joy and pride a maker feels when they craft an entirely new object from simple mundane parts.

Of course, it didn't go totally smoothly to begin with:

My one is the rude looking stripey one

My one is the rude looking stripey one

This was my first attempt at making a sock monkey at the Crafternoon put by Jo Maiden of the Ethical Fashion Forum, a fundraising event where the proceeds went towards a project to set up an ethical fashion production facility in Soko, Kenya, that directly supplies the UK retail trade. 

We turned up at the Hub with a fiver and a pair of socks with us, and in return, we were taught how to make a monkeys from socks, and given more tea and cake than we could possibly eat. This is a good way to spend a Satruday afternoon.

I could say more, but the chances are the penile appendage coming out the sock monkey's chest has probably distracted you somewhat. And rightly so; it's an abomination.

Like I said before, there are people who are good with their hands, and I'm not one of them.

But mercifully, there's a sewing kit at home, and when I headed home at the end of the day on Saturday, I took the instruction set with me, and over the weekend, managed to remove the unintentionally hilarious phallus/arm hybrid growing out of the torso, and end up with something with a passing resemblance to what a sockmonkey is supposed to look like.

Sockmonkey, post-op

My sockmonkey, post-op

The stitching on this is terrible, it's badly stuffed, I made an embarrassing number of false starts, where I had to undo loads of stitching and redo work, and in all, it took me absolutely aaaaaaaages to make, but despite this, it's my misshapen, badly stitched soft toy, and I'm pretty damn proud of it.

And it's also helped me get past whatever block I had when it came to handling garments, needles and threads. I'm actually fixing and adjusting my own clothes now - this week, for the first time in years, trousers that were too long finally fit me, so I don't have to do a adopt a strange hop-step gait to avoid destroying them as I walk through the streets of London.

Interested?

If this kind of stuff interests you, you could do a lot worse than check out The Make Lounge just off Liverpool in Angel Islington - they run workshops like this regularly, and while they're more expensive, I'm told that the post-workshop glow is similarly euphoric. Alternatively, you there's always O'Reilly's Craft Magazine, and if you're free on Feb 4th and like the look of this event, there's another Fundraiser for the Soko project.

There are people who are good with their hands, and I'm not one of them yet, but it doesn't feel out of reach forever now.

Huzzah!

  • Share/Bookmark
Posted in Journal | Tagged , , | Leave a comment

Tinkering at the windmill

I love my job.

But after a day of starring at a laptop screen in your own home, it's nice to get out and interact with real people, instead of mediated avatars or disembodied voices on skype.

So a couple of days ago, I spent an evening at the Tinker meetup at the the Windmill, a normally charming pub, meeting a load of new faces working in the embryonic hardware hacking/ physical computing scene.

Someday I'll get tired and jaded about technology, and all the stories of ingenuity and resourcefulness will just sound like people talking about themselves and how good they are at hacking, but for now, these nights are revelatory for me - I've come away with so many useful new perspectives on the work I'm doing, but it's also been good to get an idea of what's out there in London for someone relatively new to the world of physical computing.

Sadly, the Windmill had started putting on a pub quiz the same night that Tinker normally have their hardware show & tell sessions, so we ended up passing around examples of 3d printing, to the sound track of distorted pub trivia questions booming out of cheap speakers; quite a strange juxtaposition.

Whither London resistor?

After reading about NYC Resistor in New York, and my own experiences of meeting so many interesting people in The Hub, and finding lots of interesting and fulfilling work as a result, I'm convinced that there needs to be a similar venue in London that lets people meet up, and put simply, hack together and share what they're building on.

In Arduino, we as developers, designers, and tinkerers have a free, open platform that serves a similar purpose to what html, but for ubiquitous computing - a standardised platform that abstracts away enough of the hard stuff associated with electronics to make it accessible to a much, much wider audience. In my opinion this is a wonderful thing - it means being able to come from a domain like web development, and dip your toes into the world of physical computing is possible, and in our experience, deeply satisfiying.

So why don't we have a place like NYC Resistor in London? It's not like there isn't interest.

I asked Alex from Tinker this, and this developed into a fairly involved conversation - the main take away points seem to be that there are two factors stopping things in London;

1) Health and safety

2) Universities

Health and safety

The UK's health and safety standards are generally more stringent than equivalents in the US. This is usually a very good thing. But it also means that when it comes to amateur electronics, you have a lot more regulation to deal with, which is time consuming and expensive, especially when such a space would be at least semi-public.

Universities

If you are linked to a uni, then you're in a great position to make use of equipment they have access to, like laser cutters, 3D printing devices and suchlike, usually at very favourable rates. Again, this is normally a good thing, but this easy access for alumni means that setting up  an independent place to reach the same experienced people who might attracted other relative newcomers is even harder, as anyone setting up such a place is competing against comparatively well funded institutions, who aren't subject the brutal economic realities facing down businesses in London.

Will things change?

These barriers are high, but they don't seem totally insurmountable. You'd really need somewhere relatively central, that's accessible, is cheap and has space for people to meet and hack, in a relatively informal setting.

At times the Hub in Angel Islington feels like it would meet at least some of these criteria, especially after 6pm, and there's already something of a workshoppy vibe here already. It also looks pretty cool:


This still doesn't solve the problem of tools though, or maintenance.

Damn.

At least it's a start.

Update - turns out we do have a space in London after all, called L-space, according to hackerspaces.org. Sadly we've no photos. Come on guys!

  • Share/Bookmark
Posted in Journal | 3 Comments

My latest reason for wanting to scoop IE7’s eyes out with a sharpened spoon.

When we're developing for the web, adapting for Interet Explorer is an unavoidable pain that we have to deal with.

But it's rare to find a problem that rears its ugly head in Internet Explorer 7, but not its much maligned predecessor Internet Explorer 6. We're trained by experience to expect IE7 to know better, albeit only slightly.

However,  I recently learnt that this isn't always the case; IE 7 throws its toys out the pram if you dare set a width on the on the main html element on a page like so:

<html>

<style type="text/css" media="screen">
html{
width:700px;
margin: 0 auto;
background:#444;
}

body{
width:650px;
margin: 0 auto;
background:#eee;
padding:18px;
}

#wrapper{
width:550px;
margin: 0 auto;
background:#435434;
padding:18px;
}

</style>

<body>
 <div id="wrapper">
 Yammer yammer
 </div>
</body>
</html>

 

Do this, and you'll find your layout clings to the leftmost side of the browser window in IE7, for no good reason.

But look at it in IE6, Opera, Safari or Firefox, and you'll see a series of boxes in the centre of the screen, behaving properly.

It's really rather frustrating.

I've put also put this into a test page here, as a sanity check for myself, and also to see if IE8 displays the same asinine behaviour.

I can't get back the time it took to work out this bug, the best I can hope for that this post saves time for another developer.

Such is life.

  • Share/Bookmark
Posted in Coding | Tagged , , | Leave a comment

Renaming stuff with Ruby

I've been mucking around on the command line with Ruby again of late, and one thing that tripped me up initially, but is now firmly on my list of things I Like About Programming is how Ruby handles loops.

With javascript, actionscript, php, it's pretty common to iterate through an array with a for loop something like this:

for (i =o; i = array.length; i ++ ) {
 // call function foo() on array iteration 'i', with argument 'bar'
 array[i].foo(bar)
}

This is doable in Ruby too, but the following is much more common:

array do |i|
 // call function 'foo' on array iteration 'i'  
  i.foo(bar)
end

You could argue that you lose some context inside the loop if it's a long enough method, but for quick loops like in this file renaming widget me and Chris Mear wrote for the Open Rights Group, the expressiveness is pretty impressive.

Here's the full code we used for renaming the 6000-odd files that Photoshop spat out for the ORG founding 1000 badges. Chris knocked this out in about 5 minutes, and I've now commented it to the point that it's parsable even when I'm hungover. 

 

# this script iterates through about 6000 files that have been generated by Photoshop, 
# then renames them to fit naming conventions for a web app, as specified in a CSV file 'codes.csv'
# The Ruby CSV module allows to iterate through csv file easily
require 'csv'
# declare array literal to put desired filenames into
codes = []
# take column two of each row in codes.csv, and put it into 
# the first column of each row of the recently declared codes array 
CSV.open("codes.csv", 'r') do |row|
  codes[row[1].to_i] = row[0]
end
# switch into the directory 'export'
Dir.chdir 'export'
# bookmark current directory to return to later  
wd = Dir.getwd 
# glob is a function that returns an array of items matching the pattern given.
# in this case it this returns pretty much every directory or file name everything
# we could also substitute with Dir.entries('.')
('') do |dirname|
  # Dir.chdir is the Ruby equivalent to 'cd dirname'
  Dir.chdir(dirname)
  # perform a search for all .png files, (all files ending with '.png'  )
  Dir.glob('.png') do |filename|
    # read each filename, find the part of the filename that isn't the number (the '/\D/' part of the regular expression), 
    # then strip it out, leaving just the number, making sure to convert this to an integer, not a string
    number = filename.gsub(/\D/, '').to_i
    # local variable 'code' exists inside this loop only
    code = codes[number]
    new_filename = "#{code}.png"
    puts "Renaming #{filename} to #{new_filename}."
    File.rename(filename, new_filename)
  end
  # switch back to the starting directory before looping through the    
  # next folder 
  Dir.chdir(wd)
end

  • Share/Bookmark
Posted in Journal | Tagged , , | 2 Comments