DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets

  • submit to reddit

Recent Snippets

                    Looking up the length of an array on each iteration of a loop is slow and inefficient (if the length of the array isn't changing).

If it's OK to iterate from back to front:
for ( var i=myArray.length-1; i>=0; --i ){
  ...
}

If you need to go from front to back:
for ( var i=0, len=myArray.length; i<len; ++i ){
  ...
}
                
                    
Math.randomMax = function(maxVal,asFloat){
	var val = Math.random()*maxVal;
	return asFloat?val:Math.round(val);
}

For a random integer between 0 and 10 (inclusive), simply:
var theNumber = Math.randomMax( 10 );

For a random float value between 0 and 10, pass a truth value to the second parameter:
var theNumber = Math.randomMax( 10, true );
                
                    
/usr/sbin/ioreg -p IODeviceTree -n battery -w 0 | grep IOBatteryInfo
or

ioreg -l -w0 | grep -i IOBatteryInfo
                
                    
@params[:tags].map do |tag|
	Tag.find_by_name (tag) rescue nil
end
                
                    When you don't want an application to apply to a certain action.. say AJAX or RSS/xml output..

layout 'application', :except => :create_with_ajax
                
                    
Person.find_by_user_name_and_password(user_name, password)
                
                    
<%= select('user', 'sites', Site.find_all.collect  {|site| site.name}) %>
                
                    Someone in #rubyonrails wrote this. Forget who!

def paginate_from_sql(model, sql, total, per_page)
  @object_pages = Paginator.new self, total, per_page, @params['page']
  @objects = model.find_by_sql(sql + " LIMIT #{per_page} " +
                               "OFFSET #{@object_pages.current.to_sql[1]}")
end
                
                    
class Song < ActiveRecord::Base
  # Uses an integer of seconds to hold the length of the song

  def length=(minutes)
    write_attribute("length", minutes * 60)
  end

  def length
    read_attribute("length") / 60
  end
end