What we'd like to do is have a quick way of sending text to the clipboard from terminal in linux. We can accomplish this with pipes and xclip. We'll install and configure xclip and then review the proper usage.

First we install xclip:

sudo apt-get install xclip

Next we want to configure an alias for xclip so that the arguments "-selection c" are used every time we call xclip. This ensures that the text is piped (copied) into the correct clipboard. This command will place the alias specification into the .bashrc file in our home directory.

echo "alias xclip=\"xclip -selection c\"" >> ~/.bashrc

Now we need to load our new .bashrc settings into the current window or open a new window.

source ~/.bashrc

Now we can use xclip as follows:

uptime | xclip

In my case I like being able to copy my public keys directly from file into github, so I use it like so:

cat ~/.ssh/id_rsa.pub | xclip

I'm a huge GNU/Linux fan and I like to think of myself as a FOSS advocate. So I chose an image of Tux to emblazon on my new credit card. There is some opaque process for determining which images can be used and which cannot, due to licensing issues. Unfortunately my image was flagged and denied, falling under "Celebrities such as actors, musicians, athletes, or cartoons." Now certainly Tux may be a celebrity, but that doesn't mean I can't use his glorious image! I mean, look at that mug!

Tux Credit Card

So not wanting to give up, I call in to appeal the decision. That's when things got funny:

Me: The image on the card is a cartoon penguin named Tux. Not like a cartoon you'd see on television though. He is the Linux mascot. Are you familiar with Linux?

Capital One CS: No response.

Me: Linux is a free, open source operating system for your computer. It is free to use, modify, share or sell. The image is free to use. I know it can be a funny concept for some people.

Capital One CS: Ok, and the organization is?

Me: ... There is no organization, Linux can be freely downloaded, used and modified by anyone, no one necessarily owns or controls it.

Capital One CS: And this is legal?

Me: *chuckles* Yes, it certainly is.

How about that? I've heard of people receiving this exact response before, but it is absolutely stunning to hear it myself. What does that say about our culture? Especially the culture in technology and software. It is certainly disappointing, but I will admit, there is a part of me that feels a glowing pride, knowing that Linux is so awesome, so mind bending to the common person, that hell, it might not even be legal. These days, let's ensure that it remains that way.

In short, the published Vendor ID for Motorola is not correct for the Motorola Triumph. Instead of 22b8, use 0489. When we connect our android device to the computer via USB for development purposes, we have to set a UDev rule which specifies how the system should be allowed to access that device. For this purpose we can refer to the Android Developer Docs. These docs give instructions for Ubuntu users. You need to make sure you're using the correct location for the rules file for your distribution. You can can see at the arch wiki, the location for udev rules is /etc/udev/rules.d/.

