switch-case in python

Python is a great language if you’re coding to IoT (Internet of Things) like small devices. If you’re coming from another language though you might be surprised that it doesn’t include the classic switch-case statement construct like you’d find in JavaScript, for example.

Fortunately, I just managed to create something that seems to work and the syntax isn’t too far off from the expected.

def switch(key, default):
    case = {
        0.0: 'zero-point-zero',
        0.1: 'zero-point-one',
        0.2: 'zero-point-two',
        0.3: 'zero-point-three',
        0.4: 'zero-point-four'
    }
    return case.get(key, default)

print switch(0.1, 'Unknown')
Running this would produce “zero-point-one”. This isn’t as robust as JavaScript’s or C’s implementation but this can be adjusted for lambda functions in a similar fashion.

 

python

metro app is metro

I thought I’d share a couple screenshots of a web app I worked on a couple of months ago. I was cleaning up my computer’s Desktop space today and it made me smile, remembering the work that I’d done then.

I doubt if I’ll continue the project since I’m now working on something new.

home

login

The site was to be a code-learning area for kids. The requirements for not using/saving personal data was the reason for the interesting username behavior shown above. Usernames are combinations of adjective-noun and passwords then are combinations of color + icon.

rpi-update => bricked raspberry

The Internet is full of advice. This is especially the case in the world of Raspberry Pi tutorials. The problem is that sometimes you get an anti-pattern with respect to upgrading the Pi’s firmware and/or operating system: people are confused and they’re giving the wrong advice. And then this same wrong advice is repeated over and over.

Two Upgrade Paths and Only One Is Correct

There are two paths available to people so that they may upgrade their Raspberry Pi. One is for a tiny fraction of the coders out there, those who actually create the Raspbian operating system itself. And then the other path is for everyone else.

Incorrect:
sudo rpi-update

Correct:
sudo apt-get update
sudo apt-get -y upgrade

Why is This?

Unfortunately, the people who wrote the Raspbian operating system included the tools they themselves use to develop it. Just because it’s there as a command line tool, that doesn’t mean that most of us were supposed to use it.

Granted, people will take the fewest steps to get somewhere. If they think that they can save a few characters with what looks to be a simpler command, they’ll try to use it. If things don’t figuratively blow up in their face, they assume it’s good and they’ll give this advice to others.

What’s the Difference?

When you run the sudo apt-get -y upgrade version, you’re pulling the latest code from the stable master branch of Raspbian. That sudo rpi-update command instead pulls from the development branch known as next. It’s a great way of trashing your Ethernet and wi-fi driver stack so that you can no longer get to it remotely, turning your Raspberry Pi into a brick.

brick

programming through advertisements

Imagine an alternate universe to ours, similar in many ways. Watching television and browsing through magazines is the norm in this world. Just as we in our universe have ad impressions and our own ideas about society are shaped in this way, the people in this other universe are also programmed on a daily basis. How to treat others, what to wear, what to eat and what’s socially-acceptable and even expected are all topics which are schooled, if-you-will, in both worlds by our & their collective media “teachers”.

Using some pretty sophisticated multi-universe equipment that I’ve just invented, I’ve managed to pull some of their advertisements across the ether over into our world to share with you but a warning: some of these images may seem shocking to you. One can only imagine what a wretched society would result from social programming such as this.

This slideshow requires JavaScript.

the zen of source code formatting

 

Source code—assuming for a moment that you didn’t already know this—is a collection of (often English) words and symbols for humans which usually is turned into something more meaningful for a computer to understand when the program is running. Each computer language has its own rules about how you order the words and symbols but most allow for a fair amount of leeway with respect to whitespace, the “rests within the melody”, if-you-will.

“most [computer languages] allow for a fair amount of leeway with respect to whitespace, the rests within the melody…”

“Source code formatting is the task of using that whitespace to maximize… something.”

Source code formatting is the task of using that whitespace to maximize… something. This of course means different things to different people. For some, they believe that source code formatting can be done only one way. To format code using any other method, in their mind, would be the equivalent of breaking some sort of law.

Others believe that your text editor knows best and should be the authoritarian on the matter. There’s usually a feature to “format document” which they believe always gets this right.

