Thursday 6 December 2012

Printing from the Linux command line

To print a file from the Linux command line, use the simple command:
 lpr FILENAME  
It's that easy!

I came across this while trying to print all pdf files in a directory. To do this, the simple bash script you need is:
 #!/bin/bash  
 for file in *.pdf; do  
   /usr/bin/lpr "$file"  
 done  

Save this into a file - I called mine print-all-pdfs.sh. Then make it executable using
 chmod +x print-all-pdfs.sh  

Copy it to the directory you want to run it in, then execute with
 ./print-all-pdfs.sh  

For an additional challenge, can anyone adapt the above script to print all .pdfs from directories recursively? Answers in the comments below!


[References] Bash script adapted from a LinuxForums post.

Wednesday 5 December 2012

Notes on using Heroku

These are a few common things I find myself looking up when working with Heroku - I update this post if I find myself repeated searching for how to do the same tasks.

Running commands from a folder not linked to Heroku

Simply append --app APP_NAME to any relevant Heroku command:
HEROKU_COMMAND --app APP_NAME  

Deployment

If trying to push to Heroku:
 git push heroku master  
but get a publickey error:
 Permission denied (publickey).  
 fatal: The remote end hung up unexpectedly  
You need to add your public key to Heroku.
 heroku keys:add path_to_publickey  
If you don't have a public key, Heroku can prompt and generate one for you - simply use the command:
 heroku keys:add  

Resetting the application database

 heroku pg:reset DATABASE_URL  
To reset the database without a validation prompt, use:
 heroku pg:reset DATABASE_URL --confirm APP_NAME  

Rake

To run a rake task on Heroku, create the task in app/lib/tasks (Rails), test locally then deploy. To run, use:
 heroku run rake TASK_NAME


If you have any useful commands you regularly use while working with Heroku, let me know in the comments below!

Tuesday 4 December 2012

How to add a menu item for SPSS in Linux

I keep forgetting where SPSS installs itself - this .desktop file may be of help to others too.

Create .desktop file for SPSS:
 sudo leafpad /usr/share/applications/spss.desktop  

Add this text to that file:
 [Desktop Entry]  
 Name=SPSS  
 GenericName=SPSS  
 Comment=Statistics program  
 Exec=/opt/IBM/SPSS/Statistics/19/bin/stats  
 Icon=gnome-monitor  
 Terminal=false  
 Type=Application  
 Categories=Application;Education;  

Save, then log out and back in again, or restart the desktop using
 xfdesktop --reload  
if using an XFCE desktop.

 SPSS will now be available under Applications -> Education.

Monday 26 November 2012

Find all files and move to a target directory from the Linux command line

For this example, we're going to be moving all .mp3 files from the subdirectories of the current directory into current directory.

To do this, we need to combine two different commands. To find all the files in the current directory and its subdirectories, we use the find command:
 find -name \*.mp3  

The \ escapes the *, so it's interpreted as a wild card on the command line. The -name argument allows us to check only the file names.

To move files around on the command line, we use the mv command, and for our example, we add the -t argument, which lets us define the target directory:
 mv -t <target-directory> <file-to-move>
where target-directory is where we want to move the file to, and file-to-move is the file we want to move.

With a bit of command-line magic, we can combine these commands using the -exec switch on find, to give us our final command:
 find -name \*.mp3 -exec mv -t . {} \+  
-exec takes the command we want to execute, and {} \+ appends each find result to the command, which in our case is mv. So the above line will find all files end in .mp3 and move them to the current directory.

Monday 19 November 2012

Fail Fast - A Lesson In Not Wasting Time


fail fast




Around a year ago, I had an idea for a small browser based application that had the potential to smooth and streamline a workflow within universities around the country. The concept was simple and wouldn't have taken a huge amount of time to develop. Given my position working in a university setting, I had the ideal environment to test and prototype, but due to constraints on my time I didn't take the concept any further.

Fast forward to last week. I'd finally found the inspiration, motivation, and time to solidify and explore this idea. It took me less than an hour to map out the specifics of my concept, and email a few academic contacts to see what they thought of the idea. Feedback was positive; I'd found a niche. Unfortunately, the very same week, the university have announced that they are trialling a new, much larger system which implements a substantial feature list, and includes the subset of functionality I was aiming to provide.

