Smiley Happy Coder

Post a new Tweet from anywhere via Tweetbot using Keyboard Maestro

I’ve long heard of all the great things that Keyboard Maestro can do. I’ve wanted to play with it for absolutely ages, so I started to tinker.

The first thing I decided to create was a method to post a new tweet from anywhere within the operative system. New tweet with tweetbot

So what does this workflow achieve?

We’ll put simply, to create a new tweet I have to work through a couple of steps.

  • Open Tweetbot
  • Click to the “New Tweet” button or menu item
  • Start typing
  • Click “Tweet” or type “Cmd” Return”

I don’t want to waste the time and in all honestly it prevents me from tweeting things because I just won’t move away from what I’m doing.

Often when I want to tweet it’s something that just crossed my mind. I don’t want to wander away from what I’m doing, I just want to post the Tweet as fast as I can.

My macro will, really quickly, switch to Tweetbot and open the new Tweet dialogue.

Heres what it looks like

New Tweet Macro

So, by typing “newtweet” absolutely anywhere within the operative system the macro is fired.

Link to macro on GitHub

  • Top

Prevent screen output from bash scripts

More recently I’ve been working on a few bash scripts that do repetitive tasks for me. One such script will build a new development web server and install various bits of software so that I can get working really fast. One of the things I dislike is the screen output of these scripts. It often looks like a massive mess and since I’ve been planning to release some of these scripts into the wild, a mess just wont do!

Screen Output

I read a lot about preventing screen output and I tested a lot of things I found but I think I’ve come across about the best solution. And let me just point out, its not, by any means, perfect.

I’ve talked before about piping command line outputs to different apps, for example my recent post on the Sublime Text command line tool

The best solution

It seems the best solution is to try to pipe the output to somewhere else. One solution I came up with was to pipe the screen output to a new file and then remove that file. But that feels somewhat hacky, however it does work.

The solution I have been using is to pipe the screen output to /dev/null So something like this.

git clone http://path-to-repository . | /dev/null

Since the path /dev/null doesn’t exist then nothing happens.

Caveat: I have found a few commands that seem to ignore this and just give the screen output regardless. As I said, its not perfect.

  • Top

Add empty element to Laravel dropdowns

Laravel’s Eloquent is an amazing bit of kit, I personally feel its one of Laravel’s top attributes. It just make life so simple and writing code a pleasant experience. For instance generating Laravel dropdowns is a snap. I’ve written about it before

Laravel dropdowns

Using the lists() method works really well and gives you a nice collection containing the ID and name of the record. I normally build my Laravel dropdowns something like this.

return User::select('name', 'id')
                    ->lists('name', 'id');

Sometimes you might find a situation whereby you need an empty row at the start of the collection. I found a way to achieve this in a previous post. this method relies on concatenating an array to the beginning of the collection inside the blade view. Like this.

{{ Form::select('user', 
array('default' => 'Please select a user') + $users , 
null ) }} 

While this works it feels a bit nasty. So I looked for a better solutions and today I discovered another of Eloquent’s hidden gems.

The Prepend Method

The prepend method allows you to “Push an item onto the beginning of the collection.” It accepts two parameters, a value and key however the key is not required.

In my case it looks like this.

return User::select('name', 'id')
                    ->lists('name', 'id')
                    ->prepend('Please select a user');

And now the output looks like this, just what I needed.

0 => "Please select a user"
1 => "Jayne"
2 => "Amanda"
  • Top

Edit your spelling dictionary on OSX

If you’re anything like me, you quite often type words that aren’t “dictionary” words. OSX will automatically try to correct the “typo” unless you have Autocorrect turned off I’ve previously written about that. The operating system stores your custom words in its own spelling dictionary. Here’s how to edit that dictionary.

OSX stores your custom dictionary items in a text file, this file is hidden away within the operating system. As far as I am aware there is not a GUI interface where you can update the dictionary so here are a couple of ways you could make changes.

