Twitter Updates

Saturday, 19 December 2009

Sinatra Second Blog attempt

Example of how to setup a basic Sinatra web application.

This Sinatra app uses erb for the templating and active record for the database ORM. To get the cod eto show up I have had to change "< a" to <-a tags and insert extra space in other tags, unfortunately this means they are not quite cut and paste. To simplify The setup I have created a ./create_db.rb file.

./create_db.rb
require 'rubygems'
require 'sequel'

# Connect to the database
DB = Sequel.sqlite('./db/blog.db')

unless DB.table_exists? :posts
DB.create_table :posts do
primary_key :id
varchar :title
text :body
end

# populate the table
DB[:posts].insert(:title => 'Post Man Pat', :body => "has a black and white cat" )
DB[:posts].insert(:title => 'Sandwiches', :body => "Peanut butter and Marmite, Yum")
DB[:posts].insert(:title => 'Leaves', :body => "Grow on trees")
end

class Posts < Sequel::Model
end


The Main Application. ./app.rb
require 'rubygems'
require 'sinatra'
require 'active_record'

#Load extra functions
require 'url_logic'

ActiveRecord::Base.establish_connection(
:adapter => 'sqlite3',
:database => './db/blog.db'
)

class Post < ActiveRecord::Base
end

$blogpath = "article"

get '/' do
erb :index
end

#Setup paths for blog
get '/article/?' do
@posts = Post.all()
erb :readallblog
end

#view a post
get '/article/:id/?' do
@posts = Post.find(params[:id])
erb :showoneblog
end

#edit a post
get '/article/:id/edit/?' do |id|
@posts = Post.find(params[:id])
erb :editblog
end

#Update post
put '/article/:id/?' do
@posts = Post.find(params[:id])
@posts.title = params['post']['title']
@posts.body = params['post']['body']
@posts.save
erb :showoneblog
end


#create a Post
post '/article/?' do
Post.create(
:title =>params['post']['title'] ,
:body => params['post']['body']
)
@posts = Post.all()
erb :readallblog
end

#delete an article
delete '/article/?' do
@posts = Post.find(params['post']['id'])
@posts.delete
@posts = Post.all()
erb :readblog
end


./views/readallblog.erb
readBlog All Posts
<%# $blogpath is global set in the main controller%>
<% for post in @posts %>
< h 1><-a href="/<%=$blogpath%>/<%=post.id%>"><%=post.id%>:<%= post.title %>< / a>
<%=post.body%>

<-a href="/<%=$blogpath%>/<%=post.id%>/edit">edit< / a>
<% end %>

< f orm method="post" action="/<%=$blogpath%>/">
< i nput name="_method" type="hidden" value="post" />
< d iv>
Title< i nput type="text" name="post[title]" value="title"/>

Body< i nput type="text" name="post[body]" value="body"/>

< b utton type="submit">Create
< / d iv>
< / f orm>

./views/showoneblog.erb
Show Single Post

< h 1><%=@posts.id%>:<%= @posts.title %>< / h 1>
< p ><%= @posts.body%>

<-a href="/<%=$blogpath%>/<%=@posts.id%>/edit">edit< / a>



./views/blog
Edit Single Post

< h 1><%=@posts.id%>:<%= @posts.title %>< / h 1>
<%=@posts.body%>

< f orm method="post" action="/<%=$blogpath%>/<%=@posts.id%>/">
< i nput name="_method" type="hidden" value="put" />
< d iv>
Title< i nput type="text" name="post[title]" value="<%=@posts.title%>"/>

Body< i nput type="text" name="post[body]" value="<%=@posts.body%>"/>

< b utton type="submit">Update
< / div>
< / f orm>


Hopefully this has covered creating new, editing and retrieving database entries using ActiveRecord. I have probably missed some of the tricks to simplify writing Sinatra apps.

Tuesday, 15 December 2009

Sinatra First Blog attempt

After getting Xcode for Snow leopard correctly installed and restarting. The basic sinatra works correctly.

hi.rb
----
require 'rubygems'
require 'sinatra'
get '/hi' do
"Hello World!"
end

Command line:
$ gem install sinatra
$ ruby hi.rb

Then checkout 127.0.0.1:4567.

Turning it an almost blog, with some erb and an sqlite 3 database.
Assuming you have macports installed you can do (or look up installing sqlite3):
$ sudo port install sqlite3
cd Sinatra_dir
sqlite3 blog
#you are now in the sqlite command prompt
sqlite> create table posts (title text, body text );
sqlite> insert into posts values('title1','Very long article');
sqlite> insert into posts values('Sinatra Blog Post','text text text text text');

hi.rb
----
require 'rubygems'
require 'sinatra'
require 'active_record'

ActiveRecord::Base.establish_connection(
:adapter => 'sqlite3',
:dbfile => 'blog.db'
)
class Post < ActiveRecord::Base
end

get '/news/?' do
@posts = Post.all()
erb :index
end


Now create ./views/index.erb
----
HelloWorld!

<% for post in @posts %>
< h 1><%= post.title %>< / h 1>
< p ><%= post.body%>< / p>
<% end %>


$ ruby hi.rb and goto 127.0.0.1:4567.
If all goes well you should see some thing like this:

Monday, 14 December 2009

whereis alternative to which

whereis is a nice alternative to which for finding the location of unix programs.

$ which ruby
> /usr/local/bin/ruby

$ whereis ruby
> /usr/bin/ruby

Problems with Snow Leopard and Ruby Gems

UPDATE 2 (update 1 at the bottom with some extra ruby version info)
When you install Xcode make sure is is the latest version. I must have at some point installed the old Leopard version. then when things did not work reinstalled that same old version. I found xcode321_10m2003 in my downloads folder not the older one I had put in a software folder. You may still need to update Ruby to a new version.

Make sure you have the latest Xcode.


I have been trying to get the very simple Sinatra (a light ruby on Rails) setup working following the verysimple instructions on http://www.sinatrarb.com/

Make a file called hi.rb with this inside:
require 'rubygems'
require 'sinatra'
get '/hi' do
"Hello World!"
end

Then run these commands:
$ gems install sinatra
$ ruby hi.rb


They fail with:
hi.rb:2:in `require': no such file to load -- rubygems (LoadError)
from hi.rb:2

After removing the require 'rubygems', is it actually still required ?
hi.rb:3:in `require': no such file to load -- sinatra (LoadError)
from hi.rb:3

To fix this I ran through the instructions at http://hivelogic.com/articles/compiling-ruby-rubygems-and-rails-on-snow-leopard/

Their instructions worked well until the mysql gem which I do not require at the moment but do like to get my set up the same as the tutorial. I found the following line on stackoverflow.
$ sudo env ARCHFLAGS="-arch x86_64" gem install mysqlplus


Finally got the basic sinatra working by calling:
$ /usr/local/bin/ruby hi.rb
Even though which ruby returns /usr/local/bin/ruby, so why does ruby hi.rb not just work!

What is going on just thought I would check to see if calling the other ruby breaks it, but it works fine.
$ /usr/bin/ruby hi.rb


UPDATE
For completeness and to answer Spyro7's Question:
$ /usr/local/bin/ruby -v
> ruby 1.8.7 (2009-06-12 patchlevel 174) [i686-darwin10.2.0]

$ /usr/bin/ruby -v
> ruby 1.8.7 (2008-08-11 patchlevel 72) [universal-darwin10.0]

Sunday, 13 December 2009

Rediscovering Airfoil

Apple produces quite a cheap way to stream audio into another room/Hifi all you need is an airport express plug it into an amp or a powered set of speakers then iTunes can transmit over wifi to these external speakers.

There is a nice piece of software called airfoil by rogueamoeba which is available for $25 (25 us dollars). It allows you to stream certain application or all audio to these external speakers. You can also select which speakers to transmit to.

