Archive for the computer science Category

DRY jQuery to toggle elements

Friday, 09 September 2009

I always have links that will hide something on a page. something like:

Hot Sheet
Uploaded with plasq’s Skitch!

This is how I have done it in the past:

  $("#rollup").click( function() {
    $("#new_capacity_form").slideToggle();
  });

But by adding a rel value to your links, you can do it smarter

  $('#rollup').click( function(){
    var what = $(this).attr('rel');
    $('#' + what ).slideToggle();
  });

In my views, I add this link

  link_to "cancel", "#", :id => 'rollup', :rel => 'new_capacity_form'

vois la! now I am able to rollup all over my site with only one line of jQuery.


apple script can move all of your windows to main display

Thursday, 06 June 2009

So I just got home from doing a bit of coding at my favorite coffee shop. I probably have 25-30 application windows open right now and as soon as I plug into my external display I will have to readjust all 30 windows. The problem is that when I am just using my MacBook Pro I like to have all of my app’s windows on that display… obviously! But when I come home and plug into my external display I no longer want my windows open in the MacBook Pro’s 15″ display, I want them open on my 24″ display. So for the past year I have manually dragged each application over to my large display. I estimate that I have wasted 4-5 hours in the past couple of months. I will not do the machines work any longer! Enter this script and you will add hours to your life!! I am really surprised that Apple has not addressed this issue.

 
tell application "System Preferences"
	set current pane to pane id "com.apple.preference.displays"
	reveal (first anchor of current pane whose name is "displaysArrangementTab")
	tell application "System Events" to tell process "System Preferences"
		set frontmost to true
		click checkbox "Mirror displays" of group 1 of tab group 1 of front window
	end tell
	set current pane to pane id "com.apple.preference.displays"
	reveal (first anchor of current pane whose name is "displaysArrangementTab")
	tell application "System Events" to tell process "System Preferences"
		set frontmost to true
		click checkbox "Mirror displays" of group 1 of tab group 1 of front window
	end tell
end tell
quit

working with webrat + factory girl

Monday, 05 May 2009

Webrat is a nice driver for your integration testing. I have been using it in place of my controller and view specs. Factory Girl is what you should replace your fixtures with. So . . . . When you are using factories in your webrat integration tests, it is sometimes helpful to do things like this:

Given a customer exists with an id of "12345"

and that translates into a step like this:

Factory.factories.each do |name, factory|
  Given /^an? #{name} exists with an? (.*) of "([^"]*)"$/ do |attr, value|
    Factory(name, attr.gsub(' ', '_') => value)
  end
end

And all of this default behaviour is what you get when you install cucumber and factory girl. But today i ran into a little issue. One of my features needed to use the object that was created by Factory Girl in another step, so i caught the factory object with this addition

Factory.factories.each do |name, factory|
  Given /^an? #{name} exists with an? (.*) of "([^"]*)"$/ do |attr, value|
     ######
    @object = Factory(name, attr.gsub(' ', '_') => value)
  end
end

Now i can use @object in my other steps!

That is all.


has_many has many features

Wednesday, 04 April 2009

Not only is `has_many` an excellent way to set up foreign keys ( Person has_many :fingers where fingers represents an Active Record class Finger) but has_many can also define custom relationships. Behold,

class Book < ActiveRecord::Base
  has_many :listings
  has_many :users, :through => :listings
  has_many :active_listings, :class_name => "Listing", :conditions => { :market_status => 1 }
end

.

This way whenever I want to grab all of the active listings that a book has, i can do this:

  @book.active_listings.count

That is all.


Safari 4 open new link in tab

Sunday, 03 March 2009

I like the new Safari a whole lot. Unfortunately there is no easy way to force Safari to open links in a new Tab. However, with this simple terminal command, the aforementioned annoyance can be laid to rest.

defaults write com.apple.Safari TargetedClicksCreateTabs -bool true

Restart Safari and voila!


skinny controllers in Rails

Thursday, 03 March 2009

Your controller is so fat I took a screenshot of it last Christmas and it is still printing. We have all heard stories about how we should keep our controllers slim and fit but there can never be a definitive answer on how to accomplish the athletic pose. For you see, there are an infinite amount of ways that your controller can take on husk. In this blog-post I will attempt to define and solve one of these problems.

