Saari Development

Ali Rizvi's Technical Blog as a Professional Software Development Engineer

Archive for the ‘code’ Category

Rails: Non-DB field in Model with validation

leave a comment »

Challenge: Add a field to the model representing system date, time & timezone that is not stored in the database and have validation on it.

Solution:

  • Add attr_accessor & attr_accessible (for bulk update), add getter (sys_date_time) & setter (sys_date_time=) methods.
  • Return system date time in UTC from getter and show in user (browser) timezone on client side (using moment-timezone.js which is moment.js extension select the download with timezone data)
  • When the setting come to be saved using update_attributes in controller it eventually calls model setter (sys_date_time=) where you convert it back to utc given the timezone info (ActiveSupport::Timezone[zone] is your friend with ActiveSupport::TimeZone[zone].parse then in_time_zone(‘UTC’))
  • Validation is tricky as this is not a db backed and getter returns the calculated value which is always valid. You need to validate input first thing in setter and set a new member variable with errors found. Then add a validate do … end block where you iterate through the new member variable with errors and do errors.add(attr, message).

Will add code snippets when time permits.

 

Advertisements

Written by imsaar

April 7, 2016 at 2:02 pm

Posted in code, rails, ruby

My Advice To New Software Developers

leave a comment »

  • Don’t settle too early and don’t artificially constraint yourself. For instance:
    • Don’t say I am a Java or .NET developer and restrict yourself to only those platforms
    • Don’t stay in the same company for too long, some times you settle for 1 year of experience repeated 5 times rather than 5 years of real experience. You can always come back to a company if you like it better than the next one. In large companies you can move to a different group.
    • Don’t move too fast, take the time to learn from the smart people around you. If you are the smartest person there leave immediately.
  • Keep learning new and perspective changing technologies and not learn more of the same. For instance:
    • If you know a object oriented language (C++) learn functional language like Haskell
    • If you know a statically typed language (Java) learn a dynamically typed language like Ruby
    • Keep an eye on the trending technologies and briefly explore them to get a taste of them
  • Teach what you have learned to others, you have learned it if you can teach it

Written by imsaar

September 3, 2014 at 12:37 pm

Using Adobe’s New Source Code Fonts in Sublime Text 2 on Mac

with one comment

I just tweeted how much I love using the newly discovered Adobe Code fonts in Sublime Text 2 and though I should document the steps I followed to use them:

  1. Download font from Adobe Sourceforge: Source Sans Pro & Source Code Pro
  2. The easiest way I found to install all the font files on a Mac was to go to the terminal; cd to the downloaded font directory and type:

    open *.otf

  3. All the files will open in the Font Book app; Click “Install” button for each of them
  4. Now to use it open Sublime Text 2; open Preference -> Settings – User
  5. Add the following lines to the existing settings (if empty add these lines inside braces {}) to use the Light version of Source Sans Pro font in Size 17

    "font_size": 17.0,
    "font_face": "Source Code Pro Light"
    //"font_face": "Source Sans Pro Light"

  6. You can toggle the “//” on the two lines to try out the other font and adjust the font size as you prefer

Happy Coding!!!

Written by imsaar

September 28, 2012 at 9:21 am

Posted in code, editor, macosx

Ruby: Add a prefix to all files in a directory

leave a comment »

I found myself looking for a way to rename all files in a directory by appending a prefix and couldn’t find a utility to do such a renaming after quick search so I wrote my own.


# Quick script to bulk prepend prefix to filenames to all files in a directory
# Also strips any spaces in the filename
# Example usage : ruby prepend_rename.rb Disc1_ C:\AudioBook\Disc1\

raise "Prefix and Directory are required" if ARGV.size < 2

prefix = ARGV[0]
dir = ARGV[1]

raise "Non-word character prefix #{prefix}" unless prefix =~ /^\w+$/
raise "No such directory: #{dir}" unless Dir.exists?(dir)

Dir.chdir(dir)
Dir.entries(dir).each do |file|
 next if File.directory?(file)
 new_name = prefix + file.gsub(/\s+/, '')
 File.rename(file, new_name)
end

Written by imsaar

February 7, 2010 at 6:11 pm

Posted in code, ruby, windows

Rails: Skipping Base Class Filters in Subclasses

with 3 comments

I encountered a case where we needed to skip a filter as it was causing infinite redirection in a subclass. I found my answer in: Rails Filters Documentation

Filter chain skipping