There is a new application which I have not seen before, Airfoil Speakers this allows a Mac or Windows PC to be turned in to a receiving Airport express!

There is also an Airfoil Speakers for the iPod Touch! So you get wireless headphones capability

Thursday, 10 December 2009

Mac OS X NTFS Drivers speed test

I have had to transfer some data from one USB NTFS formatted drive to another USB NTFS formatted drive. These are the results using the different Mac NTFS drivers available.

NTFS-3G (With MAC FUSE) Caching disabled:


NTFS-3G with caching enabled:


Tuxera NTFS for Mac (25 Euro) (based on NTFS-3G) Caching enabled:


Also missing, For comparison HFS+ test:







NTFS-3G (No Caching) 183 MB/Minute
NTFS-3G (Cached) 610 MB/Minute
TUXERA (Cached) to HFS 1000 MB/Minute
TUXERA (Cached) 1223 MB/Minute
NTFS-3G (Cached) to HFS 1391 MB/Minutes
HFS+ SATA to USB 1464 MB/Minures

Wednesday, 9 December 2009

Mac OX Speed test your (USB) Hard Drive

Just tried xbench to speed test my harddrives, very surprised that it still works as it looks like the last time it got any updates was for OS 10.3 a few years ago.


http://www.xbench.com/


The Results from my main Hard Drive Mac OS X:


Aaargh, it refuses to test USB drives the only reason I was trying it out!

Monday, 7 December 2009

201st Post: Finally fixed wrapping text in pre tags

pre tags are used in html to maintain the display of whitespace as it is written in the html. This lends itself nicely to code snippets but unfortunately means that it does not wrap text nicely by default.

By adding this [1] to the embedded or external style sheets you can get text to behave nicely inside pre tags.

[1]
pre {
white-space: pre-wrap; /* css-3 */
white-space: -moz-pre-wrap !important; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}


Original source:
http://labnol.blogspot.com/2006/10/html-css-trick-for-displaying-code.html

Saturday, 5 December 2009

Snow Leopard Get Summary

OS X has a very use shortcut for getting info on files which is cmd-i or the 'apple key' and 'i' will bring up an info window. If you select more than 1 file you get an info window for each! probably not what you wanted.

On OS X 10.6 if you hold down the control 'ctrl' key as well as cmd-i (ctrl-cmd-i) then you get a neat summary of those files. Very useful for getting the disk spaced used by multiple files.

if only one file is selected ctrl-cmd-i and cmd-i perform the same function, why is ctrl-cmd-i not the default!

If you would like to have a multiple file summary by default try this:
Open your system preference is your usual way, I use quick silver so just pres ctrl-space type sys and enter.

Go to the Keyboard item. Key board shortcuts then press then plus in the bottom left of the main panel.

Add a shortcut for application finder. command is 'Get Summary Info' then in the keyboard command type the shortcut you want, in this case cmd-i.


NB: You may also need to uncheck the Show Info option in Keyboard shortcuts->Service->Files and Folders->Show Info.

Google Tasks

Just discovered that google have added a Task list function into gmail.

http://mail.google.com/mail/help/tasks/

This will probably become my main todo list. I do not think that it will replace all the notes I am keeping with Evernote though (Evernote has a very functional free mode).

Windows XP Picture Screen Saver

Windows XP comes with a slideshow screensaver which can be pointed at a folder and displays the picture one at a time. For me it refused to display most of my pictures out of about 2000 only 12 would be shown.

On my search to fix this I was unable to find the spec for the photos allowed through the Windows screen saver, I did however discover that google has a screensaver that comes packaged with picasa. This also has and pan & Zoom effect just like the mac screen saver.

Get from :
http://pack.google.com/screensaver.html

All you actually need is Picasa, so you can uncheck every thing else if you want.
Once installed you do not have set picasa up just choose the new screensaver from the standard place.

Thursday, 26 November 2009

Tame the firefox by blocking flash

My web browser firefox keeps hogging the cpu 30-40% sometimes going crazy and taking 140% I believe that this is mainly due to embeded flash content. I have just started using the FlashBlock pluggin hoping it will help tame Firefox's cpu usage.


http://flashblock.mozdev.org/

Monday, 23 November 2009

Snow Leopard Shortcut to Home in Finder

Snow Leopard by default does not have a 'Mac OS X' Icon on the desktop but there is a keyboard short-cut to launch a new finder window open with your home directory.

cmd-shift-h (Shortcut to Home)
cmd-shift-a (Shortcut to Applications)

Wednesday, 18 November 2009

Scripting pinning Subversion Externals

How to control Subversion externals with scripts (bash):

Command Line setting 1 External
cd ./ProjectB/Reuse/A
svn propset svn:externals "Generic -r 19049 http://svnl/ReuseA/something" .


Command Line setting multiple Externals
cd ./ProjectC/Reuse
echo "A -r 16234 http://svnl/ReuseA/something" > svn.externals
echo "B -r 18086 http://svnl/ReuseB/something" >> svn.externals
svn propset svn:externals . -F svn.externals
#Optional
rm svn.externals
svn update
cd -

Subversion find all externals

When working in a subversion repository it is some times (often) nesecary to pin the externals. This requires the often tricky task of finding them all first, made easier with this command:

$ svn propget svn:externals -R

Which will recursively list all you externals from the current directory.

Tuesday, 3 November 2009

CD to Computer Music File

For audio conversion on Windows I use CDex. The file name string I prefer is:
%1\%Y-%2\%1-%Y-%2-%7-%4

On Mac OS X Snow Leopard I prefer to use Max. The file name string I use is:
{fileFormat}/{albumArtist}/{albumDate}-{albumTitle}/{trackArtist}-{albumDate}-{albumTitle}-{trackNumber}-{trackTitle}

My prefered output formats are:
[1] FLAC for archive/media server copies.
[2] 112kbps AAC for portable media.

[1] FLAC is a lossles codec and represent exactly what is on the cd, this is a great free codec with players available on most platforms. It will compress a 700MB cd on average to 400MB.

[2] AAC is high quality (Superior to MP3) lossy audio codec. Setting to 112kbps with a variable rate codec means that I actually get files sizes expected from a constant bit rate 128kbps codec. The loss in sound quality is not that important when listening with headphones.

Monday, 2 November 2009

mac ports since OS X Snow Leopard upgrade

Since upgrading to Snow Leopard I have noticed that Mac Ports (Previously called Darwin Ports) started giving me lots of errors. So I manually downloaded and installed the latest version, from here.

I then had to run through the insructions here [1] to clean every thing up:
[1] http://trac.macports.org/wiki/Migration

$ port installed > myports.txt
$ sudo port clean all
$ sudo port -f uninstall installed


The look through myports.txt and install any you need.

$ sudo port install fping scite

Wednesday, 28 October 2009

Hugin for panoramas

hugin seems to be quite a good open source program for joining photos together for panoramas etc.

My first attempt joining 3 photos.
morganp-20091028-Hugin-3-EdinClouds

Wednesday, 21 October 2009

OpenOffice Annoying auto correct

I often have to document small snippets of code and other case sensitive things so often find it very annoying when my editors decide to auto correct these things for me.

Currently I have been trying to use OpenOffice Impress to prepare a slide show.

To disable auto sentence capitalisation: OpenOffice main toolbar 'Tools' --> 'AutoCorrect Options ...' --> 'Options' tab and deselect 'Capitalize first letter of every sentence'

Thursday, 15 October 2009

Edit with SciTE right click menu option

If you are a windows scite user there is a dll which you can use to give you an "edit in SciTE" right click menu option.

download from: http://www.burgaud.com/scite-context-menu/

instructions for Windows XP: all included in the readme

copy the correct dll 32 or 64bit to your scite directory probably "C:\Program Files\wscite".
start -> run -> cmd
cd "C:\Program Files\wscite"
regsvr32 wscitecm.dll