Why do I tell you this story? Well, there's lessons here. Despite my initial disappointment, this is a perfect example of failing fast and learning quickly. While there was a part of me that felt I shouldn't release my idea into the world until I had built the application and had a full, perfect implementation to demonstrate, had I done this I would have committed hours, days, or weeks of my time to building a system that had zero chance of ever being used. Here's what this experience taught me:
  1. Talk about your ideas. It's natural to feel protective of your concepts, and worry that they might be stolen or plagiarised (or laughed at - see 3.). In my experience, it's highly unlikely that they will, and if they do, talking to enough people makes it clear where the idea originated. The knowledge and insights you stand to gain from sharing knowledge and ideas far outweigh any perceived risks of collaboration.
  2. Act Early. If you have an idea, or discover a niche you could occupy, act on it early. If I'd had the confidence to explore my concept a year earlier, I'd have been first to market, so to speak, and would have been in a much better position to compete with the larger system that has come along now. Who knows, I might have gained enough traction to have become that larger system.
  3. Fight your inner perfectionism. The world is imperfect, and so your contributions to it can be too. Don't spend forever perfecting designs, ideas and implementations. However scary it might be, put yourself and your ideas out there, and you'll be pleasantly surprised at the what happens.
So there we have it, it took me less than a day to establish that, despite a market need, my good idea wasn't commercially viable in current circumstances. My time is now free to explore my next project. Next time you find yourself thinking "maybe there's a need for this... one day I'll have the time..." - take the time to explore, find feedback and fail fast or fly.


[Image credit] http://thumannresources.files.wordpress.com

Friday 16 November 2012

Finding out what Matlab tooboxes are available for use

Finding out what toolboxes are available to a Matlab installation is actually relatively simple - it's just a case of typing:
 ver  

at the Matlab prompt.

On it's own, however, this function doesn't supply much useful information, as it doesn't tell you what licences are available to the installation, and hence which toolboxes you can actually use (which is probably what you care about when you're trying to find out what toolboxes are available).

It is possible to find out what licenses are available to the installation, however it takes a bit more work.

First, we need to define a feature string, which is just a list of all the toolboxes potentially installed:
 featureStr = {'Aerospace_Blockset'; ...  
        'Aerospace_Toolbox'; ...  
        'Bioinformatics_Toolbox'; ...  
        'Communication_Blocks'; ...  
        'Communication_Toolbox'; ...  
        'Compiler'; ...  
        'Control_Toolbox'; ...  
        'Curve_Fitting_Toolbox'; ...  
        'Data_Acq_Toolbox'; ...  
        'Database_Toolbox'; ...  
        'Datafeed_Toolbox'; ...  
        'Dial_and_Gauge_Blocks'; ...  
        'Distrib_Computing_Toolbox'; ...  
        'Econometrics_Toolbox'; ...  
        'EDA_Simulator_Link_DS'; ...  
        'Embedded_Target_c166'; ...  
        'Embedded_Target_c2000'; ...  
        'Embedded_Target_c6000'; ...  
        'Embedded_Target_MPC555'; ...  
        'Excel_Link'; ...  
        'Filter_Design_HDL_Coder'; ...  
        'Filter_Design_Toolbox'; ...  
        'Fin_Derivatives_Toolbox'; ...  
        'Financial_Toolbox'; ...  
        'Fixed_Income_Toolbox'; ...  
        'Fixed_Point_Toolbox'; ...  
        'Fixed-Point_Blocks'; ...  
        'Fuzzy_Toolbox'; ...  
        'GADS_Toolbox'; ...  
        'IDE_Link_MU'; ...  
        'Identification_Toolbox'; ...  
        'Image_Acquisition_Toolbox'; ...  
        'Image_Toolbox'; ...  
        'Instr_Control_Toolbox'; ...  
        'Link_for_Incisive'; ...  
        'Link_for_ModelSim'; ...  
        'Link_for_Tasking'; ...  
        'Link_for_VisualDSP'; ...  
        'MAP_Toolbox'; ...  
        'MATLAB'; ...  
        'MATLAB_Builder_for_dot_Net'; ...  
        'MATLAB_Builder_for_Java'; ...  
        'MATLAB_Distrib_Comp_Engine'; ...  
        'MATLAB_Excel_Builder'; ...  
        'MATLAB_Link_for_CCS'; ...  
        'MATLAB_Report_Gen'; ...  
        'MBC_Toolbox'; ...  
        'MPC_Toolbox'; ...  
        'NCD_Toolbox'; ...  
        'Neural_Network_Toolbox'; ...  
        'OPC_Toolbox'; ...  
        'Optimization_Toolbox'; ...  
        'PDE_Toolbox'; ...  
        'Power_System_Blocks'; ...  
        'Real-Time_Win_Target'; ...  
        'Real-Time_Workshop'; ...  
        'RF_Blockset'; ...  
        'RF_Toolbox'; ...  
        'Robust_Toolbox'; ...  
        'RTW_Embedded_Coder'; ...  
        'Signal_Blocks'; ...  
        'Signal_Toolbox'; ...  
        'SimBiology'; ...  
        'SimDriveline'; ...  
        'SimElectronics'; ...  
        'SimEvents'; ...  
        'SimHydraulics'; ...  
        'SimMechanics'; ...  
        'Simscape'; ...  
        'SIMULINK'; ...  
        'Simulink_Control_Design'; ...  
        'Simulink_Design_Verifier'; ...  
        'Simulink_HDL_Coder'; ...  
        'Simulink_Param_Estimation'; ...  
        'SIMULINK_Report_Gen'; ...  
        'SL_Verification_Validation'; ...  
        'Spline_Toolbox'; ...  
        'Stateflow'; ...  
        'Stateflow_Coder'; ...  
        'Statistics_Toolbox'; ...  
        'Symbolic_Toolbox'; ...  
        'SystemTest'; ...  
        'Video_and_Image_Blockset'; ...  
        'Virtual_Reality_Toolbox'; ...  
        'Wavelet_Toolbox'; ...  
        'XPC_Embedded_Option'; ...  
        'XPC_Target'};  