Declaring a filter on a base class conveniently applies to its subclasses, but sometimes a subclass should skip some of its superclass’ filters:

  class ApplicationController < ActionController::Base
    before_filter :authenticate
    around_filter :catch_exceptions
  end

  class WeblogController < ApplicationController
    # Will run the :authenticate and :catch_exceptions filters.
  end

  class SignupController < ApplicationController
    # Skip :authenticate, run :catch_exceptions.
    skip_before_filter :authenticate
  end

  class ProjectsController < ApplicationController
    # Skip :catch_exceptions, run :authenticate.
    skip_filter :catch_exceptions
  end

  class ClientsController  :index
  end

Written by imsaar

November 10, 2009 at 9:07 pm

Posted in code, documentation, rails, ruby

Java: Rediscovering the basics

leave a comment »

It’s been a while since I did some Java but now it seems to be the right tool for the job at hand so I am rediscovering Java with a masochistic twist, ‘look boss no IDEs’.

I am experimenting with the SSJ Java library for Stochastic Simulation as I mentioned in an earlier post and here is some sample source code:

import umontreal.iro.lecuyer.randvar.*;
import umontreal.iro.lecuyer.probdist.*;
import umontreal.iro.lecuyer.rng.*; 

public class GenerateDemandArrivals {
  private RandomStream randomStream;
  private RandomVariateGen expArrival;
  private RandomVariateGen poissonArrival;
  private double lambda;
  private int times;

  public GenerateDemandArrivals() {
    randomStream = new MRG32k3a();
    lambda = 10.0;
    times = 5;
    expArrival = new RandomVariateGen(randomStream, new ExponentialDist(lambda));
    poissonArrival = new PoissonGen(randomStream, new PoissonDist(lambda));

  }

  public void demandArrival() {
    for (int i = 0; i < times; i++) {
      System.out.println("Here is the next random int : " + randomStream.nextInt(0, 10));
    }
  }

  public void demandArrivalExpDist() {
    for (int i = 0; i < times; i++) {
      System.out.println("Here is the next exponential dist double : " + expArrival.nextDouble());
    }
  }

  public void demandArrivalPoissonDist() {
    for (int i = 0; i < times; i++) {
      System.out.println("Here is the next poisson dist double : " + poissonArrival.nextDouble());
    }
  }

  public static void main(String&#91;&#93; arg) {
    new GenerateDemandArrivals().demandArrival();
    new GenerateDemandArrivals().demandArrivalExpDist();
    new GenerateDemandArrivals().demandArrivalPoissonDist();
    
  }
}
&#91;/sourcecode&#93;

I was tried of doing the following everytime I changed the source code in my favorite editor Vim:

<pre>
javac -cp "C:\Program Files\Java\jdk1.6.0_02\lib\ext\ssj.jar;." GenerateDemandArrivals.java
java -cp "C:\Program Files\Java\jdk1.6.0_02\lib\ext\ssj.jar;." GenerateDemandArrivals
</pre>


I already had ant installed on my Windows machine but so I said why not take advantage of it, I looked for <a href="http://ant.apache.org/manual/using.html">simple ant file</a> and found something quite close in apache ant manual.

After little bit more search and refinement here is what I came up with:


<project name="Sim" default="run" basedir=".">
    <description>
        simple example build file
    </description>
  <!-- set global properties for this build -->
  <property name="src" location="."/>
  <property name="build" location="."/>
  <path id="project.class.path">
    <pathelement path="C:\Program Files\Java\jdk1.6.0_02\lib\ext\ssj.jar"/>
    <pathelement path="."/>
  </path>

  <target name="run"
    description="run the program" 
    depends="compile">
    <java classname="GenerateDemandArrivals">
      <classpath refid="project.class.path"/>
    </java>
  </target>

  <target name="compile"
        description="compile the source " >
    <!-- Compile the java code from ${src} into ${build} -->
    <javac srcdir="${src}" destdir="${build}">
    <classpath refid="project.class.path"/>
    </javac>
  </target>

</project>

Now I can simple type ant (while I am in the directory containing the build.xml file above) after any changes to the file and it compiles and run my code.

I feeling ashamed of feeling good and writing about such basic stuff but I am thinking there would be another person like me (could be myself at some future point where I have to leave my lovely Ruby world and come back to Java out of necessity).

Written by imsaar

November 20, 2008 at 7:06 pm

Posted in code, java

Tagged with , , , ,

JRuby: Stochastic Simulation with SSJ

with 2 comments

I needed to work on a simulation project that involved working with the SSJ java library.
If I haven’t mentioned before I love Ruby (the programming language) and Java, though a tool in my toolkit, does not evoke the same feeling.