Sunday, 11 October 2009

Rails Simple Pages

Ruby on Rails good for handling data models and folowing an MVC framework but there seems to be a lack of documentation for adding simple pages, I did find asmallguide on the has_many :through blog
with only a few omissions that some one new to rails might not know.

First setup the routes so that when entering http://127.0.0.1:3000/about it knows which controller to use.

config/routes.rb
 map.root :controller => 'home'
map.home ':page', :controller => 'home', :action => 'show', \
:page => /about|contact/


Now setup the controller.

app/controllers/home_controller.rb
class HomeController < ApplicationController
def index
# render the landing page
end

def show
render :action => params[:page]
end
end


Now create the 'home' folder. so we have a apps/views/home to put about.html or about.html.erb in.

Linking to this page can now be don via:
 link_to 'About', home_path('about') 


This tutorial was very closely based on 'Has many :through simple pages'

Saturday, 3 October 2009

Rails Menus using Partials

I have struggled to find a good tutorial on this, probably would not need it if I knew Rails better though. I would like to make a menu which is used through out my Ruby on Rails site, partials seem to be the correct thing to use.

under
app/views/
create a new folder 'shared'
and create a new file called _menu.rhtml.
'app/views/shared_menu.rhtml'

which contains the menu something like (sorry for the extra spaces only way I could stop it rendering):
< id="menu">
< class="menubar">
< class="menubar">< href="http://127.0.0.1:3000/">Home< / a>< / l i>
< class="menubar">< href="http://www.blogger.com/Posts">Posts< / a>< /l i >
< class="menubar">< href="http://www.blogger.com/Tags">Tags< / a>< / l i>
< / u l>
< / d i v>
Then add <%= render(:partial => "shared/menu") %> to all default layouts. in:
'views/layouts/*.html.erb'

Firefox redirect mailto links to gmail

If you use Firefox as your browser and gmail as a web based email client then this is a really nice setting that was added in firefox 3. In firefox open the preferences, Applications tab and find 'mailto' in the 'Content Type'. Then just select 'Use Gmail' as the 'Action'.

Now when click on email links on web pages an new tab will open and start composing an email from your currently logged in gmail account.

Firefox-mailto-gmail

Friday, 2 October 2009

Ruby on Rails

I found this [1] tutorial to be a very good introduction to ruby on rails 2.0.

[1] http://akitaonrails.com/2007/12/12/rolling-with-rails-2-0-the-first-full-tutorial

I only really followed it far enough to get a working blog with comments, That next step would be to get a working many to many relationship setup for tagging. There is a lot of confusion over how todo tagging with many different gems and plugins. Since the introduction of rails 2.x there much better ways to do the many to many relationships and except in the case of tag clouds setting up tags are relatively straight forward.

This [2] was the best tutorial I found for setting up many to many relationships and [3] was very good for describing the different relationships.

[2] http://dagobart.wordpress.com/2008/06/18/for-purpose-of-reference-doing-many-to-many-relationships-in-rails/
[3] http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

Some tips for ~/.inputrc

If you use the command line alot on Unix, Linux or Mac (I know it is a unix) you might be interested in some options that you can set in your ~/.inputrc file.

If the file does not exist you can just create it.
$ cd ~
$ vim ~/.inputrc

My favourite option is (just enter it any where in the file):
set completion-ignore-case on

This makes tab completion non-case sensitive, since discovering this I have cut down massively on the amount of backspace I have to type to get the tab completion I wanted.

Another option that may be useful is:
set match-hidden-files off

Which stops tab completion using hidden files, but since I edit my .bashrc .inputrc etc alot I often do want to tab complete hidden files.

For more info on options just have a look at:
man readline

Sunday, 27 September 2009

Lightroom temp files

Lightroom stores its previews in '.lrdata' folders. You can turn on an option telling lightroom to delete previews after 30days. I however use a lightroom catalogue for each shoot which means some catalouge are not opened for a really long time so the previews never get deleted.

to find the files and the space they take you can just run these commands.
$ cd ~/Pictures
$ find . -iname "*.lrdata" | xargs -I{} du -sh {}

To Remove the files
$ cd ~/Pictures
$ find . -iname "*.lrdata" | xargs -I{} rm -r {}

I worte a small ruby script to help me do this:
lightroom_remove_previews.rb.

It has a hradcoded path to my Pictures folder so you would have to modify that. When calling the script it has 2 main options, --report and --remove, which call the the two main commands described above.

Saturday, 26 September 2009

Regular Expressions Backreference (Grouping)

One of my favourite features of regular expressions is backreferencing, I always think it is called grouping though.

Simply place () round brackets around part of the expression your interested in and use \1 backslash one to reference the first group. \2 for the second.

For example to strip every thing but the information you want out of a file belonging to a tv series.
Match: (.*)[-. ](S\d\d)-(EP\d\d).*
Replace with : \1-\2-\3

The notation used in the expression:
. :Any Character
* :0 or more of previous character (.* will match anything)
[] :Match any charater in the set (- only works as a literal if it is first)
\d :Match one Decimal number

http://www.regular-expressions.info/brackets.html

Friday, 18 September 2009

Adobe Lightrrom 2.5 Update

The latest Update for lightroom 2 is available (LR2.5):

Lightroom 2.5 Direct Download

Standard download link

Wednesday, 16 September 2009

New NTFS driver for Mac OS X

There is a recent driver out for Read/Write support of NTFS drives under Mac OS X.
Download

There is now an NTFS-3G item in the system preferences. I would recommending unchecking the "File system Caching enabling". This with disk caching the mutliple read writes to the same data can be much faster but can corrupt the disk if the buffer is not flushed before removal. Ejecting or unmounting the disc is the way you tell the computer you want to flush the buffers and remove the disk. BUT I occasionally forget to do this for external discs and I dont want to lose all my data. On the plus side I do not work (edit data) on external discs just transfer/Archive data or play/read files so I do not see any performance loss.

The new driver also has a force button for when windows did not shut it disc down correctly. So you can force OS X to load the disc any way, this was a real pain in my old version of the driver.

Release Notes Updates can be found here:
http://macntfs-3g.blogspot.com/

Find Out Ubuntu Version Name

To find out your Ubuntu version name just run:

$ cat /etc/lsb-release

Drobo & Drobo Share £356

Just saw this on Amazon and think it is a great price for the device.
Drobo + DroboShare (Network Attach) £356

The Drobo is a 4 Drive bay raid system (1 Disk redundancy) that automagically adds new/bigger drives into the system. As long as you only replace one drive at a time. The Drobo Share adds NAS, takes the Drobos usb interface and makes the drive avaliable on the Network.

I still think the Drobo Pro version will be much better investment in the long term as it has 8 bays and can do double disk redundancy but does cost £970 with out drives and is not NAS (Network Attached Storage)

Saturday, 12 September 2009

Make Audiobooks

I have recently got some audiobook CDs and have been looking for the best way to convert them for use with iPods. iTunes (Apple) have defined a special format for Audiobooks, it is the *.m4b format. It is really just the m4a format but with last a for audio changed to b for books. This Format uses AAC, quite superior compared to the mp3 codec but not as portable.

When imported the m4b format should automatically be set to book-markable or remember position. When listening to music you normally want to start at the beginning of the song, when listening to a book you normally want to start from exactly the same position you left off.

I found the best method for me is to convert all CDs into Wave files, as the best tool available rencodes into the AAC format and you do not want to do lossy conversion more than once as the audio quality will degrade. Once you have got all your wave files together I recommend using Audiobook Builder ($10 paypal, then auto-email codes to you).

With Audio Book builder I normally change the genre to 'Audiobook', search amazon for an image of the book cover and have to add the year manually in itunes, itunes does then update the file.

