Friday, November 30, 2012

Getting Started with Ruby

After more than two years of absence from my blog I thought of coming back to document something with which I've got my hands on these days. After coding for about an year in python I thought of giving Ruby on rails a go. But one thing I discovered when I went to setup ruby was that there wasn't any consistent guide that explained how to setup ruby on both linux & mac environments. So I thought of documenting what I went through when I first setup Ruby on my mac & linux machines with the hope that this would become useful to someone else in the future.
            First of all if you're planning to start doing web development with a scripting language like ruby or Python it's always a best practice to setup your development environment in either a linux box or a mac. From past experience I could say that Setting up Ruby/Python on a windows box & getting it up and running for software development is simply just painful.
             To get things going firstly we need to install the RVM or the Ruby Version Manager. This is something similar to the Python Virtualenv utility that enables us to install several versions of ruby on the same machine.Plus it's also the way how 'cool kids' install Ruby these days.
  •  To install the RVM first download using curl on your Linux box or your mac using the terminal.  
 curl -L get.rvm.io | bash -s stable  
       
           If you're using a linux box (in my case ubuntu 12.04 LTS) you also can simply install rvm using the apt-get utility.

 sudo apt-get install ruby-rvm  
  • Then On mac you have to make the RVM available in the terminal by editing the .bash_profile     file as follows. In linux this is usually added automatically.
 cd ~/  
 sudo vim .bash_profile  

          Then add the following line at the bottom of that file as follows,then quit and reopen the terminal again.

 [[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm"  
  •  If you're on a mac before proceeding further to the next step make sure you have the XCode  latest version installed on your system with the command line tools support.
  • Now you can check the available  versions of ruby using the rvm tool.
 rvm list known  

  • Now you could simply install the latest version of ruby using the rvm as shown below. The latest version number of Ruby at the time of writing is 1.9.3. Make sure you always install the latest version.
 rvm install 1.9.3  

  • Now make sure you're making use of the latest installed version of the ruby.
 rvm use 1.9.3  

      If you get an error when running the above command on a linux terminal then  select preferences
      from the edit menu and make sure you've checked the "run command as login shell" check box 
     under the "title and command" tab.
  • Now let's make the latest version of ruby the default.
 rvm --default use 1.9.3  

      You can also check the current version of the ruby like;

 ruby -v  

Important : When you're running the above commands on the terminal make sure you're not using the 'sudo' as it would simply install and configure ruby for the root user and not the current user.
  • Ok now we've installed ruby properly it's time to install rails. The rails come as a gem in ruby,which is similar to a package in python. For installing gems in Ruby we could use the 'gem' command,which is the 'pip' equivalent of python for Ruby.
 gem install rails  
  • Once you've installed rails on your machine it's time to test it out by creating a sample application. This is as simple as typing a single command in Ruby.
 rails new mynewappname  

The above command will generate all the files and folder structures of a sample web application inside a folder named "mynewappname",this will be more than enough for you to get started on developing your first web application out of the box.
  • Now you can simply run  the web application  using the Ruby's development server.
 cd mynewappname  
 rails server  

Note: If you get and error when you run the development server in Linux saying it couldn't find a Javascript runtime then make sure you've installed the Node.js as shown here.
  • Now you could view the sample/demo web application on your local web browser. By connecting to localhost on port 3000.
 localhost:3000/mynewappname  


Conclusion

This article shows how quick and easy it is to start developing dashing web applications using the Ruby on Rails. And these days in the ever changing and rapidly progressing world of web development , language tools like Ruby on Rails and Django python leads the pack !!. Hope this post was helpful to you. If you have any questions or doubts with regard to the Ruby on Rails setup please drop a comment below.

Thanks,
./Ramesh




Some Useful MySQL Commands Used Day to Day

Today I thought of presenting you with something of a little different taste.Therefore I thought of publishing some useful and more common mysql commands that will be useful to developers in their day to day development tasks. As mysql is the most commonly used opens ource database in java EE based development I think this post content will be useful to a lot of novice fresh graduate developers who are entering the industry. I've used a small mysql comment line to explain briefly the purpose of each command mentioned below.
  -- Getting a MySQL Dump(From remote DB):  
  mysqldump -u root -ppassword -h server_name db_name > database_dump_name.sql 
   
  -- Restore a MySQL Dump(To remote DB):    
  mysql -u root -ppassword -h server_name db_name < database_dump_name.sql 
   
  -- Output Data To a File    
  SELECT * FROM table_name INTO OUTFILE 'c:/file_name.file_extention';   
 
  -- Optimize Data Table : Used to defragment the table data file    
  optimize table table_name;    

  -- Monitor/View MySQL Memoty Usage On Linux /shell    
  top -u mysql    

  -- Create an Index for an existing Table In MySQL    
  CREATE INDEX table_column ON table_name(table_column);    

  -- Create a New User and Assign him all privileges to an existing database   
   GRANT ALL ON cpsdb.* TO user@localhost IDENTIFIED BY 'password';   

Wednesday, December 23, 2009

Java Based Photo Organizer

Today,while going through my office x-mas party photos on fb, I came across a new idea that could be implemented quickly & could be very useful. It was a simple java class file that we can use to re-order the photos depending on their last modified time stamp. After about 3 hours of coding & testing I was able to produce the following piece of code.You can re-use this code to order them,number them and re-encode them. This is currently implemented in command line mode. But could be easily integrated to a java desktop of web application front end. I thought of publishing it as I thought it could be useful to anyone in the future.

Following is the Code Listing for the Java Based Photo Organizer Class
 import java.awt.image.BufferedImage;   
  import java.io.File;   
  import java.io.FilenameFilter;   
  import java.util.Arrays;   
  import java.util.Date;   
  import java.util.Iterator;   
  import java.util.List;   
  import java.util.Scanner;   
  import javax.imageio.ImageIO;   
  /**   
  *    
  * @author mootarpe   
  */   
  public class PhotoSorterMain {   
    // Program Constants   
    private static String IMAGE_PREFIX = "shen747";   
    private static int IMAGE_ST_INDEX = 1;   
    private static final String OUT_FOLDER = "sorted_out";   
    /* Method Sorting the Images Using Binary Sort Algorithm */   
    private List sortImages(List imageList) throws Exception {   
       // Convert List to Array   
       File[] f = (File[]) imageList.toArray(new File[0]);   
       // Sort the Array Uisng bubble sort   
       for (int i = 0; i < (f.length - 1); i++) {   
         // Loop once for each element in the array.   
         for (int index = 0; index < (f.length - 1) - i; index++) {   
            // Once for each element, minus the counter.   
            if (getTimeStamp(f[index]) > getTimeStamp(f[index + 1])) {   
              // Test if need a swap or not.   
              System.out.println("Swapping File -> " + f[index].getName()   + " with " + f[index + 1].getName());   
              // These three lines just swap the two elements:   
              File temp = f[index];   
              f[index] = f[index + 1];   
              f[index + 1] = temp;   
            }   
         }   
       }   
       // Convert Again to List &amp; Return   
       return Arrays.asList(f);   
    }   
    /* Method Returning the Corresponding TimeStamp for an Image */   
    private Long getTimeStamp(File file) throws Exception {   
       return file.lastModified();   
    }   
    /* Method Listing the Photo List In the Directory */   
    private List getPhotoListInDirectory(String dirPath) throws Exception {   
       File dir = new File(dirPath);   
       File[] files = dir.listFiles(new FilenameFilter() {   
         public boolean accept(File dir, String name) {   
            if (name.endsWith(".jpg") | name.endsWith(".JPG")) {   
              return true;   
            } else {   
              return false;   
            }   
         }   
       });   
       // Converting the Array To List &amp; Returning   
       return Arrays.asList(files);   
    }   
    /* Method Writing the Photos to the Output Folder */   
    private void prepareImages(List photoList, String dir) throws Exception {   
       System.out.println("Received : " + photoList);   
       String seperator = System.getProperty("file.separator");   
       // Create Output Folder   
       File foutDir = new File(dir + seperator + OUT_FOLDER);   
       foutDir.mkdir();   
       // Write Files to the Output Folder   
       for (Iterator itr = photoList.iterator(); itr.hasNext();) {   
         File f = (File)itr.next();   
         System.out.println("\n\nEncoding File --&gt; " + f.getName());   
         // Writing the File Object Directly to File   
         String fileName = foutDir.getAbsolutePath() + seperator+ IMAGE_PREFIX + "-" + IMAGE_ST_INDEX + ".jpg";   
         System.out.println("New File Name --&gt;" + fileName+ " With time Stamp = "+ new Date(getTimeStamp(f)).toString());   
         // Copy the Files   
         BufferedImage bufImg1 = readImageFromFile(f);   
         writeImageToJPG(new File(fileName), bufImg1);   
         // Increating the Image Name Index   
         IMAGE_ST_INDEX++;   
       }   
    }   
    /*   
     * The Core Process Method Carring Out the Process (Bussiness Logic Method)   
     */   
    public boolean doPhotoSortingProcess(String photoDir) {   
       try {   
         // 1.Set the Photo Directory Path   
         String dir = photoDir;   
         // 2.Get the Photo List In The Directory   
         List photos = getPhotoListInDirectory(dir);   
         System.out.println("PHOTOS : " + photos);   
         // 3.Sort The Photo List &amp; Derefecne the List Obj   
         List sortedImages = sortImages(photos);   
         // 4.Out put the sorted List to a output folder   
         prepareImages(sortedImages, dir);   
         // 5.Clean Up Everything/Return Status   
         return true;   
       } catch (Exception ex) {   
         System.out.println("The following Exception Occured : "+ ex.getMessage());   
         ex.printStackTrace();   
         return false;   
       }   
    }   
    /* Method Reading a Image to a buffer */   
    public static BufferedImage readImageFromFile(File file) throws Exception {   
       return ImageIO.read(file);   
    }   
    /* Method Writing a File as a JPEG Image */   
    public static void writeImageToJPG(File file, BufferedImage bufferedImage)   
         throws Exception {   
       ImageIO.write(bufferedImage, "jpg", file);   
    }   
    // Main Method For Local Testing   
    public static void main(String[] args) {   
       // Modified to Command Line Mode   
       Scanner s = new Scanner(System.in);   
       // Getting Input   
       System.out.println("Enter Picture Directory Path and Press Enter : ");   
       String dir = s.nextLine();   
       System.out.println("You Entered : " + dir);   
       PhotoSorterMain phm = new PhotoSorterMain();   
       boolean status = phm.doPhotoSortingProcess(dir);   
       System.out.println("Photo Ordering Status : " + status);   
    }   
  }   

Thursday, December 17, 2009

Java Sample Algorithms

Contains some sample algorithms That I wrote and thought of publishing. This post will be updated from time to time,depending on the rate I write them. Hope this will be useful to someone.The Language I've used here in writing these algorithms is Java.

1. Euclid's Algorithm to Find the GCD (Greatest Common Divisor)
      private int findGcd(int m, int n) {  
           do {  
                if (m > n) {  
                     m = m - n;  
                }  
                if (n > m) {  
                     n = n - m;  
                }  
                if (m == n) {  
                     m = m - n;  
                }  
           } while (m > 0);  
           return n;  
      }  

Tuesday, December 15, 2009

Java One Liners Collection

Today while I was going through my discrete maths notes It occurred to me that there are some algorithms that we could easily implement as just one liners. I just thought of publishing them so that they could be useful to anyone in the future. Please don't forget to comment and also add more algorithms of this style if you have. Also the last algorithm is left for you to be implemented :-).

The Following Class contains the Code 
  /**   
  *    
  * @author SHEN   
  */   
  public class OneLinerAlogrothmCollection {   
    /*   
     * One Liner Algorithm for Calculating the Corresponding Fibonachi series   
     * number for a given integer   
     */   
    public int fib(int n) {   
       {   
         return (n <= 2) ? 1 : fib(n - 1) + fib(n - 2);   
       }   
    }   
    /*   
     * One Liner Algorithm for Calculating the Corresponing Factorial for a   
     * Given Integer   
     */   
    public int fact(int n) {   
       return (n <= 1) ? 1 : fact(n - 1) * n;   
    }   
    /*   
     * One Liner Algorithm for Determining if a given Number is a Perfect Square   
     * or not   
     */   
    public boolean isPerfectSquare(int n) {   
       return (n > 1) ? (n & (n - 1)) == 0 : false;   
    }   
    /*   
     * One Liner Algorithm for Determining if a Given integer is a odd or a even   
     * integer returns : true -> for even integers false -> for odd integers   
     */   
    public boolean isEven(int n) {   
       return (n & 1) == 0;   
    }   
    /*   
     * One Liner Algorithm for Determining if a Given Integer is a Prime Number   
     * returns : true -> for prime integers false -> for others   
     */   
    public boolean isPrime(int input) {   
       throw new UnsupportedOperationException("It's Up to You to Implement this");   
    }   
  }