+++*

Symbolic Forest

A homage to loading screens.

Blog : Post Category : Geekery : Page 8

Astronomy

The art of not seeing very much (as yet)

The other day I mentioned The Children have just turned seven. As The Child Who Likes Animals has spent quite a lot of time in recent months liking space instead, watching Brian Cox’s The Planets innumerable times, memorising lists of dwarf planets, Kuiper Belt objects, centaurs and so on, and learning the difference between a red dwarf, a white dwarf and a brown dwarf. We decided, therefore, that it might be a nice idea for The Mother to get him a telescope, as a suitably grandmothery sort of present. Not trusting The Mother to judge what might be suitable, I reached out to a few astronomers I know for recommendations, and found something that both fell into The Mother’s budget and had a reasonable chance of imaging the rings of Saturn. The number of times I’ve looked down a telescope myself before can be counted on the fingers of one hand; but if I was age seven, was given a telescope, and found that it couldn’t show the rings of Saturn I’d be terribly disappointed.

Of course, I messed up to a certain extent. I’m sure I achieved my objectives, but there’s no way really that The Child Who Likes Animals would be able to actually point the telescope at something himself. So, this is going to be the sort of present that one of his mums sets up in the garden on dark nights; find out what he wants to point it at; try to point it; and then he looks down the eyepiece. Naturally, it becomes a family event, with The Child Who Likes Fairies also wanting to get involved.

As I said, I’ve hardly ever been near a telescope before, despite having books and books on astronomy when I was that age myself. So, on the few nights we’ve had so far when the cloud has at least been broken rather than blanketing, it has gone something like this: I set up the telescope outside. A child asks to point it at something, in a brief pause for breath whilst running around with crazed excitement. If it is an easy thing—the moon, say—I contort myself to the right angle to try to see through the finder, point the telescope and roughly nudge it about until we can see what we’re looking for, all the time with said thing bouncing up and down in the eyepiece as children bounce up and down on the decking. A child then steps up, instinctively grabs the telescope and knocks it out of alignment, and we go back to square one.

Eventually everyone has seen what we’re looking at, and one of them will name something else. I try to work out how to find it, with my laptop and a copy of Stellarium. I fail to find it, and end up sawing the telescope back and forth across the sky desperately trying to find the thing they have asked for. I try again with the finder, drape myself over the telescope and twist it around until the red finder dot is in just the right place; then look through the eyepiece and see nothing but haze. I look up at the sky again, and my target patch of sky, clear a few moments before, is suddenly covered in thick cloud. This cycle repeats a few times, until we either look at the moon again instead, or The Children get bored and go back into the house.

So far, we’ve successfully looked at the moon, Mars, and some random patches of sky that have lots of stars in but nothing I can actually put a name to. Oh well. I’m sure at some point we will get the hang of it, even if I end up becoming the main telescope user myself. It certainly has shown me just how non-empty an empty-looking patch of sky actually is, even living in a hazy, foggy, light-polluted city like this one. I’ll let you know if I manage to find anything less easy to spot. Or, indeed, if we do ever see the rings of Saturn.

The mighty chopper

Or, an eye for detail

Regular readers will know I’m the sort of person who always has an eye for odd little details, odd little quirks of history or mechanical gubbins. You’ll probably be unsurprised to know that this has never really changed much.

Last week I posted photos of my first ever trip to the Ffestiniog Railway, from back when I was still in primary school. I can still remember being intrigued by the “chopper” couplings the Ffestiniog has used as standard since the 1950s (and to some degree since the 1870s—naturally the full details are online). I can’t say it was the first time I had seen them, but it was the first time I had been close enough to notice they were a novelty to me, enough for me to want to take photographs of how they work. So, naturally, I did.

Coupling on Car 100

This is my grainy 110-film photo of the coupling on FfR Car 100. On the far left is its electrical connector, with a hood to shelter it. In the middle is the coupling: a central buffer with a hinged hook fitting into a slot, and a weight (the “bob”) hanging below. Bear in mind that when I took this picture I didn’t know any of this; I was just intrigued by this peculiar metal prong. I’ve learned the technical details since.

Car and loco coupled together

After the loco (Mountaineer) coupled up to the train, this is what it looked like. The hook on each coupling is swung down into the opposite slot, but initially it doesn’t drop all the way; it’s blocked by a camshaft attached to the bob. The bob is swung to one side until the hook drops into its running position, and then swung back; the bob’s camshaft locks the hook into place and prevents it lifting. After that, you can attach the brake hoses.

Nowadays, of course, there are probably a thousand videos of how this works online, that you can go and watch whenever you like. I’m quietly pleased with myself, though, that back in the day when you couldn’t do that, this is the sort of thing I felt worth recording on film.

