Category Archives: CodeUnit

CodeUnit houses software and programming tips, snippets and tutorials, complemented with the occasional hardware review.

When Will I be Load Shed with EskomSePush Software & Sites 13 FEB 2019

The slickest, easiest way to currently get the answer to when will you be load shed on a particular day is by downloading the quite frankly well written local load shedding schedule app, EskomSePush. (We will all agree to look past the juvenile joke name, okay?)

Written by Dan Wells and Herman Maritz a handful of years ago, EskomSePush is an extremely user friendly tool that does little more than ask you to download and install the app on your phone, click on the plus button to bring up the location search, and then select the location that you are interested in. The resulting screen then gives you a nice concise view of what your load shedding schedule looks like (across any of Eskom’s seemingly limitless stages) for any particular upcoming day.


The app is easy to read, sends warning push notifications when needed, and is simple enough that most people should get the hang of it. For my part, it works like a charm and its load shedding reporting has yet to fail me, meaning that our rolling blackouts by another name still hasn’t caught me with my pants around my ankles and no torch in sight.

Given the big amount of electricity generation worries on the Eskom horizon, it is probably a good idea to hang on to the app for some time to come.

Related Link: EskomSePush | Google Play

Check your JSON with JSONLint Software & Sites 16 JAN 2019

Seven years later and I still find myself using JSONLint whenever I need to check that a script is indeed producing or being supplied with a valid JSON string.

Pleasingly, a lot of my original 2012 post still checks out: “JSON, or JavaScript Object Notation, is a lightweight text-based open standard designed for human-readable data interchange. It is derived from the JavaScript scripting language for representing simple data structures and associative arrays, called objects. Despite its relationship to JavaScript, it is language-independent, with parsers available for many languages.”

In other words, a good option to shuttle a whole lot of key/value data between AJAX web services. The JSONLint tool itself validates JSON text, and also acts as a reformatter, making it much easier to debug a big chunk of JSON text.

Using the online JSON validator is as simple as copying your JSON text string into the big text area and hitting the “Validate JSON” button.

Useful little tool indeed.

Related Link: JSONLint

Generate Your Instagram Top Nine Software & Sites 28 DEC 2018

At the end of every year, Instagram users all tend to start releasing their “Best Nine” post for that year, essentially a collage image featuring the top nine posts (in terms of likes) for that account.

Strangely enough, Instagram doesn’t actually offer this fun little feature as a native function within their app – meaning that you need to turn to other apps or websites to do the dirty work for you.

Now bear in mind, there are a few websites/apps that require you to authenticate or at least link your Instagram account in order to proceed (essential if you operate a private Instagram feed), but seeing as I don’t really want to trust any third party site unless I absolutely have to, I skipped all of those and headed straight over to the 2018 Best Nine website.

A quick enter of my Instagram handle (craiglotter), a little twiddling of the thumbs, and out popped a nice square collage, ready for sharing. Simple stuff.

(Bonus: If you are looking for an alternative, then Top Nine also does a pretty good job.)

Related Link: 2018 Best Nine | Top Nine

How to Download a High Quality Image from an Instagram Post Software & Sites 01 NOV 2018

These days I try to almost always use photos that I myself took when writing posts for this blog, and seeing as Instagram has very much become my social media network of choice over the last year or two, I essentially always have a picture on hand when I need it.

That said, grabbing a high quality image off of Instagram is much harder than what it should be, which is then exactly where the exceedingly useful DownloadGram steps in.

First, grab the Instagram post that you want to get the image from (easiest is to click on the share icon and select the Share URL/Copy Link option), next, fire up the DownloadGram website, paste the link into the first big textbox, and hit the “Download” button.

If DownloadGram successfully identifies the source of the image, it presents to you a big green “Download Image button”. Click on that and you have your better than low-res image.

Useful.

(Bonus: If you are looking for an alternative to DownloadGram, then 10insta also does a great job of locating the higher quality versions of Instragram post images.)

Related Link: DownloadGram

PHP: Get the first Key of an Associative Array Tips, Tricks and Tutorials 16 JUN 2018

I am not completely sure about it, but I somehow don’t think that I’ve ever needed to get the first key of an associative array using PHP before. Sure, a simple problem with a simple solution, but seeing as I needed to Google this one, I’m jotting down the answer here for future reference.

So, our example for the day then: Given the following array, print out the first key.

$months = array(
'jan'=>'January',
'feb'=>'February',
'mar'=>'March',
'apr'=>'April',
'may'=>'May',
'jun'=>'June',
'jul'=>'July',
'aug'=>'August',
'sep'=>'September',
'oct'=>'October',
'nov'=>'November',
'dec'=>'December'
);

reset($months);
$result = key($months);
if ($result !== NULL){
echo $result; //this will print 'jan'
}

The important bits are reset(), which moves the internal array pointer back to the first element of the array, and then key(), which retrieves the index element at the current array position (dictated by the internal pointer).

Simple (when you read the documentation).

UPDATE: As pointed out by one of my readers, if you know you have an array with at least one element in it, you could always just use array_keys($months)[0] as an alternative.

Related Link: reset() | key()

PHP: “JPEG library reports unrecoverable error: Not a JPEG file: starts with 0x89 0x50” Error Solved Tips, Tricks and Tutorials 30 OCT 2017

My cross-platform Kinetica TouchandTell app running on an old iPad 3 was not successfully uploading images to our new RedStation hosted Ubuntu server (the Android builds were doing it just fine), and I wasn’t really sure why. The Appcelerator Titanium code seemed all okay and in fact it wasn’t until I checked the server’s PHP error logs that I finally spotted the reason why. Exhibit A:

“JPEG library reports unrecoverable error: Not a JPEG file: starts with 0x89 0x50”