Let us suppose that you have a User model and a Job model.

class User < ActiveRecord::Base
  has_many :jobs
end
 
class Job < ActiveRecord::Base
  belongs_to :user
end

Ok, so this proverbial Job is a very complex model. It has many attributes that are activated by complex algorithms. The job’s algorithms are influenced by input from the user.

class Job < ActiveRecord::Base
  belongs_to :user
 
  def algorithm!( input )
    case input
    when :variation_one
      # do a bunch of crap
    when :variation_two
      # do even more crap
    end# case
  end# algorithm
 
end# Job

Now that we have this model with extremely complicated algorithms that depends on loads of user input; we need to find a RESTful way to call these methods. Please keep in mind that these methods require the users input which will come from the params hash. Since our app is RESTful, we will be ‘updating’ the object by sending a PUT request with data that will be received by the Jobs controller.

Our edit.html.erb should have something like this in it:

 
<%= f.check_box :important_input_that_is_not_apart_of_the_model %>

This data’s purpose is to instruct the algorithm on how to execute. However, it is not apart of the model. There is NO column that corresponds to this data. So the question now becomes: How do i get this data from the view/controller (params hash) to the model?

The way I attack this problem is by adding this to my model:

 
class Job < ActiveRecord::Base
  belongs_to :user
  attr_accessor :important_input_that_is_not_apart_of_the_model
 
  def before_save
    self.algoritm!( self. important_input_that_is_not_apart_of_the_model )
  end
 
  def algorithm!( input )
 
    case input
    when :variation_one
      # do a bunch of crap
    when :variation_two
      # do even more crap
    end
  end# algorithm
end# Job

In this case we have added NO extra code to our update method in the Jobs controller. However we have added heaps of functionality.
Let me know if there is better way to do this ?


Rake is cake!

Tuesday, 03 March 2009

I Have been using C++ the last few days and without an IDE to boot. I am so comfortable with TextMate that i started to vomit when i began working in xCode. This is discouraging as i have an Objective-C project looming over my future. However, for the time being i decided to keep my Mate.

I quickly got swamped with all sorts of dependency issues, hence i found Rake. Here is my file:

 
require 'rake/clean'
 
  APPLICATION = 'one_upper'
  CLEAN.include('*.o')
  CLOBBER.include('one_upper')
 
  task :default => ["#{ APPLICATION }"]
 
  SRC = FileList['*.cpp']
  OBJ = SRC.ext('o')
 
  rule '.o' => '.cpp' do |t|
    sh "g++ -c -o #{t.name} #{t.source}" 
  end
 
  file "#{ APPLICATION }" => OBJ do
    sh "g++ -o #{ APPLICATION } #{ OBJ }" 
  end
 
  # File dependencies 
  file 'main.o' => ['main.cpp', 'stack_manager.h']
  file 'stack_manager.o' => ['stack_manager.cpp']

I updated my TM Bundle to reply with a ” rake ” command whenever i hit apple-B.


Newton’s Method .to_ruby

Sunday, 03 March 2009

here is the math behind Newton’s Method

PRECISION = 0.0001
 
def newtonian_guess( guess,fx,fdx )
  loop do
    better_guess = guess - ( fx.call( guess ).to_f / fdx.call( guess ).to_f )
    return better_guess if ((better_guess - guess).abs <= PRECISION)
    guess = better_guess
  end
end
 
def sqrt( num )
  guess = num/2
  return newtonian_guess( guess,
            lambda {|x| (x**2)-num } ,
            lambda {|x| 2*x } )
end
 
class Float
  def to_sqrt
    sqrt( self )
  end
end
 
p 2.0.to_sqrt
# => 1.41421356237469

terminal tip #1

Tuesday, 03 March 2009
open . -a finder

will open the current directory with finder.


Code on Shakedown Street

Thursday, 02 February 2009

This has got to be the wildest thing that i have ever heard. There can be no way that Cisco approves of this. . . . Programming on LSD; really!?

cisco_on_acid