Monday, December 10, 2012

LINUX Links


If you plan to set your foot in LINUX world, out of the love for LINUX or due to hate for other OSs these links can come really handy for you. In the initial days you will need some assistance on basic stuff like how do I set up my WiFi, how to play Flash, or how to upgrade, update, how to change UNity to KDE & vice-versa. As time progesses you will be able to find your way out, but may need information on some esoteric issues like how to build application, do some kernel programming etc. All through the time, one thing is for sure. Access to GEEK community or otherwise called LINUX support group

Here are a few of them I constantly go to
Want information on LINUX kernels, their releases, logs and more such
http://kernelnewbies.org/

If you have specific questions on LINUX feel free to post it here
http://www.linuxquestions.org/questions/
If you need information on any of the Ubuntu families, these may be more than handy
http://www.itworld.com/software/325974/14-most-useful-linux-websites?page=0,3&source=ITWNLE_nlt_today_2012-12-06
http://www.omgubuntu.co.uk/
http://askubuntu.com/

Informative LINUX sites
I love reading the following sites
http://www.linuxtoday.com/
http://lwn.net/
http://www.linux-magazine.com/
This is a wonderful collection for LINUX geeks
http://www.linuxjournal.com/
This site is not as updated as some of the other sites are
http://www.linux-mag.com/

If you are in the LINUX work and is a games breed, here's one for you. There may be many more too. I am not a games person and I have this for the sake of the BLOG. Many people recommended this site to me when I was composing sites for LINUX
http://www.phoronix.com/scan.php?page=home

One of the best location for LINUX how to's and documentation
http://www.tldp.org/

Information on different trpes of dstro's and their download counts etc 
http://distrowatch.com/

Feel free to add more if you think there are some nice sites I missed









Sunday, September 30, 2012

Convert files to .mp4 format - Python Script

We all download videos of our favorite songs, animation, tutorials, movie, dramas from like's of youtube, blip.tv, vimeo etc.This artical is not about how to download these files, I'll reserve that for later. What I am going to tell you is something more intriguing.

Today is the world of gadgets. Our houses have variety of gadgets like iPhone, iPad, iPod, Android music players, Android phones, W8 laptops/tablets (& sometimes) W8 phones too. If you download video from any of these websites the format of the downloaed file is inconsistent. It can be mp4, avi, webm, flv...etc. Give the diversity of devices, it makes sense to have files in one format so as to maintain some consistency in the apps we downoad and use.

ffmpeg is an excellent utility for such conversions. You can install it with the command
sudo apt-get install ffmpeg

To convert (say) .webm file to .mp4
ffmpeg -i some_file.webm my_fav_file.mp4

That was easy, wasn't it? Yep it is. But imagine if you have to convert an entire collection of files. That will be an arduous task. Won't it be better if we could write a simple utility that will convert all files in a directory. Yep, that's where I am heading to. Here's a simple script that will convert .webm files to .mp4. You can easily customize it to convert any other file to .mp4, if you want to

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  ConvertToMP4.py


#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.

#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.

#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.


import glob
import os
from optparse import OptionParser

class ConvertToMP4:
    def __init__(self):
        self.webmFiles = []
       
    def get_all_wbm_files_from_directory(self, directory_name):
        print("Scanning directory: " + directory_name)
        if len(directory_name) == 0:
            print('ERROR: Source directory name cannot be NIL/NULL.')
            print('Provide a valid directory name to proceed!')
            return
        os.chdir(directory_name)
        for files in os.listdir('.'):
            if files.endswith('.webm'):
                print('convert file: ' + files)
                self.webmFiles.append(files)

    def convert_wbm_file_to_mp4_file(self):
        # check to see if the list is empty, if not proceed
        if len(self.webmFiles) <= 0:
            print("No files to convert!")
            return
        for webm_file in self.webmFiles:
            mp4_file = webm_file.replace('.webm','.mp4')
            cmd_string = 'ffmpeg -i "' + webm_file + '" "' + mp4_file + '"'
            print('converting ' + webm_file + ' to ' + mp4_file)
            os.system(cmd_string)

def main():
    usage = "usage: %prog -d <source directory for webm files>"
    parser = OptionParser(usage=usage)
    parser.add_option("-d", "--sourcedirectory", action="store",
        type="string", dest="sourcedirectory", default="./",
          help="source directory where all the webm files are stored!")
    (options, args) = parser.parse_args()
    webm_to_mp4 = ConvertToMP4()
    webm_to_mp4.get_all_wbm_files_from_directory(options.sourcedirectory)
    webm_to_mp4.convert_wbm_file_to_mp4_file()
    return 0

if __name__ == '__main__':
    main()

Even better, if you can provide a link to the utility and the utility download's it for you in mp4 format. That will be my next area of work

Audio issues in Ubuntu

I had some issues with the audio controls in my machine. I was not able to figure out what was going on. However after a restart things were back to normal. I was not able to figure out what was going on. The same thing happened one more time logs did not have much information either or may be I was not looking at the right places. However after witnessing this a couple of times, I noticed this was more a sound card issue

Here are some commands that helped me

Open Terminal and type the following command 'alsamixer'
You will be shown the sound card configuration, follow the help, re-configure  and your sound card will be back in action

Alternatively you can use pavucontrol too
sudo apt-get install pavucontrol

Pavucontrol widget makes it easy for you to setup and identify issues like this. Add it to startup application if needed (especially if you are using old computers)

Sunday, August 12, 2012

Xubuntu desktop for Ubuntu

I had long wanted to try XFCE for my Ubuntu. People had always appreciated XFCE for it's simplicity. For starters, post-installation, XFCE can be intimidating. Home screen after login will have nothing, absolutely nothing.

Right-click on the the desktop and create a panel with applets of your choice. Isn't that simple. If you are tired of looking at UNITY and don't like KDE and Ubuntu classic, XFCE is worth an experience to try. It gives a wonderful blend of customization and default behavior.

How to install Xubuntu desktop in Ubuntu12.04

sudo apt-get install xubuntu-desktop

If you did not like what you see, you can get rid of it in 2 ways. Here's how you can remove the items exclusively. You have a choice of cho0sing what you want to remove