That's a lot of typing, so I'd just copy and paste from above, into your Matlab prompt.

Next, we want to check that licenses exist for each of the items in the above list:
 index = cellfun(@(f) license('test',f),featureStr);  
 availableFeatures = featureStr(logical(index));  

Licences that exist are now stored in availableFeatures, so typing that at the prompt gives us a list of licences that are available to the installation:
 availableFeatures  

To see if a single license exists, we can also simply supply license('test',<feature_name>) with the single feature string we care about. For example:
 license('test', 'Neural_Network_Toolbox')  

This is normally as much information as we need, but if we need to know if a licence is available to checkout at the present time, we can continue as below.

NB: Using license('checkout',<license>), as described below, is not normally a good idea when using network licences, as the license will not be released until Matlab is shut down. Usually, licenses are checked out automatically, as and when they are required by a toolbox.

So far, we've found out whether or not a license exists, but not if one is presently available for us to check out. To actually checkout a license, such as the Signal Toolbox, we can do:
 license('checkout','Signal_Toolbox')  
Where Signal_Toolbox comes for the feature string list at the top of this post.

If Matlab returns:
 ans = 1  

Then the license checkout was successful. We can also look at the licenses we currently have checked out out using:
 license('inuse')  

As usual, I hope this has been helpful, and feel free to add any notes or observations in the comments below.

References:

  1. Matlab documentation: license()
  2. Matlab newsgroup: License checking
  3. StackOverflow: How would one check for installed MATLAB toolboxes in a script/function?


Tuesday 6 November 2012

Fixing Print Screen in Linux Mint XFCE

To enable Print Screen key functionality in Linux Mint XFCE:

Ensure xfce4-screenshooter is installed:
 sudo apt-get install xfce4-screenshooter  

Then, in the Menu, go to Settings -> Keyboard then Application Shortcuts -> Add. In the Command field, enter xfce4-screenshooter and then click OK, before pressing the Print Screen key on the keyboard, to set that shortcut.

Remote Desktop in Ubuntu 12.04

This is the first post in a three part series exploring Ubuntu-based remote desktop options. See posts two and three for further exploration and conclusions.

In my opinion, both of the mainstream remote desktop/windowing approaches in Linux do not compare with the ease of use, and the speed of Windows remote desktop. VNC is inherently insecure, and setting up VNC over an SSH tunnel isn't the most user friendly of experiences. X forwarding over SSH is better, but in my experience there's simply too much latency when using it outside a LAN. Enter NX, or NoMachine - the only Linux remote desktop solution I've come across used that isn't a pain to get up and running, and is more than fast enough to be useable.

Here's what you need to do to get going with NoMachine. Below, target machine refers to the machine you want to connect to, and client machine refers to the machine you are connecting from.

On the target machine:

If it's not already installed, add openssh server to your machine:
 sudo apt-get install openssh-server  

Add the FreeNX repository to your system using:
 sudo add-apt-repository ppa:freenx-team  

Then install FreeNX with:
 sudo apt-get update  
 sudo apt-get install freenx  