As someone who’s been coding now for almost forty years, I’d like to share what I’ve learned and to permission you to completely ignore those first two camps who would say that you must do it their way.

The Virus

In my humble opinion, nearly all of the source code formatting as seen in the world’s collection of code suffers from poor readability. And this is so because of the attitudes surrounding the topic as well as the self-imposed “leaders” and big players who believe their way is better, demanding adherence to their own opinions.

In many software development firms, this is a hot topic for debate. Coders feel strongly about how all this plays out. Outspoken individuals like Douglas Crockford (author of jslint) have even developed tools to enforce their own (wrong) ideas about how code must be formatted.

As large corporations like Google publish more in the open source area, they bring with them this kind of Draconian mindset. If you bring in their code, you’re very likely also bringing in format-enforcing restrictions which come along for the ride.

“If we think of jslint as a virus that self-propagates, then cloning a Google-published project has now infected your project.”

I have personally been held hostage for days trying to make the jslint build tool happy when I’ve been forced to use it. It’s one of the worst anti-patterns I’ve seen in this industry, to be honest.

An Innovative & Meaningful Method of Formatting Your Source Code

For me, I choose to maximize whitespace instead so that I may understand the code instantly. The more I understand the code, the less likely it is that I will later introduce a bug into this code. The faster I can speed-read the code, the more productive and happier I’ll be.

“Code Complete” by Steve McConnell

The genesis of this new method comes in part from my having read this excellent book at least twenty years ago. At the time, this was ground-breaking in its revelations of coding statistics with respect to bugs and the impact of good source code formatting to minimize their presence in code.

My method goes beyond the author’s original suggestions and is the work of a couple decades in the making.

A Practical Example

Below, I show a pair of examples. It is the same code, just differently formatted. The code language is JavaScript and is written for NodeJS, more specifically. The other examples below also are written in JavaScript.

Before (classic jslint-like formatting)

Screen Shot 2018-11-29 at 12.20.13 PM
Figure 1

After (new, suggested method)

Screen Shot 2018-11-29 at 12.22.26 PM
Figure 2

Hopefully you will see the appeal to the second method. The spacing in Fig. 2 allows us to quickly see that this section includes the creation of several variables by pulling them in from separate files and modules. Additionally, they are alphabetized to make it easier to spot accidental double-inclusions.

Given the column-like behavior and the symmetry of those “require” functions, it’s now much easier to scan down the list. It’s now a pleasure to read.

Before (classic jslint-like formatting)

Screen Shot 2018-11-29 at 12.30.22 PM
Figure 3

After (new, suggested method)

Screen Shot 2018-11-29 at 12.17.01 PM
Figure 4

Here, by tightening up the first/third activities to become single-line events in Fig. 4, it’s easier to then see that we have what appears to be a sandwich-like construction:

  1. fs.closeSync() something
  2. create a variable
  3. fs.closeSync() with that variable

The second activity now has some pretty radical source code formatting. But it follows the column rule introduced from before:  columns make assignments easier to scan.

1) The Column Rule

To sum this up: use consistent whitespace to create columns out of assignments (storing a value into a variable). This applies to multi-line assignments as well as to assignments which take more than one line to accomplish.

Create columns: “…use consistent whitespace to create columns out of assignments…”

2) Squash for Readability

If it is possible to remove vertical space so that an entire function may be reviewed in one screenful in your editor, then consider doing so. Good candidates for this treatment are the open/close pairs of file functions seen in Fig. 4. The pairing makes sense to most coders so it’s a welcome form of abbreviation.

Squash: “If it is possible to remove vertical space so that an entire function may be reviewed in one screenful in your editor, then consider doing so.”

3) Comment the Breadcrumb Trail

When there are several levels of braces in one group at the end of something, clearly comment each with judiciously-provided whitespace so that they line up as a column as seen in Fig. 5.

Screen Shot 2018-11-29 at 12.45.00 PM
Figure 5

Breadcrumbs: “When there are several levels of braces in one group at the end of something, clearly comment each with judiciously-provided whitespace so that they line up as a column…”

4) Semicolons for Readability

Use line-ending punctuation to tell one type of scope/block from another. In Fig. 5 above, fs.readdir() and fs.unlink() as function calls are each terminated with a semicolon after the ending brace. Here, I’m omitting the terminal semicolons for both the sections in the if blocks and the for loop at their ending braces.