Technical advice post of the week

Or, what to do with a particular compilation problem

This week, Microsoft released .NET 5, and it reminded me I’ve been meaning to post a piece of technical advice that has bitten me a few times but which doesn’t seem to be very well-documented or well-described online. It’s a piece of technical advice, though, that will slowly be fading away in relevance because it’s advice on .NET Framework; so I thought I should put it up here whilst it is still helpful to people.

(Note for non-technical readers, who are used to photos of trains and cemeteries and probably won’t find this post very interesting: .NET 5 is the latest version of .NET Core, which is the replacement for .NET Framework, hence Microsoft have dropped “Core” from the name to try to make that clearer. .NET 5 is the successor to .NET Core 3, because there were many very popular versions of .NET Framework 4.x which were and are heavily used for a long time, so Microsoft thought reusing the number 4 would be just Too Confusing. Are you less confused now?)

This problem, too, is pretty much specific to people working in teams. It only happens (well, I’ve only seen it happen) if all of the following apply:

  • you’re working in parallel in a team, on a complex system, probably that has solutions containing a relatively large number of projects
  • you’re using the MSBuild tool as part of your continuous integration pipeline, deployment process, or similar
  • you’re using Git as your version control system

The symptoms of the problem are:

  • You can open the solution in Visual Studio and build it with no problems
  • When MSBuild tries to build the solution, it immediately errors, claiming that the solution file has a syntax error on line 2.

Spoiler: there is no syntax error on line 2.

Another note for non-technical readers who are still here: what you might think of loosely as a programming project, in any kind of .NET flavour, has a primary file called a “solution” (its name ends in .sln). The solution contains one or more “projects”; each project contains code. Visual Studio can open your solution file and your project files and turn the projects into some sort of output product, such as a program, a website, a code library or whatever. However, you don’t have to use Visual Studio to do this. .NET Framework has a program called MSBuild that does the same thing. If you have automated your build process (which if you’re working in a team you probably should) and you’re using .NET Framework, your build process will probably use MSBuild to do its work. What happens here is one of a range of problems called “well it worked on my machine”. A developer has code that seems to be in a happy, working state, they upload their code to the team’s server, the automated build process runs, and the automated build process falls over and says it doesn’t work.

The cause of the problem is: two people on the team have added different projects to the solution, in parallel. Now, Git is often quite good, when two people change code at the same time, at either working out how to merge the changes together, or at least, asking you to sort the situation out manually. This, though, is a situation where Git does the wrong thing and breaks your solution file—but it breaks it in a way that only MSBuild notices, and that Visual Studio happily ignores.