The spelling dictionary file exists in the users library file. The path to that file is:-

~/Library/Spelling/LocalDictionary

Via “THE TERMINAL”

I know this puts people off so if you’re not into playing terminals then check out the finder method

Step 1

Open a new Terminal window.

Step 2

Open the file in your editor of choice. Mine is generally nano but if you have sublime and have the shortcut setup then feel free to use that.

Enter the following command

nano ~/Library/Spelling/LocalDictionary

Or this if you have sublime text set up

subl ~/Library/Spelling/LocalDictionary

Step 3

Add your new words. Each new word should be on its own line.

Step 4

Save and close the file.

Or as I said, you could choose to use the Finder method.

Via the Finder

Editing your spelling dictionary can just as easily be done via the terminal

The Library folder is one of those places that Apple doesn’t want you to go. I can understand why as it could be quite easy to cause damage to your user account.

Step 1

Open a new finder window

Step 2

From the menu, choose the “Go” menu and then the “Go to Folder” option. Finder, Go to folder to find spelling dictionary

Step 3

In the popup window, enter the following path

~/Library/Spelling

and click “Go” Go to folder dialogue to find spelling dictionary

Now you will see something similar to this Spelling Dictionary Folder

Step 4

Open the “LocalDictionary” file with Text Edit or your editor of choice. You should see something like this Spelling dictionary LocalDictionary File

Step 5

Add your new words. Each new word should be on its own line.

At this juncture its only fair to point out that the operating system will try to autocorrect whatever you type, so be aware and make sure the entry is correct.

Save and then close the file and your changes should start to work.

  • Top

Using Sublime Text 3 command line access

If you use Sublime Text 3 and you use the Terminal on OSX then you might want to enable the Sublime Text 3 command line tool. This will enable you to really quickly open a file or folder in Sublime Text 3 straight from the terminal.

Read On >

  • Top

Turn spelling autocorrect off on Mac OSX

Having the whole operating system autocorrect your spelling as you type is fantastic. Except when its not.

Read On >

  • Top

Fixing the PDO Exception in your first laravel migration under MAMP

I admit, this one has caught me a couple of times so I thought I’d write a very quick post about it.

Each time I install Laravel on MAMP I get a PDO Exception issue and I wonder why.

PDO Exception

The issue arrises when MySQL tries to connect. MAMP prefers connecting via a socket so the easy fix is to add this line to database.php

'unix_socket'   => '/Applications/MAMP/tmp/mysql/mysql.sock',

That’s all folks, worlds shortest blog post.

  • Top

Making bash scripts run globally

To make your scripts run globally you need to place them in a specific folder.

Bash scripts run globally

When you enter a command at the prompt the system will head off to this bin folder to check if a programme exists there first. If it doesn’t then you get an error message. My bin folder is /usr/local/bin/

To make scripts run globally, move the script to the correct folder

NOTE: Please don’t actually do this step. You’ll see in a few minutes. To make the scripts run globally you can simply move them to the bin folder. This command ought to do the trick

mv scriptname.sh /usr/local/bin/scriptname.sh

Now you can just type scriptname.sh anywhere and the script will be found and run.

But, we can do better

While this works well, it now means if I want to do any work to that file I need to move to the bin folder to do it. Personally I have the file in git version control in my Dropbox. I could just re-copy the file after each update but thats just a pain.

Lets not actually move the file, but make the system think its there. How can we do that?

Symbolic Links

A symlink is like an alias. Its just a link that says this here points to that over there.

And now you see why I said not to do the previous step

So I ran a command to create my symlink

ln -s ~/Dropbox/scriptname/scriptname.sh scriptname

And now I can just type scriptname anywhere on my system and boom it works.

The astute amongst you will have spotted that the file extension. Since unix doesn’t really use extensions I was able to set the symlink to omit the .sh extension.

Beware of existing program names

Placing the script in the bin folder is great but you have to be careful not to name your script the same as an existing unix program.

  • Top