As Unity3D is too heavy to use over a WAN connection, allow fallback to a gnome session:
 sudo apt-get install gnome-session-fallback  

On the client machine:
Use the NX client of your choice - personally I used Remmina, with the Remmina NX plugin: Update: While Remmina works well, the offical NX client gives a lot more options - see below for more.
 sudo apt-get install remmina
 sudo apt-get install remmina-plugin-nx

Start Remmina, and create a new connection. You should now be able to choose to connect using the NX protocol, as seen below.

Enter the target machine's IP address into the server field, and the username and password of the user account you wish to connect to. Hit connect and after a few moments your remote desktop will open.


You can also use the official NX client, and if you're connecting from Windows or Mac, that's probably easiest. For Linux, the official client download and install instructions are currently here.


I've not yet had the chance to experiment, but it may be possible to run the NX client from a different desktop on the target machine - if so, then this would make NX a complete, drop in replacement for Windows remote desktop, as far as I can see. Which is no bad thing, as other than the obvious proprietary graphics issues Linux can suffer from, a decent RDP implementation was the only only key feature I've noticeably missed since moving to Linux full-time (yes, there's X forwarding over SSH, but even with compression there's still too much lag to be usable over my connections). Update: It looks like the official NX client has a shadowing mode - again, I've not yet tested it, but it may be useful for the above.

Update Nov-16-2012: As noted in the comments, Cendio also offer a Linux remote desktop solution - after testing and comparing, my thoughts can be found in post two.


Monday 5 November 2012

Installing the latest version of R into Debian Stable

The R packages available in the Debian repository are are little out of date - to install the latest (stable) version we need to add a backports repository. Just follow the steps below!

Open the sources list with:
 sudo nano /etc/apt/sources.list  

Then add this line to the bottom of the file (use your favourite mirror if desired):
 deb http://cran.ma.imperial.ac.uk/bin/linux/debian squeeze-cran/  

The Debian backports are signed with the key of "Johannes Ranke (CRAN Debian archive) <jranke@uni-bremen.de>", with key ID 381BA480 . Import this using:
 sudo apt-key adv --keyserver subkeys.pgp.net --recv-key 381BA480  

Then, update the packages cache - this should complete without errors.
 sudo apt-get update  

Finally, install R and the R recommended packages using:
 sudo apt-get r-base r-recommended   

To check the version of R that is now installed, use:
 R --version  

To start R, simply type
 R  

at a command prompt. As usual, let me know of any issues or problems in the comments below.

Thursday 27 September 2012

Problems with R and RGtk2

I ran across this issue while installing Rattle, a data mining library for the statistical programming language R, on to a Debian system. When installing the package RGtk2, seeing the below error means that your GTK version is not the version required by RGtk2.
 * installing *source* package ‘RGtk2’ ...  
 ** package ‘RGtk2’ successfully unpacked and MD5 sums checked  
 checking for pkg-config... /usr/bin/pkg-config  
 checking pkg-config is at least version 0.9.0... yes  
 checking for INTROSPECTION... no  
 checking for GTK... no  
 configure: error: GTK version 2.8.0 required  
 ERROR: configuration failed for package ‘RGtk2’  

The required version can be found in libgtk2.0-dev, so install this using your preferred package manager - for example using apt-get:
 sudo apt-get install libgtk2.0-dev    

Then reload R and:
 install.packages('RGtk2')  

Now, after the installation has finished, you should see:
 * DONE (RGtk2)  

As usual, let me know if it works for you in the comments below.

If you like this blog, and use R for statistical processing, you can help support my writing by purchasing a book from my bookstore. For both beginning and more advanced R users, I'd recommend Kenneth Knoblauch.

Thursday 20 September 2012

Install the latest version of R in Ubuntu

The R version in the Ubuntu repositories is not the latest, so here's how to install R into Ubuntu 12.04:

Add the SSL key and import into apt:
 gpg --keyserver keyserver.ubuntu.com --recv-key E084DAB9  
 gpg -a --export E084DAB9 | sudo apt-key add -  

Add the repository to your sources list, by doing:
 sudo nano /etc/apt/sources.list  

Then add this line to the bottom of the sources file:
 deb http://cran.ma.imperial.ac.uk/bin/linux/ubuntu precise/  

Then, to install the latest version of R, do:
 sudo apt-get update  
 sudo apt-get install r-base  

Hit yes at the prompts, and voila, the latest version of R is installed!

Monday 10 September 2012

Great gEdit Theme Repository