[Note added 03/03/2010]
Audiobook Maker does not look like it is compatible with Snow Leopard
[/Note]
If you already have a bunch of MP3s this tool is free Audiobook Maker (only imports MP3s) and then converts to m4b, but you are doing conversion to mp3 then to aac so you get two types of conversion loss, probably do not notice with speech though.

Quicktime X playing avi

I have just installed DivX 7 (thought they were upto 10 but never mind) on OS X Snow Leopard and it seems to have given me all the codecs to play DivX XviD encoded media. This did not work last time I tried. The trim function in the new quicktime even works although have to export to either .mov or .m4v.

http://www.divx.com/en/mac

NB: I still recommend VLC as the best player for Mac OS X

Thursday, 10 September 2009

Omni Disk Sweeper

Just tried Omni Disk Sweeper for identifying large files eating up my disk space. It is very easy to use and just spotted 20Gigs of file I do not need and had forgotten all about.

http://www.omnigroup.com/applications/omnidisksweeper/

Monday, 31 August 2009

Recursively Search for file with text

Using the find command below in Unix/Linux/OS X terminal you can search from a given path recursively looking in all files for text that matches 'find this text'.

$ find ./searchPath/ | xargs -I {} grep -iHn 'find this text' {}

or

$ grep -R -iHn 'find this text' *

grep Options:
-i makes it incase sensitive
-H outputs the filename before the matching line.
-n outputs the matching line number before the matching line.
-R Recursive from current location

[UPDATE 1]
Ignore Subversion folders
$ find ./ -not -name *'.svn'* | xargs -I {} grep -iHn 'find this text' {}

Saturday, 22 August 2009

Directory to Podcast

Just finished (largelgy based on an example) a small simple php script to take files from a folder and turn into a podcast feed. Directory to Podcast PHP script.

This may be useful if you want to setup a cron script/server application on a home server to download your latest podcast shows. Using this script you can then reserve the downloaded files as a local podcast feed.

This is useful at home as your server can download at none bandwidth critical times, when your isp applies limits or around 9pm when the internet is going really slow. When your main machine is switched on the podcasts will download very quickly over your local network.

Tuesday, 11 August 2009

require_gem is now gem

I have been working through the Ruby on Rails 2 Create a blog in 15 minutes and it only took me a few hours, but was much quicker and gave me a better understanding of rails than finishing the book on rails I was reading.

After this I had wanted to add tags like most blogs and photo site now have. So I am currently working through a act_as_taggable tutorial.

The main point I want to make is that at some point the require_gem command has been replaced with gem.

incorrect: require_gem 'acts_as_taggable'
Correct: gem 'acts_as_taggable'

Monday, 3 August 2009

Easy Create DMG Files with background images

I just discovered this [1] helper application for creating DMG file for distributing your Mac Applications.

[1] iDMG http://www.nscoding.co.uk/

Easily define Icons and Background images.

Changing Icons for Shoes Rasins Programs

How to change Icons for compiled shoes applications. There is no configuration options in shoes for this but with some free tools you can change the included icons.

For Mac OS X dmg file if you open the .app as folder by right-click Show Package Contents, through an alternative file browser or go into it in the terminal and replace Shoes.icns and /Resources/Shoes.icns with your Mac Icon .icns of choice. My guide on creating these and replacing them in a xCode java application.

For windows you can use a free tool called IcoFX (but license says you are never allowed to charge for an application which include icons created with this tool) to create Windows icons .icn. Using the IcoFX resource editor you can then change the included icon for a .exe.

Friday, 31 July 2009

Word Visio Stop capitilisation

Finally got around to switching off first letter capitalisation (capitalization) For word 2007 and visio 2003.

The options are in the AutoCorrect Menus if you know how to find them. Microsofts instructions for Visio are here:
http://support.microsoft.com/kb/290586

Basically, Visio -> Tools -> AutoCorrect Options, DeSelect "Capitalize first letter of sentences"

StopVisio2003ManglingYourText

For Word 2007 I had to make the mistake then select the smart tag to get to the Auto correct options. but then the options were very similar to Visio.

StopWord2007ManglingYourText

Thursday, 30 July 2009

Create Icons *.icns for OS X

To create icons for your OS X Applications, first create a master 512pixel x 512pxel master image. create smaller versions if required ie if you want the smaller logos to be different.

The size options you can create for are:
512x512
256x256
128x128
32x32
16x16

Once you have your images, my logo is simple so I only created one 512 master copy, from photoshop save as a tiff with transparency and Image compression:no compression, Layer Compression:discard all layers and save a copy.

Then open (you need the developer tools xcode):
/Developer/Applications/Utilities/Icon Composer.app

Then drag you 512x512 tiff on to the largest square I then let it auto scale this image for the smaller options. Then just go File Save As. and you *.icns file is created.

A very helpful tutorial was.
http://tutorialdog.com/how-to-create-icons-for-mac-os-x/

A generic guide to integrating the icns into your mac app is:
http://stackoverflow.com/questions/646671/how-do-i-set-the-icon-for-my-applications-mac-os-x-app-bundle

Because I am working on a project setup by xCode I can just replace the file in:
ProjectRoot/resources_macosx/projectName.icns

Wednesday, 29 July 2009

File Release on SourceForge

Recently SourceForge made an untested 'Upgrade' which broke my main method of making file release. it would have been ok if the new systems put in place worked but they do not!

Webdav has been disabled as a method for upload. The recommend options in order that they seem to recommend are Web interface [1], scp [2], rsync [3] and sftp [4].
[1] Does not work at all.
[2] Can not create new folders or delete files.
[3] Keep a copy of all versions of files, I only want to keep the latest version.
[4] Works but you need to know where to look and require a good client (CyberDuck for OS X).

You need to be a SourceForge member to view this help page!
https://sourceforge.net/apps/trac/sourceforge/wiki/Release%20files%20for%20download

So SFTP it is then,

Server : frs.sourceforge.net
Username : jsmith,fooproject
or command line
$ sftp jsmith,fooproject@frs.sourceforge.net

This will take you to:
/home/groups/f/fo/fooproject
you actually want to be here for file releases:
/home/frs/project/f/fo/fooproject/

The Project webpage is here:
/home/groups/f/fo/fooproject/htdocs

Windows DNS

On Linux and Mac OS X systems if you need/want to hard wire a computer name to an IP address so that scripts can work reliably on startup, before DNS has really kicked in, you can easily add a line to the /etc/hosts file.

I just discovered that this is also easy on Windows (XP at least). Just add a line to the file:
c:\WINDOWS\system32\drivers\etc\hosts

Some thing like
192.168.1.1 router

Then you can just type http://router in to your browser to be taken to your router login page.
Thanks to @philip_roberts

Sunday, 19 July 2009

Mac OS X and sshd

To ssh into a mac you need to turn this service on which is very easy.

From the terminal (/Applications/Utilities/Terminal.app)
$ ssh localhost
>ssh: connect to host localhost port 22: Connection refused

Now go to '/Applications/System Preferences.app' -> 'Sharing' then enable 'Remote Login'
Sharing

Now Try ssh again:
$ ssh localhost
Password:
Last login: Sun Jul 19 16:31:39 2009 from localhost
$

OSX eat my GNU

Trying to setup snapback2 bbackup software but started running into issues because the os x commands are based on the BSD variants not the more standard GNU versions used on most Unix's and Linux's.

Tried some manual installs but eventually after hitting a few dead ends found the package in port (mac ports formerly darwin ports).

1) Assuming Mac Ports is already installed (if not do that first, to tired to give instructions for that)
2) $ sudo port install coreutils
NB: since os x 10.5 sudo only works if you have a password set.
3) Get that pesky BSD cp out the way
$ sudo mv /bin/cp /bin/cp-osx
4) link to the new shiny GNU
$ ln -s /opt/local/bin/gcp /bin/cp

