Smiley Happy Coder

Importing into MySQL using Source

I recently found the Source command for MySQL. When importing .sql files into MySQL the normal way would be to run the following command from outside of MySQL

mysql -u username -p databasename < filename.sql

This is a great command but sometimes the file size is just too large for this command to handle. I haven’t looked into why that is however, I have found a solution.

The Source Command

Source Command

This command appears to loop through the file line by line rather than try to import the whole file as one. However it works, works is the key work here 🙂

The Syntax

source /var/www/filename.sql

It is important to note that this is a MySQL command rather than a linux command which means you must already be logged into MySQL.

Share me...Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInBuffer this pagePin on PinterestEmail this to someone
  • Top

Simple way to humanise files sizes in PHP

This is just a very quick post to show something I’ve just been working on.

I came upon the need to display file sizes in a human readable way. The PHP method FILESIZE returns the size of the file in bytes. You might see a file size of 1500 or even 23462966. Now what do that mean to the average user? Nothing, so lets humanise it.

The function to humanise files sizes

private function humaniseBytes($bytes , $precision = 2)
{
    //Get the length of the string
    $length = strlen($bytes);

    if ($length <= 3){
        return $bytes . 'B';
    } elseif( $length > 3 && $length < 7){
        return number_format($bytes / 1000 , $precision) . 'KB';
    } elseif( $length > 6 && $length <10 ){
        return number_format($bytes / 1000000 , $precision) . 'MB';
    } elseif ( $length > 9 && $length < 13){
        return number_format($bytes / 1000000000 , $precision) . 'GB';
    } elseif ( $length > 12){
        return number_format($bytes / 1000000000000 , $precision) . 'TB';
    }
}

The first thing you’ll note are the parameters passed, obviously the $bytes are passes as well as a variable called $precision. This variable just determines the decimal places that should be returned from the number_format function.

I then just simple loop through and find the length and divide by whatever I need to in order to move the decimal place correctly.

Some functions you might see calculate based on the actual file size, my method however uses the string length. Now I will say that this might not be the most accurate solution since a KB isn’t actually 1000 bytes but rather 1024 bytes.

I hope this helps someone out there.

Share me...Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInBuffer this pagePin on PinterestEmail this to someone
  • Top

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

Share me...Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInBuffer this pagePin on PinterestEmail this to someone
  • 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.

Share me...Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInBuffer this pagePin on PinterestEmail this to someone
  • 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"
Share me...Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInBuffer this pagePin on PinterestEmail this to someone
  • 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.

Share me...Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInBuffer this pagePin on PinterestEmail this to someone
  • 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 >

Share me...Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInBuffer this pagePin on PinterestEmail this to someone
  • 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 >

Share me...Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInBuffer this pagePin on PinterestEmail this to someone
  • 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.

Share me...Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInBuffer this pagePin on PinterestEmail this to someone
  • 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.

Share me...Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInBuffer this pagePin on PinterestEmail this to someone
  • 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.

Share me...Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInBuffer this pagePin on PinterestEmail this to someone
  • 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.

Share me...Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInBuffer this pagePin on PinterestEmail this to someone
  • Top