I'm a fan of light on dark backgrounds when writing or coding, and Githubber kalmi maintains a great collection of gEdit (the default text editor in Gnome) themes - they can be found here: https://github.com/kalmi/gedit-themes

To use, clone the repo into a temporary directory, using:
 git clone https://github.com/kalmi/gedit-themes.git 

Then copy them into a styles folder in the gEdit directory, using the install script from the repo:
 cd gedit-themes
 ./install.sh  

To use them, open gEdit, then go to Edit -> Preferences -> Fonts and Colours. The themes should now be available in the Colour Scheme scroll box.

Enjoy!

Thursday 19 July 2012

Mounting an executable CD Drive in Linux

I ran into the below problem while installing Matlab onto a Linux machine. Hopefully this will help someone else!

On most modern Linux systems, CD drives are automatically mounted. The problem comes when they are mounted without any exec permissions - this means that any scripts, etc on the CD, or .iso, will be unable to run. To resolve this, follow the steps below:
  1. Find the name of your mounted CD drive by using:
     mount  
    
  2. Then remount the device with the exec bit set:
     mount -o remount,exec $DEVICE
Where $DEVICE is the name of the CD drive.

You'll then be able to run all executables on the drive - in my case, the Matlab executable was then launched using the below commands:
 $ su  
 $ /path/to/mounted/cdrom/./install  

Remember to logout as root when the installer has finished!
 logout  

Wednesday 18 July 2012

Betty and George - an overview


This is the first in a series of posts detailing my latest hobby project. The bulk of the work was completed in under 10 hours, with minor styling tweaks taking a little longer to get right. The project is currently hosted here, and the source code is on Github here. As usual, please post any comments or opinions in the comments below, or tweet me directly @matalangilbert.

Introduction

Betty and George are Artificial Intelligence entities - they chat with each other in real time, and, somewhat incredibly in my opinion, make sense most of the time! They're sometimes witty, sometimes poignant, and sometimes inane, but they keep talking, no matter what!


Technical Overview