Semicolons: “Use line-ending punctuation to tell one type of scope/block from another.”

I’m sure this one will have its critics. I would argue that the introduction of chained functions and the concept of “Promises” have created some rather interesting “dogpiles” of code at times which are too difficult to follow without this strategy.

Applicability to Other Languages

The suggestions indicated also apply to other languages. One notable caution, though, goes out to Python-related code which is fairly picky about beginning indentation style. The beginning of each line of Python marks logical blocks of codes as you might see in a matching pair of braces in JavaScript. It’s therefore critical to first make Python happy in this regard before attempting to then adhere to these suggestions. The continuation line technique seen in Fig. 4 above would not work in Python for this reason.

mojave, the last safe osx version?

Apple recently came out with macOS Mojave as the latest in a series of operating systems. Like most of us, you might believe that all upgrades are good upgrades. The truth is another matter entirely with respect to compatibility.

You probably didn’t know this but Apple is dropping 32-bit support in the next release.

They’ve been migrating to a full 64-bit operating system for several major versions now. You probably didn’t know this but they’re dropping 32-bit support in the next release. This is big news and it isn’t being talked about. Think of it as a means of extorting lots of money from the community of Apple developers. If those developers haven’t purchased new computers and they haven’t upgraded to the very latest version of XCode and if they haven’t paid their annual developer fees year after year then they won’t be able to exist in the next major version of OSX. Their apps just won’t work unless they comply.

What does this mean?

Simply put, perhaps a quarter of the OSX apps—especially those you have paid for—will not run anymore.

Apple’s quiet announcement

Behind-the-scenes, Apple has put up a page which warns developers what’s coming. But it’s not like they’re actually warning their own users NOT to upgrade their operating system. Of course, we’ll be nagged daily to upgrade as usual. Imagine how angry you’ll be some day in the future where you endure the typical hour-long upgrade only to find out that your Adobe Photoshop doesn’t run after the upgrade. Typical of Adobe, they’ll likely end support for the version of their software that’s only 32-bit and you’re caught in the crossfire.

How to tell

Here’s how to tell if a particular app won’t work with the next major release of OSX:

Apple menu -> About This Mac -> Software -> Applications -> select application -> 64-bit: yes/no

In this example, we see one of the pieces of programming provided by Adobe indicates “No” in that field meaning it will stop working soon.

Screen Shot 2018-11-05 at 8.41.19 AM

You can adjust the sizing of the report’s columns and then to sort by that 64-bit heading to show a list of the ones which won’t work.

Screen Shot 2018-11-05 at 8.49.41 AM

You have to laugh when you seen two of Apple’s own apps in that list and they’re responsible for their updates of course.

on the mad exodus from github.com

If you don’t code for a living, you probably didn’t hear about the US7.5B deal in which Microsoft is now purchasing github.com. For the rest of us, this is big news.

GitHub Inc. is a web-based hosting service for version control of software using git. They offer both private repositories and free accounts (which are commonly used to host open-source software projects). With its 28 million public repositories, it’s the largest host of source code in the world.

Github’s competitors are reporting record numbers of customers moving their repositories away from the now Microsoft-owned provider.

What Microsoft now controls

Presumably, Microsoft now controls both Atom and Electron, two extremely powerful platforms in the coding space. The former is a great code editor and the latter is the underlying executable program which allows others to code in JavaScript to create a very usable desktop/GUI application.

Microsoft also now control the revenue stream. Each private repository costs $7/month or $9/month, depending upon whether its personal- or business-related.

Microsoft now apparently has access to the code in those private repositories. Just imagine what their competitors must be thinking, now that Microsoft has a copy of their internal project code to include any secret ideas those competitors have been working on.

Alternatives

We’ve all been lulled by github’s ease-of-use, it’s free nature and such. We haven’t even considered alternatives before now, to be honest. The specter of this new playing field means that we must look at our options.

Gogs.io is an open-source option for hosting your own github-like service.

Gogs

Over the last three days, I’ve now setup my own private, internal Gogs service called gitjs.io. Since I own the domain name I may later push this into the cloud but for now, it’s running on one of my computers here at home.

After the initial hurdles to get OSX to startup the Gogs service on a privileged port (http/80) and to automatically start upon bootup, I must say that I love it.