The reason this happens is down to the syntax of solution files. The part which lists the projects they contain looks a bit like this:

Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Important.Project.Library", "Important.Project.Library\Important.Project.Library.csproj", "{E6FF8E04-A41D-446B-9F8A-CCFAF4B08AD2}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Important.Project", "Important.Project\Important.Project.csproj", "{9A7E2940-50B8-4F3A-A535-AB6220E6CE3A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Important.Project.Tests", "Important.Project.Tests\Important.Project.Tests.csproj", "{68035DDB-1C24-407C-B6B3-32CEC1D964E5}"
EndProject

Don’t worry too much about what each line says: the important thing to spot is that each project has a pair of lines: a Project(...) = line that contains the important information, and an EndProject line that, er, doesn’t. The projects are in a fairly arbitrary order, too; on your screen in Visual Studio they get sorted alphabetically, but that isn’t reflected in the file, where they are in the order they were added in.

The real cause of the problem is that Git doesn’t know that every Project... has to be followed by an EndProject. So, imagine two people have added new, different projects to the solution file. Git sees this and thinks: Alice has added Project... to line 42, and Bob has added a different Project... to line 42. So I’ll make those into lines 42 and 43. Alice added EndProject to line 43, and so did Bob, so I’ll just pop that in as line 44. So you get this:

Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Alices.Library", "Alices.Library\Alices.Library.csproj", "{0902233A-3857-4E5E-99F4-54F3F5E695E5}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Bobs.Library", "Bobs.Library\Bobs.Library.csproj", "{56ABE9BB-1373-43D3-B1C5-1526E443AD73}"
EndProject

Visual Studio is quite unpeturbed by this. MSBuild, however, doesn’t like it at all. It reads the file, realises there’s a Project without a matching EndProject, and falls over. For some reason, it always complains that the error is on line 2, even though it isn’t anywhere near line 2.

The fix for this, as you might have guessed, is to open up the solution file in a text editor and manually enter that missing EndProject line after Alice’s project. And that’s it. Or, if you don’t feel comfortable going in and hacking your solution file directly, remember I said that Visual Studio is completely unfazed by this? You can make some sort of small change in Visual Studio that will imply a different change to the solution file: for example, tell it not to build one of the projects in one of the build configurations. Visual Studio doesn’t just change that bit, it will write out the whole file from scratch, so the problem gets silently fixed for you. Which one is less work depends on which one you’re happier doing, to be honest.

That’s the abstruse technical post over for now. Next time I write one, I’ll see if I can find something even more technically obscure.

Photo post of the week

Neu, hanes Cymreig

Occasionally, when I visit The Mother, I look through old photos. Either family ones, or ones from my own albums. My first camera was a Christmas present I’d asked for when I was age 7 or 8: a Halina-branded Haking Grip-C compact camera that took 110 cartridge film. With a fixed focus, a fixed shutter-speed and a choice of two apertures, it was an almost-entirely mechanical beast. The shutter was cocked by a lever which engaged with the film’s sprocket holes (a single hole per frame on 110 film) and the only electrical component was a piezoelectric switch attached to the shutter, for firing a Flipflash bulb if you’d inserted any. I might still have an unused Flipflash somewhere.

A photography geek might look at the above spec and be amazed that I managed to photograph anything recognisable on that type of camera. Frankly, even aged 7 so was I: to go with the camera I’d been given a book called something like A Children’s Guide To Photography which made no bones about this type of camera being a very basic one that it was hard to get good results from. It lasted me a few years though, despite at least one drop that popped the back off; I was still using it in my teens, I think.

Sometimes on this blog I’ve mentioned visiting the Ffestiniog Railway; last December for example. The last time I visited The Mother, though, I dug out the photos I’d taken on my very first visit, on which we did a single round trip from Blaenau to Porthmadog and back again behind the Alco. All the photos were taken right at the start of the day, it seems.

The Alco at Blaenau

The Alco at Blaenau

The Alco at Blaenau

The weather in Blaenau is famously murky and damp; I’m not sure quite how much of the murk and grain in those photos is down to the camera and how much is down to the weather. Still, what the photos lack in sharpness, they certainly have in atmosphere.

We can rebuild it! We have the technology! (part four)

Or, finishing off the odds and ends

Settling down to see what else I should write in the series of posts about how I rebuilt this website, I realised that the main issues now have already been covered. The previous posts in this series have discussed the following:

And throughout the last two, we touched on some other important software engineering topics, such as refactoring your code so that you Don’t Repeat Yourself, and optimising your code when it’s clear that (and where) it is needed.

There are a few other topics to touch on, but I wasn’t sure they warranted a full post each, so this post is on a couple of those issues, and any other odds and ends that spring to mind whilst I am writing it.

Firstly, the old blog was not at all responsive: in web front-end terms, that means it didn’t mould itself to fit the needs of the users and their devices. Rather, it expected the world to all use a monitor the same size as mine, and if they didn’t, then tough. When I wrote the last designs the majority of the traffic the site was receiving was from people on regular computers; nowadays, that has changed completely.

However, the reason that this isn’t a particularly exciting topic to write about is that I didn’t learn any new skills or dive into interesting new programming techniques. I went the straightforward route, installed Bootstrap 4.5, and went from there. Now, I should say, using Bootstrap doesn’t magically mean your site will become responsive overnight; in fact, it’s very straightforward to accidentally write an entirely non-responsive website. Responsiveness needs carefully planning. However, with that careful planning, and some careful use of the Bootstrap CSS layout classes, I achieved the following aims:

  • The source code is laid out so that the main content of the page always comes before the sidebars in the code, wherever the sidebars are actually displayed. This didn’t matter so much on this blog, but on the Garden Blog, which on desktop screens has sidebars on both sides of the page, it does need to be specifically coded. Bootstrap’s layout classes, though, allow you to separate the order in which columns appear on a page from the order in which they appear in the code.
  • More importantly, the sidebars move about depending on page width. If you view this site on a desktop screen it has a menu sidebar over on the right. On a narrow mobile screen, the sidebar content is down below at the bottom of the page.
  • The font resizes based on screen size for easier reading on small screens. You can’t do this with Bootstrap itself; this required @media selectors in the CSS code with breakpoints chosen to match the Bootstrap ones (which, fortunately, are clearly documented).
  • Content images (as opposed to what you could call “structural images”) have max-width: 100%; set. Without this, if the image is bigger than the computed pixel size of the content column, your mobile browser will likely rescale things to get the whole image on screen, so the content column (and the text in it) will become too narrow to read.

On the last point, manual intervention is still required on a couple of types of content. Embedded YouTube videos like in this post need to have the embed code manually edited, and very long lines of text without spaces need to have soft hyphens or zero-width spaces inserted, in order to stop the same thing happening. The latter usually occurs in example code, where zero-width spaces are more appropriate than soft hyphens. All in all though, I’ve managed to produce something that is suitably responsive 95% of the time.

The other point that is worth writing about is the build process of the site. As Wintersmith is a static site generator, every change to the site needs the static files to be built and deployed. The files from the previous version need to be deleted (in case any stale ones, that have disappeared completely from the latest iteration of the output, are still lying about) and then Wintersmith is run to generate the new version. You could do this very simply with a one-liner: rm -rf ../../build/* && wintersmith build if you’re using Bash, for example. However, this site actually consists of three separate Wintersmith sites in parallel. The delete step might only have to be done once, but doing the build step three separate times is a pain. Moreover, what if you only want to delete and rebuild one of the three?

As Wintersmith is a JavaScript program, and uses npm (the Node Package Manager) for managing its dependencies, it turns out that there’s an easy solution to this. Every npm package or package-consumer uses a package.json file to control how npm works; and each package.json file can include a scripts section containing arbitrary commands to run. So, in the package.json file for this blog, I inserted the following:

"scripts": {
  "clean": "node ../shared/js/unlink.js ../../build/blog",
  "build": "wintersmith build"
}

You might be wondering what unlink.js is. I said before that “if you’re using Bash” you could use rm -rf ../../build. However, I develop on a Windows machine, and for this site I use VS Code to do most of the writing. Sometimes therefore I want to build the site using PowerShell, because that’s the default VS Code terminal. Sometimes, though, I’ll be using GitBash, because that’s convenient for my source control commands. One day I might want to develop on a Linux machine. One of the big changes between these different environments is how you delete things: del or Remove-Item in PowerShell; rm in Bash and friends. unlink.js is a small script that reproduces some of the functionality of rm using the JavaScript del package, so that I have a command that will work in the same way across any environment.

So, this means that in the main blog’s folder I can type npm run clean && npm run build and it will do just the same thing as the one-liner command above (although note that the clean step only deletes the main blog’s files). In the other Wintersmith site folders, we have a very similar thing. Then, in the folder above, we have a package.json file which contains clean and build commands for each subsite, and a top-level command that runs each of the others in succession.

"scripts": {
  "clean:main": "cd main && npm run clean",
  "clean:misc": "cd misc && npm run clean",
  "clean:garden": "cd garden && npm run clean",
  "clean": "npm run clean:misc && npm run clean:main && npm run clean:garden",
  "build:main": "cd main && npm run build",
  "build:misc": "cd misc && npm run build",
  "build:garden": "cd garden && npm run build",
  "build": "npm run build:misc && npm run build:main && npm run build:garden"
}

And there you have it. By typing npm run clean && npm run build at the top level, it will recurse into each subsite and clean and build all of them. By typing the same command one folder down, it will clean and build that site alone, leaving the others untouched.

When that’s done, all I have to do is upload the changed files; and I have a tool to do that efficiently. Maybe I’ll go through that another day. I also haven’t really touched on my source-control and change management process; and all I have to say there is, it doesn’t matter what process you use, but you will find things a lot more straightforward if you find a process you like and stick to it. Even if you’re just a lone developer, using a sensible source control workflow and release process makes life much easier and makes you less likely to make mistakes; you don’t need anything as rigid as a big commercial organisation, but just having a set process for storing your changes and releasing them to the public means that you are less likely to slip up and make mistakes. This is probably something else I’ll expand into an essay at some point.

Is the site perfect now? No, of course not. There are always more changes to be made, and more features to add; I haven’t even touched on the things I decided not to do right now but might bring in one day. Thoe changes are for the future, though. Right now, for a small spare-time project, I’m quite pleased with what we have.

Putting things into practice

Or, time to get the model trains out

A couple of times recently I’ve mentioned my vague model railway plans and projects, including the occasional veiled hint that I’ve already been building stock for the most fully-fleshed out of these ideas. At the weekend I had some time to myself, so I unpacked my “mobile workbench” (an IKEA tray with a cutting mat taped firmly to it) and had a look at which projects I could move on with.

The other week I’d been passing my local model shop and popped in to support them by buying whatever bits and pieces I could remember I needed. I’ve been wondering the best way to weight some of my stock, so bought a packet of self-adhesive model aircraft weights. I wasn’t convinced they would be ideal because they’re a bit on the large side for 009 scale, but the 5g size do just fit nicely inside a van.

Wagon and weights

Yes, I know I didn’t clean off the feed mark on the inside of the wagon; nobody’s going to see it, are they. The weights are very keen to tell everyone they are steel, not lead. I wasn’t really sure what amount to go with especially given that (like most Dundas wagon kits) it has plastic bearings; it now has 10g of steel inside it and feels rather heavy in the hand.

Another project that’s been progressing slowly is a Dundas kit for a Ffestiniog & Blaenau Railway coach, which will be a reasonable representation of the first generation of Porthdwyryd & Dolwreiddiog Railway coaches. The sides were painted early on with this kit so that I could glaze it before it was assembled; it still needs another coat on the panels but the area around the window glazing shouldn’t need to see the paintbrush again I hope. In my last train-building session I fitted its interior seating; in this one, it gained solebars and wheels and can now stand on the rails. Its ride is very low, so low that, given typical 009 flanges, it needs clearance slots in the floor for the wheels.

Coach underside

This made it a little awkward to slot the wheels into place, but when I did it all fitted together rather nicely, with little lateral slop in the wheels and a quick test showing everything was nice and square.

Standing on a perspex block to check for squareness

To show just how low-riding it is—like many early narrow gauge carriages—I used a piece of card and a rule to measure how much clearance there is above rail level.

Height measurement

This shows rather harshly that I’ve let this model get a bit dusty on the workbench.

It needs couplings, of course, so I made a start on folding up a pair of Greenwich couplings for it. I’m still trying to find the perfect pliers for making Greenwich couplings. They don’t need any soldering, at least, but they do need folding up from the fret and then fitting the two parts—buffer and loop—together with a pin. These small flat-nosed pliers are very good for getting a crisp fold.

Greenwich coupling fret

Part-folded Greenwich buffer

I should give those pictures a caption about the importance of white balance in photography, given how differently the green cutting mat has come out between them. By the time I got to this stage it was starting to get a bit too dark to fit two tiny black pieces of brass together with a black pin and get them moving freely, never mind wrapping ferromagnetic wire around the loop tail. Still, all in all, I think everything seemed to be coming along quite nicely.

The only perfect railway is the one you invent yourself

Or, some completely fictional history

The other week, I wrote about how there are just too many interesting railways to pick one to build a model of, which is one reason that none of my modelling projects ever approach completion; indeed, most of them never approach being started. Some, though, have developed further than others. In particular, I mentioned a plan for a fictitious narrow-gauge railway in the Rhinogydd, and said I’ve started slowly aquiring suitable stock for it. What I didn’t mention is that I’ve also put together the start of a history of this entirely invented railway. I first wrote it down a few years ago, and although it is a very high-level sketch, has a fairly high level of implausibility to it, and probably needs a lot of tweaks to its details, I think it’s a fair enough basis for a railway that is fictional but interesting.

Narrow-gauge modelling general does seem to have something of a history of the planning and creation of entire fictional systems; rather, I think it’s something that has disappeared from British standard gauge railway modelling, partly due to the history of the British railway network. This, then, is my attempt at an entry into this genre. If you don’t know the Rhinogydd: they are the mountain range that forms the core of Ardudwy, the mountains behind Harlech that form a compact block between the Afon Mawddach and the Vale of Ffestiniog. The main change I have made to real-world geography is to replace Harlech itself with a similar town more usable as a port; all the other villages, hamlets and wild mountain passes are essentially in the same place as in the real world, and if you sit down with this fictional history and the Outdoor Leisure map that covers the district, you should be able to trace the route of these various railways without too much trouble.

The primary idea behind the railway is that profitable industry was discovered in the heart of the Rhinogydd. Not slate as in Ffestiniog; the geology is all wrong for that. The industry here would be mining for metal ores, and it isn’t really too far from the truth. There genuinely were a whole host of mines, largely digging up manganese ore, in the middle of what was and is a very inhospitable area; all of them were very small and ultimately unsuccessful. The fiction is that an intelligent landowner realised that a railway would enable the mines to develop; so, using part of an earlier horse-drawn tramway, a rather circuituous route was built from the middle of the mountains down to a port at the mouth of the Afon Dwyryd. The earlier tramway, also fictional, would have run in a very different direction, from the Afon Artro up to the small farms in the hills overlooking Maentwrog. Why you would want to build a horse tramway over such a route I’m still not entirely sure, but it means that my Porthdwyryd & Dolwreiddiog Railway can be a network, a busy well-trafficked main line in one direction, and a half-abandoned branch line in the other. This is of course not too dissimilar to the Welsh Highland Railway, with its Croesor and Bryngwyn branches, originally both main lines but both later superseded.

I did, a few years ago, draft a whole outline history for the railway, trying to explain quite why such a thing would and could exist, and how it might have at least partially survived through to the present day. It was an interesting exercise, although I’m not sure it would be a very interesting piece of writing to post here. I do like the thought, though, of writing it up as a full history, complete with some unanswered questions; and then, when I do build models of the line, I can claim that it is at least an approximately accurate model of something that actually did run on the railway. I quite like the idea of steadfastly maintaining that it is actually a real place—what do you mean, you’ve never heard of it before?—and that I am trying to model, however imperfectly, trains that really did exist. I can always be very apologetic when my model “isn’t as accurate as I’d like”, or when I “haven’t been able to find out” exactly what colour a given train was painted in a given year. I wonder how persuasive I will manage to be.

The railway in the woods

Or, some autumnal exploration

Today: we went to wander around Leigh Woods, just outside Bristol on the far bank of the Avon Gorge. It’s not an ancient woodland: it is a mixture of landscapes occupied and used for various purposes for the past few thousand years. A hillfort, quarries, formal parkland, all today merged and swallowed up by woodland of various forms and patterns, although you can see its history if you look closely. I love walking around damp, wet countryside in autumn; although today was dry, everything had a good soaking yesterday and earlier in the week. The dampness brings out such rich colours in photos, even though I didn’t have anything better than the camera on my phone with me.

Twisted roots

Twisted trunks

Part of the woods, “Paradise Bottom”, belonged to the Leigh Court estate and was laid out by Humphry Repton, the garden and landscape designer who should not be confused with *Boulder Dash*. It includes a chain of ponds which are now very much overgrown, their water brown and their bottoms thick with silt; and some of the first giant redwood trees planted in Britain, around 160 years ago now.

Redwood, of not inconsiderable size

The ponds drain into a sluggish, silty stream which trickles through the woods down into the Avon, the final salt-tinged part of the stream running under a handsome three-arched viaduct built by the Bristol & Portishead Railway, back when when the redwoods were newly-planted.

Railway viaduct

Railway viaduct

If you’ve heard of the Bristol & Portishead, it may be because of the ongoing saga of when (if ever) it will reopen to passengers again. It closed to passenger traffic back in the 1960s, freight in the early 1980s, but unusually was mothballed rather than pulled up and scrapped. At the start of the 21st century it was refurbished and reopened for freight trains, but not to full passenger standards. Although there have been plans on the table for ten or fifteen years now to reopen it to passenger traffic, years have passed, the leaves in the wood have fallen and grown again, and nothing keeps on resolutely happening. The main issues are the signalling along the line (token worked, I understand, with traincrew-operated instruments) and its single track, which limits maximum capacity to one train each way per hour at the very most. Aside from putting in a station or two, these are the main factors which at present prevent it from being reopened to passengers.

When I moved to Bristol, over ten years ago now, the Bristol & Portishead line was busy every day with imported coal traffic. Now that that is fading away, the line itself is much quieter, and indeed can go for days at a time with no trains at all. Its railheads are dull, not shiny, as it curves through the lush green woodland. I walked up to the top of one of its tunnel mouths, and looked down upon it silently.

The railway in the woods

We can rebuild it! We have the technology! (part three)

Introducing Pug

If you want to start reading this series of articles from the start, the first part is here. In the previous part we discussed how I adapted Wintersmith to my purposes, adding extra page generators for different types of archive page, and refactoring them to make sure that I wasn’t repeating the same logic in multiple places, which is always a good process to follow on any sort of coding project. This post is about the templating language that Wintersmith uses, Pug. When I say “that Wintersmith uses”, incidentally, you should always add a “by default” rider, because as we saw previously adding support for something else generally wouldn’t be too hard to do.

In this case, though, I decided to stick with Pug because rather than being a general-purpose templating or macro language, it’s specifically tailored towards outputting HTML. If you’ve ever tried playing around with HTML itself, you’re probably aware that the structure of an HTML document (or the Document Object Model, as it’s known) has to form a tree of elements, but also that the developer is responsible for making sure that it actually is a valid tree by ending elements in the right order. In other words, when you write code that looks like this:

<section><article><h2>Post title</h2><p>Some <em>content</em> here.</p></article></section>

it’s the developer who is responsible for making sure that those </p>, </article> and </section> tags come in the right order; that the code ends its elements in reverse order to how they started. Because HTML doesn’t pay any attention to (most) white space, they have to be supplied. Pug, on the other hand, enforces correct indentation to represent the tree structure of the document, meaning that you can’t accidentally create a document that doesn’t have a valid structure. It might be the wrong structure, if you mess up your indentation, but that’s a separate issue. In Pug, the above line of HTML would look like this:

section
  article
    h2 Post title
    p Some
      em content
      | here.

You specify the content of an element by putting it on the same line or indenting the following line; elements are automatically closed when you reach a line with the same or less indentation. Note that Pug also assumes that the first word on each line will be an opening tag, and how we can suppress this assumption with the | symbol. You can supply attributes in brackets, so an <a href="target"> ... </a> element becomes a(href="target") ..., and Pug also has CSS-selector-style shortcuts for the class and id attributes, because they’re so commonly used. The HTML code

<section class="mainContent"><article id="post-94">...</article></section>

becomes this in Pug:

section.mainContent
  article#post-94 ...

So far so good; and I immediately cracked on with looking at the pages of the old Wordpress blog and converting the HTML of a typical page into Pug. Moreover, Pug also supports inheritance and mixins (a bit like functions), so I could repeat the exercise of refactoring common code into a single location. The vast majority of the template code for each type of page sits in a single layout.pug file, which is inherited by the templates for specific types of page. It defines a mixin called post() which takes the data structure of a single post as its argument and formats it. The template for single posts is reduced to just this:

extends layout
block append vars
  - subHeader = '';
block append title
  | #{ ' : ' + page.title }
block content
  +post(page)

The block keyword is used to either append to or overwrite specific regions of the primary layout.pug template. The content part of the home page template is just as straightforward:

extends layout
block content
  each article in articles
    +post(article)

I’ve omitted the biggest part of the home page template, which inserts the “Newer posts” and “Older posts” links at the bottom of the page; you can see though that for the content block, the only difference is that we iterate over a range of articles—chosen by the page generator function—and call the mixin for each one.

The great thing about Pug, though, is that it lets you drop out into JavaScript at any point to run bits of code, and when doing that, you don’t just have access to the data for the page it’s working on, you can see the full data model of the entire site. So this makes it easy to do things such as output the sidebar menus (I say sidebar; they’re at the bottom if you’re on mobile) with content that includes things like the number of posts in each month and each category. In the case of the tag cloud, it effectively has to put together a histogram of all of the tags on every post, which we can only do if we have sight of the entire model. It’s also really useful to be able to do little bits of data manipulation on the content before we output it, even if it’s effectively little cosmetic things. The mixin for each post contains the following Javascript, to process the post’s categories:

- if (!Array.isArray(thePost.metadata.categories)) thePost.metadata.categories = [ thePost.metadata.categories ]
- thePost.metadata.categories = Array.from(new Set(thePost.metadata.categories))

The - at the start of each line tells Pug that this is JavaScript code to be run, rather than template content; all this code does is tidy up the post’s category data a little, firstly by making sure the categories are an array, and secondly by removing any duplicates.

You can, however, get a bit carried away with the JavaScript you include in the template. My first complete design for the blog, it turned out, took something like 90 minutes to 2 hours to build the site on my puny laptop; not really helpful if you just want to knock off a quick blog post and upload it. That’s because all of the code I had written to generate the tag cloud, the monthly menus and the category menus, was in the template, so it was being re-computed over again for each page. If you assume that the time taken to generate all those menus is roughly proportional to the number of posts on the blog, O(n) in computer science terms (I haven’t really looked into it—it can’t be any better but it may indeed be worse) then the time taken to generate the whole blog becomes O(n2), which translates as “this doesn’t really scale very well”. The garden blog with its sixtyish posts so far was no problem; for this blog (over 750 posts and counting) it wasn’t really workable.

What’s the solution to this? Back to the Wintersmith code. All those menus are (at least with the present design) always going to contain the same data at any given time, so we only ever need to generate them once. So, I created another Wintersmith plugin, cacher.coffee. The JavaScript code I’d put into my layout templates was converted into CoffeeScript code, called from the plugin registration function. It doesn’t generate HTML itself; instead, it generates data structures containing all of the information in the menus. If you were to write it out as JSON it would look something like this:

"monthData": [
  { "url": "2020/10/", "name": "October 2020", "count": 4 },
  { "url": "2020/09/", "name": "September 2020", "count": 9 },
  ...
],
"categoryData": [
  { "name": "Artistic", "longer": "Posts categorised in Artistic", "count": 105 },
  ...
],
"tagData": [
  { "name": "archaeology", "count": 18, "fontSize": "0.83333" },
  { "name": "art", "count": 23, "fontSize": "0.97222" },
  ...
]

And so on; you get the idea. The template then just contains some very simple code that loops through these data structures and turns them into HTML in the appropriate way for each site. Doing this cut the build time down from up to two hours to around five minutes. It’s still not as quick to write a post here as it is with something like Wordpress, but five minutes is a liveable amount of overhead as far as I am concerned.

The Plain People Of The Internet: So, you’re saying you got it all wrong the first time? Wouldn’t it all have been fine from the start if you’d done it that way to begin with?

Well, yes and no. It would have been cleaner code from the start, that’s for certain; the faster code also has a much better logical structure, as it keeps the code that generates the semantic content at arm’s length from the code that handles the visual appearance, using the data structure above as a contract between the two. Loose coupling between components is, from an architectural point of view, nearly always preferable than tight coupling. On the other hand, one of the basic principles of agile development (in all its many and glorious forms) is: don’t write more code than you need. For a small side project like this blog, the best course of action is nearly always to write the simplest thing that will work, be aware than you’re now owing some technical debt, and come back to improve it later. The difficult thing in the commercial world is nearly always making sure that that last part actually happens, but for a site like this all you need is self-discipline and time.

That just about covers, I think, how I learned enough Pug to put together the templates for this site. We still haven’t covered, though, the layout itself, and all the important ancillary stuff you should never gloss over such as the build-deploy process and how it’s actually hosted. We’ll make a start on that in the next post in this series.

*The next post in this series, in which we discuss responsive design, and using `npm` to make the build process more straightforward, is here*

Too much to choose from

Or, why are there so many different trains in the world

Yesterday I said that having more blog posts about trains than about politics would be a good target to aim for by this time next year; and regardless of how frequently I post here overall, that’s probably still a good rule of thumb to aim for. So today, I thought I’d talk about model trains, and how I end up never building any.

I’ve always wanted a model train of some kind, ever since I was small and had a Hornby “Super Sound” trainset with an allegedly realistic chuff, generated by a sound machine wired in to the power circuity. However, there have always been a few problems with this, aside from the perennial problems of having enough time and space for such a space-gobbling hobby. There are two fundamental ones, at root: firstly, I am perennially pedantic, and secondly, I just like such a broad range of different railways and trains that it would be extremely hard to choose just one to stick with as a project. Given the first point, I would always want anything I build to be as accurate as I could make it; given the second, I can never stick with one idea for long enough to build enough stuff to practice the skills sufficiently and be a good enough model-builder to achieve this. Whilst drafting this post in my head, I tried to think just how many railways I’ve been interested in enough to start working out the feasibility of some sort of model railway project. It’s a long list.

  • Some sort of rural German branch line (I did actually start buying stock for this)
  • A fictitious narrow-gauge line in the Rhinogydd, in Ardudwy (again, this has reached the stock-acquiring level)
  • Grimsby East Marsh or somewhere else in Grimsby Docks
  • Something inspired by the Cambrian Railways’ coast section (although the actual stations are mostly fairly unattractive, apart from possibly Penrhyndeudraeth)
  • Woodhall Junction, on the Great Northern
  • Bala Junction (ever since I saw a plan of it in a Railway Modeller years and years ago)
  • Wadebridge (come on, who doesn’t like the North Cornwall Railway)
  • North Leith on the North British Railway (at 1:76 scale, you could do it to exact scale and it would still fit inside a 6 foot square)
  • Something fictitious based on the idea that the Lancashire, Derbyshire and East Coast Railway had actually finished their planned line east of Lincoln, which was always a wildly implausible plan in the real world.
  • The Rosedale Railway (although in practice this would probably be very dull as a model)
  • Moorswater, where the Liskeard and Looe Railway and Liskeard and Caradon Railways met (ideally when it was still in use as a passenger station, although that means before it was connected to the rest of the railway network)

Even for a modelling genius, or the sort of modeller who can produce an amazing, detailed landscape, then immediately packs it away in a box and starts working on the next one, that’s a lot of different ideas to vacillate between. And some of these would require just about everything on the model to be completely hand-made: Moorswater, for example, would have to have fully hand-made track, stock, locomotives and buildings in order to even vaguely resemble the original. With something like Woodhall Junction or Grimsby Docks most of the place-specific atmosphere is in the buildings rather than the trains, but even so, getting a good range of location-specific locos and stock would be difficult.

Just lately, there’s been another one to add to the list: I read a small book I picked up about the Brecon and Merthyr Railway, and was intrigued. I quickly found it had an intriguing range of operations, reached 1923 without ever owning any bogie coaches, and standardised on using somersault signals. The large-scale OS maps that are easily available (ie, those in the National Library of Scotland collection) show some very intriguing track layouts, its main locomotive works at Machen was an attractive and jumbled mix of 1820s stone and 1900s corrugated iron, and it even had some halts on the Machen-Caerffili branch which were only ever used by trains in one direction. However, on the other hand, the small book I picked up seems to be practically the only book ever written about the line, with very little information available easily about it. I suspect I’d end up writing a book about it myself before I got around to building anything.

I am going to try to build more models, and hopefully the more I build, the better they will get and the happier with my skills I’ll become. I’m going to have to try to stick to one and only one of the above, though, and try not to get distracted. That might be the hardest part.