Friday, 30 November 2012

Check if a javascript variable contains a function

Problem:

How do I check if a value stored in a javascript variable is a function?

Solution:

While there are many ways to do this, the following code should work:

function isFunction(toCheck){
  return toCheck != null 
      && {}.toString.call(toCheck) == '[object Function]';
}

Notes:

Note that the first conditional, toCheck != null, may not be necessary. However, if null or nothing is passed to the function the result could be undefined otherwise (this was encountered, at least, in some older (or buggy?) implementations of javascript but might be a non-issue today -- feel free to test it out).

An alternative (and closely-related) method of checking is to directly call Object.prototype.toString.call() instead of instantiating an anonymous object.

References:

Thursday, 15 November 2012

Workaround for Symfony 2.1 composer.phar update timezone error

Problem:

Every time I run "php composer.phar update", I get an error similar to:

Warning: date_default_timezone_get(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/Los_Angeles' for 'PST/-8.0/no DST' instead in /path/to/symfony21/project/vendor/monolog/monolog/src/Monolog/Logger.php line 112

Script Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::clearCache handling the post-update-cmd event terminated with an exception

[RuntimeException] An error occurred when executing the "'cache:clear --no-warmup'" command.

What's worse is that my php.ini file has a timezone already set. For instance, when I run the shell command "php -i | grep date.timezone", a timezone is produced, e.g. "date.timezone => America/Los_Angeles => America/Los_Angeles".

Workaround:

A quick workaround to this issue is to explicitly set a timezone in the app/console script. Open the app/console script in a text editor. In app/console, near the top (for instance, right before set_time_limit(0);), add the following line, replacing the example timezone from below with one of the valid PHP timezones found on the PHP docs page:

date_default_timezone_set('America/Los_Angeles');

When you save your changes to app/console and run "php composer.phar update" once more, it should now work.

Notes/Disclaimer:

This workaround isn't by any means an ideal fix, and it will affect the timezone of all Symfony2 commands run using the app/console script. (A fortunate side-effect, however, would be the workaround of timezone issues in other scripts using app/console.) This workaround may or may not also affect any scripts that try to upgrade app/console. To reverse this change, simply remove the "date_default_timezone_set" line you inserted into app/console. (Or even better, prior to modifying app/console, copy the old app/console script, rename the copy to app/console.old, and replace the script with the copy if you need to revert.) This workaround was tested with Symfony 2.1.3, PHP version 5.3.6 using MAMP 2.0.5 under OS X 10.7. Your mileage may vary with other versions.

Saturday, 10 November 2012

Batch resize images to a fixed width and add watermarks

Problem:

I've got a bunch of images that I want to make a resized version of to post online. Additionally, I want to add a watermark to each of these resized images. I already have ImageMagick installed in my OS X or Linux computer.

Solution:

This is quite a specific problem with a very specific solution. This post assumes that you have read and understood the previous post found here. If not, the solution in this blog post should still be somewhat clear, if not a little fast-paced.

For the sake of this post, let's assume that the source images are a bunch of .JPG images. Additionally, let's assume that we want to resize our images to a width of 320 pixels while maintaining the aspect ratio of the original image. Finally, let's assume that we want to give our images the semi-transparent watermark "grammarofdev.blogspot.com", using the font located at "/Library/Fonts/Arial.ttf". To prevent overriding our original images, we will also create a new sub-folder called 'results'. Below is an example Terminal command of how to do all of this (with line-breaks added for legibility):

$ mkdir ./results
$ mogrify -font /Library/Fonts/Arial.ttf -pointsize 88 -verbose
          -draw "fill rgba(255,255,255,0.5) text 24,75
                 'grammarofdev.blogspot.com'"
          -path ./results -resize 320 -quality 86 -format jpg *.JPG

Phew, what an ugly, long command. What does it all mean?

The "-font /Library/Fonts/Arial.ttf -pointsize 88" selects the Arial TrueType font with a point-size of 88pt. The "-verbose" flag outputs verbose information to the terminal while the conversion is being done. The "-draw "fill rgba(255,255,255,0.5) text 30,80 'grammarofdev.blogspot.com'"" portion tells ImageMagick to render the text "grammarofdev.blogspot.com" with a fill colour of white and an alpha of 0.5, starting at the (x,y) coordinate of (24,75) of the original image.

The "-path ./results" indicates that the resized images should be written to the "results" sub-folder. Note that all files in that sub-folder with the same name will be written over without warning! Additionally, omitting this flag will write over all of your original images!

Next, "-resize 320 -quality 86 -format jpg" indicates that the images should be resized to have a width of 320 pixels, maintaining the original aspect-ratio, and then converted to jpeg with a quality of 86. Finally "*.JPG" indicates that this command should convert all images with the suffix .JPG (case-sensitive).

Note that the text is drawn onto the original image prior to the image being scaled down to the final desired size.

Let's see how well this worked. The following two images will show an image before this command is run, and the resulting image afterwards. Note that the original image dimensions are 3264x2448 pixels, however this image is not included in this post. (A slightly-larger version can be found here!)

Original image (scaled to width 300px):

Watermarked image:

Where can this be useful:

Imagine that you had a hundred images you wanted to automatically watermark and resize, or imagine that you have created a web app that requires re-sizing and watermarking previews of images. Using ImageMagick to perform this task is a quick way to achieve the desired results without needing to program anything complex, or use programs such as Photoshop. This post only touched the surface of what ImageMagick can do. For more details on resizing, or details on drawing on images automatically with ImageMagick, check out the following references.


References:

OS X Terminal says 'you have mail'

Problem:

Whenever I open OS X Terminal, it says "you have mail". Why is this, and how can I get rid of this message?

Explanation:

OS X machines, just like Linux and Unix machines, have the capability to send emails to other machines, as well as receive emails from other machines directly to and from your local machine's user account. Long story short, if you are seeing the "you have mail" message in your Terminal window, your computer's local SMTP server has somehow received an email message to your account. (For far more details, look at the references below, or Google the terms "postfix", "sendmail", and "OS X").

Solution (using Terminal only):

This solution solely uses the Terminal. If you are not comfortable with this, please do not follow the rest of this how-to as you can cause some serious damage to your system if you don't know what you're doing. If you'd still like to poke around your system, try the "partially without Terminal" solution below.

The mail received in your account is saved in the file "/var/mail/$USER", where $USER is the name of your account. For instance, if your account was named "someone", and if your home folder shows up in the OS X filesystem as "/Users/someone", then the mail on your machine has been stored in "/var/mail/someone".

Because this is a regular text file, you can simply open it in a text editor to read the mail stored in this file, or you can view the file's contents directly in the Terminal with the command "more /var/mail/$USER", replacing "$USER" with your username (although typing in the command exactly will also suffice in this case, as Terminal will replace $USER with your username).

To get rid of the "you have mail" message, simply move or delete the email file from /var/mail. For instance, assuming again that your account name is "someone", you can type into the terminal "sudo rm -i /var/mail/someone", then confirm deletion when prompted. This command is permanent and possibly destructive if done wrong, so do not make any typos.

Finally, if you have reason to believe that something unusual is sending out emails from your machine after looking at your email file in /var/mail, you can check out the mail log on your machine with the command "more /var/log/mail.log" to see what email activity has occurred on your machine.

Solution (partially without Terminal):

To view the local mail folder on your OS X system in the Finder, type the following command into the Terminal window:

open /var/mail

Once open in the finder, to view the mail on your local machine, open the text file that matches your user in the "/var/mail" folder. For instance, if your username is "someone" and your home folder is "/Users/someone", then the email file to open is "/var/mail/someone".

With the OS X Finder still open to the "/var/mail" folder, in order to remove the "you have mail" message from the Terminal move the email text file from the "/var/mail" folder, or delete it altogether. For instance, if your user is "someone", you will want to either move or delete the file "/var/mail/someone".

After reading your email, if you suspect that there is unusual email activity happening on your local machine, you can confirm this by looking at the machine's email log with the following Terminal command:

open /var/log/mail.log

References:

Friday, 9 November 2012

Batch convert PNG images to 50% scaled jpg images with mogrify

Problem:

How do I convert a bunch of PNG images to jpeg images at 50% of their original dimensions? I'm on an OS X computer and have already installed ImageMagick.

Solution:

You can use the 'mogrify' command that comes with ImageMagick in the Terminal. Note however, that mogrify has the ability to silently overwrite images, so *be careful*! In the following example a destination folder is created to save images in order to preserve the original images.

$ mkdir ./results
$ mogrify -path ./results -resize 50x50% -quality 80 -format jpg *.PNG

So what did all of that mean?

The first part, "mkdir ./results" created a sub-folder named 'results' to save all of the converted images. You can make a different sub-folder if you already have a folder named 'results' to avoid overwriting contents in that existing sub-folder. Remember to change the folder in the -path portion of the mogrify command, too.

The next part batch converts all of the .PNG images to .jpg images of half the width and height. Note that the extensions are case-sensitive. The "-path ./results" flag indicates that results of the conversion are written to the "./results" folder. All destination images are overwritten if they already exist. The "-resize 50x50%" portion shrinks the final width and height to 50% of the original. The "-quality 80" indicates the compression level of the resulting jpeg images. The "-format jpg" indicates that the final image format should be jpeg. Finally, the "*.PNG" indicates that the input images will be every .PNG image in the current folder.

References:

Wednesday, 7 November 2012

PHP timezone error

Problem:

When trying to make a new DateTime object using PHP, or use any built-in time-related functions, I keep getting the following exception thrown: "DateTime::__construct(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/New_York' for 'EST/-5.0/no DST' instead"

Solution:

This error means that a PHP script should have some method of having its default timezone set besides the unsafe method of using the system's setting (making for more predictable and consistent behaviour of the script).

In the case of PHP, you can either use date_default_timezone_set() somewhere prior to calling any date or time functions. Alternatively, you can edit the /etc/php.ini file to add a valid timezone to the date.timezone parameter (e.g. date.timezone = "America/New_York") so that all scripts will use this timezone unless set otherwise by using date_default_timezone_set().

Reference:

Handle MySQL max_allowed_packet error

Problem:

My web application keeps giving the error "#1153 – Got a packet bigger than ‘max_allowed_packet’ bytes" and fails.

What's happening:

This error occurs when a statement to the MySQL server exceeds a certain size. For instance, if the max_allowed_packet is set to 2M but a statement attempts to INSERT a 5MB BLOB, the query will fail.

Solution:

There are two solutions around this problem, so long as you have sufficient privileges to access the configuration of your MySQL server, and are comfortable with either SSH or editing configuration files. Additionally, you should know how to safely restart your MySQL server.

  1. The first solution is to log into your server via SSH, then connect to your MySQL. Assuming you want the maximum packet size to be 16MB, when logged into MySQL type the following command into the prompt: mysqld --max_allowed_packet=16M
  2. The other solution is to find your MySQL configuration file, usually named my.cnf (though if not, you can easily Google how to find the location of this file on your current OS version). Assuming again that you want a max packet size of 16M, inside this file under the section [mysqld], add or change the following parameter to max_allowed_packet=16M

Once this is completed, you may have to restart your MySQL server to see the change. Note that this is a global change and every script that accesses the database on this server will now, by default, have a maximum allowed packet size to what you set it to.

Tuesday, 6 November 2012

Increase phpmyadmin import file size limit

Problem:

I'd like to increase the import file size limit for phpmyadmin.

Solution:

The import size limit of phpmyadmin is the file upload size limit of your php configuration, so the most direct method of increasing this limit is to increase the upload limit in your php.ini file.

If you have shell access with root privileges, (or high enough privileges,) you can follow these steps in the terminal to increase this limit:

  • find your php.ini file if you don't know its location, you can find it by the shell command "whereis php.ini"
  • open your php.ini file and search for the line that contains "upload_max_filesize". It may look something like "upload_max_filesize = 2M"
  • change this to the size that you need, e.g. "upload_max_filesize = 8M"
  • you may need to restart your apache server to see the change

Notes:

Note that by performing this change, the upload limit of all php scripts, not only phpmyadmin will be increased.

Monday, 5 November 2012

Restart a BlackBerry Bold 9900 (and earlier)

Problem:

For those of you still sporting your favourite BlackBerry handset, you may have noticed that on many models, such as the 9900, the only apparent way to restart your handset is to take out the battery and put it back in. Placing your phone in the "power off" mode from the menu only seems to suspend the handset rather than shut it off. For many, taking out the battery isn't a major problem. However, if you happen to keep your handset in a case the aforementioned procedure can become substantially more difficult.

Solution:

Luckily, there is another way to restart your BlackBerry handset, so long as it is equipped with a physical keyboard:

  • Press and hold down the Alt key. Continue holding this key through the next 2 steps.
  • Press and hold down the Right Shift key along with the Alt key. Continue holding these two keys through the next step.
  • While holding the other two keys, press the Backspace/Delete key. Your screen will turn off and the handset will restart.

Notes:

The restarting procedure in this post is called a "soft reset" and can be used to help troubleshoot problems with the phone. It will not erase data nor restore the phone to factory settings.

Additionally, the above procedure will not work on very old BlackBerry devices such as the RIM 850, 857, 950, nor 957.