5) test old version
$ cp-osx --version
>/bin/cp-osx: illegal option -- -
>usage: cp [-R [-H | -L | -P]] [-fi | -n] [-pvX] source_file target_file
>cp [-R [-H | -L | -P]] [-fi | -n] [-pvX] source_file ... target_directory

Note The excellent handling when requesting the version!

6) Now the new version:
$cp --version
>cp (GNU coreutils) 7.4
>Copyright (C) 2009 Free Software Foundation, Inc.
>License GPLv3+: GNU GPL version 3 or later .
>This is free software: you are free to change and redistribute it.
>There is NO WARRANTY, to the extent permitted by law.
>
>Written by Torbjörn Granlund, David MacKenzie, and Jim Meyering.

This can be repeated for any other GNU commands you would like to map from /opt/local/bin/ to /bin. Most are prepend with g but if it is a 3rd party script that you are trying to get working it is often easier to make the default the gnu version.

Saturday, 18 July 2009

CocoaDialog DialogBoxes for scripts

I just discovered CocoaDialog, this allows scripts (Ruby, Perl, Bash) to ask for user input in a pretty way. Will be useful for creating double click runnable script/programs

Download .dmg and copy CocoaDialog.app to /Applications/

test run from bash terminal (/Applications/Utilities/Terminal.app)
$ /Applications/CocoaDialog.app/Contents/MacOS/CocoaDialog standard-inputbox --title "Your Name" --informative-text "Enter your name"

Example should show this:
CocoaDialog-standard-inputbox

Pressing ok will return:
>1
>enteredText

Pressing cancel will output:
>2

Friday, 17 July 2009

Setting up Time Machine on any NAS

Start by opening the Time Machine option pane, "/Applications/System Preferences.app" then choose Time Machine under "Systems"

I would also like to point out something I find very odd which is that Time Machine needs to target a particular partition (Drive letter in windows speak, or volume in mac speak). So for a network drive I would create a new network share called timemachine_computerName

[ADDED 20/07/2009 ]
Most of the following is to setup the new network share so that it will work with time machine. I have program TimeMachineAnyNetworkDrive which will setup most of this for you. then just copy the sparsebundle from your home directory to the networkshare and try time machine again.


First problem is apple does not allow any NAS (Network attached storage) device to be used by default, only their premium priced time capsule!

01NO-NAS

To allow non-apple network drives run this command (from the terminal):
defaults write com.apple.systempreferences TMShowUnsupportedNetworkVolumes 1

02NAS_ALLOWED

Selected NAS but after first attempt the backup fails.
03-NAS-DENIED

What we need to do is create a sparse dmg which gives timemachine all the required file system functions on any filesystem. For this we use the hdiutil command.
NB: The hdiutil command will only work on local (internal and external) drives not network drives.

So we create the sparsebundle (dmg) locally then copy to the remote drive, when copied through the command interface I got a few errors so I copied through finder (graphical interface).

The Sparse bundle name needs to be computerName_MAC.
All the following are typed from the terminal (/Applications/Utilities/Terminal.app) $ inputs > output from the terminal.

To check the computer name you can just run:
$ hostname -s
> Queeg500

The Mac address of the first wired port EN0 is normally used. Every network socket/wifi will have its own MAC. To find your MAC

$ ifconfig en0 | grep ether
> ether 00:1b:63:a6:7e:5b


Sparsebundles takeup only the size of the data they contain, but the size property limits the maximum size. Here we limit to 200Gigabytes.
cd ~
hdiutil create -verbose -size 200g -fs HFS+J -type SPARSEBUNDLE -volname "Backup of Queeg500" Queeg500_001d4ffac84b.sparsebundle
#may be better to move graphically
mv Queeg500_001d4ffac84b.sparsebundle /Volumes/timemachinetest/


Then try the timemachine backup again.
04NAS-WORKING


Very good article here.

Applescript What Property?

My apple script (applescript) just made a massive leap forward or at least my unerstanding of how people go about figuring it out. I never could work out how people new what all those scriptable properties where called until now.

Open Script Editor (/Applications/AppleScript/Script Editor.app) may be open a script you have been writting / downloaded.

The really clever bit:
from Script editor File-> Open Dictionary
Now choose the application you are scripting and you will get a browsable searchable list of properties that the script can get and set!

Monday, 13 July 2009

Desktop Background

A nice background to help organise your icons:

http://www.flickr.com/photos/gr/182329376/in/set-72157594188036656

Friday, 10 July 2009

Amazon Store

Just got my amazon associate store setup, not quite complete yet.
http://astore.amazon.co.uk/morgue-21

Thursday, 9 July 2009

Amazon.co.uk lists

Amazon seem to hide the link to create lists for list mania so here it is:
UK: http://www.amazon.co.uk/gp/richpub/listmania/createpipeline
US :http://www.amazon.com/gp/richpub/listmania/createpipeline

Body Of Secrets

Body of Secrsts
ISBN:0099427745
About £9

Very interesting book on the history of the NSA and GCHQ.

Monday, 6 July 2009

Disable jqs.exe on Windows

In my windows task manager I noticed a process called jqs.exe which had over 5,000,000,000 I/O Read Bytes the most out of any process on my computer by a factor of 4.

It is a java quick launch application which constantly brings a small part of java back in to main moemory. Sine I do not run java applications that often I do not mind a little bit of lag and followed the instructions here [1] to diable it

[1] http://jsbi.blogspot.com/2009/05/what-is-process-jqsexe-and-how-to.html

Saturday, 4 July 2009

Ruby Parsing Command Line Options

Ruby has built in methods for dealing with parsing command line options, it is called optparse.

optparse rdocs

some optparse examples

A Small example (cut down from the above) showing most common requirments.
Also on github.


#!/usr/bin/env ruby

require 'optparse'
require 'optparse/time'
require 'ostruct'
require 'pp'

class OptparseExample


#
# Return a structure describing the options.
#
def self.parse(args)
# The options specified on the command line will be collected in *options*.
# We set default values here.
options = OpenStruct.new

options.verbose = false
options.time = 0
options.delay = 0
options.leftovers = nil


opts = OptionParser.new do |opts|
opts.banner = "Usage: example.rb [options]"
opts.separator ""
opts.separator "Specific options:"

# Boolean switch.
opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
options.verbose = v
end

# Cast 'time' argument to an integer.
opts.on("-t", "--time [TIME]", Integer, "Begin execution at given time") do |time|
options.time = time
end

# Cast 'delay' argument to a Float.
opts.on("--delay N", Float, "Delay N seconds before executing") do |n|
options.delay = n
end

# List of arguments.
opts.on("--list x,y,z", Array, "Example 'list' of arguments") do |list|
options.list = list
end

opts.separator ""
opts.separator "Common options:"

# No argument, shows at tail. This will print an options summary.
opts.on_tail("-h", "--help", "Show this message") do
puts opts
exit
end

# Another typical switch to print the version.
opts.on_tail("--version", "Show version") do
#puts OptionParser::Version.join('.')
puts "Version 0.1.0"
exit
end
end

options.leftovers = opts.parse!(args)
options
end # parse()

end # class OptparseExample

options = OptparseExample.parse(ARGV)
pp options
puts ""
puts ""
puts options.leftovers

Saturday, 27 June 2009

Lightroom 2.4 Update

The 2.4 Update for Adobe Lightroom is available here
Or Direct

Remove Parallels from Mac OS X

I used this article [1] to remove parallels from my Mac OS X 10.5 machine.

[1] http://kb.parallels.com/en/4709

Basically reload the .DMG used to install it. and run the remove app.

it also recommend removing these files manually (all of them were automatically deleted for me)

cd /Library/StartupItems/
sudo rm -rf Parallels
cd /Applications
sudo rm -rf Parallels
cd /System/Library/Extensions/
sudo rm -rf vmmain.kext
sudo rm -rf hypervisor.kext
sudo rm -rf Pvsvnic.kext
sudo rm -rf ConnectUSB.kext
sudo rm -rf Pvsnet.kext


