<?xml version="1.0" encoding="UTF-8"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
  <id>tag:refactormycode.com,2007:users1friends</id>
  <link type="application/atom+xml" href="http://refactormycode.com/users/1/friends" rel="self"/>
  <title>macournoyer friends</title>
  <updated>Thu Sep 18 01:08:56 +0000 2008</updated>
  <entry>
    <id>tag:refactormycode.com,2007:Code496</id>
    <published>2008-09-18T01:08:56+00:00</published>
    <updated>2008-09-23T04:05:05+00:00</updated>
    <title>[Ruby] require_dependency</title>
    <content type="html">&lt;p&gt;Rails require_dependency usage&lt;/p&gt;

&lt;pre&gt;class Listing &amp;lt; ActiveRecord::Base
  require_dependency &amp;quot;listing/property_related&amp;quot;
  require_dependency &amp;quot;listing/price_related&amp;quot;
  require_dependency &amp;quot;listing/contact_related&amp;quot;
  require_dependency &amp;quot;listing/address_related&amp;quot;
  require_dependency &amp;quot;full_text_search/listing_config&amp;quot;
  ....
end
&lt;/pre&gt;</content>
    <author>
      <name>Tien Dung</name>
      <email>dungtn@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/496-require_dependency" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code402</id>
    <published>2008-07-29T09:30:25+00:00</published>
    <updated>2008-09-17T23:18:04+00:00</updated>
    <title>[JavaScript] Handling Keyboard Shortcuts in JavaScript</title>
    <content type="html">&lt;p&gt;I found below code very useful:
&lt;br /&gt;&lt;a href="http://www.openjs.com/scripts/events/keyboard_shortcuts/" target="_blank"&gt;http://www.openjs.com/scripts/events/keyboard_shortcuts/&lt;/a&gt;
&lt;br /&gt;Especially when I need to handle keyboard combination (disable default events for &amp;quot;crtl+p&amp;quot; and &amp;quot;ctrl+s&amp;quot; for example)&lt;/p&gt;

&lt;p&gt;The code work nicely but the source code is not in a good form. I puts it here so it has chances to become more beautiful shortly.&lt;/p&gt;

&lt;p&gt;Here is a copy of original code:&lt;/p&gt;

&lt;pre&gt;/**
 * http://www.openjs.com/scripts/events/keyboard_shortcuts/
 * Version : 2.01.B
 * By Binny V A
 * License : BSD
 */