Get the first element in an array using PHP reset

PHP Reset
In my last post we discovered how to find the last element in an array by using the end() function. This is brilliant and no doubt going to help you out on a regular basis. But now we’ve set the pointer to the end of the array, how do we get it back to the start?

We use the reset function of course!

The reset function can be used like this
<?php
$things = [ 'bat' , 'sponge' , 'cabbage' ];
//Lets just jump to the end of the array for the fun of it.
end( $things );
echo reset( $things); //Will echo "bat"
?>

Now you might be thinking, “Why the heck do I need to remember this function, when I can just call the 0 index?”

I have to admit I totally agree, surely something like this is exactly the same thing?
<?php
echo $things[0];
?>

Anyone any thoughts as to why reset is better if, in fact, it is?

Update

Thanks to @olimortimer for highlighting a couple of bugs, now been fixed.

@WarpcodeUk also suggested that this would be a viable answer to handle associative arrays. Using reset() in this case would simply return the first array.

$things_values = array_values($things); echo $things_values[0];

Thanks very much to both.

  • Top

Select the last element in an array using PHP’s end function

PHP end function

Arrays play a huge role in most programming languages. I use arrays in PHP many times every day.

Finding the last element of an array can be a useful thing to know. So how would you go about it?
Well the junior developer might think that this is a good answer.

<?php
$things = [ 'car' , 'toaster' , 'tree' ];
$count = count( $things ) - 1;
echo $things[ $count ];
?>

So what is the thought process here?

I know I can get an element by passing the index. Like this echo $things[2];
Firstly I need to know how many elements are in the array so I’ll use count() to tell me that.
But, damn, arrays are zero indexed so count() in this instance will return 3. Okay so just take one off.
Thats it, its working.

Some programming languages offer things like
$things[-1];