The application is split into two main parts. The backend is a Ruby program managing two Cleverbot instances (http://www.cleverbot.com), juggling responses between each instance. There's not too much to this, but I will go over the technical details in a future post.

Each conversational response is posted to a Rails application endpoint by the Ruby program, and then the front-end takes over. The frontend is backed by a Rails application, which receives data from the Ruby program, and displays it on the live site. There's a couple of neat techniques used on the main application page, which update the page in the background. The first is a background AJAX request, which hits the server every 5 seconds, retrieving new responses and adding them to the top of the scrolling conversation on the site. The second is an "Endless River of News" style endless scroll implementation. This invisibly loads more of the conversation as the user scrolls down the page, in much the same way as Twitter and other sites do. Individually, neither of these techniques are particularly new on their own, but combining them seamlessly was technically satisfying. I'll talk more about these techniques in a dedicated future post.


Hosting

At present, both the conversation program and the Rails application are hosted at Heroku. A future post will detail a few of the technical subtleties I discovered while deploying the live Betty and George website.

Now visit Betty and George!

OK, so this was just a brief overview of the Betty and George architecture - now go check them out, and let me know what you think in the comments below!


Monday 16 July 2012

Thursday 12 July 2012

Getting number of lines in all files in a directory - Unix

The bash command
 wc -l <file>
will print out the number of lines in <file>.

If you have a collection of files (.csv in the example below), and want to know how many rows are in each file, the command:
 for f in *.csv; do wc -l $f; done  
will print out a list of all the files ending in .csv, along with the number of lines in them.

To print the number of lines, without the filename, the cut command can be used, with the following parameters:
cut -d' ' -f1  

Combining them, we can use:
 for f in *.csv; do wc -l $f |cut -d' ' -f1; done  
to print out just the number of lines in each file ending in .csv in the directory.

Thursday 31 May 2012

Consolidating an online presence

I've recently spent some time consolidating my online presence - something I've been working towards for a while, but I've finally pulled a lot of my most active online hangouts (this blog, Twitter, Github), under the umbrella of Mat Alan Gilbert. I've felt it was important to amalgamate my profile into something more coherent, so that it's easier to track what's going on in my world at any particular time.

It's become clear however, that there's one incredibly important part of my life who isn't represented in my online presence nearly as much as she should be. Becky Prince, my wonderful fiancé, is a huge part of my life, and as such, I'm dedicating the first 1000 blog views (this milestone was passed a while ago, but it's still a nice achievement), and my 100th tweet to her. I can't wait to marry her in Minneapolis, and am looking forward to a life in the sun with her.

Becky, thank-you for all your love and support - my life is so much richer for having you in it.



And P.S. happy almost-anniversary!

Wednesday 16 May 2012

Visual Ruby and Glade: cannot create instance of abstract (non-instantiatable) type `GtkBox'

If you get the error:

GLib-GObject-WARNING **:cannot create instance of abstract (non-instantiatable) type `GtkBox'

When using Visual Ruby and/or Glade to design a Ruby-GNOME2 user interface, the reason is that the latest version of Glade (3.10) has dropped support for Gtk::VBox and Gtk::HBox - it replaces them both with Gtk::Box. This breaks Gtk::Builder. The solution is to use Glade 3.08, which can be installed (for Ubuntu, and Ubuntu based distributions such as Linux Mint) using:
 sudo apt-get install glade-gtk2=3.8.0-0ubuntu3  


To find the correct version/package name for your distribution, use:
 apt-cache showpkg glade-gtk2  

and find version 3.8.0.

If using Visual Ruby, be sure to update the Glade Command Line setting by going to Tools -> Settings and entering
 glade-gtk2  

in the Glade Command Line box.

Friday 11 May 2012

Connecting to a VPN from the command line in Linux Mint / Ubuntu

Set up the VPN using the Network Manager applet, then open a Terminal. The command to connect to a VPN is:
 nmcli con up uuid <your-uuid-here> 

To find out the UUID of the VPN connection, use:
 nmcli -p con list

The command to disconnect from a VPN is:
 nmcli con down uuid <your-uuid-here>

Fixing Hibernate Problems in Linux Mint Part II

My previous attempts to make hibernation work for my Linux Mint installation didn't entirely solve the problem. My system has been hanging far less than usual, but would still occasionally hang at the s2disk hibernating screen.

After a lot of reading, it seems to me that there's problem with the s2disk utility, and so I've worked around the problem using an older, more stable method of hibernation:
 sudo echo disk > /sys/power/state  

This will hibernate the machine, and resume the session when it is powered back up. It's not as fast as s2disk, and doesn't display any information while hibernating (it shows a black screen unless there are errors), but is far more stable, for my set up at least.

I put the command into a one line script, in /usr/bin/hib-script.sh, then added an entry in sudoers (see this post) to remove the requirement for a password to be entered. Finally, I added a launcher to Cairo-dock, so that now I have a consistent, stable hibernation function for my Linux Mint installation.


How to run a script requiring sudo without needing a password

To run a script that has a sudo command in it, without needing to enter a password whenever the script is executed, add an entry in sudoers.
First, open sudoers using visudo:
 sudo visudo  

Then add the following line to the bottom of the file:
 <user> ALL=NOPASSWD: <absolute_path_to_script_file>  

Where <user> is the user running the script, and <absolute_path_to_script_file> is...self explanatory :). Though I've found that the script needs to be placed in /usr/bin/ to for the entry in sudoers to be effective.

Save the changes to the file, and log in and out to enact the change. Now, when you sudo script, there will be no prompt for a password.

Monday 7 May 2012

Spell Checking a Latex Document using Aspell

Use:
 aspell --mode=tex check <filename>  
or

 aspell --mode=tex -c <filename>  

Where <filename> is the file to be spell checked.

Saturday 28 April 2012

Fixing Hibernate Problems in Linux Mint

Hibernate was working fairly inconsistently on my machine; sometimes it would work, and sometimes it would hang with s2disk pending onscreen. Google turns up a lot of Linux hibernate problems, below is how I resolved mine.

First, ensure you have more swap space than RAM (1.5 - 2x RAM as a guideline), using the command:
 swapon -s  

If you don't have enough space, follow the instructions here before continuing.

Once you are sure you have enough swap space, if hibernate still isn't working, install the powermanagement-interface package, using:
 sudo apt-get install powermanagement-interface  

This got hibernation working on my machine, I hope it helps you too.

Update: Make sure you check out Part II of this post, should this post not help you fully resolve your hibernate problems.

Friday 27 April 2012

Finding and killing a process in Linux

To find a process, use
 ps ux | grep <process_name>  

Where <process_name> is the name, or part of the name of the process you want to find.

Look up the process ID (the number in the output), and then use
 kill -9 <process_number>  

Where <process_number> is the process ID of the process you want to kill.

Thursday 26 April 2012

Increasing swap file size in Linux

If you need to increase your Linux swap space, but don't want to repartition your hard drives, you can use a swap file.

First, create an empty file, of the size you want.
 dd if=/dev/zero of=/mnt/my_swap bs=1M count=2048  

The above creates an empty file of size 2GB, called mnt/my_swap. To create a file of a different size, replace the 2048 with the size of swap file you require, in MB.

Next, format the file as swap space:
 mkswap /mnt/my_swap  

Then tell the operating system to begin using it:
 swapon /mnt/my_swap  

Finally, to persist the change, and ensure the OS uses the new swap file on every boot, open /etc/fstab and add the following line:
 /mnt/my_swap none swap sw 0 0  

To open /etc/fstab, you can use gedit with this line:
 gedit /etc/fstab  


Additionally, to check the current swap spaces in use by the system, you can use:
 swapon -s  


With thanks to DistroWatch Weekly, Issue 388, 17 January 2011 for this information!

Wednesday 25 April 2012

attr_accessor and attr_accessible in Rails

While trying to figure out why I was getting this error in a Rails application:
 WARNING: Can't mass-assign protected attributes  

I realised I'd confused the two below terms in my Rails model:

 attr_accessor  
is built into Ruby and defines a getter and setter method for a class attribute.


 attr_accessible  
is defined by Rails and makes the attribute mass-assignable.

Generally, in a Rails application, it's attr_accessible we want to be using.

Monday 23 April 2012

Creating a Redcar Launcher in Linux

The inspiration for the Redcar editors name

To create a Redcar launcher in Linux, first create a script which launches Redcar from the command line (I keep my scripts in ~/bin). Save this as start_redcar.sh, or similar (the .sh extension is required). The contents of this script are:
 #!/bin/bash
 source ~/.bashrc  
 /home/<USERNAME>/.rvm/gems/ruby-1.9.3-p125/bin/redcar  
Redcar Launcher Script

In the above script, <USERNAME> is my Linux username, and it's followed by my Redcar installation path. Your Redcar installation path may be different - to find it, open a terminal window and type:
 which redcar  

This will output your Redcar installation path.

The key to the above script is the source command. This means the launcher will have access to your RVM and Redcar installations - without this line, the script will work when you run it from within a terminal window, but fail when you create the launcher, as the terminal has access to .bashrc, whereas by default, the launcher won't.

To test the script, first make it executable, by opening a terminal window and navigating to the script directory. Then run
 chmod +x start_redcar.sh  

Then launch the script, typing
 ./ start_redcar.sh  

Where start_redcar.sh is the name of your script.

If Redcar opens, everything has gone according to plan so far - now we need to create the launcher. To do this, right click on the desktop, and find Create New Launcher. Under Name, enter "Redcar" (without the quotes), and under Command, browse to the script we previously created. Finally, to give the launcher the Redcar icon, click the icon, and browse to:
 /home/<USERNAME>/.rvm/gems/ruby-1.9.3-p125/gems/redcar-icons-0.3/icons/redcar-icon-beta.png  

Press OK and the launcher will be created on your desktop. To add this to Cairo-dock, or another Linux dock interface, simply drag the launcher onto the dock.

Examples of the two files created above can be found in this gist. Enjoy your new Redcar launcher!

P.S!  Are you learning Ruby or Ruby on Rails? I highly recommend The Ruby Programming Language and The Rails 3 Way as useful references. Of course, you can always check out the bookstore for other books I've found useful.

Update May-20-12: This post is now linked to from the Redcar Wiki!


Friday 20 April 2012

Undoing a Rails generate

To undo an action in Rails (generation of a scaffold, model, migration, etc), you can use
 rails destroy  

For example, generating and then destroying a controller called Posts would look like this:

 $ rails generate controller Posts  
    create app/controllers/posts_controller.rb  
    invoke erb  
    create  app/views/posts  
    invoke test_unit  
    create  test/functional/posts_controller_test.rb  
    invoke helper  
    create  app/helpers/posts_helper.rb  
    invoke  test_unit  
    create   test/unit/helpers/posts_helper_test.rb  
    invoke assets  
    invoke  coffee  
    create   app/assets/javascripts/posts.js.coffee  
    invoke  scss  
    create   app/assets/stylesheets/posts.css.scss  

$ rails destroy controller Posts  
    remove app/controllers/posts_controller.rb  
    invoke erb  
    remove  app/views/posts  
    invoke test_unit  
    remove  test/functional/posts_controller_test.rb  
    invoke helper  
    remove  app/helpers/posts_helper.rb  
    invoke  test_unit  
    remove   test/unit/helpers/posts_helper_test.rb  
    invoke assets  
    invoke  coffee  
    remove   app/assets/javascripts/posts.js.coffee  
    invoke  scss  
    remove   app/assets/stylesheets/posts.css.scss  

Thursday 19 April 2012

Adding a background image to tabs menu in Blogger


Add the following CSS to Template -> Layout -> Advanced -> Add CSS

 #PageList1 ul {  
 background-image: url(<url_to_image>);  
 }  