So to enable our Motorola Triumph android phone for development we must add the following to /etc/udev/rules.d/51-android.rules (again, check for your distribution's docs for the correct udev rules location)

SUBSYSTEM=="usb", ATTR{idVendor}=="0489", MODE="0666", GROUP="plugdev"

Once you save this file UDev should automatically load in your new rule, but you will have to unplug and reconnect your phone in order for the new rule to take effect.

Now browse to the platform tools folder of your sdk (In my case /opt/android-sdk/platform-tools/) and run adb to ensure your device is properly recognized, like so:

$ ./adb devices
List of devices attached
FD1M1019202100 device

Without the proper UDev rule, your Triumph will not be mounted with the correct permissions and neither your nor your Eclipse SDK will be able to access your phone properly. Running adb without the proper UDev rule will yield something like this:

$ ./adb devices
List of devices attached
???????????? no permissions

In order to determine the vendor id and product id of a phone, connect it to your computer (the previously mentioned UDev rules do not have to be in place), and run lsusb and find your phone amongst the devices listed.

$ lsusb
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 004 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 002 Device 002: ID 0bda:0158 Realtek Semiconductor Corp. USB 2.0 multicard reader
Bus 002 Device 003: ID 5986:01a6 Acer, Inc Lenovo Integrated Webcam
Bus 001 Device 016: ID 0489:c001 Foxconn / Hon Hai

In this case we're interested in the last one, named "Foxconn / Hon Hai". The Vendor ID and Product ID directly precede the name and are separated by a colon. For example, in the case of this particular Motorola Triumph, the Vendor ID is 0489, and the Product ID is c001. To save yourself time and frustration, take a moment to run this command when you're creating your UDev rules to ensure you have the proper ID's for your particular device.

Spotify has a great linux client but I had trouble getting Spotify playlist URLs to load properly. When you a click a spotify URL in your browser it utilizes xdg-open to determine which application should be launched. I'm running Ubuntu 11.04 with Gnome 3, and the following solution worked well for me and is quite elegant.

Enter the following into the file /usr/share/applications/spotify-url.desktop

[Desktop Entry]
Name=Spotify
GenericName=Spotify
Comment=Listen to music using Spotify
Icon=spotify-linux-512x512
TryExec=spotify
Exec=spotify -uri %u
Terminal=false
Type=Application
Categories=Qt;AudioVideo
MimeType=x-scheme-handler/spotify
NoDisplay=true

Then run the following command to update your desktop database to enable the new command. If successful this command will return silently, without any error or success message.

sudo update-desktop-database

Spotify links should now work! Have a better solution? Having trouble finding a solution for your particular setup, let me know.

In the new gnome-shell, otherwise known as Gnome 3, there is an accessibility menu called "Universal Access" that cannot be removed by any apparent means. Fortunately it can easily be removed, hidden, or disabled by editing a file and restarting the shell. This method works for gnome-shell version 3.0 (this reportedly works in Gnome 3.2 as well), it may or may not work in future versions.

Edit the file /usr/share/gnome-shell/js/ui/panel.js

Look for the following line, (line 38 in my case):

'a11y': imports.ui.status.accessibility.ATIndicator,

Comment out this line like so:

//'a11y': imports.ui.status.accessibility.ATIndicator,

Then restart gnome-shell by typing Alt-F2 to run command, enter "r" without the quotes, and hit enter. This will quickly restart the shell and you should find that the Universal Access menu no longer appears. If you should find a use for it in the future, simply un-comment the lines found in /usr/share/gnome-shell/js/ui/panel.js

Thanks to the endlessly helpful folks who maintain ArchWiki for this tip.

This is a firefox extension which allows you to add, modify, remove and disable keyboard shortcuts for Firefox. We're going to use this to disable the pesky shortcut for quitting firefox which is Ctrl-Q. Ctrl-Q is right next to Ctrl-W which is the handy shortcut for closing tabs, and if you hit it by mistake your entire session will be lost; sometimes it vanishes so quickly you don't even know what hit you.

Simply install the extension, restart Firefox, and then open Preferences for keyconfig in the Add-ons section. Then scroll down and highlight the shortcut for Quit and click disable. Voila, no more Ctrl-Q rage.

This extension was created by dorando, and can be found here: http://forums.mozillazine.org/viewtopic.php?t=72994 and here: http://mozilla.dorando.at

According to the forum post linked above, you can support the creator of this extension by donating something towards his hosting bill here: http://www.dreamhost.com/donate.cgi?id=3048

Since this extensions works so well for many people and the only trace of it seems to be a forum post, I've decided to host a mirror of it on my server, just in case. You can find that here: http://conjurecode.com/keyconfig.xpi

Let's using SSH port forwarding to tunnel a service from a remote server to our local machine. For example, many servers restrict mysql connections to localhost only. Using this technique we can tunnel our mysql connection through the remote machine transparently and securely. Let's set up our example. We have an instance of MySQL running at mysql.remoteserver.com on the default port of 3306. To make things interesting (and perhaps easier to follow), we're going to assume that you're also running an instance of MySQL on your local machine on the same port. So, let's tunnel the mysql connection from the remote server to our local machine on port 3307 so there are no conflicts.

ssh -L 3307:127.0.0.1:3306 user@mysql.remoteserver.com -N

If you're not using public key authentication, you will be prompted for a password. By specifying the -N option, we suppress opening a shell session and your command prompt will merely hang after you've entered your password. This can be safely omitted if you like, and a shell session will be opened for you. You can read more about the ssh command at it's man page.

To connect to our MySQL server, we need to specify our local address and port (Note: Using "localhost" will NOT work in this case, make sure to 127.0.0.1), and the login information for the instance of MySQL on our remote server. In Python you might use the following:

db = MySQLdb.connect(host='127.0.0.1', port=3307, user='myusername', passwd='mypassword', db='databasename')

We're going to walk through the process of creating a status indicator applet for the latest version of Ubuntu running Unity. In this example we're going to create a basic new mail indicator which works with GMail. This will give you a solid grounding in the basic structure of an applet while providing a real-world (albeit simplistic) example that you can easily extend.

Let's go through the final script piece by piece, first our header:

#!/usr/bin/env python

import sys
import gtk
import appindicator

import imaplib
import re

PING_FREQUENCY = 60

The first line instructs the system to find the current environment's version of python and use it to run this file. The first three imports are probably going to be used in every indicator you use. sys is used so we can offer a "Quit" option, GTK drives the interface, and appindicator provides Unity-specific code for creating indicator applets. The last two includes are required for this indicator's specific functionality, checking GMail. Finally we have one application wide constant which dictates how often we should ping (or check) GMail's servers for new mail, in seconds.

class CheckGMail:
    def __init__(self):
        self.ind = appindicator.Indicator("debian-doc-menu",
                                           "indicator-messages",
                                           appindicator.CATEGORY_APPLICATION_STATUS)
        self.ind.set_status(appindicator.STATUS_ACTIVE)
        self.ind.set_attention_icon("new-messages-red")

        self.menu_setup()
        self.ind.set_menu(self.menu)

Next we create a class called CheckGMail which will hold all of our indicator's functionality. To initialize our class first we create the variable "ind" which holds an Indicator object. According to the API this constructor takes 3 (or 4) arguments, a unique id for our indicator, an icon name, and an indicator category.

We set an initial status for our indicator with ind.set_status and then define the icon to use when our indicator requires attention (in this case when we have new mail waiting). Then we call our custom menu_setup() function (which we haven't defined yet), and then the set_menu() function on the Indicator object which takes a GTK menu as an argument and attaches it to our indicator.

def menu_setup(self):
        self.menu = gtk.Menu()

        self.quit_item = gtk.MenuItem("Quit")
        self.quit_item.connect("activate", self.quit)
        self.quit_item.show()
        self.menu.append(self.quit_item)

Here is the aforementioned menu_setup() function. Here we create a new GTK Menu and then define a single menu item called "quit_item". We define the text label for the menu, and then connect it with an action. We instruct the menu item to launch the quit() function when the item is "activated" (clicked) and then add the item to our menu variable.

def main(self):
        self.check_mail()
        gtk.timeout_add(PING_FREQUENCY * 1000, self.check_mail)
        gtk.main()

The main() function constitutes our primary program loop. When our indicator is first loaded we run this function. First it runs the check_mail() function (which has yet to be defined), and then creates a timeout. This causes our program to wait the specified amount of time and then run the given callback function, which is in this case, check_mail(). Then finally we run our main() function again, putting our program into an infinite loop, since we'd like our applet to continually check mail as long as it's running.

def quit(self, widget):
        sys.exit(0)

Here we define the quit() function which we referenced in menu_setup(). This function makes a call to sys.exit which will cause our application to stop running. At this point the process will stop and our indicator applet will disappear.

def check_mail(self):
        messages, unread = self.gmail_checker('myaddress@gmail.com','mypassword')
        if unread > 0:
            self.ind.set_status(appindicator.STATUS_ATTENTION)
        else:
            self.ind.set_status(appindicator.STATUS_ACTIVE)
        return True

This is the core functionality of this specific indicator applet. We're calling the function gmail_checker() which we've borrowed from Martin Brook for the purposes of this example. We load in the number of total messages and the number of unread messages from the provided GMail account. (I should note, this will work with Google Apps account, you are not required to have a @gmail.com address). If there is more than one unread messages found, we change the status of our indicator to STATUS_ATTENTION, which is this case turns our icon red, notifying you of new messages.

def gmail_checker(self, username, password):
        i = imaplib.IMAP4_SSL('imap.gmail.com')
        try:
            i.login(username, password)
            x, y = i.status('INBOX', '(MESSAGES UNSEEN)')
            messages = int(re.search('MESSAGES\s+(\d+)', y[0]).group(1))
            unseen = int(re.search('UNSEEN\s+(\d+)', y[0]).group(1))
            return (messages, unseen)
        except:
            return False, 0

This is the final function of our indicator applet class, and it is the code that we borrowed from Martin. It creates an SSL encrypted connection to an IMAP server, in this case GMail, and will attempt to determine how many total and unread messages are available.

if __name__ == "__main__":
    indicator = CheckGMail()
    indicator.main()

We come a the close of our file with some basic python initialization. This special block will be run when our file is called directly. It instantiated an object of the CheckGMail class and then runs the main() function, which set's everything off for us.

Here is our entire file:

#!/usr/bin/env python

import sys
import gtk
import appindicator

import imaplib
import re

PING_FREQUENCY = 10 # seconds

class CheckGMail:
    def __init__(self):
        self.ind = appindicator.Indicator("new-gmail-indicator",
                                           "indicator-messages",
                                           appindicator.CATEGORY_APPLICATION_STATUS)
        self.ind.set_status(appindicator.STATUS_ACTIVE)
        self.ind.set_attention_icon("new-messages-red")

        self.menu_setup()
        self.ind.set_menu(self.menu)

    def menu_setup(self):
        self.menu = gtk.Menu()

        self.quit_item = gtk.MenuItem("Quit")
        self.quit_item.connect("activate", self.quit)
        self.quit_item.show()
        self.menu.append(self.quit_item)

    def main(self):
        self.check_mail()
        gtk.timeout_add(PING_FREQUENCY * 1000, self.check_mail)
        gtk.main()

    def quit(self, widget):
        sys.exit(0)

    def check_mail(self):
        messages, unread = self.gmail_checker('myaddress@gmail.com','mypassword')
        if unread > 0:
            self.ind.set_status(appindicator.STATUS_ATTENTION)
        else:
            self.ind.set_status(appindicator.STATUS_ACTIVE)
        return True

    def gmail_checker(self, username, password):
        i = imaplib.IMAP4_SSL('imap.gmail.com')
        try:
            i.login(username, password)
            x, y = i.status('INBOX', '(MESSAGES UNSEEN)')
            messages = int(re.search('MESSAGES\s+(\d+)', y[0]).group(1))
            unseen = int(re.search('UNSEEN\s+(\d+)', y[0]).group(1))
            return (messages, unseen)
        except:
            return False, 0

if __name__ == "__main__":
    indicator = CheckGMail()
    indicator.main()

Now we just need to mark the file as executable and run it to see the results.

chmod +x check_gmail.py
./check_gmail.py

Now if you have a bunch of unread messages in your gmail account it will always be red, so you'll have to extend this example if you want to make the new message checking more intelligent. We've learned how to setup a basic indicator applet with it's own menu and icon, and give it a useful piece of functionality. You could easily replace the check_email() function with almost anything else you could program in python normally. Hope this helps to get you started with creating indicators, if you have any questions or comments, please let me know!

Let's say we've got a left over Time Machine backup disk from our old, sacrilegious OSX install, and we'd like to keep those backups but also shrink the partition down and recover some usable space. Here is an easy way to shrink an HFS+ partition in linux. Please use common sense and make sure that you have another backup of this data before attempting this.

Note to OSX/Time Machine users: I've had some people end up here looking for a way to resize their Time Machine partition. You can easily follow this article with an Ubuntu Live CD.

First plug in the drive and determine which device it is on. In my case it is /dev/sdb. The first thing we need to do is unmount the partition we're looking to resize. You can figure out which partition that is by running parted, like so:

sudo parted /dev/sdb

You will be greeted with a "(parted)" prompt. Enter "print" to view details of the partitions on the drive. In my case, I want to resize partition 2, so we'll "quit" out of parted and unmount partition 2.

sudo umount /dev/sdb2

Now let's go back into parted and resize our partition. We're going to enter into parted, select the partition we'd like to resize, and then we'll be prompted for a start and end to the partition. In my case, I had about 512Gb of data on my 1TB drive. I also had a small partition before this one, which is why it prompted me to start my partition at 210MB. You should probably select whatever it suggests as the start (by simply not entering anything, the item in brackets is the proposed default), and then selecting an end which is a little larger than your usage. I chose 550GB for my end, just to be safe. Below is an output of the whole process:

Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) print                                                            
Model: WD My Passport 071A (scsi)
Disk /dev/sdb: 1000GB
Sector size (logical/physical): 512B/512B
Partition Table: gpt

Number  Start   End     Size    File system  Name                  Flags
 1      20.5kB  210MB   210MB   fat32        EFI System Partition  boot
 2      210MB   1000GB  1000GB  hfsx         Time Machine Backups

(parted) resize                                                          
WARNING: you are attempting to use parted to operate on (resize) a file system.
parted's file system manipulation code is not as robust as what you'll find in
dedicated, file-system-specific packages like e2fsprogs.  We recommend
you use parted only to manipulate partition tables, whenever possible.
Support for performing most operations on most types of file systems
will be removed in an upcoming release.
Partition number? 2                                                      
Start?  [210MB]?                                                          
End?  [1000GB]? 550GB                                                    
(parted) quit

After you specify an end point and hit enter, the program will go to work and may take some time to finish. I have a relatively fast machine and I believe the drive is 7200rpm. It took only a few minutes to complete. A successful resize should bring you back to the (parted) prompt. Then just enter "quit" to exit parted. At this point I opened gparted and used it's visual editor to create a file system on the newly created partition. When you plug in the drive you should now see the old and new partitions and have access to all the files on both. Again, please, be smart, back up your data.

When we're browsing the web from a public place we'd like to ensure all our traffic travels over an encrypted channel. W can accomplish this easily with an SSH based proxy. You're going to need a shell (SSH) account on a remote server. The following process will work on *nix and OSX and probably other systems as well. For windows you'll want to use something like PuTTY/Plink, but beyond that you're on your own.

Create a file in your home directory and name it whatever you like, I'm using tunnel.sh. In that file enter the following:

ssh user@server.com -p 22 -ND 8080

First of all, pay attention to case here, we're using a lower case -p to specify the remote port we're connecting on, and a capital -D to specify the local port to serve the proxy from. If you're connecting to your server via port 22 like the example you can actually leave it off, but I've included it in the example since many sysadmins use non-standard ports for ssh (and so should you, if possible). The -N is optional and signals SSH not to open a shell session, so after you've connected and provided a password, the command will simply sit there as if it were hanging, instead of providing you with a command prompt.

Let's flag our file as executable:

chmod +x tunnel.sh

Now we can run our file which will connect to your server and prompt you for your password. Once you enter your password it will simply sit there. You must keep this window open, so either minimize it or move it to a different desktop if you can. Now we have a SOCKS5 compatible port-forwarding proxy at our disposal. Normally when you make a request over the internet, it travels from your computer's network card to your local router and then to the internet in effectively plaintext. Anyone with the slightest inclination is able to view what sites you're visiting, and obtain your login information if it is not being transmitted in a secure fashion (including email, ftp, and many websites). You may have been following the whole firesheep fiasco.

Now that we have our SSH proxy running, we can tunnel all of our traffic through an SSH encrypted channel which effectively hides all of your internet traffic from curious/malicious users on your local network. In order to do this we have to tell our software to use the local proxy running on port 8080. For firefox I recommend foxyproxy. Most instant messengers allow you to use a proxy for a given account. In either case, you need to make sure that you use "localhost", port 8080, and check the options for SOCKS5 proxy. You can check that it works by checking your IP at http://checkip.dyndns.org before and after enabling the proxy.