NB: Remember SUDO will only work on Leopard OS X 10.5 when you have a password set.

Also I had some virtual machines that were very large in:
~/Documents/Parallels

and there was a shared folder created at:
/Users/Shared/Parallels

I deleted those 2 extra folders.

Wednesday, 24 June 2009

Blogger Minimum Profile Widget

I thought I would expand my profile on blogger.com / blogspot.com a little bit. Soon after doing so I noticed that the "About Me" widget which links to my profile had grown in size and included a full copy of the profile I had just written.

If I provide a link to a page all about me I dont expect the link to be an entire copy of that page why google thinks that this is a good behaviour I will never know.

There did not appear to be any option for the current widget to only provide the links, so I sought after my own method of doing this. I could not get the auto completion working to pull data from your blogger profile so unfortunately you will have to cut and paste all the links, but if you look here http://munkymorgy.is-a-geek.net/BloggerMinProfile/.

There are a few boxes to fill out/cut paste urls. click refresh to load the data into the preview, this also refreshes the text box at the bottom, which allows manual edits before clicking the "Add Min Profile Widget" which sends the data to blogger .com which them prompts you for which blog you would like to add the widget to.

If you do not like it they are very easy to remove. login (to bolgger.com) and got to customise, Layout, Page Elements, select the widget you want to edit / remove and select edit. The remove button is in the bottom left c orener of the new window.

Just for comparsison I include a small screen grab here:

New Minimum profile Widget on top, wierd original one below.

Saturday, 13 June 2009

Lightroom Shortcuts

Just a quick reminder to myself of some of the short cut keys available in Lightroom.

Overall control
f next view mode (show title bar)
l light table mode (blacks out everything except photo)
g Jump to Library Grid module
d jump to Develop module
tab toggles displaying side panels
shift-tab toggles displaying top/bottom panels

Photos selected in the film strip
p pick
u unpick
x reject

o Toggle mask when using Adjustment brush

cmd-backspace or Photo->"Delete Rejected Photos..."

In Develop Module
alt develop controls get individual resets!

Facebook nice url

Facebook has recently (this morning 1/06/2009) released the ability to have a nice or vanity url pointing to your profile. You know just like everybody (twitter myspace etc) has always had since always.

just login to facebook then go to facebook.com/username and select your username, certain ones seem to be blocked for some reason munkymorgy was not allowed.

Friday, 12 June 2009

iPhone (iPod Touch) sync google conatcts and calendar

Following the instructions here [1] it is easy to setup your iphone to sync your google contacts and calendars directly. Mail sync is not supported yet though. This all happens under the google sync project.

[1] http://www.google.com

Tuesday, 9 June 2009

Stuff that might be nice to have

Terra Nova Superlight Voyager 2009
http://www.uttingsoutdoors.co.uk/ £279

ThermaRest
Original £67 or Traillight £30

Headlamp
One with red leds for efficient night time Navigation

Camera gear
Canon EF 24mm f1.4L USM II
Review, Review, Buy
Canon EF 70-200 f4L IS USM
Review, Review, Buy

Sunday, 7 June 2009

Import flickr photos into Facebook

Just found this application [1] for facebook, which is very useful if you mainly post pictures to flickr.

[1] http://www.keebler.net/flickr2facebook/

You Have to authorise the appliaction in face book, getting to this page was a little tricky and cant remember how I did it. But once it is done you just add an link to your shortcuts and when ever you find a flickr image you want in a facebook album just click the link and it will upload it to the album of your choice.

Thursday, 4 June 2009

Create a link to your facebook profile

How Do I link to my facebook profile page was a question I often asked myself. It is actually quite straight forward. You just need to know your facebook id number. To find your facbook.com id number login then select the link which is just your real name left of 'settings' and 'log out'. This should take you to some thion like http://www.facebook.com/profile.php#/profile.php?id=604686891&ref=name

Shorten this to

http://www.facebook.com/profile.php?id=604686891

and start telling people. you need to login to see it. not sure what happens if you dont have permission to see it. and I dont know any one who is on facbook and does not already have me added as a friend so can not test it. Can some try this out and leave a comment as to what happens if you click the link and login.

There is lso links to make a face bookbadge which for me creates a link to this page:
http://en-gb.facebook.com/people/Morgan-Prior/604686891

Friday, 8 May 2009

Microsoft Word Changing Case

Changing the case of text in Microsoft Word is no longer done in the fomatting pane. It has its own 'Change Case' menu item.

Select/Highlight text then select Format -> Change Case

WordChangeCase01

Select from these 5 options. Sentences case is useful if you accidentally typed everything upper case

WordChangeCase02

Firefox shorcuts Tips and Tricks

If you use Subversion or other web based tools you might have cgi scripts/web pages that take the url of another page as an argument, this is a nice trick for easily entering the the new page with the other url as a refference.

Create a new shortcut in firefox.
Right click and select properties.
Set Name to What ever you would like.
Set Location to be:
javascript:location = 'http://newpage.com/new.php?url='+escape(location); void 0

goto google.com then select your new shortcut then you will load http://newpage.com/new.php?url=google.com

Tip Originated from here:
http://www.mvps.org/dmcritchie/firefox/kws.htm#url

Wednesday, 6 May 2009

Convert sections of Web pages to images

If you find a need to convert a web page into an image, say saving a section of a google map, Abduction is a good plugin for Firefox 3.

Once installed, just right click on the web page choose 'Save Page As Image'. A preview window then opens which lets you select which part gets included in the image, where and what image format.

Tuesday, 5 May 2009

Java delete non-empty folders

The Java File.delete(); method only works on empty folders to delete a folder and its contents recursivly do some thing like:


   public static void recDelete(File folder) {
if(folder.exists()) {
if(folder.isDirectory()) {
File[] files = folder.listFiles();
for(int i=0; i < files.length; i++) {
File curFile = files[i];
// call to delete the current file/folder
recDelete(curFile);
}
}
//If a folder Deleted all contents
//If a File Jump straight here
folder.delete();
}
}

Tuesday, 28 April 2009

Displaying code Snippets on blogspot

I have been trying to show pretty code snippets on blogspot.com/blogger.com. I found for larger files github.com displays code nicely but not very handy for short inline examples. Today I discovered prettify by google



This post describes setting up code.google prettify on blogger.com



Originally explained here:
http://lukabloga.blogspot.com



Include this before the head tag in the blogger template.



I have made a modified version of the css file suitable for displaying code on darkbackgrounds, I use this instead:





Then change the body tag to:



Then use the prettyprint class when using pre tags around code:



Monday, 27 April 2009

Scite bash script config

in Scite the config for bash/shell scripts are handled by the perl.properties by default.

I believe this is the section of the config file which applies it to .sh file by default.
file.patterns.perl=*.pl;*.pm;*.cgi;*.pod
file.patterns.bash=*.sh;*.bsh;configure

shbang.perl=pl
shbang.sh=sh

filter.perl=Perl (pl pm)|$(file.patterns.perl)|
filter.bash=Bash (sh bsh)|$(file.patterns.bash)|

lexer.$(file.patterns.perl)=perl
lexer.$(file.patterns.bash)=bash

Ruby Shoes, Get full path of current application

After reading this post [1] I though that [2] would return the full path, as the url suggest it is only a relative path. For Ruby scripts executing under Shoes the current dir can change so it is always best to refer to a full path. The short script at [3] should give just that.

[1] http://stackoverflow.com/questions/757455/relative-file-paths
[2] File.dirname($PROGRAM_NAME)

[3]:
def getFullPath
modulepath = File.expand_path($PROGRAM_NAME)
modulepath = $modulepath.gsub($PROGRAM_NAME,"")
return modulepath
end