Some quick Googling led me to understand that the PHP GD library was failing when trying to parse the received JPG file from the iPad, primarily because the supplied photo was not in the accepted JPEG format. (In fact, chances are that the encoding is in fact either that of a PNG file or perhaps the brand new HEIC image format that has just rolled out with iOS 11).

Although the documentation states that the old imagecreatefromjpeg function is meant to return FALSE if it fails to open the supplied file, there is (annoyingly) a listed bug tracking the fact that the function is in practice actually triggering a Fatal Error instead!

So instead of adopting a practice of trying to open an image based on its file extension, a better solution to get around this problem would be to make use of the similar imagecreatefromstring function, which returns an image resource representing the photo obtained from the given file.

In practice:

$image = false;
$image_data = file_get_contents($imagefilepath);
try {
      $image = imagecreatefromstring($image_data);
} catch (Exception $ex) {
      $image = false;
}
if ($image !== false){
//process $image resource
}

(These image types will be automatically detected if your build of PHP supports them: JPEG, PNG, GIF, BMP, WBMP, and GD2.)

Related Link: imagecreatefromstring

MacBook Air and Xcode: Free up Disk Space by Removing Unwanted/Unavailable Device Simulators Tips, Tricks and Tutorials 29 OCT 2017

iOS software development on a MacBook Air inevitably then means that you have a couple of Xcode versions installed on your device, and as we all know, these chew up a fair bit of disk space in the process. One way to free up some disk space is to remove some of the unwanted or perhaps unavailable device simulators that build up with each Xcode update.

The first step is of course to see what you do in fact have installed, and the easiest is to do this is to make use of the simctl tool that comes with Xcode 6+. To do this, launch a terminal and run:

xcrun simctl list devices

Note the use of xcrun to locate and execute the latest development tools. In a user friendly twist, simctl allows you to bulk delete all unavailable simulators with:

xcrun simctl delete unavailable

You can also target specific devices for deletion by simply specifying them either by name or ID:

xcrun simctl delete D26C18BC-268C-6F0B-9CD8-8EFFDE6619E3

This process can actually free up quite a bit of space, particularly if you’ve been through a number of Xcode updates in the past.

Related Link: Xcode

MySQL: Solve sql_mode=only_full_group_by Error by Turning off Strict SQL Mode Tips, Tricks and Tutorials 26 OCT 2017

When moving an older MySQL-based project to a new server instance, one of the SQL query errors bound to immediately strike is that of triggering the sql_mode=only_full_group error, caused by your SQL select statements referring to columns that are not functionally dependent on the GROUP BY column. (Best explained here in the MySQL documentation)

This new, “Strict SQL Mode” (which is actually a collection of enabled “Server SQL Modes”) is now switched on by default for any MySQL Server 5.7 and up installation, and because in the real world refactoring an entire project just to suit these new settings isn’t really an option, to resolve the issue you need to “disable” this new default on your server instance.

The two newly enabled SQL mode setting that we want to target (because they are the main culprits here) are STRICT_TRANS_TABLES and ONLY_FULL_GROUP_BY.

To do this, you first need to create an additional configuration file for your MySQL server instance:

sudo nano /etc/mysql/conf.d/disable_strict_mode.cnf

Add these two lines to the blank file and then save your changes.

[mysqld]
sql_mode=IGNORE_SPACE,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

As you can see, essentially what we are doing is just declaring a new SQL mode with our two culprit modes omitted.

Finally, restart the MySQL server with:

sudo service mysql restart

Try running your fault trigger SQL statement again, and you should now no longer get this error message staring back at you any more:

Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'yourdbname.tblname.address' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

Related Link: MySQL Group By Handling | Server SQL Modes

Ubuntu Server: How To Enable OPcache for PHP 7 on Apache Tips, Tricks and Tutorials 23 OCT 2017

PHP is what is known as an interpreted coding language, meaning that unlike compiled apps that have already been compiled down into bytecode (i.e. you have to compile your application first so that the OS can run it), PHP scripts are only compiled and interpreted by the runtime engine on script request.

So, if you have scripts that are relatively static (i.e. you aren’t changing them very often), one good way to accelerate your PHP project is to use some sort of caching system that essentially pre-compiles your scripts down to bytecode, meaning less work come request time and thus theoretically, faster code execution.

Enter opcode caching. OPcache, originally a closed source part of the Zend Server project (under the moniker of Zend Optimizer), is an open source module that stores (caches) precompiled PHP script bytecode in shared memory, thus removing the need for PHP to first load and parse scripts on each request.

Since PHP 5.5.0, the module has come bundled with PHP (though disabled by default), meaning that for all intents and purposes, OPcache is now pretty much the standard when it comes to PHP accelerating.

To set up OPcache on an Ubuntu 16.04 server running PHP 7 over Apache, you first need to enable OPcache via the standard php.ini file. To edit the file:

sudo nano /etc/php/7.0/apache2/php.ini

To enable the module once you have the php.ini file is open, find the line reading ;opcache.enable=0, uncomment it by removing the ; and then enable by changing the 0 to 1:

opcache.enable=1

There are quite a few OPcache related settings that you can change while doing the setup, with the php.ini doing a good job of explaining the role of each one. The important ones to keep track of are: opcache.memory_consumption, opcache.max_accelerated_files, and opcache_revalidate_freq.

Save your changes and then enable the module via:

sudo phpenmod opcache

Finally, restart PHP:

sudo service apache2 restart

Monitoring OPCache is a whole other story (worth a google), but the easiest way just to make sure that it is in fact running is to call phpinfo() on one of your webpages. If enabled, you’ll see a bold section under the title of Zend OPcache, with the first column “Opcode Caching” listing a value of “Up and Running”.

Related Link: PHP OPcache | Wikipedia