But not PHP, that would result in an undefined index. :-(

While this way works there is another, better way. Introducing the end() function!

<?php
$things = [ 'car' , 'toaster' , 'tree' ];
$count = count( $things ) - 1;
echo end( $things );
?>

The end function literally just moved the current position within the array to, you guessed it, the end.

The function returns the last element of the array or false if the array is empty.

This is really useful because now I can just echo out the content of that element.

The end function also works on multi dimensional arrays just as well as flat arrays.

  • Top

Using customers secure account passwords in a sensible way

Secure Passwords

Being a web developer it is sometime necessary to log in to some of our customers accounts and therefore know their passwords. Accounts like domain registrars or social media services. Some of our customers don’t give a seconds thought to their passwords security and happily hand them out to any Tom, Dick or Harry, or even me!
Now I suppose I could be flattered that they have this level of trust in me and I have never and would never abuse that trust, but some people might.
I sometimes come across users who are completely on the other side of the spectrum and won’t hand out passwords at all. I completely understand but that can occasionally make my job difficult to do.

Trusting me with passwords

Trust is an interesting thing. Just like their passwords some folks throw it around like its nothing and others really make you earn it. I personally feel it should be earned to some level. But this isn’t about me.

Sometimes its not even as much about trust as it is about the fact that this password is the same as they use for their bank accounts or mobile phone provider. Now the astute amongst us know that this is a bad idea to use a single password but people still do it.

Storing Passwords

I would rather not store peoples passwords. Where should I keep them? Is what I would call secure the same as the owner? Do I keep them on a Post It stuck to my screen? What happens if my machine is lost or stolen?

I use a product called 1Password to store my passwords but that isn’t a decision I can make with customers passwords.

So whats the answer?

Well I’m not going to say that my method is the only answer but it is certainly an answer.

Each time I need to access a customers account I always suggest that it might be a good idea for them to reset the password to a new password which they don’t mind sharing with me.
I can then go off and do what I need to do and then they can change the password back.

This way I have the access I need to do my job but only for as long as I need it. The customer also has piece of mind that their account stays within their control.

  • Top

A good specification in plain English

Let me take you back to America in the early 60’s. One of the most important men in the world at the time, JFK, petitioned the US Congress to put aside adequate funds in order to, in his words “Land a man on the moon and return him safely to the Earth.”
You could say that this was a specification. NASA was challenged to take a man from the Earth, to the Moon and back. This is pretty much a user story.

moon-landings

User Stories

Most projects, be it interstellar travel or building a new website, involve a lot of different people with all sorts of technical ability. So why do we insist on writing these massively complex specification documents that are confusing for everyone except the developer who wrote it. This is where User Stories come in.

What is a User Story?

A user story is a way of writing a specification in a non technical, but none less accurate or in depth way. The American public, effectively the customer if were sticking with the Moon landings as an example, hasn’t the first clue about building larger rocket boosters or the challenge of coupling two spacecraft moving at thousands of miles an hour in orbit of the Moon. Why should they? The understand that men will be transported to the Moon and back again.

Lets switch back to web development, I know a bit more about that than travel in outer space!
Lets say a customer engages you to build a new e-commerce website for their business. Does the customer need to understand the intricacies of creating an order object? Or just that items can be added to the basket? Do they need to know about recalculating basket quantities including rebuilding coupon code calculations? Or just that the user is able to update basket quantities?

I think you can see where I’m going.

Using User Stories we can draft a good quality specification that has just enough pertinent information to make it useful but not so complex as to baffle the customer.

Danger!

The danger with User Stories is becoming too generalised within the story. Lets take JFK’s user story. “Put a man on the Moon”.

After a matter of weeks the Director of NASA contacts the White House to report that they are ready to perform their task, to “put a man on the moon”.
The President, half of the White House and various Generals from all branches of the US Military all travel to the launch site in anticipation of the making of history.
When the president questions the director of NASA on how they were able to come up with a viable plan so fast, the director replies, the specification was so simple.

The gathered throng of dignitaries all make their way out to a specially erected seating area, spirits are high and silence soon falls. The assembled crowd are all staring up at the huge wooden structure before them. Not wishing to question to intellectual prowess of the scientists and engineers at NASA, no-one utters a word. In the distance a man wearing a flight suit steps up towards the capsule. He forlornly looks up and waves at the visiting guests who applaud this brave, soon to be, national hero.

After what seems like an eternity the astronaut is secured into his capsule. The engineers and scientist all move back away from the structure in readiness for launch. The clock is started. As the seconds display zero there is a massive noise, not a noise that the visitors were expecting. More of a wooden noise, sounds of wood splitting under huge stresses. After what seems like an age the capsule leaves the launch pad. It rises at a frightening rate and soon disappears from view.

Once things calm down the President pushed his way through the crowd to the director of NASA. “You built a giant catapult?!” The director is shocked. At that moment the silence was broken by a voice coming over the tannoy “The capsule has impacted the surface of the moon.” The scientists and engineers all look very happy with themselves, whoops and high fives are exchanged.
The President, remaining silent throughout the launch does not look pleased. Red faced he shouts “Impacted? What do you mean impacted?”
The director looking startled replies “We’ve done exactly as you asked, we put a man on the moon”
“How do you propose that we get him back?” asks the president. The director quickly the folder tucked under his arm, he seems to read something to himself and then looks up. “You didn’t ask us to return him, you asked us to put a man on the Moon, which we have”
“But, he’ll die” sobs The President the realisation setting in.
“Oh, no need to worry about that, he suffocated long before he left the atmosphere.” replies the director. The President was a gasp.

catapult

Sorry if I disappeared into a bit of a work of fiction for a while but I think it illustrated my point.
The User Story in this case was “To put a man on the Moon” when in reality it should have been as The President originally asked.

Now I’d imagine that NASA had a much more detailed and well thought specification that was probably even signed off by the customer, but thats another post.

I hope my ramblings made some sense, while User Stories can be very useful, serving to simplify the specification process, care needs to be take to not over simplify.

  • Top