So my first reaction was I can use JRuby to benefit from the existing java library and beauty of Ruby.
The SSJ library comes with a comprehensive sets of examples and documentation. I started exploring that.

Fortunately at RubyConf 2008 with some help from Charles Nutter I was able to install jruby on my laptop, getting jruby installed and running was not trivial. I wish somebody can do a one click installer for jruby same as they did for Ruby and Rails.

I downloaded SSJ and unzipped the downloaded file containing jar files into C:\Program Files\Java\jdk1.6.0_02\lib\ext directory. Added the CLASSPATH variable in my windows environment set to this directory.

I tried the following example from examples.pdf

import umontreal.iro.lecuyer.rng.*;
import umontreal.iro.lecuyer.stat.*;
public class Collision {
    int k; // Number of locations.
    int m; // Number of items.
    double lambda; // Theoretical expectation of C (asymptotic).
    boolean[] used; // Locations already used.
    public Collision (int k, int m) {
        this.k = k;
        this.m = m;
        lambda = (double) m * m / (2.0 * k);
        used = new boolean[k];
    }
    // Generates and returns the number of collisions.
    public int generateC (RandomStream stream) {
        int C = 0;
        for (int i = 0; i < k; i++) used&#91;i&#93; = false;
        for (int j = 0; j < m; j++) {
            int loc = stream.nextInt (0, k-1);
            if (used&#91;loc&#93;) C++;
            else used&#91;loc&#93; = true;
        }
        return C;
    }
    // Performs n indep. runs using stream and collects statistics in statC.
    public void simulateRuns (int n, RandomStream stream, Tally statC) {
        statC.init();
        for (int i=0; i<n; i++) statC.add (generateC (stream));
        statC.setConfidenceIntervalStudent();
        System.out.println (statC.report (0.95, 3));
        System.out.println (" Theoretical mean: " + lambda);
    }
    public static void main (String&#91;&#93; args) {
        Tally statC = new Tally ("Statistics on collisions");
        Collision col = new Collision (10000, 500);
        col.simulateRuns (100000, new MRG32k3a(), statC);
    }
}
&#91;/sourcecode&#93;

I compiled and ran the Java code above to ensure I was getting the same results using the following steps:
<pre>
javac -cp "C:\Program Files\Java\jdk1.6.0_02\lib\ext\ssj.jar" Collision.java
java -cp "C:\Program Files\Java\jdk1.6.0_02\lib\ext\ssj.jar;C:\code\ruby\jruby" Collision
</pre>

As you can notice my code was in the C:\code\ruby\jruby directory and I was in this directory when I ran the above program.

Here is the same code example in jruby code:

require 'java'
require 'ssj.jar'

import 'umontreal.iro.lecuyer.rng.RandomStream'
import 'umontreal.iro.lecuyer.stat.Tally'
import 'umontreal.iro.lecuyer.rng.MRG32k3a'

class Collision
  def initialize(k, m)
    @k = k
    @m = m
    @lambda = m * m / (2.0 * k)
    @used = Array.new(k, false)
  end

  def generate_c(stream)
    c = 0
    @k.times { |i| @used[i] = false }
    @m.times do |j|
      loc = stream.nextInt(0, @k-1)
      if @used[loc]
        c += 1
      else
        @used[loc] = true
      end
    end
    return c
  end

  def simulate_runs(n, stream, stat_c)
   stat_c.init
   n.times { stat_c.add(generate_c(stream)) }
   stat_c.setConfidenceIntervalStudent()
   puts stat_c.report(0.95, 3)
   puts " Theoretical mean: #{@lambda} "
  end

  def self.run
    stat_c = Tally.new("Statistics on collision")
    col = Collision.new(10000,500)
    col.simulate_runs(100000, MRG32k3a.new, stat_c)
  end

end

Collision.run

The jruby code runs comparatively slower (my feeling is 5 times slower but I will measure and add it later). I am using the latest available jruby 1.1.5 at the time of this post.

Update: The JRuby version takes around 13 minutes while the equivalent Java code above takes 17 seconds. This seems to be unacceptable performance, I am not sure if this is specific to SSJ or other libraries too. If I understand correctly, JRuby should be running inside the JVM and when I call SSJ library that is the same Java code that runs so I don’t understand why it is so slow unless I have used some technique that slows down my JRuby version.

Written by imsaar

November 15, 2008 at 10:25 pm

Posted in code, java, jruby, ruby