Friday, 24 April 2009

Create new Repository on Github

github.com repositories are setup through the web page:
http://github.com/repositories/new

Which then forwrds you to these instructions (some of which can been done before setting up the repo):

Global setup:

Download and install Git
git config --global user.name "Registerd githubname"
git config --global user.email yourgithub@emailaddress.com

Next steps:

mkdir shoesexamples
cd shoesexamples
git init
touch README
git add README
git commit -m 'first commit'
git remote add origin git@github.com:git_hub_username/shoesexamples.git
git push origin master

Existing Git Repo?

cd existing_git_repo
git remote add origin git@github.com:git_hub_username/shoesexamples.git
git push origin master

Google Apps to host your Domain mail server

A mini howto forward you domain emails to google and get a gmail interface for your emails using use google apps.

Register at http://www.google.com/apps/
The standard edition is free and can have upto 50 users.

Now Configure Mail
https://www.google.com/a/cpanel/yourdomain.com/Dashboard
click "Activate Mail"

Follow Instructions for setting MX records
which are :
Priority Address TTL
1 aspmx.l.google.com 1week
5 alt1.aspmx.l.google.com 1week
5 alt2.aspmx.l.google.com 1week
10 aspmx2.googlemail.com 1week
10 aspmx3.googlemail.com 1week

The login page should be:
https://mail.google.com/a/yourdomain.com
or you can set up mail.yourdomain.com [instructions]

https://www.google.com/a/cpanel/yourdomain.com/DomainSettingsDomains
select "Service Settings" -> "Email"
Tell google what you want the domain to be.
Update your dns records by adding a cname with alias mail (should match the google setup), points to host name should be ghs.google.com ttl 1 week

It may take a few hours for google and world wide dns caches to update making it functional, just wait a and and at some point your new mail.yourdomain.com should spring to life.

Thursday, 23 April 2009

New file and directory permissions on unix

Unix and Linux based sytems define default file permissions with umask.
$ man umask

To see you current permissions just run:
$ umask
>0022


For a more user friendly format:
$ umask -S
>u=rwx,g=rx,o=rx

Person is User, Group and Other.
Properties are Read, Write and eXecute.

umask subtracts from the normal properties set by chmod.
Folder and file are the same, except files will never be set executable by default.
(the -- are just to allign the tables, the numbers are the decimal equivalent for a 1 set in that position)
--421,--421,--421
u=rwx,g=rwx,o=rwx


Say you (User) want full access to a file but not allow Group or Other access.
you want:
--421,--000,-000 ie 700
The mask would be
--000,--421,--421 => 077
to set this just run (and may be add to your ~/.bashrc file) :
$ umask 077

You (User) want full access, Group has read and execute and Other none
--421,--401,--000 ie 750
the mask would be:
--000,--020,--421 => $ umask 027

You (User) have full access and Group and other have read and execute.
--421,--401,--401 ie 755
mask would be:
--000,--020,--020 => $ umask 022

NB:
Q) How do i set umask to make files executable by default?
A) You can not create exectuable file by default using umask, it is thought to be a security issue.

Perl Variables

#Perl comments use #hash

Some general perl variables:
$scalar = 1 ; #String, integers, floats
print $scalar ;

@array = ("apple", "pair");
print $array[0];
print $array[1];

%hash = ();
$hash{"apple"} = 100;
$hash{"pair"} = 200;
print "Cost is $hash{"apple"} \n";

Perl shebang

The first (shebang) line of perl scripts should be:
#!/usr/bin/perl -w

Wednesday, 15 April 2009

Ruby decimal / frational to binary conversion

The following function can be used to convert decimal (fractional) numbers to binary format:

def dec2bin(number, int_bits, frac_bits, decimal_mark)
negative = false
if (number < 0)
negative = true
number = -number
end

## Create Integer only number
number_int = Integer(number);

## Create Fractional only number
number_frac = number - number_int;

## Create Integer Binary String
ret_bin_int = "";

## Create Fractional Binary String
ret_bin_frac = "";

##Integer
ret_bin_int = number_int.to_s(2) ;
padding_bits = int_bits - ret_bin_int.length ;
begin
ret_bin_int = Array.new(padding_bits, "0").join + ret_bin_int ;
rescue
puts "ERROR not enough integer bits to represent #{number}";
return -1;
end

## Fractional
ret_bin_frac = ""
fractional = 0
if (frac_bits > 0)
ret_bin_frac = Integer(number_frac * 2**frac_bits).to_s(2);
padding_bits = frac_bits - ret_bin_frac.length ;
ret_bin_frac = Array.new(padding_bits, "0").join + ret_bin_frac ;
fractional = ret_bin_frac.to_i(2).to_f / (2**frac_bits)
end

if (negative == true)
number = (ret_bin_int + ret_bin_frac).to_i(2)
#Perforrm this binary operation number = -number + 1
#In an integer number space
number = 2**(int_bits+frac_bits) - number
ret_bin_int = number.to_s(2)[0,int_bits]
ret_bin_frac = number.to_s(2)[int_bits, frac_bits]
end

binary = ret_bin_int + decimal_mark + ret_bin_frac;

## ret_bin Add decimal marker
return {
:binary => binary,
:int => number_int,
:frac => fractional,
:real => (fractional+number_int)
}
end


Example using the function:
intBits = 6
fracBits =4
converted = dec2bin(10.5, intBits, fracBits, "_")
puts converted[:binary]


NOTE:
Since first post I have fixed a fracbits=0 bug and now works with negative numbers (converting to a twos complement format)

Monday, 13 April 2009

module load fail when scripted

The following works on the command line
[1]$ module load something
but fails with [2] when used in make, bash, etc script files:
[2]> module: command not found

This is because the module enviroment has not been loaded, as it is for a normal user session.
Try using some thing similar to this before your module load call:
#!/bin/bash

. /usr/share/modules/init/bash
module load something

Friday, 10 April 2009

Scite sensible open action

I use the text editor scite which has a SciTEGlobal.properties file which defines the behaviour. I just found out about this option:

open.dialog.in.file.directory=1

When pressing open it forces Scite to start the open file dialog box in the folder of the currently active file.

Thursday, 9 April 2009

Java duplicate class error

I recently created a new class and when trying to compile my new code I got this error (below) and it took some time to figure out what the duplicate class error meant.

[javac] N:\morgan\utils\FileExplorer\src\fileexplorer\TransferListItem.java: 5: duplicate class: TransferListItem
[javac] public class TransferListItem extends JPanel {

The problem was that I had missed the package decleration at the start of the file.
so by adding "package fileexplorer;" on line 1 the error went away and the code started compiling again.

Saturday, 4 April 2009

Java loading Jar Resources

When moving from running java programs from a directory to running from inside a jar file, I ran into trouble with loading images.

I use to do the following :

fileIconLocation = "toolbarButtonGraphics/general/Edit16.gif";

//http://java.sun.com/docs/books/tutorial/uiswing/components/icon.html
/** Returns an ImageIcon, or null if the path was invalid. */
protected ImageIcon createImageIcon(String path, String description) {
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + imgURL.toString());
return null;
}
}


Once inside the Jar it can not find the file and always returns null.
Replacing getClass() with getClass().getClassLoader() seems to fix the problem.


protected ImageIcon createImageIcon(String path, String description) {
java.net.URL imgURL = getClass().getClassLoader().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + imgURL.toString());
return null;
}
}

Thursday, 2 April 2009

Adobe Lightroom 2.3 Updates

Adobe has released the third update to Lightroom 2. The updates can be downloaded from Adobe directly, and no need to dig out the serial number again as they do not require revalidation.

Adobe Lightroom 2.1 Update
Adobe Lightroom 2.2 Update
Adobe Lightroom 2.3 Update
NB: update 27/06/2009
Adobe Lightroom 2.4 Update