Where <url_to_image> is the URL to the image you wish to use.

P.S! Are you looking to improve your blog? I recommend you check out Bloggers Boot Camp  and Google Blogger For Dummies. Of course, you can also browse the bookstore for other inspiration!

Wednesday 18 April 2012

Sizing a background image for Blogger header

To size a background image for your Blogger header; the image width needs to be the width of your blog (check in Template -> Customise -> Adjust Widths), and the image height needs to be 200px.

Go to Layout, and edit the header widget (the one with the title text on it). This will allow you to upload your image.

Tuesday 17 April 2012

Removing the navbar on Blogger

I've been restyling this blog lately (as I'm sure regular visitors have noticed!), and picked up this little useful information today:

To remove the navbar on a Blogger site, first backup your template (go to Template -> Backup/Restore), then go to Template -> Layout -> Advanced -> Add CSS. Paste the code below into the CSS box and the navbar will no longer appear.


 #navbar-iframe {  
 display: none !important;  
 }  




This is the the claim token for Technorati and will be removed soon: A8KTUYQ2C8ET

Monday 16 April 2012

Conditionally hiding the sidebar on Blogger

I've recently added a small bookstore to this blog, as I thought my readers might be interested in the books I find interesting and useful. You can access it via the link in the bar above this post. If you open the "Bookstore" tab above, you'll notice that the right sidebar isn't present there, yet reappears when you reopen the "Blog" tab. This is achieved by a inserting a bit of CSS magic at the top of the HTML of the Bookstore page:

 <style type="text/css">   
  .main-inner .columns {padding-right: 0;}  
  .main-inner .fauxcolumn-center-outer {right: 0;   
  _width: expression(this.parentNode.offsetWidth -   
  parseInt("$(main.column.left.width)") + 'px');}  
  .main-inner .fauxcolumn-right-outer {width: 0px;}   
  .main-inner .column-right-outer {width: 0px; margin-right: 0;  
  display: none;}  
 </style>   