shortcut = {
	'all_shortcuts':{},//All the shortcuts are stored in this array
	'add': function(shortcut_combination,callback,opt) {
		//Provide a set of default options
		var default_options = {
			'type':'keydown',
			'propagate':false,
			'disable_in_input':false,
			'target':document,
			'keycode':false
		}
		if(!opt) opt = default_options;
		else {
			for(var dfo in default_options) {
				if(typeof opt[dfo] == 'undefined') opt[dfo] = default_options[dfo];
			}
		}

		var ele = opt.target
		if(typeof opt.target == 'string') ele = document.getElementById(opt.target);
		var ths = this;
		shortcut_combination = shortcut_combination.toLowerCase();

		//The function to be called at keypress
		var func = function(e) {
			e = e || window.event;
			
			if(opt['disable_in_input']) { //Don't enable shortcut keys in Input, Textarea fields
				var element;
				if(e.target) element=e.target;
				else if(e.srcElement) element=e.srcElement;
				if(element.nodeType==3) element=element.parentNode;

				if(element.tagName == 'INPUT' || element.tagName == 'TEXTAREA') return;
			}
	
			//Find Which key is pressed
			if (e.keyCode) code = e.keyCode;
			else if (e.which) code = e.which;
			var character = String.fromCharCode(code);
			
			if(code == 188) character=&amp;quot;,&amp;quot;; //If the user presses , when the type is onkeydown
			if(code == 190) character=&amp;quot;.&amp;quot;; //If the user presses , when the type is onkeydown

			var keys = shortcut_combination.split(&amp;quot;+&amp;quot;);
			//Key Pressed - counts the number of valid keypresses - if it is same as the number of keys, the shortcut function is invoked
			var kp = 0;
			
			//Work around for stupid Shift key bug created by using lowercase - as a result the shift+num combination was broken
			var shift_nums = {
				&amp;quot;`&amp;quot;:&amp;quot;~&amp;quot;,
				&amp;quot;1&amp;quot;:&amp;quot;!&amp;quot;,
				&amp;quot;2&amp;quot;:&amp;quot;@&amp;quot;,
				&amp;quot;3&amp;quot;:&amp;quot;#&amp;quot;,
				&amp;quot;4&amp;quot;:&amp;quot;$&amp;quot;,
				&amp;quot;5&amp;quot;:&amp;quot;%&amp;quot;,
				&amp;quot;6&amp;quot;:&amp;quot;^&amp;quot;,
				&amp;quot;7&amp;quot;:&amp;quot;&amp;amp;&amp;quot;,
				&amp;quot;8&amp;quot;:&amp;quot;*&amp;quot;,
				&amp;quot;9&amp;quot;:&amp;quot;(&amp;quot;,
				&amp;quot;0&amp;quot;:&amp;quot;)&amp;quot;,
				&amp;quot;-&amp;quot;:&amp;quot;_&amp;quot;,
				&amp;quot;=&amp;quot;:&amp;quot;+&amp;quot;,
				&amp;quot;;&amp;quot;:&amp;quot;:&amp;quot;,
				&amp;quot;'&amp;quot;:&amp;quot;\&amp;quot;&amp;quot;,
				&amp;quot;,&amp;quot;:&amp;quot;&amp;lt;&amp;quot;,
				&amp;quot;.&amp;quot;:&amp;quot;&amp;gt;&amp;quot;,
				&amp;quot;/&amp;quot;:&amp;quot;?&amp;quot;,
				&amp;quot;\\&amp;quot;:&amp;quot;|&amp;quot;
			}
			//Special Keys - and their codes
			var special_keys = {
				'esc':27,
				'escape':27,
				'tab':9,
				'space':32,
				'return':13,
				'enter':13,
				'backspace':8,
	
				'scrolllock':145,
				'scroll_lock':145,
				'scroll':145,
				'capslock':20,
				'caps_lock':20,
				'caps':20,
				'numlock':144,
				'num_lock':144,
				'num':144,
				
				'pause':19,
				'break':19,
				
				'insert':45,
				'home':36,
				'delete':46,
				'end':35,
				
				'pageup':33,
				'page_up':33,
				'pu':33,
	
				'pagedown':34,
				'page_down':34,
				'pd':34,
	
				'left':37,
				'up':38,
				'right':39,
				'down':40,
	
				'f1':112,
				'f2':113,
				'f3':114,
				'f4':115,
				'f5':116,
				'f6':117,
				'f7':118,
				'f8':119,
				'f9':120,
				'f10':121,
				'f11':122,
				'f12':123
			}
	
			var modifiers = { 
				shift: { wanted:false, pressed:false},
				ctrl : { wanted:false, pressed:false},
				alt  : { wanted:false, pressed:false},
				meta : { wanted:false, pressed:false}	//Meta is Mac specific
			};
                        
			if(e.ctrlKey)	modifiers.ctrl.pressed = true;
			if(e.shiftKey)	modifiers.shift.pressed = true;
			if(e.altKey)	modifiers.alt.pressed = true;
			if(e.metaKey)   modifiers.meta.pressed = true;
                        
			for(var i=0; k=keys[i],i&amp;lt;keys.length; i++) {
				//Modifiers
				if(k == 'ctrl' || k == 'control') {
					kp++;
					modifiers.ctrl.wanted = true;

				} else if(k == 'shift') {
					kp++;
					modifiers.shift.wanted = true;

				} else if(k == 'alt') {
					kp++;
					modifiers.alt.wanted = true;
				} else if(k == 'meta') {
					kp++;
					modifiers.meta.wanted = true;
				} else if(k.length &amp;gt; 1) { //If it is a special key
					if(special_keys[k] == code) kp++;
					
				} else if(opt['keycode']) {
					if(opt['keycode'] == code) kp++;

				} else { //The special keys did not match
					if(character == k) kp++;
					else {
						if(shift_nums[character] &amp;amp;&amp;amp; e.shiftKey) { //Stupid Shift key bug created by using lowercase
							character = shift_nums[character]; 
							if(character == k) kp++;
						}
					}
				}
			}
			
			if(kp == keys.length &amp;amp;&amp;amp; 
						modifiers.ctrl.pressed == modifiers.ctrl.wanted &amp;amp;&amp;amp;
						modifiers.shift.pressed == modifiers.shift.wanted &amp;amp;&amp;amp;
						modifiers.alt.pressed == modifiers.alt.wanted &amp;amp;&amp;amp;
						modifiers.meta.pressed == modifiers.meta.wanted) {
				callback(e);
	
				if(!opt['propagate']) { //Stop the event
					//e.cancelBubble is supported by IE - this will kill the bubbling process.
					e.cancelBubble = true;
					e.returnValue = false;
	
					//e.stopPropagation works in Firefox.
					if (e.stopPropagation) {
						e.stopPropagation();
						e.preventDefault();
					}
					return false;
				}
			}
		}
		this.all_shortcuts[shortcut_combination] = {
			'callback':func, 
			'target':ele, 
			'event': opt['type']
		};
		//Attach the function with the event
		if(ele.addEventListener) ele.addEventListener(opt['type'], func, false);
		else if(ele.attachEvent) ele.attachEvent('on'+opt['type'], func);
		else ele['on'+opt['type']] = func;
	},

	//Remove the shortcut - just specify the shortcut and I will remove the binding
	'remove':function(shortcut_combination) {
		shortcut_combination = shortcut_combination.toLowerCase();
		var binding = this.all_shortcuts[shortcut_combination];
		delete(this.all_shortcuts[shortcut_combination])
		if(!binding) return;
		var type = binding['event'];
		var ele = binding['target'];
		var callback = binding['callback'];

		if(ele.detachEvent) ele.detachEvent('on'+type, callback);
		else if(ele.removeEventListener) ele.removeEventListener(type, callback, false);
		else ele['on'+type] = false;
	}
}&lt;/pre&gt;</content>
    <author>
      <name>Tien Dung</name>
      <email>dungtn@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/402-handling-keyboard-shortcuts-in-javascript" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code401</id>
    <published>2008-07-29T04:09:42+00:00</published>
    <updated>2008-07-29T04:09:42+00:00</updated>
    <title>[Ruby] How to extend a class properly?</title>
    <content type="html">&lt;p&gt;Recently, I need to extend ThinkingSphinx::Search class to support sort by expresion (via :sort_expr option). Here is my straight forward code. Is there any better way?&lt;/p&gt;

&lt;pre&gt;module ThinkingSphinx
  class Search
    class &amp;lt;&amp;lt; self
      alias_method :original_set_sort_options!, :set_sort_options!
      
      def set_sort_options!(client, options)
        expr = options[:sort_expr]
        if expr.nil?
          original_set_sort_options!(client, options)
        else
          client.sort_mode = :expr
          client.sort_by = expr
        end
      end
    end # class &amp;lt;&amp;lt; self
  end # Search
end # ThinkingSphinx&lt;/pre&gt;</content>
    <author>
      <name>Tien Dung</name>
      <email>dungtn@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/401-how-to-extend-a-class-properly" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code373</id>
    <published>2008-07-16T16:59:17+00:00</published>
    <updated>2008-07-18T02:46:37+00:00</updated>
    <title>[Ruby] Password update code</title>
    <content type="html">&lt;p&gt;Mostly straight from a tutorial, but it's uuuugly:&lt;/p&gt;

&lt;pre&gt;class AccountsController &amp;lt; ApplicationController

  layout 'application'
  before_filter :login_required, :except =&amp;gt; :show

  # Change password action  
  def update
  return unless request.put?
    # we authenticate with email 
    if Dj.authenticate(current_dj.email, params[:old_password])
      if ((params[:password] == params[:password_confirmation]) &amp;amp;&amp;amp; !params[:password_confirmation].blank?)
        current_dj.password_confirmation = params[:password_confirmation]
        current_dj.password = params[:password]        
    if current_dj.save
        flash[:notice] = &amp;quot;Password successfully updated.&amp;quot;
        redirect_to dj_path(current_dj.login) #profile_url(current_dj.login)
      else
        flash[:error] = &amp;quot;An error occured, your password was not changed.&amp;quot;
        render :action =&amp;gt; 'edit'
      end
    else
      flash[:error] = &amp;quot;New password does not match the password confirmation.&amp;quot;
      @old_password = params[:old_password]
      render :action =&amp;gt; 'edit'      
     end
   else
      flash[:error] = &amp;quot;Your old password is incorrect.&amp;quot;
      render :action =&amp;gt; 'edit'
    end 
  end    
end
&lt;/pre&gt;</content>
    <author>
      <name>danielharan</name>
      <email>chebuctonian@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/373-password-update-code" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code360</id>
    <published>2008-07-11T08:40:17+00:00</published>
    <updated>2008-08-22T17:31:29+00:00</updated>
    <title>[C#] Balance HTML Tags</title>
    <content type="html">&lt;p&gt;For the subset of HTML tags we care about, this function ensures that all tags in the input HTML are balanced (but not correctly nested, necessarily) -- it does this by *removing* any extra opening or closing tags it finds in the HTML string. Note: this routine is NOT designed to be a XSS sanitizer! It assumes it is running on safe, pre-sanitized HTML.&lt;/p&gt;

&lt;pre&gt;private static Regex _namedtags = new Regex
    (@&amp;quot;&amp;lt;/?(?&amp;lt;tagname&amp;gt;\w+)[^&amp;gt;]*(\s|$|&amp;gt;)&amp;quot;,
    RegexOptions.Singleline | RegexOptions.ExplicitCapture);

/// &amp;lt;summary&amp;gt;
/// attempt to balance HTML tags in the html string
/// by removing any unmatched opening or closing tags
/// &amp;lt;/summary&amp;gt;
public static string BalanceTags(string html)
{
    var tagname = &amp;quot;&amp;quot;;
    var tag = &amp;quot;&amp;quot;;
    var ignoredtags = &amp;quot;&amp;lt;p&amp;lt;img&amp;lt;br&amp;lt;li&amp;quot;;
    var match = 0;

    MatchCollection tags = _namedtags.Matches(html);
    bool[] tagpaired = new bool[tags.Count];

    // loop through matched tags in reverse order
    for (int i = tags.Count - 1; i &amp;gt; -1; i--)
    {
        tagname = tags[i].Groups[&amp;quot;tagname&amp;quot;].Value.ToLower();
        tag = tags[i].Value;
        match = -1;

        // skip any tags in our ignore list; assume they're self-closed
        if (!tagpaired[i] &amp;amp;&amp;amp; !ignoredtags.Contains(&amp;quot;&amp;lt;&amp;quot; + tagname))
        {
            if (tag.StartsWith(&amp;quot;&amp;lt;/&amp;quot;))
            {
                // if searching backwards, look for opening tags
                for (int j = i - 1; j &amp;gt; -1; j--)
                {
                    if (!tagpaired[j] &amp;amp;&amp;amp; tags[j].Value.ToLower().StartsWith(&amp;quot;&amp;lt;&amp;quot; + tagname))
                    {
                        match = j;
                        break;
                    }
                }
            }
            else
            {
                // if searching forwards, look for closing tags
                for (int j = i + 1; j &amp;lt; tags.Count; j++)
                {
                    if (!tagpaired[j] &amp;amp;&amp;amp; tags[j].Value.ToLower().StartsWith(&amp;quot;&amp;lt;/&amp;quot; + tagname))
                    {
                        match = j;
                        break;
                    }
                }
            }

            if (match &amp;gt; -1)
            {
                // found matching opening/closing tag
                tagpaired[match] = true;
                tagpaired[i] = true;
            }
            else
            {
                // no matching opening/closing tag found -- remove this tag!
                html = html.Remove(tags[i].Index, tags[i].Length);
                tagpaired[i] = true;
                System.Diagnostics.Debug.WriteLine(&amp;quot;unbalanced tag removed: &amp;quot; + tags[i]);
            }
        }
    }

    return html;
}&lt;/pre&gt;</content>
    <author>
      <name>Jeff Atwood</name>
      <email>jatwood@codinghorror.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/360-balance-html-tags" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code333</id>
    <published>2008-06-20T08:24:46+00:00</published>
    <updated>2008-10-03T03:51:48+00:00</updated>
    <title>[C#] Sanitize HTML</title>
    <content type="html">&lt;p&gt;Takes a provided HTML string and removes any potentially dangerous XSS HTML tags using a whitelist approach. Useful when you want to allow a small subset of &amp;quot;safe&amp;quot; HTML tags in user content.&lt;/p&gt;

&lt;p&gt;UPDATED: July 11th to reflect all refactorings, plus optimizing for speed. Now 2x faster!&lt;/p&gt;

&lt;p&gt;UPDATED: Sept 1st, bugfixes&lt;/p&gt;

&lt;pre&gt;private static Regex _tags = new Regex(&amp;quot;&amp;lt;[^&amp;gt;]*(&amp;gt;|$)&amp;quot;, RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.Compiled);
private static Regex _whitelist = new Regex(@&amp;quot;
    ^&amp;lt;/?(a|b(lockquote)?|code|em|h(1|2|3)|i|li|ol|p(re)?|s(ub|up|trong|trike)?|ul)&amp;gt;$
    |^&amp;lt;(b|h)r\s?/?&amp;gt;$
    |^&amp;lt;a[^&amp;gt;]+&amp;gt;$
    |^&amp;lt;img[^&amp;gt;]+/?&amp;gt;$&amp;quot;,
    RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace |
    RegexOptions.ExplicitCapture | RegexOptions.Compiled);

/// &amp;lt;summary&amp;gt;
/// sanitize any potentially dangerous tags from the provided raw HTML input using 
/// a whitelist based approach, leaving the &amp;quot;safe&amp;quot; HTML tags
/// &amp;lt;/summary&amp;gt;
public static string Sanitize(string html)
{

    var tagname = &amp;quot;&amp;quot;;
    Match tag;
    var tags = _tags.Matches(html);

    // iterate through all HTML tags in the input
    for (int i = tags.Count-1; i &amp;gt; -1; i--)
    {
        tag = tags[i];
        tagname = tag.Value.ToLower();

        if (!_whitelist.IsMatch(tagname))
        {
            // not on our whitelist? I SAY GOOD DAY TO YOU, SIR. GOOD DAY!
            html = html.Remove(tag.Index, tag.Length);
        }
        else if (tagname.StartsWith(&amp;quot;&amp;lt;a&amp;quot;))
        {
            // detailed &amp;lt;a&amp;gt; tag checking
            if (!IsMatch(tagname,
                @&amp;quot;&amp;lt;a\s
                  href=&amp;quot;&amp;quot;(\#\d+|(https?|ftp)://[-A-Za-z0-9+&amp;amp;@#/%?=~_|!:,.;]+)&amp;quot;&amp;quot;
                  (\stitle=&amp;quot;&amp;quot;[^&amp;quot;&amp;quot;]+&amp;quot;&amp;quot;)?\s?&amp;gt;&amp;quot;))
            {
                html = html.Remove(tag.Index, tag.Length);
            }
        }
        else if (tagname.StartsWith(&amp;quot;&amp;lt;img&amp;quot;))
        {
            // detailed &amp;lt;img&amp;gt; tag checking
            if (!IsMatch(tagname,
                @&amp;quot;&amp;lt;img\s
              src=&amp;quot;&amp;quot;https?://[-A-Za-z0-9+&amp;amp;@#/%?=~_|!:,.;]+&amp;quot;&amp;quot;
              (\swidth=&amp;quot;&amp;quot;\d{1,3}&amp;quot;&amp;quot;)?
              (\sheight=&amp;quot;&amp;quot;\d{1,3}&amp;quot;&amp;quot;)?
              (\salt=&amp;quot;&amp;quot;[^&amp;quot;&amp;quot;]*&amp;quot;&amp;quot;)?
              (\stitle=&amp;quot;&amp;quot;[^&amp;quot;&amp;quot;]*&amp;quot;&amp;quot;)?
              \s?/?&amp;gt;&amp;quot;))
            {
                html = html.Remove(tag.Index, tag.Length);
            }
        }
        
    }

    return html;
}


/// &amp;lt;summary&amp;gt;
/// Utility function to match a regex pattern: case, whitespace, and line insensitive
/// &amp;lt;/summary&amp;gt;
private static bool IsMatch(string s, string pattern)
{
    return Regex.IsMatch(s, pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase |
        RegexOptions.IgnorePatternWhitespace | RegexOptions.ExplicitCapture);
}&lt;/pre&gt;</content>
    <author>
      <name>Jeff Atwood</name>
      <email>jatwood@codinghorror.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/333-sanitize-html" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code271</id>
    <published>2008-04-01T16:10:13+00:00</published>
    <updated>2008-04-09T22:58:51+00:00</updated>
    <title>[Ruby] Ruby has_finder on has_many ?</title>
    <content type="html">&lt;p&gt;This smells... one of the main points of using has_finder was to isolate domain logic to the appropriate model (&lt;a href="http://jamesgolick.com/2008/2/25/plugins-i-ve-known-and-loved-2-has_finder" target="_blank"&gt;http://jamesgolick.com/2008/2/25/plugins-i-ve-known-and-loved-2-has_finder&lt;/a&gt;), but here it's scattered again.&lt;/p&gt;

&lt;p&gt;Any ideas on how to elegantly clean this up?&lt;/p&gt;

&lt;pre&gt;class JobBoard &amp;lt; ActiveRecord::Base
  has_many :job_board_postings
  
  has_finder :distributed_by, lambda {|distributor_code| {:conditions =&amp;gt; ['distributor = ?', distributor_code.to_s]} }
  has_finder :push,   :conditions =&amp;gt; {:push =&amp;gt; true}
  has_finder :manual, :conditions =&amp;gt; {:manual =&amp;gt; true}
  
  def push
    ! pull
  end
  alias_method :push?, :push
end

class JobBoardPosting &amp;lt; ActiveRecord::Base
  belongs_to :job
  belongs_to :job_board

  has_finder :distributed_by, lambda {|distributor_code| {:conditions =&amp;gt; ['job_boards.distributor = ?', distributor_code.to_s], :include =&amp;gt; :job_board} }
  
  # TODO: couldn't this be a delegated finder? not very DRY
  has_finder :pushed, :conditions =&amp;gt; [&amp;quot;job_boards.pull = ?&amp;quot;, false],  :include =&amp;gt; :job_board
  has_finder :manual, :conditions =&amp;gt; [&amp;quot;job_boards.manual = ?&amp;quot;, true], :include =&amp;gt; :job_board
end&lt;/pre&gt;</content>
    <author>
      <name>danielharan</name>
      <email>chebuctonian@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/271-ruby-has_finder-on-has_many" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code240</id>
    <published>2008-02-20T04:38:08+00:00</published>
    <updated>2008-09-24T14:52:17+00:00</updated>
    <title>[Ruby] DataMapper threaded benchmark</title>
    <content type="html">&lt;p&gt;third of three - slowest of those tested, even though it's thread-safe - why?&lt;/p&gt;

&lt;pre&gt;require 'rubygems'
require 'data_mapper'
require 'benchmark'

DataMapper::Database.setup({ :adapter =&amp;gt; 'sqlite3', :database =&amp;gt; 'perf_dm.db' })

# set up DataMapper
class DmItem
  include DataMapper::Persistence
  set_table_name 'items'
  property :name, :string
  property :description, :text
  property :active, :boolean
  property :created_at, :datetime
end
database.save(DmItem)
# DataMapper::Persistence.auto_migrate!

1000.times do |i|
  x = DmItem.new(:name =&amp;gt; &amp;quot;record_#{i}&amp;quot;, :description =&amp;gt; &amp;quot;test record&amp;quot;, :active =&amp;gt; i.remainder(3).zero?)
  x.save
end

# run benchmarks
Benchmark.bmbm do |x|
  
  x.report('DataMapper single-thread') do
    100.times do
      DmItem.all(:active =&amp;gt; false)
    end
  end
  
  x.report('DataMapper threaded') do
    threads = []
    10.times do
      t = Thread.new do
        10.times do
          DmItem.all(:active =&amp;gt; false)
        end
      end
      threads.push(t)
    end
    threads.each { |t| t.join }
  end
  
end

&lt;/pre&gt;</content>
    <author>
      <name>Kevin Williams</name>
      <email>kevwil@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/240-datamapper-threaded-benchmark" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code239</id>
    <published>2008-02-20T04:35:56+00:00</published>
    <updated>2008-02-20T04:35:56+00:00</updated>
    <title>[Ruby] Sequel threaded benchmark</title>
    <content type="html">&lt;p&gt;second of three, not as fast as ActiveRecord - why?&lt;/p&gt;

&lt;pre&gt;require 'rubygems'
require 'sequel'
require 'benchmark'

# set up Sequel
Sequel::Model.db = DB = Sequel.sqlite('perf_sequel.db')

class SequelItem &amp;lt; Sequel::Model(:items)
  set_schema do
    primary_key :id
    varchar :name
    text :description
    boolean :active
    timestamp :created_at
  end
end

# create schema and populate
SequelItem.create_table!

1000.times do |i|
  DB[:items].insert(:name =&amp;gt; &amp;quot;record_#{i}&amp;quot;, :description =&amp;gt; &amp;quot;test record&amp;quot;, :active =&amp;gt; i.remainder(3).zero?, :created_at =&amp;gt; Time.now)
end

# run benchmarks
Benchmark.bmbm do |x|
  
  x.report('sequel single-thread') do
    100.times do
      SequelItem.where(:active =&amp;gt; false).all
    end
  end
  
  x.report('sequel threaded') do
    threads = []
    10.times do
      t = Thread.new do
        10.times do
          SequelItem.where(:active =&amp;gt; false).all
        end
      end
      threads.push(t)
    end
    threads.each { |t| t.join }
  end
  
end

SequelItem.drop_table

&lt;/pre&gt;</content>
    <author>
      <name>Kevin Williams</name>
      <email>kevwil@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/239-sequel-threaded-benchmark" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code238</id>
    <published>2008-02-20T04:33:28+00:00</published>
    <updated>2008-02-20T04:36:49+00:00</updated>
    <title>[Ruby] ActiveRecord threaded benchmark</title>
    <content type="html">&lt;p&gt;first of three benchmarks, expected AR to be slowest but it was fastest - why?&lt;/p&gt;

&lt;pre&gt;require 'rubygems'
require 'active_record'
require 'benchmark'

ActiveRecord::Base.establish_connection :adapter =&amp;gt; 'sqlite3', :database =&amp;gt; 'perf_ar.db'

# set up ActiveRecord
class ArItem &amp;lt; ActiveRecord::Base
  set_table_name 'items'
end

# created schema and data
class NewItem &amp;lt; ActiveRecord::Migration
  def self.up
    create_table :items do |t|
      t.column :name, :string
      t.column :description, :text
      t.column :active, :boolean
      t.column :created_at, :datetime
    end
  end
  def self.down
    drop_table :items
  end
end
NewItem.up

1000.times do |i|
  ArItem.create(:name =&amp;gt; &amp;quot;record_#{i}&amp;quot;, :description =&amp;gt; &amp;quot;test record&amp;quot;, :active =&amp;gt; i.remainder(3).zero?)
end

# run benchmarks
Benchmark.bmbm do |x|
  
  x.report('active_record single-thread') do
    100.times do
      ArItem.find(:all, :conditions =&amp;gt; [&amp;quot;active = ?&amp;quot;, false])
    end
  end
  
  x.report('active_record threaded') do
    ActiveRecord::Base.allow_concurrency = true
    threads = []
    10.times do
      t = Thread.new do
        10.times do
          ArItem.find(:all, :conditions =&amp;gt; [&amp;quot;active = ?&amp;quot;, false])
        end
      end
      threads.push(t)
    end
    threads.each { |t| t.join }
  end
  
end
ActiveRecord::Base.verify_active_connections!
NewItem.down

&lt;/pre&gt;</content>
    <author>
      <name>Kevin Williams</name>
      <email>kevwil@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/238-activerecord-threaded-benchmark" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code192</id>
    <published>2007-12-20T21:54:34+00:00</published>
    <updated>2007-12-22T03:14:03+00:00</updated>
    <title>[Ruby] Challenge: Ugliest Ruby FizzBuzz</title>
    <content type="html">&lt;p&gt;So, after seeing some ugly fizzbuzzes, instead of trying to create the best fizzbuzz ever (an easy task), we decided the worst fizzbuzz ever would be a bigger challenge.&lt;/p&gt;

&lt;p&gt;Oh, and before you ask, it's because spaceships are awesome.&lt;/p&gt;

&lt;pre&gt;class Fixnum
  def &amp;lt;=&amp;gt;(b)
    self % b
  end
  
  def fizz?
    self % 3 == 0
  end
  
  def buzz?
    self % 5 == 0
  end
end

(1..100).each do |number|
  if number.fizz?
    if number.buzz?
      puts 'FizzBuzz'
    else
      puts 'Fizz'
    end
  else
    puts 'Buzz'
  end
end&lt;/pre&gt;</content>
    <author>
      <name>jamesgolick</name>
      <email>jamesgolick@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/192-challenge-ugliest-ruby-fizzbuzz" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code137</id>
    <published>2007-11-05T20:27:18+00:00</published>
    <updated>2007-11-06T01:02:42+00:00</updated>
    <title>[Ruby] resource_controller: Redesign My API</title>
    <content type="html">&lt;p&gt;Backstory on my blog: &lt;a href="http://jamesgolick.com/2007/11/5/resource_controller-redesign-my-api-at-refactormycode-com" target="_blank"&gt;http://jamesgolick.com/2007/11/5/resource_controller-redesign-my-api-at-refactormycode-com&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;## Before / After / Response

class PostsController &amp;lt; ResourceController::Base

  # block syntax
  create do
    before { @post.user = current_user }
    response do |wants|
      wants.html
      wants.js
    end
  end
  
  # chain syntax
  update.failure.wants.js
  
  # hybrid syntax
  update.failure do
    flash &amp;quot;There was a problem saving your object.&amp;quot;
    wants.js
  end

end

## Alternate Model/Route/Object Naming

class PostsController &amp;lt; ResourceController::Base
  private
    def model_name
      'blog_post'
    end
    
    def route_name
      'article'
    end
end

## Alternate find syntax

class PostsController &amp;lt; ResourceController::Base
  private
    def object
      @object ||= end_of_association_chain.find_by_permalink(param)
    end
    
    def collection
      @collection ||= end_of_association_chain.find(:all, :page =&amp;gt; {:current =&amp;gt; params[:page], :size =&amp;gt; 10})
    end
end

## Specific Actions

class PostsController &amp;lt; ResourceController::Base
  actions :all, :except =&amp;gt; :edit
end

## Possible Parents

class PostsController &amp;lt; ResourceController::Base
  belongs_to :user, :category
end&lt;/pre&gt;</content>
    <author>
      <name>jamesgolick</name>
      <email>jamesgolick@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/137-resource_controller-redesign-my-api" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code121</id>
    <published>2007-10-30T22:30:23+00:00</published>
    <updated>2007-10-31T14:59:35+00:00</updated>
    <title>[JavaScript] I care about older browsers without JS</title>
    <content type="html">&lt;p&gt;I found this great piece of code from an ad server and thought to myself that I should learn to make my own JS legacy compliant.  Can anyone please tell me if they know a better way to do this?  Thanks in advance.&lt;/p&gt;

&lt;pre&gt;document.write ('&amp;lt;noscript&amp;gt;\n');
document.write (imageClick);
document.write (&amp;quot;&amp;lt;/noscript&amp;gt;&amp;quot;);&lt;/pre&gt;</content>
    <author>
      <name>Gary Haran</name>
      <email>gary.haran@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/121-i-care-about-older-browsers-without-js" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code118</id>
    <published>2007-10-30T15:29:16+00:00</published>
    <updated>2007-12-02T16:29:55+00:00</updated>
    <title>[Ruby] Is This String Postal?</title>
    <content type="html">&lt;p&gt;We've had the debate over wether it was a good idea or not to do this.&lt;/p&gt;

&lt;pre&gt;class String 
  def postal?  
    self.match(/[a-zA-Z]{1}\d{1}[a-zA-Z]{1}([\x20-])*\d{1}[a-zA-Z]{1}\d{1}/) ? true : false
  end
end&lt;/pre&gt;</content>
    <author>
      <name>Gary Haran</name>
      <email>gary.haran@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/118-is-this-string-postal" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code112</id>
    <published>2007-10-26T18:25:22+00:00</published>
    <updated>2007-10-29T20:57:29+00:00</updated>
    <title>[Ruby] Rails migration conflict repair</title>
    <content type="html">&lt;p&gt;Explained here: &lt;a href="http://www.danielharan.com/2007/10/26/rails-migrations-handling-naming-conflicts/" target="_blank"&gt;http://www.danielharan.com/2007/10/26/rails-migrations-handling-naming-conflicts/&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;namespace :migrations do
  
  desc 'reverts, renames and re-executes uncommitted migrations that conflict with already committed migrations'
  task :repair =&amp;gt; :environment do
    uncommitted = `svn status`.select {|line| line =~ /db\/migrate\//}.collect {|line| line.match(/ db\/migrate\/(.*rb)/)[1]}
    committed   = Dir.glob('db/migrate/*').collect {|line| line.match(/db\/migrate\/(.*rb)/)[1]} - uncommitted
    
    highest_committed   = committed.collect(&amp;amp;:to_i).max
    lowest_uncommitted  = uncommitted.collect(&amp;amp;:to_i).min
    
    schema_version = ActiveRecord::Base.connection.select_one(&amp;quot;select version from schema_info&amp;quot;)[&amp;quot;version&amp;quot;].to_i
    
    # revert uncommitted migrations
    uncommitted.sort_by(&amp;amp;:to_i).reverse.each do |migration|
      version = migration.to_i
      if version &amp;lt;= schema_version
        name = migration.match(/(\d*_.*).rb/)[1]
        class_name = (require 'db/migrate/' + name)[0]
        puts class_name.constantize.down 
      end
    end
    
    #set it back to the version prior to all the uncommitted migrations - this doesn't get done automatically by calling down
    ActiveRecord::Base.connection.execute(&amp;quot;update schema_info set version=#{schema_version-1}&amp;quot;)
    
    version_offset = (highest_committed - lowest_uncommitted) + 1
    
    uncommitted.each do |old_name|
      version  = old_name.to_i + version_offset
      new_name = version.to_s.rjust(3,'0') + old_name.gsub(/\d/, '')
      `mv db/migrate/#{old_name} db/migrate/#{new_name}`
    end
    
    puts &amp;quot;Uncommited migrations have been reversed and renamed. You can now migrate.&amp;quot;
  end
end&lt;/pre&gt;</content>
    <author>
      <name>danielharan</name>
      <email>chebuctonian@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/112-rails-migration-conflict-repair" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code78</id>
    <published>2007-10-12T04:27:08+00:00</published>
    <updated>2007-10-12T04:30:57+00:00</updated>
    <title>[Ruby] Dynamic migrations for rails</title>
    <content type="html">&lt;p&gt;How do you create a rails project if you don't know the schema in advance? ERB to the rescue!&lt;/p&gt;

&lt;p&gt;Blogged background: &lt;a href="http://www.danielharan.com/2007/10/12/rails-migration-hackery-with-erb/" target="_blank"&gt;http://www.danielharan.com/2007/10/12/rails-migration-hackery-with-erb/&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;require 'erb'
class ClientMigrator
  def self.create(fields)
    erb_migration = ERB.new &amp;lt;&amp;lt;-EOS
  class AddClients &amp;lt; ActiveRecord::Migration
    def self.up
      create_table :clients do |t|
        &amp;lt;% fields.each do |name, type| %&amp;gt;t.column :&amp;lt;%= name %&amp;gt;, :&amp;lt;%= type %&amp;gt;
        &amp;lt;% end %&amp;gt;
      end
    end

    def self.down
      drop_table :clients
    end
  end
EOS
    File.open(&amp;quot;db/migrate/003_add_clients.rb&amp;quot;, &amp;quot;w+&amp;quot;) do |f|
      f.puts erb_migration.result(binding)
    end
    `rake db:migrate`
  end
end

# Example call
ClientMigrator.create(:name =&amp;gt; :string, :phone =&amp;gt; :string)&lt;/pre&gt;</content>
    <author>
      <name>danielharan</name>
      <email>chebuctonian@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/78-dynamic-migrations-for-rails" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code75</id>
    <published>2007-10-11T19:15:38+00:00</published>
    <updated>2007-10-11T19:15:38+00:00</updated>
    <title>[Ruby] Iffy</title>
    <content type="html">&lt;p&gt;With all the magic surrounding ruby I can't help but think that there are shorter and more readable ways to do this.&lt;/p&gt;

&lt;pre&gt;if self.location_type.to_s == 'point'
  breaker = self.lang == 'fr' ? 'proximite' : 'near'
 else  
  breaker = self.lang == 'fr' ? 'dans' : 'in'
end&lt;/pre&gt;</content>
    <author>
      <name>Gary Haran</name>
      <email>gary.haran@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/75-iffy" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor358</id>
    <published>2007-10-10T05:00:58+00:00</published>
    <title>[Bash] On Open a new tab in current directory from iTerm</title>
    <content type="html">&lt;p&gt;Macournoyer, I tried your function and it opens the server on my window then launches me to another tab. I prefer stay in my tab and launch the process in another tab. After some digging I came up with the code bellow, the difference in the command call is that you don't need use the &amp;quot;;&amp;quot;.&lt;/p&gt;

&lt;p&gt;So, what was: tab; script/server
&lt;br /&gt;Now should be: tab script/server&lt;/p&gt;

&lt;p&gt;The only thing I could not solve is that iTerm changes the tab on a launch, so I had to bring it back with a &amp;quot;select session&amp;quot; call.&lt;/p&gt;

&lt;pre&gt;## [bash]

tab()
{
        osascript -e &amp;quot;
        tell application \&amp;quot;iTerm\&amp;quot;
         tell the first terminal
          set currentSession to current session
          launch session \&amp;quot;Default Session\&amp;quot;
          tell the last session
           write text \&amp;quot;cd $(pwd)\&amp;quot;
           write text \&amp;quot;$*\&amp;quot;
          end tell
          select currentSession
         end tell
        end tell&amp;quot;
}&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha.gravatar@mailnull.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/63-open-a-new-tab-in-current-directory-from-iterm/refactors/358" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor312</id>
    <published>2007-10-06T15:40:51+00:00</published>
    <title>[Java] On Hello World</title>
    <content type="html">&lt;p&gt;Ok, your HelloWorld is not problematic and not need a refactoring, but just for fun you can avoid call the main method.&lt;/p&gt;

&lt;pre&gt;## HelloWorld [java]


public class HelloWorld {
    static {
        System.out.println(&amp;quot;Hello World&amp;quot;);
        System.exit(0);
    }
}&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha.gravatar@mailnull.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/66-hello-world/refactors/312" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor255</id>
    <published>2007-10-03T16:31:20+00:00</published>
    <title>[Ruby] On Integer puzzle</title>
    <content type="html">&lt;p&gt;Here is the full solution, after some refactorings that speed it up (almost an order of magnitude) and help readability a bit.&lt;/p&gt;

&lt;pre&gt;class ITA
  
  class Number
    include Comparable

    def initialize(millions, thousands=0, units=0)
      @millions, @thousands, @units = millions, thousands, units
    end

    def value
      @millions * 1_000_000 + @thousands * 1_000 + @units
    end

    def size
      to_s.size
    end

    def to_s
      @st ||= NumberWriter.write(@millions,@thousands,@units)
    end

    def self.sorted_numbers
      @@sorted_nums ||= (0..999).collect {|num| Number.new 0,0,num}.sort.collect {|i| i.value}
    end

    def &amp;lt;=&amp;gt;(anOther)
      to_s &amp;lt;=&amp;gt; anOther.to_s
    end
  end
  
  class NumberWriter
    UNITS = { 0 =&amp;gt; '', 1 =&amp;gt; 'one', 2 =&amp;gt; 'two', 3 =&amp;gt; 'three', 4 =&amp;gt; 'four',
              5 =&amp;gt; 'five', 6 =&amp;gt; 'six', 7 =&amp;gt; 'seven', 8 =&amp;gt; 'eight', 9 =&amp;gt; 'nine'}

    TEENS = { 10 =&amp;gt; &amp;quot;ten&amp;quot;, 11 =&amp;gt; &amp;quot;eleven&amp;quot;, 12 =&amp;gt; &amp;quot;twelve&amp;quot;, 13 =&amp;gt; &amp;quot;thirteen&amp;quot;, 14 =&amp;gt; &amp;quot;fourteen&amp;quot;,
              15 =&amp;gt; &amp;quot;fifteen&amp;quot;, 16 =&amp;gt; &amp;quot;sixteen&amp;quot;, 17 =&amp;gt; &amp;quot;seventeen&amp;quot;,  18 =&amp;gt; &amp;quot;eighteen&amp;quot;, 19 =&amp;gt; &amp;quot;nineteen&amp;quot; }

    TENS  = {10 =&amp;gt; &amp;quot;ten&amp;quot;, 20 =&amp;gt; &amp;quot;twenty&amp;quot;, 30 =&amp;gt; &amp;quot;thirty&amp;quot;, 40 =&amp;gt; &amp;quot;forty&amp;quot;, 50 =&amp;gt; &amp;quot;fifty&amp;quot;,
             60 =&amp;gt; &amp;quot;sixty&amp;quot;, 70 =&amp;gt; &amp;quot;seventy&amp;quot;, 80 =&amp;gt; &amp;quot;eighty&amp;quot;, 90 =&amp;gt; &amp;quot;ninety&amp;quot; }

    def self.write(millions, thousands=0, units=0)
      (millions &amp;gt; 0 ?  format_units(millions) + 'million' : '' ) + 
      (thousands &amp;gt; 0 ? format_units(thousands) + 'thousand' : '' ) + 
       format_units(units)
    end
    
    def self.string_size(millions,thousands=0,units=0)
      (millions &amp;gt; 0 ?  @@sizes[millions] + 7 : 0 ) + 
      (thousands &amp;gt; 0 ? @@sizes[thousands] + 8 : 0 ) + 
       @@sizes[units]
    end

    def self.format_units(value)
      ret = @@formatted_units[value]
      ret
    end

    def self.format_unit(value)
      hundreds = value / 100
      st = (hundreds &amp;gt; 0) ? (UNITS[hundreds] + 'hundred') : ''
      remainder = value % 100
      tens    = remainder / 10
      if (tens == 1)
        st += TEENS[remainder]
      else
        st += TENS[tens*10] if (tens &amp;gt; 1)
        units = remainder % 10
        st += UNITS[units] if units &amp;gt; 0
      end
      st
    end

    @@formatted_units = (0..999).collect {|i| format_unit(i)}
    @@sizes = @@formatted_units.collect {|f| f.size}
  end
  
  class Range &amp;lt; Number
    include Enumerable
    
    attr_accessor :millions, :thousands
    def initialize(millions,thousands=0)
      @millions = millions
      @thousands = thousands
    end
    
    def to_s
      @st ||= NumberWriter.write(@millions, @thousands)
    end
  end

  class ThousandRange &amp;lt; Range
    def child_values
      @thousands * 1_000_000 + 499500
    end

    def child_sizes
      NumberWriter.string_size(0, @thousands) * 1_000 + 18440
    end

    def each
      Number.sorted_numbers.each do |i|
        yield Number.new(0, @thousands, i)
      end
    end
  end

  class MixedRange &amp;lt; Range
    def child_values
      @millions * 1_000_000_000 + @thousands * 1_000_000 + 499500
    end

    def child_sizes
      NumberWriter.string_size(@millions, @thousands) * 1_000 + 18440
    end

    def each
      Number.sorted_numbers.each do |i|
        yield Number.new(@millions, @thousands, i)
      end
    end
  end

  class MillionRange &amp;lt; Range
    def child_values
      @millions * 1_000_000_000_000 + 499_999_500_000
    end

    def child_sizes
      NumberWriter.string_size(@millions) * 1_000_000 + 44_872_000
    end
    
    def children
      ((Number.sorted_numbers - [0]).collect {|i| MixedRange.new(@millions, i) } &amp;lt;&amp;lt; 
        [MixedRange.new(@millions, 0).to_a]).flatten
    end

    def each
      children.sort.each do |i|
        yield i
      end
    end
  end
  
end

@target = 51_000_000_000
@sum = @size = 0

# recursion isn't nice to puts
def echo(msg)
  puts msg
end

def seek(elements)
  elements.each do |e|
    if e.class== ITA::Number
      @sum  += e.value
      @size += e.size
    else
      if ((@size + e.child_sizes) &amp;gt; @target)
        seek(e) # recurse to avoid overshooting target
      else
        @sum  += e.child_values
        @size += e.child_sizes
      end
    end
    if @size == @target
      echo &amp;quot;number:&amp;quot; + e.to_s
      echo &amp;quot;sum: &amp;quot; + @sum.to_s
      exit
    end
  end
end

seek((1..999).collect {|i| [ITA::Number.new(0,0,i), ITA::MillionRange.new(i), ITA::ThousandRange.new(0,i)]}.flatten.sort)&lt;/pre&gt;</content>
    <author>
      <name>danielharan</name>
      <email>chebuctonian@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/8-integer-puzzle/refactors/255" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor225</id>
    <published>2007-10-02T21:49:08+00:00</published>
    <title>[Java] On Fastest way to sort doubles and their key - like in an array - in descending order</title>
    <content type="html">&lt;p&gt;I forgot to paste the Quicksort here is.&lt;/p&gt;

&lt;pre&gt;## Quicksort (Java)

/* Copyright (c) 2007 the authors listed at the following URL, and/or
the authors of referenced articles or incorporated external code:
http://en.literateprograms.org/Quicksort_(Java)?action=history&amp;amp;offset=20061122163828

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
&amp;quot;Software&amp;quot;), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED &amp;quot;AS IS&amp;quot;, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Retrieved from: http://en.literateprograms.org/Quicksort_(Java)?oldid=8141
*/




public class Quicksort {
	
	static &amp;lt;T extends Comparable&amp;lt;? super T&amp;gt;&amp;gt; void quicksort(T[] array)
 {
		
		quicksort(array, 0, array.length - 1);

	}
	
	static &amp;lt;T extends Comparable&amp;lt;? super T&amp;gt;&amp;gt; void quicksort(T[] array, int left0, int right0)
 {
		
		int left, right;
		T pivot, temp;
		left = left0;
		right = right0 + 1;

		
		pivot = array[left0];

		
		do {
			
			do left++; while (left &amp;lt; array.length &amp;amp;&amp;amp; array[left].compareTo(pivot) &amp;lt; 0);

			
			do right--; while (array[right].compareTo(pivot) &amp;gt; 0);

			
			if (left &amp;lt; right) {
				temp = array[left];
				array[left] = array[right];
				array[right] = temp;
			}

		}
		while (left &amp;lt;= right);
 
		
		temp = array[left0];
		array[left0] = array[right];
		array[right] = temp;

		
		if (left0 &amp;lt; right) quicksort(array, left0, right);
		if (left &amp;lt; right0) quicksort(array, left, right0);

	}
	
}

&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha.gravatar@mailnull.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/43-fastest-way-to-sort-doubles-and-their-key-like-in-an-array-in-descending-order/refactors/225" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor224</id>
    <published>2007-10-02T21:45:43+00:00</published>
    <title>[Java] On Fastest way to sort doubles and their key - like in an array - in descending order</title>
    <content type="html">&lt;p&gt;Well, first of all I'm not an expert in sort algorithms. What I did was use a Quicksort to verify if the sorting time improves and seems that worked.&lt;/p&gt;

&lt;p&gt;Let's talk about the code bellow. Arrays.sort() uses a modified version of Mergesort, checking Wikipedia ( &lt;a href="http://en.wikipedia.org/wiki/Sorting_algorithm#List_of_sorting_algorithms" target="_blank"&gt;http://en.wikipedia.org/wiki/Sorting_algorithm#List_of_sorting_algorithms&lt;/a&gt; ) you will see that Mergesort is a pretty good algorithm, but since Quicksort is very popular I've tested it in your code. &lt;/p&gt;

&lt;p&gt;The Quicksort implementation I've tested was found in ( &lt;a href="http://en.literateprograms.org/Quicksort_" target="_blank"&gt;http://en.literateprograms.org/Quicksort_&lt;/a&gt;(Java) ) and this code accept objects that implement a Comparable interface, so your code should work. &lt;/p&gt;

&lt;p&gt;I had to change your compareTo() method to keep right the spec in Comparable interface. If you want a reverse sort you can revert the walk in the &amp;quot;for&amp;quot;. StackOverflows can happen, and happened in this case, if your compareTo() break the spec of Comparable interface.&lt;/p&gt;

&lt;p&gt;For a loop of 10000000 sorts, Arrays.sort() takes about 12 seconds and Quicksort about 10 seconds in my machine. The code used to test is bellow too so you can test in your machine as well.&lt;/p&gt;

&lt;pre&gt;## Relation [java]

import java.util.Arrays;

class Relation implements Comparable&amp;lt;Relation&amp;gt; {

  public Relation(double array_value, int array_index) {
    this.array_value = array_value;
    this.array_index = array_index;
  }

  public double getValue() {
    return array_value;
  }

  public int getIndex() {
    return array_index;
  }

  //*** We need descending order
  public int compareTo(Relation relation) {

    double cmp_to = ((Relation) relation).array_value;
    double my_val = array_value;
 
    if (my_val &amp;gt; cmp_to) {
			return 1;
    } else if(my_val &amp;lt; cmp_to) {
			return -1;
    } else {
			return 0;
	}

  }
  
  private double array_value;
  private int array_index;
  
}


## SortWithIndexRefact [java]

public class SortWithIndexRefact {
  
  public static void main(String[] args) {

    
    //*** Some test data: 9 values and 9 keys will form 9 pairs...
    int keys[] = { 
			14, 12, 42, 56, 36, 61, 78, 83, 93 
	};
    double values[] = { 
			48.2d, 103.6d, 4.3d, 4.8d, 99.0d, 1.2d, 4.8d, 48.2d, 4.8d 
	};

    
    //*** A new array that will hold all the pairs
    Relation[] all_relations = new Relation[keys.length];    


    //*** Keys and Values in a new relation object are grouped and stored in the all_relations array    
    for (int i = 0, n = keys.length; i &amp;lt; n; i++) {
      all_relations[i] = new Relation(values[i], keys[i]);
    }


    //*** Display the pairs before sorting them
    System.out.println(&amp;quot;\nORIGINAL:\n------------&amp;quot;);
    for (Relation relation : all_relations) {
      System.out.println(relation.getValue() +&amp;quot; =&amp;gt; &amp;quot;+ relation.getIndex());
    }


    //*** Sort the array
 


     // This is the test, a recurrent loop of the same sort
	Relation[] relation_temp = new Relation[all_relations.length];

	for(int i = 0; i &amp;lt;= 10000000; i++) {
          relation_temp = all_relations.clone();

          // change the comment to test different algorithms
          
          //Arrays.sort(relation_temp);
          Quicksort.quicksort(relation_temp);
	}


    //*** Display the pairs after sorting them    
    System.out.println(&amp;quot;\nSORTED:\n------------&amp;quot;);
    for (Relation relation : relation_temp) {
      System.out.println(relation.getValue() +&amp;quot; =&amp;gt; &amp;quot;+ relation.getIndex());
    }
  }
}

## Quicksort [java]
&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha.gravatar@mailnull.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/43-fastest-way-to-sort-doubles-and-their-key-like-in-an-array-in-descending-order/refactors/224" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor208</id>
    <published>2007-10-02T13:54:53+00:00</published>
    <title>[Ruby] On Accept Language Array</title>
    <content type="html">&lt;p&gt;You can get a list of matching languages in the right order like so:&lt;/p&gt;

&lt;pre&gt;@matches = @languages.collect {|s| s[0..1]} &amp;amp; SUPPORTED_LANGUAGES.flatten
# [&amp;quot;en&amp;quot;]&lt;/pre&gt;</content>
    <author>
      <name>danielharan</name>
      <email>chebuctonian@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/46-accept-language-array/refactors/208" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor197</id>
    <published>2007-10-02T06:41:39+00:00</published>
    <title>[Java] On Fastest way to sort doubles and their key - like in an array - in descending order</title>
    <content type="html">&lt;p&gt;There&#194;&#180;s a reason to not use a TreeMap? (&lt;a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/TreeMap.html" target="_blank"&gt;http://java.sun.com/j2se/1.5.0/docs/api/java/util/TreeMap.html&lt;/a&gt;)&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha.gravatar@mailnull.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/43-fastest-way-to-sort-doubles-and-their-key-like-in-an-array-in-descending-order/refactors/197" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor189</id>
    <published>2007-10-01T22:05:32+00:00</published>
    <title>[Ruby] On Integer puzzle</title>
    <content type="html">&lt;p&gt;Some explanations for the above code in my blog post:
&lt;br /&gt;&lt;a href="http://www.danielharan.com/2007/10/02/ita-word-puzzle-ruby-solution-10000-times-faster-than-c/" target="_blank"&gt;http://www.danielharan.com/2007/10/02/ita-word-puzzle-ruby-solution-10000-times-faster-than-c/&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>danielharan</name>
      <email>chebuctonian@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/8-integer-puzzle/refactors/189" rel="alternate"/>
  </entry>
</feed>