Remove Xubuntu desktop completly from ubuntu 12.04
sudo apt-get remove abiword abiword-common abiword-plugin-grammar abiword-plugin-mathview bison blueman brltty-x11 catfish elementary-icon-theme exo-utils flex gigolo gimp gimp-data gmusicbrowser gnome-icon-theme-full gnome-system-tools gnome-time-admin gnumeric gnumeric-common gnumeric-doc gstreamer0.10-gnomevfs gthumb gthumb-data gtk2-engines-pixbuf gtk2-engines-xfce indicator-application-gtk2 indicator-messages-gtk2 indicator-sound-gtk2 indicator-status-provider-pidgin leafpad libabiword-2.8 libaiksaurus-1.2-0c2a libaiksaurus-1.2-data libaiksaurusgtk-1.2-0c2a libao-common libao4 libaudio-scrobbler-perl libbabl-0.0-0 libclutter-1.0-0 libclutter-1.0-common libclutter-gtk-1.0-0 libcogl-common libcogl5 libconfig-inifiles-perl libencode-locale-perl libept1 libexo-1-0 libexo-common libfile-listing-perl libfont-afm-perl libgarcon-1-0 libgarcon-common libgdome2-0 libgdome2-cpp-smart0c2a libgegl-0.0-0 libgimp2.0 libglade2-0 libgnomevfs2-extra libgoffice-0.8-8 libgoffice-0.8-8-common libgsf-1-114 libgsf-1-common libgstreamer-perl libgtk2-notify-perl libgtk2-trayicon-perl libgtkmathview0c2a libhtml-form-perl libhtml-format-perl libhtml-parser-perl libhtml-tagset-perl libhtml-tree-perl libhttp-cookies-perl libhttp-daemon-perl libhttp-date-perl libhttp-message-perl libhttp-negotiate-perl libid3tag0 libido-0.1-0 libilmbase6 libio-socket-ssl-perl libjpeg-progs libkeybinder0 liblink-grammar4 libloudmouth1-0 liblwp-mediatypes-perl liblwp-protocol-https-perl libmad0 libmailtools-perl libnet-dbus-perl libnet-http-perl libnet-ssleay-perl liboobs-1-5 libopenexr6 libotr2 libots0 libpolkit-gtk-1-0 libsexy2 libtagc0 libthunarx-2-0 libtie-ixhash-perl libtimedate-perl libtumbler-1-0 liburi-perl libwv-1.2-3 libwww-perl libwww-robotrules-perl libxfce4ui-1-0 libxfce4util-bin libxfce4util-common libxfce4util4 libxfcegui4-4 libxfconf-0-2 libxml-parser-perl libxml-twig-perl libxml-xpath-perl libxss1 lightdm-gtk-greeter link-grammar-dictionaries-en m4 mpg321 murrine-themes orage parole pastebinit pidgin pidgin-data pidgin-libnotify pidgin-microblog pidgin-otr plymouth-theme-xubuntu-logo plymouth-theme-xubuntu-text python-configobj python-glade2 quadrapassel ristretto screensaver-default-images synaptic system-tools-backends tango-icon-theme tango-icon-theme-common tcl8.5 thunar thunar-archive-plugin thunar-data thunar-media-tags-plugin thunar-volman ttf-droid ttf-lyx tumbler tumbler-common xchat xchat-common xfburn xfce-keyboard-shortcuts xfce4-appfinder xfce4-cpugraph-plugin xfce4-dict xfce4-fsguard-plugin xfce4-indicator-plugin xfce4-mailwatch-plugin xfce4-mixer xfce4-mount-plugin xfce4-netload-plugin xfce4-notes xfce4-notes-plugin xfce4-notifyd xfce4-panel xfce4-places-plugin xfce4-power-manager xfce4-power-manager-data xfce4-quicklauncher-plugin xfce4-screenshooter xfce4-session xfce4-settings xfce4-smartbookmark-plugin xfce4-systemload-plugin xfce4-taskmanager xfce4-terminal xfce4-utils xfce4-verve-plugin xfce4-volumed xfce4-weather-plugin xfconf xfdesktop4 xfdesktop4-data xfwm4 xfwm4-themes xscreensaver xscreensaver-data xscreensaver-gl xubuntu-artwork xubuntu-default-settings xubuntu-desktop xubuntu-docs xubuntu-icon-theme xubuntu-wallpapers && sudo apt-get install ubuntu-desktop

If that is way complicated for you, here are some other alternatives for you
sudo apt-get autoremove --purge xubuntu-* && sudo apt-get autoremove --purge xfce*
sudo apt-get autoremove --purge $( dpkg-query -l *xubuntu* | grep ii | tr -s " " | cut -d" " -f2; dpkg-query -l *xfce* | grep 'ii' | tr -s " " | cut -d" " -f2 )

Fix repository issues in Ubuntu

If you are experimenting on your LINUX PC chances are highly likely that you will mess up your repository. Then on it will be a pain to do an update, either through command line or from synaptic package manager

I am restless with my LINUX box all the time, I am either installing something in it or changing configurations. Quite recently I installed KDM/XFCE to evaluate it for my friend and I somehow seem to have  messed up my environment. Every time I attempted to execute "sudo apt-get update" I'd see the following message. I tried to go around the issue with Synaptic. But Synaptic will throw this error when I open it. So I was sort of struck and I need to get out soon. Here's what I had to do to fix it

Error
.......
.......
Fetched 2 B in 8s (0 B/s)                                                    
W: Failed to fetch gzip:/var/lib/apt/lists/partial/us.archive.ubuntu.com_ubuntu_dists_precise-updates_main_i18n_Translation-en  Encountered a section with no Package: header
W: Failed to fetch gzip:/var/lib/apt/lists/partial/us.archive.ubuntu.com_ubuntu_dists_precise-updates_universe_i18n_Translation-en
E: Some index files failed to download. They have been ignored, or old ones used instead.

Note: Make sure you close Synaptic/package manager before you attempt to do any of this

After a lot of hunt, I creates a simple shell script "fix_update.sh" with the following contents