Tuesday, 31 March 2009

Apple Student Discount

For the best students discounts on Apple products visit http://apple.procureweb.ac.uk/ from in side you educational institutions network. If they are registered you will see the lowered prices.

Saturday, 28 March 2009

Ruby list directory contents

Ruby listing directory contents:
Dir.entries returns the array,
Dir.foreach itterates.
#!/usr/bin/env ruby 

mycontents = Dir.entries("/")
mycontents.each { |x|
puts x
}

Dir.foreach("/") { |x|
puts x
}

Friday, 27 March 2009

Sony BDP-S350 Resetting Screen Resolution

I bought a Sony BDP-S350 Blu-Ray player a while a go, but recently had to return my Samsung A686 Screen and used an older lower resolution monitor. When first switching back to the older screen I got the error message this screen does not support this resolution aargh!

Any way I found the manual online

And you wait 30 seconds with out doing anything, this means that all the menus will have defaulted back to a known state. Then press and hold stop on the player (not the remote) for 10 seconds, then the player defaults back to the lowest resolution and your ready to go again.

Thursday, 26 March 2009

Ubuntu adding/archiving on to new hard drive

So you just got a new bigger hard drive and want to use it to replace the main storage device on your Ubuntu Linux server, or just add the extra storage to it.

First powerdown (may not be necesariy with SATA) connect new drive and power up.
loggin and get to the terminal.

Find out the new device name, likely to be some thing along the lines of /dev/sdb
$ sudo fdisk -l
----
Disk /dev/sda: 1000.2 GB, 1000204886016 bytes
255 heads, 63 sectors/track, 121601 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0x00000000

Device Boot Start End Blocks Id System
/dev/sda1 1 121601 976760032 83 Linux

Disk /dev/sdb: 1500.3 GB, 1500301910016 bytes
255 heads, 63 sectors/track, 182401 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0xe53eaeaf

Device Boot Start End Blocks Id System
/dev/sdb

Not Formatted
----

It is the unformatted drive that we had to look out for.
Next Creat a partition table, It is a storage device so only want the one partition.

$ sudo fdisk /dev/sdb
press n to create new partition choose primary, the defaults should be good for use the full disk.
press w to save changes to disk.

This has created partition /dev/sdb1, which requires formatting for ext3 do:
$ sudo mke2fs -j /dev/sdb1

Creat a point to mount it, I only want this to be temprorayt but if it is for permenent installation choose the names carfully.
$ sudo mkdir -p /mnt/insertHostName/tempdrive

Mount it (One off)
$ sudo mount -t ext3 /dev/sdb1 /mnt/insertHostName/tempdrive/

To mount the drive on sytem restarts do:
$ sudo vim /etc/fstab
added this line
/dev/sda1 /mnt/hostname/partitionname ext3 rw,auto,async,errors=remount-ro 0 1
then reload the fstab (mount the new drive)
$ sudo mount -a

Now start the Archiving process (Copying the files from old drive on to new).
The -a flag is very good for this it will Recursively copy maintaining permissions, Access dates and recreate links.
$ sudo cp -a /mnt/insertHostName/oldDrive/* /mnt/insertHostName/tempdrive/

once the copy is complete you can compare the space used available using:
$ df -h
>Filesystem Size Used Avail Use% Mounted on
>/dev/sda1 925G 866G 12G 99% /mnt/insertHostName/oldDrive
>/dev/sdb1 1.4T 866G 451G 66% /mnt/insertHostName/tempdrive

Wednesday, 25 March 2009

Get those pesky .DS_stores off my network

Mac OS X has a very annoying habit of creating a .DS_store file in every folder it visits.

This is very annoying in a mixed OS network. So to disable this behaviour for remote drives (Samba, ftp, webdav) you can just enter this at the command line:
$ defaults write com.apple.desktopservices DSDontWriteNetworkStores true

To get at the command line (Terminal) you find it in /Applications/Utilities/Terminal.app

Beware though that it is the .DS_store that finder uses to decide on file location when in grid view and stores the notes on files in there as well. So these features (Notes and rearranging the icons) will be reset every time you leave the folder.

Sources 1 2

Why put a laptop drive in a desktop pc?

This is a follow on from my Low Power Server recommendation

Why do I keep talking about laptop drives:
A laptop drive in a fully active Read/Write state uses only 3 watts and can idle at less than 1Watt and when it spins down is next to nothing at all, and has ten times the life span of a desktop drive in terms of spin up/down toggles, but they are a lot more expensive per GB than a standard 3.5" desktop drive.

So extending the life of your server drives, getting better value for money and saving power can be reached by combining the 2 types of drive.

The bulk of your storage should sit on a 3.5" desktop drive, cheap storage. The server should spin down this power hungry drive after it has not been used for some thing like 1 hour, this ensure it is not spinning up/down all day, but saves loads of power when inactive for periods of time (You go to work and sleep at night, don't you?).

The Operating System should live on a 2.5" laptop drive which will be on for most of the time (because of writing to log files) but could handle a really short spin down inactivity time if you wished. This greatly reduced the idle power of your PC, assuming that you used a low power mother board and cpu.

Power Dissipation of laptop drive from Western Digital
Read/Write 2.50 Watts
Idle 0.85 Watts
Standby 0.25 Watts
Sleep 0.10 Watts


Power Dissipation of desktop drive from Western Digital
Read/Write 6.00 Watts
Idle 3.7 Watts
Standby 0.80 Watts
Sleep 0.80 Watts

Tuesday, 24 March 2009

Low Power Server Recommendations

Every one needs a low power server, my current recommendations are:

Option [1]
If you only require a Network drive this is a really good (cheap/simple) option (it does include some basic server functionality)
Icy Box Dual Disk with Gigabit NAS £100 http://www.scan.co.uk/ WikiSupport

Option [2]
However if you require custom services (Squeeze box, etc) then building your own is a good option:
Some thing based on an atom in a mini-itx form factor like: Jetway JNC92 £105
As much DDR2 memory as allowed (mini-itx often limits to 2GB)
Note: DDR2 is much more power efficient than the original DDR standard.

2GB DDR2 533MHz for the Jetway JNC92 is about £25

A cheap case like this from ebuyer would look reasonable for £25

I also installed Ubuntu on to an 8Gb USB flash drive for about £20. For wear and tear next time I would just use a laptop drive (£35 for a 120 GB or £50 for 320Gb), which could host the always on server parts like websites, torrents, ftp etc. and let the main storage drives spin down. If you are planning on this with only 2 sata sockets available you may want to put the laptop boot drive on a usb interface (£8 ebuyer, cant find summvision device)

Note:
I spent about £100 on a Jetway C7 1.2GHz J7F2WE1G2E not realising it could not take the Jetway expansion cards. As they make a very nice 3Socket 1GBit LAN Card. Turning your machine into a low power Gigabit switch as well (if you configure the OS to bridge the interfaces).

Option [3]
A nice alternative to putting together your own itx machine is the BBS2 for around £380 with the 2G RAM upgrade and VAT. Although 1 Drive must be the Operating System and since it uses its own mounting system low power 2.5" laptop drive can not be used for this task. It can then be set up with hardware raid on the remaining 4 channels, but Software raid is pretty good on Linux and Windows Home Server (Apparently)

The only really advantage of this over building your own system is the 5 Drive bays and Shiny case, which comes at a real price. Not forgetting if you built your own itx system you can easily add external usb drive to it, or get it to mount and share additional NAS drives like [1] or put in a large case and get some thing like this 12 port sata controller £600 or a 4 port sata controller £75

Note: The case recommended in [2] only has room for 2 hard drives using Raid1 or adding extra capacity the bootable drive if separate from the storage would have to be external.

Again the drive could be external in [3] if you wanted to use a laptop drive in 3.

Follow Up Post
Why put a Laptop drive in a desktop?