Pages

Monday, January 30, 2012

Shorten a URL Using Bit.ly in Objective-C

This is a quick and dirty way to shorten a URL using the bit.ly API in Objective C. You will need to register with bit.ly and obtain a login name and API key. The code below will shorten a URL where BitLyLogin is your bit.ly login, BitLyAPIKey is your bit.ly API Key and shortenURL is the URL that you wish to shorten. This code should return nil if it is unable to connect to bit.ly but will return the text of an error message if it fails.


NSString *shortenedURL = [NSString stringWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://api.bit.ly/v3/shorten?login=%@&apikey=%@&longUrl=%@&format=txt", BitLyLogin, BitLyAPIKey, shortenURL]] encoding:NSUTF8StringEncoding error:nil];

Thursday, August 4, 2011

Create a Perl Module Skeleton Using h2xs

The h2xs binary is used to convert C header files to Perl extensions, but it can also be used to create a Perl module template. Creating modules this way will save you a lot of time and make sure that your module is setup up correctly for submission to CPAN.

You can create your own module skeleton with h2xs using:

h2xs -A -X -n My::Module

This will create a directory called My-Module with the following files:

My-Module/lib/My/Module.pm
My-Module/Makefile.PL
My-Module/README
My-Module/t/My-Module.t
My-Module/Changes
My-Module/MANIFEST

Module.pm is your actual module, which you will edit and add your desired functionality into. Your module can be installed on your system by following these steps:

perl Makefile.PL

This creates the makefile

make test

This executes all tests, assuming you have created some.

make install

This will install the module in your system, you may have to execute this line as super user.

You can package up your module for submission to CPAN, or other distribution means by typing:

make tardist

This will create My-Module-0.01.tar.gz inside your project directory.

Wednesday, July 27, 2011

Convert YouTube Videos to MP3

I often find songs on YouTube that I can't obtain elsewhere, especially obscure remixes of popular songs. While it is possible to listen to them directly on YouTube this gets tiresome quickly since you can't add the songs into a GrooveShark or iTunes playlist or play them on your iPod.
I've used several services online that will convert a YouTube video to MP3 format and allow you to download it. These services are covered in banner ads, encode MP3s in low quality and frequently don't work at all.
While browsing MacUpdate.com, I discovered a free program called "YouTube to MP3", it's completely free and allows you to extract only the audio from a YouTube video. This program allows you to select the bitrate, and format. You select the YouTube video you want to download by either clicking the paste from clipboard button or manually typing the URL in. Another nice feature this program has is downloading several songs at the same time.

The program runs on Mac and Windows and can be downloaded from here: http://www.mediahuman.com/download.html

Friday, July 8, 2011

Backup a MySQL Database Nightly

I run several websites, which use MySQL, and I've discovered the importance of backing up my databases regularly. I've had tables become corrupt, and hard drives go without warning. It's important to have a backup plan so you can restore your website quickly if something goes wrong.

The easiest way to backup a MySQL database is to use the mysqldump program, which is included with MySQL server. The mysqldump program allows you to dump a database or table to an SQL file which can be quickly restored using the MySQL command line client. You can ensure your backup is executed on a regular basis using the crontab.

Here is a sample shell script for backing up a MySQL database:

#!/bin/sh

DATE=`date +%Y-%m-%d`
cd /PATH_TO_BACKUP/db_backup
mkdir $DATE
/usr/local/mysql/bin/mysqldump -u root DATABASENAME > /PATH_TO_BACKUP/db_backup/$DATE/DATABASENAME.sql
gzip $DATE/DATABASENAME.sql

The first line stores the current date as a string of the form YYYY-MM-DD, the next two lines change to the directory where you want the backup to be stored and creates a folder named the current date. The next line creates the actual backup using mysqldump, using the root@localhost account. The final line compresses the backup using the gzip utility, this is optional, but it is a good idea if you have a large database.

You can add this script to your crontab and have it execute daily by first typing:

sudo crontab -e

Then adding the following line into your crontab:

1 0 * * * sh /PATH_TO_BACKUP_SCRIPT/backup_mysql.sh

This will execute the script at one minute past midnight every night, but you can easily change this to suit your needs.

We can easily restore from our backup in a few easy steps. First open Terminal and navigate to the folder where our backup is stored. Then type:

gunzip -c DATABASENAME.sql.gz | mysql -u root DATABASENAME

This will decompress our backup, recreate the table structure and import all the data that was stored in the tables. Make sure you have created the database in MySQL prior attempting to restore.

Wednesday, June 29, 2011

Change Your Bash Prompt

The Bash command prompt can easily be changed by modifying the value of the PS1 environment variable. For example: PS1='yes master?> ' will change your command prompt in terminal to "yes master?> ". If you want your command prompt change to become permanent add it to your .bash_profile or .profile file in your home directory.

In addition to changing your bash profile to a simple string of text there are a number of special characters that can be used. The special characters can be used to add things like the current working directory or the current time to your prompt. Below is a list of these special characters taken from the bash manual:

\a A bell character.
\d The date, in "Weekday Month Date" format (e.g., "Tue May 26").
\D{format} The format is passed to strftime(3) and the result is inserted into the prompt string; an empty format results in a locale-specific time representation. The braces are required.
\e An escape character.
\h The hostname, up to the first `.'.
\H The hostname.
\j The number of jobs currently managed by the shell.
\l The basename of the shell's terminal device name.
\n A newline.
\r A carriage return.
\s The name of the shell, the basename of $0 (the portion following the final slash).
\t The time, in 24-hour HH:MM:SS format.
\T The time, in 12-hour HH:MM:SS format.
\@ The time, in 12-hour am/pm format.
\A The time, in 24-hour HH:MM format.
\u The username of the current user.
\v The version of Bash (e.g., 2.00)
\V The release of Bash, version + patchlevel (e.g., 2.00.0)
\w The current working directory, with $HOME abbreviated with a tilde (uses the $PROMPT_DIRTRIM variable).
\W The basename of $PWD, with $HOME abbreviated with a tilde.
\! The history number of this command.
\# The command number of this command.
\$ If the effective uid is 0, #, otherwise $.
\nnn The character whose ASCII code is the octal value nnn.
\\ A backslash.
\[ Begin a sequence of non-printing characters. This could be used to embed a terminal control sequence into the prompt.
\] End a sequence of non-printing characters.

Friday, June 24, 2011

Fun With Speech Synthesis

This is a fun way to freak out anyone around a remote Mac using SSH and the builtin text to speech libraries in OS X. The idea is to SSH into a remote Mac and execute the say command, which will convert a string of text into speech. You can use this to "talk" to people around your remote Mac. For example:

say -v "Zarvox" "hello world"

Will speak the phrase "hello world", using the voice Zarvox. If you don't specify a voice the default from the System Preferences will be used. Here is a list of other voices you can use:

Alex
Bruce
Fred
Junior
Ralph
Agnes
Kathy
Princess
Vicki
Victoria
Albert
Bad News
Bahh
Bells
Boing
Bubbles
Cellos
Deranged
Good News
Hysterical
Pipe Organ
Trinoids
Whisper
Zarvox

On the off chance that the Mac you are attempting to have speak has its volume turned down or is muted, you can also turn the volume up using the following command:

sudo osascript -e "set Volume 10"

This will set the system volume to maximum to ensure that any bystanders can hear your Mac speak. Setting the volume does however require the root password.

Monday, June 13, 2011

Programmatically Calculate Battery Charge

This is a cool way to determine what the charge of your battery is on a Mac laptop using Perl. Basically we execute the command ioreg -l in a shell and filter out all the results except MaxCapacity and CurrentCapacity, then we use regular expressions to parse out just the values. From there it's just a matter of calculating what percentage current capacity is of the max capacity and printing out the results.

#!/usr/bin/perl -w

my $MaxCapacity = `ioreg -l | grep 'MaxCapacity'`;
my $CurrentCapacity = `ioreg -l | grep 'CurrentCapacity'`;

$MaxCapacity =~ /(\d+)/;
$MaxCapacity = $1;

$CurrentCapacity =~ /(\d+)/;
$CurrentCapacity = $1;

printf("Battery Charge: %d %%" . "\n", (($CurrentCapacity / $MaxCapacity) * 100));

Executing the script produces something similar to:

Battery Charge: 90 %

If you execute this on a Mac that doesn't have a battery you will probably get a division by zero error.