sudo fuser -vvv /var/lib/dpkg/lock
sudo rm /var/lib/apt/lists/lock
sudo cp -arf /var/lib/dpkg /var/lib/dpkg.backup
sudo cp /var/lib/dpkg/status-old /var/lib/dpkg/status
sudo cp /var/lib/dpkg/available-old /var/lib/dpkg/available
sudo rm -rf /var/lib/dpkg/updates/*
sudo rm -rf /var/lib/apt/lists
sudo rm /var/cache/apt/*.bin
sudo mkdir /var/lib/apt/lists
sudo mkdir /var/lib/apt/lists/partial
LANG=C;sudo apt-get clean
LANG=C;sudo apt-get autoclean
LANG=C;sudo apt-get --purge autoremove
LANG=C;sudo apt-get update -o APT::Cache-Limit=25165824
sudo dpkg --clear-avail
sudo dpkg --configure -a
LANG=C;sudo apt-get -f install
LANG=C;sudo apt-get --fix-missing install
LANG=C;sudo apt-get update -o APT::Cache-Limit=25165824 && sudo apt-get dist-upgrade


Save the file
Grant execute privilege - chmod +x ./fix_update.sh
Execute the script - ./fix_update.sh
VOILA, you are good to go now
Save the file in your home custom scripts directory, it will always be handy

Saturday, August 4, 2012

Trackpad issues in Ubuntu


If you have problems with your trackpad - issues like right-click, drag etc. Out of the box it does not work because Ubuntu sometimes does not recognize that laptop does not have buttons over the trackpad to differentiate left and right-click's.

Here's a way to get around
Open terminal and do the following

If you are using a "samsung" laptop, do the following else skip this step
sudo add-apt-repository ppa:voria/ppa
sudo apt-get install update && sudo apt-get install upgrade
sudo apt-get install samsung-tools
sudo apt-get install samsung-laptop
sudo reboot

In the command prompt type xinput
You should see something like this along with other output

 ETPS/2 Elantech Touchpad                 id=12 [slave  pointer  (2)]

cd ~
wget "http://people.canonical.com/~cndougla/enable-clickpad.sh"
chmod +x enable-clickpad.sh
wget "http://people.canonical.com/~cndougla/enable-rightbutton.sh"
chmod +x enable-rightbutton.sh

Now that you have the scripts that will do the job for you and you have execute permissions set for them, do the following. Parameter 12 is passed to the script. We got the value from xinput  command's output (id=12). If you see some other value than 12 show up in your output, please use that
~/enable-clickpad.sh 12
~/enable-rightbutton.sh 12

Now you should be able to right-click, drag and drop easily without any external mouse.

Well issue now is when you restart your OS, all these changes are gone. You need this functionality all the time. Here's what you may have to do. Move those scripts to /usr/local/sbin directory

/usr/local/sbin/enable-clickpad.sh 12

sudo mv ~/enable-clickpad.sh /usr/local/sbin/
sudo mv ~/enable-rightbutton.sh /usr/local/sbin/

Open .gnomerc through gedit/vim/vi or editor of  you choice and type in the following
gedit ~/.gnomerc
/usr/local/sbin/enable-rightbutton.sh 12


If you don't like a naive .gnomerc file like the one above, feel free to add some error handlers to do things the way you want


That's pretty much it. Now reboot and enjoy

Wednesday, August 1, 2012

Compiz Settings for Ubuntu 12.04


Install compiz config settings manager from Ubuntu Software center

Animations and installations
In order to have support for all the animations of your choice like explode, Magic lamp, burn, 3D cube, etc, make sure you have done the following
sudo apt-get install compiz-fusion-plugins-extra compiz-fusion-plugins-main compiz-plugins

Make sure all of them are installed with out any errors

Wobbly windows
open Compiz Config Settings Manager from HUD or from terminal type "ccsm"
Select "Effects" from Category list on the left side
check on "Wobbly Windows". Make sure the checkbox is selected
Move the windows around you will see the windows wobble

Animation - Open window
open Compiz Config Settings Manager from HUD or from terminal type "ccsm"
Select checkbox against Animations
Select "Animation Add-on"
Click on Animations, that should show you more options for Animations
Select "Open Animations" tab and choose the first item, change the effect to "Leaf Spread"

Animation - Close Window
open Compiz Config Settings Manager from HUD or from terminal type "ccsm"
Select checkbox against Animations
Click on Animations, that should show you more options for Animations
Select "Close Animations" tab and choose the first item, change the effect to "Burn"

Animation - Workspace switcher
open Compiz Config Settings Manager from HUD or from terminal type "ccsm"
Select "Desktop" category from the left side of the settings manager
Select Checkbox "Desktop Cube"
Select Checkbox "Rotate Cube"
Click on "Rotate Cube", this will take you to more settings for "Rotate Cube"
Select Bindings tab choose keys you wish to use for "Rotate Left" and "Rotate Right"

Add compiz in startup
From HUD open "Startup Application"
Click on the Add button
Give it a name "Compiz" and set command as "compiz --replace"

Some common issues with CCSM and fixes
Non-movable windows
open Compiz Config Settings Manager from HUD or from terminal type "ccsm"
Select "Windows Management" from categories in the left
Make sure you have the following choices selected - "Move Window", "Resize Window", "Place Windows", "Extra Windows", "Extra WM Actions", "Window Rules"

Missing Title Bar
open Compiz Config Settings Manager from HUD or from terminal type "ccsm"
Select "Effects" from categories in the left
Make sure "Windows Decoration" is selected

Restart plugin
compiz --replace

Missing Unity
open Compiz Config Settings Manager from HUD or from terminal type "ccsm"
In the Filter search for "Unity"
Select the unity plugin that shows up in teh right
Make sure "Enable Ubuntu PLugin" is selected

Reset to default settings
open Compiz Config Settings Manager from HUD or from terminal type "ccsm"
Select Preferences
Select "Reset to Defaults"

Sunday, July 29, 2012

Things to do after UBUNTU 12.04 installation

Open up update manager and do an update


From HUD look for "Additional Drivers" and check to see if there are any available. If there are  additional drivers that need to be installed go ahead and install and restart
Note: If you "My Unity" application fails to open with the error "Your Ubuntu is enabled with 2 choice, its more often because of the additional display drivers that you may added. Deactivate them and you should be good


Install required s/w. Here are some of them I always install
  1. vim
  2. chrome - I remove Firefox
  3. IDLE with Python 3.2
  4. Audacity
  5. Cheese
  6. GParted
  7. Stellarium
  8. 7zip
  9. Skype
  10. MyUnity
  11. VLC Media player
  12. Nautilus plugin for opening terminal
  13. ShotWell Photo Manager
  14. Gimp Image Editor


When you are done with all of your installation, open terminal
(Now comes the fun part)

Save this command, you may have to it execute more than anything
sudo apt-get update && sudo apt-get upgrade

Install Ubuntu Tweak
Using Ubuntu Tweak you can install all needed applications with a simple click, you can change the window buttons from Left to right…etc.
sudo add-apt-repository ppa:tualatrix/ppa && sudo apt-get update && sudo apt-get install ubuntu-tweak

Install Cinnamon
If you don't like UNITY theme and want to try something else, cinnamon is a good choice, if you don't want Cinnamon and are happy with the way UNITY is, skip this one
sudo add-apt-repository ppa:gwendal-lebihan-dev/cinnamon-stable && sudo apt-get update && sudo apt-get install cinnamon

XBMC is a wonderful opensource media player
sudo add-apt-repository ppa:team-xbmc && sudo apt-get update && sudo apt-get install xbmc

Install common CODECs
sudo apt-get install libxine1-ffmpeg gxine mencoder totem-mozilla icedax tagtool easytag id3tool lame nautilus-script-audio-convert libmad0 mpg321

To play encrypted DVDs
sudo apt-get install libdvdcss2 && sudo /usr/share/doc/libdvdread4/./install-css.sh


Enable Full DVD playback

Though installing the restricted extras package will solve most of your problems, you may not be able to play dual layer dvds yet in your Ubuntu. Most commercial DVDs are encrypted with CSS (the Content Scrambling System), which attempts to restrict the software that can play a DVD.

sudo wget --output-document=/etc/apt/sources.list.d/medibuntu.list http://www.medibuntu.org/sources.list.d/$(lsb_release -cs).list && sudo apt-get --quiet update && sudo apt-get --yes --quiet --allow-unauthenticated install medibuntu-keyring && sudo apt-get --quiet update
sudo apt-get install libdvdcss2 

Install ccsm
sudo apt-get install compizconfig-settings-manager

Install restricted extras
sudo apt-get install ubuntu-restricted-extras

Install Unsettings
Unsettings is a newer application with similar tweaking options as MyUnity. More importantly, it has a useful 'Reset to Default' option
sudo add-apt-repository ppa:diesch/testing && sudo apt-get update && sudo apt-get install unsettings

Install XScreenSaver
sudo apt-get remove gnome-screensaver && sudo apt-get install xscreensaver xscreensaver-gl-extra xscreensaver-data-extra

Create a file to auto-start Screensaver
sudo gedit /etc/xdg/desktop/autostart.screensaver

paste the following lines in the file
[Desktop Entry]
Name=Screensaver
Type=Applicaton
Exec=xscreensaver -nosplash

Install Recent Notification indicator
sudo add-apt-repository ppa:jconti/recent-notifications && sudo apt-get update && sudo apt-get install indicator-notifications

Window Menus
If you want the Minimize, Maximize and close buttons to right
Install gConf Editor
sudo apt-get install gconf-editor 

open editor
gconf-editor

Go to the following: 'apps' -> 'metacity' -> 'general' Find the "button_layout" parameter,
Right mouse click, and select Edit Key.
Change the value to the following: menu:minimize,maximize,close then Press Enter

Change Wallpapers
Download all wallpapers from http://www.noobslab.com/2011/12/best-ubuntu-wallpapers-collection-for.html

Unzip the downloaded file and move them into /usr/share/background

Enable Nautilus to show amount of free space left
Open Nautilus file browser. Go to View - Statusbar. Enable it and you're done.

Calculator Lens/Scope for Unity Dash
sudo add-apt-repository ppa:scopes-packagers/ppa && sudo apt-get update && sudo apt-get install unity-lens-utilities unity-scope-calculator


Wednesday, May 16, 2012

GRUB load/boot issues.


All that you wanted to know about GRUB

1.
Boot your system using a "live CD" or "live DVD".
2.
Open a shell window and become root: sudo su
3.
For clarity, let’s discuss things using the shell variables $partition and $device. An example might be: partition=/dev/sda6 ; device=/dev/sda
4.
You need to know which partition holds the Linux system you want to boot. If you remember this, define $partition and $device accordingly, and skip to the next step. If you need to figure it out,
  • get a list of disk devices: ls /dev/sd? /dev/hd?
  • look at each such device: cfdisk $device or fdisk -l $device
    Look at the partition sizes and partition labels to find the partition that you want to boot. Define $partition and $device accordingly.
5.
Create a mountpoint: install -d /mnt/radicula
6.
Mount the partition containing your Linux: mount $partition /mnt/radicula
7.
Reinstall grub: grub-install --root-directory=/mnt/radicula $device
Beware: You want to install grub on the device (e.g. /dev/sda). If you install it on the partition (e.g. /dev/sda6), the grub-install program won’t complain, but the results won’t be what you wanted.
That’s probably enough to get you going. If you want to give it a try, shut down the live CD system, eject the CD, and reboot in the normal way from your favorite device (/dev/sda in the example).
If you want to improve your chances, you can do a little more work before rebooting.
8.
If the Live CD system has a /boot directory, move it out of the way: mv /boot /xxxboot
9.
Put the target system’s boot directory in its place: ln -s /mnt/radicula/boot /
10.
Back up the existing grub control file, namely grub.cfg (for Grub Version 2) and/or menu.lst (for Grub Version 1). If both exist, back up both of them. cd /boot/grub ; cp grub.cfg grub.cfg#1 ; cp menu.lst menu.lst#1
11.
Update the grub control file: update-grub.
Note that in Grub Version 1, update-grub writes the file menu.lst, whereas in Grub Version 2, it invokes grub-mkconfig to write the file grub.cfg.
Now you really should be ready to shut own the Live CD system, remove the CD, and reboot in the normal way.

1.2  Follow-Up

The procedures in section 1.1 were meant to get the system functioning again as quickly as possible. Now that the system is up and running, so that the time pressure is off, we can do some housekeeping:
  1. Optional: You may want to make sure your copy of the software is not corrupted: apt-get install --reinstall grub # (optional)
  2. You should make a backup of the MBR as described in section 3.1.
  3. Highly recommended: Rebuild the grub configuration file: update-grub
  4. Install the latest and greatest grub in the MBR: grub-install --recheck /dev/hda
In ideal situations, the work described in this section doesn’t accomplish much, because it duplicates the work done in section 1.1. However, consider the situation where the Live CD you used to restore the MBR is using a different version of grub. Maybe one system is out of date, or maybe just exercised the option to use a different version. This is your chance to install the grub version that your system thinks should be installed. If you don’t do this, you risk having some ugly problems later.

2  Scenarios and Alernatives

There are several scenarios that can lead to an MBR being overwritten or otherwise rendered unsatisfactory. Examples include:
  • On a dual-boot system, every time you install (or reinstall) Windows, it will almost certainly overwrite your MBR. See section 2.1.
  • A failed upgrade can leave grub in a bad state. In particular, if the system was using Grub Version 1 before the upgrade and wants to use Grub Version 2 afterwards, sometimes things get confused. I’ve seen it happen.
  • Viruses and other malicious software are fond of overwriting the MBR.
  • et cetera.

2.1  Dual Boot

Suppose you have a dual boot system, i.e. one that sometimes boots Linux and sometimes boots Windows. Every time you install (or reinstall) Windows, it installs its own boot loader into the MBR. This is a problem, because the MS boot loader will not load anything except the MS operating system ... in contrast to grub, which will happily allow you to boot almost anything: Linux, memtest86, various MS products, et cetera.
Some folks recommend installing MS before installing Linux, so that the Linux installation process will set up the MBR for you. This is fine as far as it goes, but it is not always possible. For instance, sometimes it is necessary to reinstall or upgrade the MS stuff, days or months or years after Linux was installed.
The grub-reinstall procedure described in this document takes only a few minutes, so feel free to install MS after Linux if you find it necessary or convenient to do so. MS will trash the MBR, but you can restore it using the techniques described here.

3  Backing Up and Restoring the MBR

3.1  Backup

It never hurts to make a backup of the MBR.
dd if=/dev/sda of=host1-sda.mbr count=1
If you have two or more Linux systems, use system "1" to store the backups pertaining to system "2" and vice versa. If you have only one system, store the backups on floppy ... and don’t forget where you put the floppy. (It does no good to store the backup on the same drive as the MBR you are backing up.)

3.2  Restore

Keep in mind that sector zero contains both the stage-0 boot code and the primary partition table. Therefore, before restoring the boot sector, you have to make a decision:
  • In the scenario where something trashes sector 0 including the partition table, then you want to restore the whole thing. This can rescue from what would otherwise be a very bad situation.
    dd if=host1-sda.mbr of=/dev/sda count=1
  • In the scenario where the partition table is not trashed, and has possibly changed since you backed up the MBR, you want to restore the boot code without disturbing the current partition table. You need to splice the backed-up boot code onto the current partition table before writing anything to sector 0. The procedure is:
    Keep a copy, just to be safe: dd if=/dev/sda of=damaged.mbr count=1
    Grab the good boot code from backup: dd if=host1-sda.mbr bs=1 count=444 > new.mbr
    Tack on the current partition table: dd if=/dev/sda bs=1 skip=444 count=68 >> new.mbr
    Write to disk: dd if=new.mbr of=/dev/sda count=1

4  Details

Some discussion of the MBR and the basic boot process can be found in reference 1.

4.1  Live CDs

  • Ubuntu: The Ubuntu Live CD that you used to install Ubuntu also serves as a nice Live CD, suitable for many purposes including the grub reinstallation process described here. So be sure to keep that CD handy. If you need to download a new copy, see reference 2.
  • Debian: The usual Debian install disk is not, alas, a fully-featured live CD. A rundown of the various Debian live CDs can be found in reference 3.
  • Slackware: RIP (reference 4) is a Slackware live CD, suitable for tasks such as grub reinstallation.

4.2  Superuser Privileges

We now discuss the step sudo su
For good reasons, when you fire up a typical live CD, you are logged in as an ordinary user, not the superuser.
You can exert superuser privileges on a command-by-command basis by prefixing each command with "sudo" ... but since every command we are about to do requires superuser privileges, it is easier to just become superuser once and for all by saying sudo su

4.3  Mountpoint

We now discuss the step install -d /mnt/radicula
Note that “radicula” is Latin for “rootlet” i.e. “little root”.
The name of the mountpoint doesn’t matter. Reasonable choices might include /tmp/root or /mnt/sda6. It’s just some directory. Any available directory can be used as a mountpoint.

4.4  Mounting Your Linux Partition

We now discuss the step mount /dev/sda6 /mnt/radicula
Not much to say, really. If you want the operating system to treat your partition as a collection of files and directories (as opposed to a bucket of bits) you need to mount it.

4.5  Grub Installation

We now discuss the step grub-install --root-directory=/mnt/radicula /dev/sda
The --root-directory=/mnt/radicula option tells grub where to look for the grub directory during the installation process. The grub directory is /mnt/radicula/boot/grub on typical distributions such as Ubuntu and Debian, but may be /mnt/radicula/grub on some *bsd setups.
The grub-install program uses the grub directory in several ways during the installation process. Among other things, it goes there to read the device.map file. It also goes there to write the core.img file. A new core.img file gets written each time you run grub-install.
Keep in mind that the Unix file system is essentially a graph (in the sense of graph theory) with edges and nodes. The edges are the paths, i.e. directory names and file names. The nodes do not have names. The nodes are where the data is stored. So: the inode of interest will be reached by the path "/mnt/radicula" during the installation process. Grub assumes this inode will be reached by the simple path "/" later, when the system on /dev/sda6 is actually booting and running.
The idea that the same inode could be reached by one path now and a different path later makes perfect sense if you think about it the right way. The grub-install program understands the distinction between the two, which is what makes it possible to reinstall grub using the easy procedure described in this document.
This distinction is, alas, not well documented. You could read the grub manpage all day and not learn anything about this distinction. The grub-install --help message says
  --root-directory=DIR    install GRUB images under the directory DIR
                          instead of the root directory
which seems somewhere between incomprehensible and self-contradictory. Is DIR the root directory (as suggested by the equation root-directory=DIR) ... or is DIR used "instead of the root directory" (as stated in the explanatory message)? Gaaack.

5  Using Grub Commands Directly

I hope you never need to know this. Usually the procedures described in section 1.1 make this unnecessary.
Imagine a scenario where grub is installed in the MBR correctly, but the grub configuration files are messed up, so all you get is the grub> prompt (rather than a menu of kernels that can be booted). Further imagine that you can’t fix it using the methods described in section 1.1.
You may be able to recover using the following procedure:
  • At the grub> prompt, type root (hd0,<tab>
    This will give you a listing of all the partitions on the hd0 device, along with their UUID, filesystem type, and modification date.
    If hd0 turns out to be not the device you want, try hd1 and so on.
  • Pick the partition you want, say #2, and issue the complete command: root (hd0,2)
  • At the grub> prompt, type linux /boot/vml<tab>
    This will give you a listing of all the filenames in the boot directory that start with “vml”. (If your kernel isn’t named vmlinuz-something, adapt these instructions accordingly.)
  • Pick the kernel you want, and issue the complete command, e.g.: linux /boot/vmlinuz-2.6.35.10 root=/dev/hde3
    Note that you generally have to add the root=... option to the linux command line.
    Beware that the way grub numbers disk devices {hd0, hd1, hd2, etc.} may be different from the way linux does it {sda, sdb, sdc, etc.} ... and the difference is not systematic. I have one system where hd0 corresponds to /dev/hde/. This is commonly an annoyance on systems that have a mixture of SATA and PATA devices.
    The numbering of partitions is also different, but the difference is systematic: grub numbers them starting from 0, while linux numbers them starting from 1, so grub partition (...,2) coresponds to linux partition /dev/...3 and so on.
  • At the grub> prompt, type initrd /boot/init<tab>
    This will give you a listing of all the initrd files. Pick the one that corresponds to your kernel, and issue the complete command: initrd /boot/initrd.img-2.6.35.10 or whatever.
  • Issue the boot command. The kernel should boot.
  • If the kernel panics because it could not mount the root fs, it means you guessed wrong about the root=... command-line argument. Maybe it is /dev/hda3 or /dev/sda3 or /dev/sde3. However ...
  • Remember that the kernel needs to know the root device twice, once when it is reading the initrd (initial ramdisk), and once again when it is starting the system for real. I have seen situations where the device is named differently in the two cases, in which case any device name you pick is going to be wrong in one context or the other, and the system will not boot correctly.
    The only way to handle this case is to refer to the disk by its UUID, using a construction of the form root=UUID=4240ce68-802b-4a41-8345-543fad0ec20f
    That is an obnoxious amount of typing, but with any luck you only have to do it once.
    Grub will tell you the UUID; see the first item in this list.
  • Once the system is booted, clean up the mess using the methods described in section 1.2.

Saturday, January 14, 2012

Ruby in a day

What is Ruby?
Ruby is a general purpose object oriented scripting language. It is inspired by PERL with Smalltalk like features. It is also functional, dynamic, imperative and reflective in all sense. It hase dynamic type system and contains automatic memory management.
Ruby was conceived on Feb 24, 1993 by Yukihiro Matsumoto, who wished to create a new language that balanced functional programming with imperative programming.


Reference
http://www.ruby-lang.org/en/


Learning a programming language
There are different ways to learn new programming/scripting language. Understand the basics and start with a simple project, keep building on the project until all areas you read are implemented in the project one way or the other. Or you can learn it by going over the basic syntax for the language. One you have the basic syntax, you can develop small modules that help you understand the basics, you inch forward until you become fairly comfortable with the language. Different people tend to have different approaches, I prefer the later approach. Reason, you hardly get dedicated time these days to pick up a project, and work end-to-end. It may take days, and some times weeks to read 200 page book. Given these limitations the second approach works better (for me). Why am I saying all this, because, I am going to run this page with the later approach, pick up bits and pieces of the language, connecting the dots is left to you. I'll throw some simple programs with some basic comments you can understand, follow and come up with your conventions. If you find any of the programs/solutions are not correct, feel free to shout, I'll try to attend to the as fast as possible.


Do I have the right tools with me
There are so many tools available for you to start programming Ruby - IronRuby, Eclipse (check Eclipse.org), NetBeans, JRuby plugin for Eclipse, and the list goes on

Let's get started
Ruby programs can be done with


Why should I always say HelloWorld first
Because you are asked to do so :) Let's follow the legacy without any more question
HelloWorld sample and Let's name it HelloWorld.rb


class HelloWorld
def initialize
puts("\nHello World\n")
end
#MAIN
helloWorld = HelloWorld.new

Let me take a minute to go over this simple program. In the above code we have created a simple class that contains nothing more than a 'initialize' (equal to a constructor in other languages like C++, C#, etc). There are no main methods in Ruby code. Anything that's coded outside a class is considered to be the main method


There are multiple ways to print text, variables. 'print' and 'puts' methods are nice ways to output text. If you want to print a value of a variable you can always do that by following the simple syntax of #{variable_name}


Well, I know what you are think. Alright, Alright, how do I accept some input form the user to print it back or manipulate on. That's where the 'gets' method come's in. Try this one out
 def self.acceptNameAndSayHello
puts("\nYour name please: ")
name = STDIN.gets
puts("\n")
print %Q{Hello friend: #{name}}
puts("\n")
end

A simple class with definition
Let's do a little more now. What if I want to add more functions that accept parameters. Here's another sample of the same.


class HelloWorld
def initialize
puts("\nHello World\n")
end

def SayHello(name)
print %Q{Hello friend: #{name}}
puts("\n")
end

def self.SayHello
print %Q{Say hello}
puts("\n")
end
end

#MAIN
helloWorld = HelloWorld.new
HelloWorld.SayHello
helloWorld.SayHello("Krishnan")

Ruby by virtue of being a scripting language, does not have any data-types. That's right feel free to use variables of your choice. Variables are dynamically associated to their types based on how they are initialized. More on that later. For now, let's move on. One point you may want to remember is, Ruby is case sensitive. If you have initialized a variable "myName" and by mistake you use "MyName" else where in the code, consider you are out of luck. That won't work the way you wanted. So make sure what you type in


Remember the first function to execute in a class is 'initialize'.


Try out sample of code that returns a variety of data types - String, integer, floating value, boolean, etc


Basic conditions sample
Now that we have got some functions on the roll, how do I do some decision making - if, else if,switch statements at a glance

Simple If condition, and ternary operator

def SimpleIfCondition(name)
if(name != nil && name.length > 0) then
print "Name is not NIL!!!"
end
end
def SimpleIfElseIfCondition(designation)
if(designation == "Manager") then
puts("\nWelcome manager, hope you will have a nice day!")
elsif (designation == "Employee") then
puts("\nWelcome employee. Now shut-up and goto work!")
end
end

def SimpleTernaryOperation(name)
puts "\n Your name is #{name}"
isAdmin = (name == "Yukihiro Matsumoto") ? true : false
if(isAdmin) then
puts "\nWelcome administrator!"
else
puts "\nNot an administrator"
end
end



Switch case condition usage

def SimpleCaseCondition
print "\nEnter day today: "
day = STDIN.gets
day.chomp!
case day
when 1:
print "Sunday"
when 2:
print "Monday"
when 3:
print "Tuesday"
when 4:
print "Wednesday"
when 5:
print "Thursday"
when 6:
print "Friday"
else
print "Saturday"
end
end
end

Picking up a scripting language is pretty easy in early days and it can't get more simple than this. Let's keep rolling and move on to do some loops in Ruby




Basic loops sample
Loops help us to execute a single/set of statements multiple times or until a condition is satisfied. Ruby feeds developers with a lot of choices when it comes to loops, use them judiciously based on your needs - Until, while, for, Times, upto, downto and loop are the choices, example below may help you understand these easily




class SimpleLoopDemonstration
#until loop
def SimpleUntilLoop
x = 1
until x >= 10 do
puts x
x += 1
end
end
# while loop
def SimpleWhileLoop
x = 1
while x <= 10 do puts x x += 1 end end # for loop def SimpleForLoop x = 1 for x in 1..5 puts x end end # time's loop def TimesLoop 10.times { x PrintText(x) } end def SimpleUpTo PrintText("Simple Up To") 1.upto(10) { x PrintText(x) } end def SimpleDownTo PrintText("Simple Down To") 10.downto(1) { x PrintText(x) } end def simpleLoop x = 1 PrintText("Simple Loop") loop do x += 1 if x == 3 then break elsif x == 5 then next else PrintText(x) end end end def PrintText(someText) puts(someText) end end # MAIN part of the program puts "Hello World" simpleLoop = SimpleLoopDemonstration.new simpleLoop.SimpleWhileLoop puts "Until loop" simpleLoop.SimpleUntilLoop puts "for loop" simpleLoop.SimpleForLoop puts "10 times loop" simpleLoop.TimesLoop simpleLoop.SimpleUpTo simpleLoop.SimpleDownTo simpleLoop.simpleLoop








Now that we know the basic conditions and iterations, you can try different mathematical operations to get more comfortable in each of them


Here are some sample on string manipulation



class SimpleStringOperations
def initialize
@myText = "simple string manipulations"
end

def createString(str)
@myText = str
end

def concatenateText(attachText)
newText = @myText + attachText
return newText
end

def concatenateNumericValue(numericVal)
newText = @myText + numericVal.to_s
return newText
end

def removeLastChar
newText = @myText.chop
return newText
end

def findLength
return @myText.length
end

def reverseText
return @myText.reverse
end

def changeCase(toUpperCase)
return (toUpperCase == true) ? @myText.upcase : @myText.downcase
end

def self.printText(message)
print %Q{#{message}}
puts("\n")
end

def getText
return @myText
end

end

#MAIN part
stringOperations = SimpleStringOperations.new
stringOperations.createString("I love programming Ruby")
SimpleStringOperations.printText(stringOperations.getText)
newText = stringOperations.concatenateNumericValue(2.1)
SimpleStringOperations.printText(newText)
SimpleStringOperations.printText("Length of text is :" + stringOperations.findLength.to_s)
SimpleStringOperations.printText(stringOperations.reverseText)
SimpleStringOperations.printText(stringOperations.changeCase(true))
SimpleStringOperations.printText(stringOperations.changeCase(false))
SimpleStringOperations.printText(stringOperations.removeLastChar)



Want help on the function definitions, here's how you can get them


Simple mathematical operations
Integer and float point functions are used the same way we used string manipulation functions on string variables. Here are some functions that may come handy - abs, ceil, coerce, mod, floor, remainder, etc. There is one additional function that surprised me - next, succ. These 2 functions does an increment operation (similar to ++ in C++, C#). Here's a one simple implementation that you may not have seen so for. Note the way '?' has been used in the sample. That's how BOOLEAN functions are tested in RUBY


def valueIsInteger(inValue)
(inValue.integer? == true) ? printMessage("variable IS integer") : printMessage("variable IS NOT integer")
end



Object Oriented programming
If not for OOP, we can as well go ahead and so everything in something like Shell, Python and Perl. By virtue of being a scripting languages, Ruby does not support all features of OOP.
Here are a few of them that may help


Encapsulation & Abstraction
So far in all of the samples you may have noticed the usage of functions. Have we seen access-specifiers yet. Nope. We have 3 of them - 'public', 'private', 'protected'. As the name implies, Public is meant for complete access, private is meant for internal access only and protected is restricted access in hierarchal structure. A simple sample is added here, you can experiment more on them when you get a bit


Simple inheritence
Ruby supports single inheritence, meaning you can derive from a singular class only (unlike C++). I have created a simple sample to explain inheritence. Example is self-explanatory, and will give you an easy understanding of how inheritence works in Ruby. You may want to attempt some code changes like change the access specifiers, add functions, properties to the class and see how the overall behavior is




class LogMe
def self.Print(message)
print %Q{#{message}}
puts("\n")
end
end

class Person
public
attr_accessor :firstName, :lastName, :gender
private
attr_accessor :dateOfBirth
public
def initialize
end

def initialize(inFirstName, inLastName, inGender, inDateOfBirth)
@firstName = inFirstName
@lastName = inLastName
@gender = inGender
@dateOfBirth = inDateOfBirth
end

def getName
return @firstName + " " + @lastName
end

def getAge
# calculate Age from date of birth
return Time.now - @dateOfBirth
end

def personDetails
LogMe.Print("Name: " + getName + ", Age: " + getAge.to_s)
end
end
class Employee < Person protected attr_accessor :empId, :designation, :salary, :type public def initialize(inFirstName, inLastName, inGender, inDateOfBirth, inEmpId, inDesignation, inSalary, inType) super(inFirstName, inLastName, inGender, inDateOfBirth) @empId = inEmpId @designation = inDesignation @salary = inSalary @empType = inType end def provideEmployeeDetails personDetails LogMe.Print("Employee Id: " + @empId.to_s + ", Designation: " + @designation + ", Type: " + @empType) end end #MAIN part #person = Person.new "Bob", "Fredunberg", "Male", Time.local(1971, 3, 4) #LogMe.Print("Name: " + person.getName) #LogMe.Print("First Name: " + person.firstName) #LogMe.Print("Age: " + person.getAge.to_s) employee = Employee.new("Bob", "Fredunberg", "Male", Time.local(1971, 3, 4), 1, "Scintist", 300000, "Permanent") employee.provideEmployeeDetails






Polymorphism


Class, instance and global variables


Arrays
Handling arrays in RUBY is one of the most easiest to do. We have an in-built generic class 'Array'. Use Array class to instantiate a new instance for your case and use the tons of in-built functions to manipulate it. I have provided a simple example of a 'Family' were in persons are added, searched for, updated and removed. Hope this explains how Arrays work at a higher level. There are more functions available for the class please go through the RUBY manual to make effective use of them




class SimpleArray
attr_accessor :family

def initialize()
@family = ["Sam", "Bob", "Fred", "Smith"]
end

def AddPerson(person)
memberCount = @family.length;
@family.push(person)
end

def RemovePerson(person)
memberIndex = GetMemberIndex(person)
if(memberIndex > -1) then
@family.delete_at(memberIndex)
end
end

def RemoveAllMembers
@family = []
end

private
def GetMemberIndex(familyMember)
memberCount = 0
@family.each do member
if(familyMember == member) then
return memberCount
end
memberCount += 1
end
return -1
end

public
def Listfamily
if(@family == nil @family.length <= 0) then print %Q{@family is NIL. Please load values into @family} else puts(@family) end end private def searchFor(person) return @family.include?(person) end public def SearchPerson(person) if(@family == nil @family.length <= 0) then print %Q{There are no members in the family to search for.} return end if(searchFor(person) == true) then print %Q{Found the person. He's part of this family} else print %Q{Sorry, he's not a member of this family} end end def ReplacePersonWith(oldPerson, newPerson) if(searchFor(oldPerson) == true) print %Q{Found person: #{oldPerson}} end memberIndex = GetMemberIndex(oldPerson) if(memberIndex > -1) then
@family[memberIndex] = newPerson
print %Q{Member replaced!!!}
end
end
end

# MAIN part of the code
myfamily = SimpleArray.new()
myfamily.AddPerson("Mari")
puts("\n")
myfamily.Listfamily
myfamily.SearchPerson("Peter")

myfamily.ReplacePersonWith("Mari", "Mary")
puts("\n")
myfamily.Listfamily
myfamily.RemovePerson("Mary")
puts("\n")
myfamily.Listfamily




Maps
Arrays provide sequential access to a collection, what is you want to have a random access, Maps are the best alternative. use 'Hash' class to achieve the same. Take a look at the following sample to understand how to use it. In my sample I store name for a website (as key) and the website (as value). You can think of something that will make you understand better, if this does not suffice


class SimpleMaps
attr_accessor :urls
def initialize
@urls = Hash.new
print %Q{Hash map initialized}
end

def AddUrl(key, value)
LOG("\nAdd a URL #{key} with #{value}")
@urls[key] = value
end

def ListMap
LOG("\n Map List")
@urls.keys.each do key
LOG("\nKey is #{key}")
end
end

def SearchForUrl(inkey)
LOG("\nSearch for URL: #{inkey}")
@urls.keys.each do key
if(key == inkey) then
LOG("\nFound the #{inkey}")
end
end
end

def SearchForValue(invalue)
# check for contains too
LOG("\nSearch for value: #{invalue}")
@urls.keys.each do key
if(@url[key] == invalue) then
LOG("\nFound the #{invalue}")
end
end
end

private
def FindKey(inkey)
@urls.keys.each do key
if(key == inkey) then
return true
end
end
return false
end

public
def RemoveUrl(key)
LOG("\nRemove URL #{key}")
if(FindKey(key) == true) then
@urls.delete(key)
end
end

private
def LOG(message)
print %Q{#{message}}
end

end

# MAIN section
maps = SimpleMaps.new
maps.AddUrl("IT news", "www.zdnet.com")
maps.ListMap
maps.SearchForUrl("IT news")
maps.RemoveUrl("IT news")
maps.ListMap
Simple Regular expressions
Regular expression are life-lines for string manipulations. Any programmer who wishes cut short his work time on string manipulations should posses expertise in regular expression. It's an exciting subject, aptitude of a developer is intensely tested when working on complex regular expressions. Here are some samples to start with but you may want to build on these.


class LogMe
def self.PrintMessage(message)
print %Q{#{message}}
puts("\n")
end
end

class SimpleRegularExpressions

def initialize
end

def textContainsWord(inText, searchWord)
return (inText =~ /#{searchWord}/) ? true : false
end

def textContainsAnyOfWords(inText, inWord1, inWord2, inWord3)
return (inText =~ /#{inWord1} #{inWord2} #{inWord3}/) ? true : false
end

def doesTextStartWith(forWord)
return ("This is a sample text" =~ /^#{forWord}/i) ? true : false
end

def doesTextEndWithWord(withWord)
return ("This is a sample text" =~ /#{withWord}$/)
end

def doesMatchCollectionCharacters
if("This is a zample text" =~ /(svjk)ample/i) then
return true
end
return false
end

def someMoreSamples
string1 = "Steve was here"
# folowing condition will match for Steve, here too
if(string1 =~ /e.*e/) then
LogMe.PrintMessage("Found matching text")
end
# what if I want to find occurrences and information on them
string1 = "I will drill for well"
if(string1 =~ /(w.ll)/) then
print "Matched on ", $2, "\n"
end

string1 = "My phone number is (508)-001-1234"
if(string1 =~ /.\d{3}.{2}\d{3}.\d{4}/) then
LogMe.PrintMessage "Found a phone number"
end
end
end

# MAIN section
inText = "This is a sample text for RUBY regular expression sample"
regExp = SimpleRegularExpressions.new
if(regExp.textContainsWord(inText, "sample")) then
LogMe.PrintMessage("Found text match")
else
LogMe.PrintMessage("Sorry, canot find text")
end

if(regExp.textContainsAnyOfWords(inText, "PERL", "Python", "iOS")) then
LogMe.PrintMessage("Ah. Looks like the text is on scripting language")
else
LogMe.PrintMessage("Sorry, does not contain any message on scripting languages")
end

if(regExp.doesTextStartWith("This") == true) then
LogMe.PrintMessage("Start's with \"This\"")
else
LogMe.PrintMessage("Does not start with \"This\"")
end

if(regExp.doesTextEndWithWord("samples text")) then
LogMe.PrintMessage("Does end with \"sample\"")
else
LogMe.PrintMessage("Does not end with \"sample\"")
end

if(regExp.doesMatchCollectionCharacters) then
LogMe.PrintMessage("matches collection characters")
else
LogMe.PrintMessage("Does not match collection characters")
end
regExp.someMoreSamples







Simple file operations
Now that we have seen many areas of RUBY, one last step is handling files. How do I read, write into a file. RUBY provides us with 'File' class that has a variety of methods to create, open, read, write, rename, delete a file. In addition, it also allows us to query the type of file, check to see if the given path refers to a file or a directory, check to see if the location is valid and a lot more. I have provided a basic example, please refer to RUBY documentation to know more about this Object



class SimpleFileOperations
public
attr_accessor :file
attr_accessor :fileName

def initialize
@file = File.new("/Users/Rick/Private/Information.txt")
@fileName = "/Users/Rick/Private/Information.txt"
end

def closeFile
if(!@file.closed?) then
@file.close
end
end

def IsFileReadable
File.readable?(@fileName) ? true : false
end

def IsFileWritable
return File.writable?(@fileName) ? true : false
end

def IsFileExecutable
return File.executable?(@fileName) ? true : false
end

def fileSize
if(File.zero?(@fileName)) then
return 0
end
return File.size(@fileName)
end

def fileType
return File.fType(@fileName)
end

def someMetaInformation
print %Q{File Created on: #{File.ctime(@fileName)} and last modified on: #{File.mtime(@fileName)} and last accessed on: #{File.atime(@fileName)}}
end

def readFile
puts("Read File - #{@fileName}\n")
@fileName="test.dmp"
begin
@file = File.open(@fileName)
#@file.each {line puts(line)}
while(line = @file.gets)
puts(line)
end
@file.close
rescue => err
puts "Exception: #{err}"
err
end
end

end

# MAIN section
puts("Hello world")
fileOperations = SimpleFileOperations.new
puts("File options - Read: #{fileOperations.IsFileReadable}, Write: #{fileOperations.IsFileWritable}, Execute: #{fileOperations.IsFileExecutable}")
puts("File Size: #{fileOperations.fileSize}")
#puts("Type: #{fileOperations.fileType}")
puts("Some meta information")
fileOperations.someMetaInformation
fileOperations.readFile
What we/you may want to do next
I'll add more posts on the following sections
  1. Have a sample for OOP - develop a utility application
  2. More samples on regular expression
  3. More examples on File based operations
  4. Polymorphism explanation