Credit to the greene teapot blog for this little gem!

Wednesday 4 April 2012

Error installing pg gem in Linux

If installing the pg gem in Linux fails with this error:

checking for pg_config... no
No pg_config... trying anyway. If building fails, please try again with
 --with-pg-config=/path/to/pg_config
checking for libpq-fe.h... no
Can't find the 'libpq-fe.h header
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.
...
 An error occured while installing pg (0.13.2), and Bundler cannot continue.


Installing libpq-dev should solve the problem.
 sudo apt-get install libpq-dev  

Tuesday 3 April 2012

Searching Flickr using the Flickraw gem

The more I look at Ruby, the more I appreciate just how powerful and succinct  it is. I'm sure my current Ruby coding style isn't yet close to The Ruby Way,but I'll keep working on that. In the meantime, I wrote this script over lunch, in preparation for a Rails application I have in mind. The script searches flickr for photos tagged with a word you supply as a command line argument, then picks a random one and launches the browser to display it. You'll need both the Flickraw and Launchy gem installed for this script to run. You'll also need a flickr API key, which you can apply for here.


Install required gems:
 gem install flickraw  
 gem install launchy  
The code:
 #!/usr/bin/env ruby  
 require 'flickraw'  
 require 'launchy'  
 FlickRaw.api_key    = 'YOUR_API_KEY_HERE'  
 FlickRaw.shared_secret = 'YOUR_SHARED_SECRET_HERE'  
 results = flickr.photos.search(:tags => ARGV[0])  
 rand = Random.new.rand(results.length)  
 info = flickr.photos.getInfo(:photo_id => results[rand].id)  
 url = FlickRaw.url_b(info)  
 Launchy.open(url)  
 (replace YOUR_API_KEY_HERE and  YOUR_SHARED_SECRET_HERE with your information from flickr)


Save this as flickr_single_tag.rb, and then run it, supplying a single search tag on the command line:
 ruby flickr_single_tag.rb surf  


Last time I ran it (with surf, as above), I got the image below. It's kind of fun to see what kind of images the returns! 





This gist contains the code from this post.