It’s a full-featured github-like experience throughout with all the screens you’d expect. You can create users, organizational levels and do the things you did over on github.

The command line git program interacts with the service as expected. The underlying code creates a global repository folder to stores everything much the same way that github might.

Screen Shot 2018-06-09 at 6.38.00 PM

The Future of Source Control

I don’t need a crystal ball to suggest that Microsoft’s purchase is going to be a game-changer for open source. The world of open source is the very antonym of what Microsoft stands for.

I would suggest that anyone and everyone with a github account highly consider the immediate need to move your code elsewhere. Microsoft has a long history of buying up competitive technologies only to starve them of air over time. In fact, internally Microsoft used the term “starve them of air” to describe how they would ruin a competitor’s advantage in the market.

It’s time to take your code and run.

add comments to a gcode file

I’ve just written a new command-line tool (CLI), this time in NodeJS/JavaScript but as usual, it’s open-source. The program will create a new version of your 3D printer’s GCODE file, adding comments along the way which describe what each command does.

repository

I would suggest that it’s best to install it somewhere in your path and then you should be able to just invoke it easily in your working directory where the GCODE file(s) live:

 

$ gcode-comments file.gcode

;FLAVOR:RepRap
;TIME:11265
;Generated with Cura_SteamEngine 2.3.1
M104 S205            ; Set extruder temperature
M109 S205            ; Set extruder temperature and wait (blocking)
;LAYER_COUNT:28
;LAYER:0
M107                 ; Turn off fan
M205 X10             ; Adjust jerk speed
G1 F2400 E-1         ; Move and/or extrude to the indicated point
...

Input:  file.gcode
Output: file_commented.gcode

talking at the speed of lightning

I give so-called “lightning talks” at San Diego JS, a four-times-per-month local group on Meetup.com. Each talk only lasts five minutes so there’s time for several speakers within the span of a single event.

The venue is typically packed. Here’s a photograph of a typical turnout—there were about 120 attendees this month alone.

I suppose you can communicate a lot in a mere five minutes. It is a bit challenging to try to distill down all the things you need to say into this timeframe. There’s really no room for story-telling, just tell the straight facts and details as you race through your slides and screenshots and nothing more. At best, you can hope that someone will ask a relevant question which may allow you to go into some detail you’d earlier hoped to have included.

Challenges

Many of my projects involve more than one computer. Unfortunately, the security settings on most wi-fi routers at venues like this don’t want you to connect from one computer to the next. The router would actively prevent your demo from working. So I’ve learned to bring along my own networking, which is a hassle. This is especially difficult with IoT projects, for what it’s worth.

Another challenge is related to power. It seems like each of the speakers needs to setup prior to the event and so they all want to bring along their power adapters and plug in. This means that the venue would need to accommodate all those brick-style adapters and they usually forget this.

And I suppose, a recurring problem is that of screen resolution compromises that you have to put up with. You will have formatted all your screens for one resolution while creating your content, only to find that you’re now presenting in a smaller resolution. This then threatens to clip off content or the font size is now too small to be seen by those near the back.

Regardless, it’s a rewarding experience and I hope to give more talks in the months to come. I would encourage others to do the same. It’s a great opportunity to give back to the community of like-minded coders.

mobile app for the robo

I’ve written a new mobile app for the Robo C2 and Robo R2 set of printers by Robo 3D, a local San Diego—based company.

Robo-Home

Details

It’s written in the Adobe PhoneGap (Cordova) platform with Framework7 for the styling and scaffolding. It communicates to the underlying OctoPrint interface inside the printer itself. Rather than building several smartphone apps and being subject to the recurring annual developer fees by Apple/Google/Microsoft, I intend to serve it up in a more economical way: embed another single-board computer inside the printer.

PiZero

This will fit nicely on a $10 Raspberry Pi Zero W computer, as shown. It’s then powered by the USB 5V supply inside the printer and would be powered on every cycle. I’d then use my iPhone’s or iPad’s browser to simply connect to the app.

Progress

The app is fully-functional for the Robo C2 printer and sports a slick-looking interface.

Repository

Screenshots

And here are some obligatory screenshots of the app.

Robo-LeftPanel

Robo-Motors

Robo-Files