tag:refactormycode.com,2007:codespopularall Popular codes Wed Nov 19 18:11:23 +0000 2008 tag:refactormycode.com,2007:Code609 2008-11-19T05:23:59+00:00 2008-11-19T18:11:23+00:00 [Ruby] Caching Methods <p>Is it possible to cache methods in a manor similar to below? (non-RoR). I have a few ideas of how this may work but any suggestions would be great</p> <pre> class Something def something_else &quot;Expensive operation&quot; end cache_method :something_else, :for =&gt; 2.hours end inst = Something.new # Empty cache inst.something_else # Primed cache inst.something_else</pre> Tj Holowaychuk tj@vision-media.ca tag:refactormycode.com,2007:Code606 2008-11-18T12:33:54+00:00 2008-11-20T00:52:58+00:00 [C] How to find max, min of three numbers? <p>I tried to use as less variables and less operators as possible. <br />Please help to make the code better.</p> <pre>int max = rand(); // or any init value int min = rand(); // or any init value int tmp = rand(); // or any init value if (max &lt; min) { if (tmp &lt; min) { if (max &lt; tmp) { tmp = max; max = min; min = tmp; } else { // max &lt; min &amp;&amp; tmp &lt; min &amp;&amp; tmp &lt;= max max = min; min = tmp; } } else { // max &lt; min &amp;&amp; min &lt;= tmp min = max; max = tmp; } } else { // min &lt;= max if (tmp &lt; min) min = tmp; else // min &lt;= max &amp;&amp; min &lt;= tmp if (max &lt; tmp) max = tmp; }</pre> Tien Dung dungtn@gmail.com tag:refactormycode.com,2007:Code613 2008-11-20T13:42:18+00:00 2008-11-21T06:12:09+00:00 [Ruby] Similar virtual attributes and their getters/setter <p>My Publication class has a few very similar virtual attributes. Is there any way to unite their setter and getter methods?</p> <pre>class Publication &lt; ActiveRecord::Base def publisher_name self.publisher.name end def publisher_name=(name) self.publisher = Publisher.find_or_create_by_name(name.strip) unless name.blank? end def organization_name self.organization.name end def organization_name=(name) self.organization = Organization.find_or_create_by_name(name.strip) unless name.blank? end end</pre> foxdemon ermin@nomail.com tag:refactormycode.com,2007:Code614 2008-11-20T22:09:32+00:00 2008-11-21T05:23:39+00:00 [Ruby] Arrays, loops, strings... <p>Can this be done in one line?</p> <pre>select = [] joins = [] %w[first second third forth].each{ |semester| joins &lt;&lt; &quot;:pdp_#{semester}_semester&quot;; (1..5).each{ |n| select &lt;&lt; &quot;pdp_#{semester}_semesters.objetive_#{n} AS #{semester}_objetive_#{n}&quot; }} [select, joins].each { |x| x.join(', ') }</pre> Ceritium ceritium@gmail.com tag:refactormycode.com,2007:Code610 2008-11-19T18:48:58+00:00 2008-11-21T07:53:19+00:00 [Ruby] Shortest regular expression for matching a subdomain. <p>I have written this regular expression which matches any subdomain (consisting of only letters and digits) right below example.com (including the domain, e.g. test.example.com) but not <a href="http://www.example.com" target="_blank">www.example.com</a>. It works, but it is not very elegant.</p> <pre>/(?&lt;part&gt;(w(?!ww)|w(?=www)|w(?=[a-z0-9]+ww)|ww(?=[a-z0-9]+w)|www[a-z0-9]+|[a-vx-z0-9])[a-z0-9]*)\.example\.com/</pre> troethom t.thomsen@judoo.dk tag:refactormycode.com,2007:Code612 2008-11-19T22:23:15+00:00 2008-11-20T16:22:15+00:00 [C#] Check type is XML Serializable <p>I need a fast method to check to see if a type is XML Serializable, be that with the [Serializable] attribute or the IXmlSerializable interface. This is what I came up with. Can we make it better?</p> <pre>/// &lt;summary&gt; /// Test to see if the type can be XML serialized /// &lt;/summary&gt; /// &lt;param name=&quot;objectToTest&quot;&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; private static bool CanBeXmlSerialized(Type objectToTest) { Type[] interfaces = objectToTest.GetInterfaces(); bool containsIXmlSerializable = interfaces.Contains(typeof(IXmlSerializable)); return containsIXmlSerializable || objectToTest.IsSerializable; }</pre> sbehnke.myopenid.com tag:refactormycode.com,2007:Code607 2008-11-18T16:22:53+00:00 2008-11-18T16:22:53+00:00 [Perl] Apache log file sorting <p>I have a huge amount of log files on my hard drive and regularly download more. All of the files end up in a single directory. The log file names contain UNIX timestamps. I wrote this script to execute in a given directory and then move the found files to a new path based on the UNIX timestamp. Each new directory is named after a year and the week of the year, e.g. 200801, the first week of 2008. (Actually, the month doesn't have a leading zero yet. I just realized.)</p> <pre>#!/usr/bin/perl -w use strict; use Time::localtime; use File::Find; use File::Copy; my $vmlogpath = $ARGV[0] or die &quot;y'all didn't enter no arguments&quot;; find(\&amp;sortFile, $ARGV[0]); sub sortFile { if ( -f ) { my $filename=$_; $filename =~ /([0-9]{5,})/; my $unixtime = $1 or print &quot;Not a log file: $filename\n&quot;; my $dirname=makeDirName($unixtime); unless(-e &quot;${ARGV[0]}/${dirname}/${filename}&quot;) { my $path=makeDir($ARGV[0], $dirname); moveFile($filename, $path); print &quot;$filename is the file name.\n&quot;; print &quot;$unixtime is the extracted unixtime.\n&quot;; print &quot;$dirname is the directory name.\n&quot;; print &quot;$path is the path.\n&quot;; } } else { print &quot;Not a plain file: $_\n&quot;; } } sub moveFile { my $tehfile=$_[0]; my $tehdir=$_[1]; move($tehfile, $tehdir) or die &quot;Could not move files!\n$!&quot;; return 1; } sub makeDir { my $currentdir=$_[0]; my $newdir=$_[1]; my $newpath=&quot;${currentdir}/${newdir}&quot;; unless (-d $newpath) { mkdir($newpath,755) or die &quot;mkdir failed for $newpath: $!\n&quot; } return $newpath; } sub makeDirName { my $tehunix=$_[0]; my $day_of_year=localtime(int($tehunix))-&gt;yday; my $week_of_year=int($day_of_year / 7) + 1; my $year=1900+localtime(int($tehunix))-&gt;year; return $year . $week_of_year; }</pre> hourback hourback@gmail.com tag:refactormycode.com,2007:Code608 2008-11-19T00:45:07+00:00 2008-11-19T00:48:25+00:00 [JavaScript] Tab-Switching in jQuery <p>Is there a better way?</p> <pre>## showcase.html [HTML] &lt;div id=&quot;showcase&quot;&gt; &lt;ul class=&quot;nav&quot;&gt; &lt;li&gt;&lt;a href=&quot;#example&quot; class=&quot;selected&quot;&gt;Example&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#another&quot;&gt;Another&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div class=&quot;first item&quot; id=&quot;example&quot;&gt; This is the first item. By default it's shown. &lt;/div&gt; &lt;div class=&quot;item&quot; id=&quot;another&quot;&gt; This is another item. By default it's hidden. &lt;/div&gt; &lt;/div&gt; ## showcase.css [css] #showcase .item { display: none; } #showcase .first { display: block; } ## showcase.js [javascript] $(document).ready(function() { var selected = $(&quot;#showcase .first&quot;); // First is selected by default $(&quot;#showcase .nav a&quot;).click( function() { if($(this) != selected) { $('#showcase .nav a.selected').removeClass('selected'); selected.hide(); selected = $($(this).attr('href')); selected.show(); $(this).addClass('selected'); return false; // Stops link from jumping to the anchor } }) });</pre> Aupajo pete@metanation.com tag:refactormycode.com,2007:Code611 2008-11-19T21:53:29+00:00 2008-11-19T21:53:29+00:00 [JavaScript] Serena Collage slideshow <p>Creating a slideshow in our crappy CMS, Collage (from Serena), using a simple doctype called 'slide'. <br />Early version.</p> <pre>## View [html] &lt;div id=&quot;slideshow&quot; style=&quot;background:#FFF&quot;&gt; &lt;h2 class=&quot;slideshowTitle&quot;&gt;Around the World with Language&lt;/h2&gt; &lt;nexus:component classid=&quot;nexus/components/AssetQuery&quot; code=&quot;/System/Components/nexusComponents.jar&quot; root=&quot;$node.path/slides&quot; levelsdeep=&quot;0&quot; filter=&quot;A.AssetType='slide' AND((A.StartDate is null) OR (A.StartDate &lt;= current timestamp)) AND ((A.ExpireDate &gt;= current timestamp) OR (A.ExpireDate is null))&quot; max=&quot;1&quot; orderonmetadata=&quot;pageListPriority&quot; orderbycode=&quot;1A&quot;&gt; &lt;div id=&quot;slide0&quot; name=&quot;slide&quot; style=&quot;display:block;&quot;&gt; &lt;h3 class=&quot;slideTitle&quot;&gt;$node.contribution(&quot;title&quot;)&lt;/h3&gt; &lt;div class=&quot;slideImage&quot; width=&quot;30%&quot;&gt;$node.contribution(&quot;image&quot;)&lt;/div&gt; &lt;p class=&quot;slideCaption&quot;&gt;$node.contribution(&quot;caption&quot;)&lt;/p&gt; &lt;/div&gt; &lt;/nexus:component&gt; &lt;nexus:component classid=&quot;nexus/components/AssetQuery&quot; code=&quot;/System/Components/nexusComponents.jar&quot; root=&quot;$node.path/slides&quot; levelsdeep=&quot;0&quot; filter=&quot;A.AssetType='slide' AND((A.StartDate is null) OR (A.StartDate &lt;= current timestamp)) AND ((A.ExpireDate &gt;= current timestamp) OR (A.ExpireDate is null))&quot; skip=&quot;1&quot; orderonmetadata=&quot;pageListPriority&quot; orderbycode=&quot;1A&quot;&gt; &lt;div id=&quot;slide$node.recordnumber&quot; name=&quot;slide&quot; style=&quot;display:none;&quot;&gt; &lt;h3 class=&quot;slideTitle&quot;&gt;$node.contribution(&quot;title&quot;)&lt;/h3&gt; &lt;div class=&quot;slideImage&quot; width=&quot;30%&quot;&gt;$node.contribution(&quot;image&quot;)&lt;/div&gt; &lt;p class=&quot;slideCaption&quot;&gt;$node.contribution(&quot;caption&quot;)&lt;/p&gt; &lt;/div&gt; &lt;/nexus:component&gt; &lt;p id=&quot;controls&quot;&gt;&lt;a href=&quot;javascript:prevslide()&quot;&gt;Previous&lt;/a&gt; &lt;a href=&quot;javascript:nextslide()&quot;&gt;Next&lt;/a&gt;&lt;/p&gt; &lt;/div&gt; ## Javascript [javascript] var slideNum = 0; var slides = new Array(); slides = document.getElementsByName(&quot;slide&quot;); function nextslide() { if (slideNum &lt; slides.length - 1) { slides[slideNum + 1].style.display = 'block'; slides[slideNum].style.display = 'none'; slideNum++; } else { slides[0].style.display = 'block'; slides[slides.length - 1].style.display = 'none'; slideNum = 0; } } function prevslide() { if (slideNum &gt; 0) { slides[slideNum - 1].style.display = 'block'; slides[slideNum].style.display = 'none'; slideNum--; } else { slides[slides.length - 1].style.display = 'block'; slides[0].style.display = 'none'; slideNum = slides.length - 1; } } </pre> tbeseda tbeseda@gmail.com tag:refactormycode.com,2007:Code603 2008-11-12T02:16:38+00:00 2008-11-12T19:17:03+00:00 [Ruby] A simple factorial program. <p>I'm quite new to Ruby, and I'm currently reading &quot;Why's (Poignant) Guide to Ruby.&quot; It's a great book. <br />Anyway, I want this to do the same thing, WITHOUT recursion, but is there a way to do it without repeating the raise statement at the beginning and using blocks instead of for?</p> <pre>def factorial( n ) if !(n.is_a? Integer) raise ArgumentError, &quot;argument must be a positive integer&quot; elsif n &lt; 0 raise ArgumentError, &quot;argument must be a positive integer&quot; end factorial = 1 for i in 1...n factorial *= i + 1 end factorial end </pre> lordzoner.myopenid.com morgan.michael@me.com tag:refactormycode.com,2007:Code598 2008-11-11T04:09:05+00:00 2008-11-18T04:53:30+00:00 [PHP] remove http from url string <p>Ive made a function simply to remove the http string from a given url string. <br />Kindly see my code below. and is there other way to make it better or make it short? <br />Thanks</p> <pre>&lt;?php /* E.g: $s = 'http://google.com'; echo remove_http($s); output: google.com */ function remove_http($url = '') { if ($url == 'http://' OR $url == 'https://') { return $url; } $matches = substr($url, 0, 7); if ($matches=='http://') { $url = substr($url, 7); } else { $matches = substr($url, 0, 8); if ($matches=='https://') $url = substr($url, 8); } return $url; } </pre> armano.myopenid.com brainwired@gmail.com tag:refactormycode.com,2007:Code601 2008-11-11T21:28:53+00:00 2008-11-12T17:56:53+00:00 [Ruby] Condensing nested conditionals <p>The code below works, but feels a bit overly complex, and looks ugly. Any suggestions on how to condense it?</p> <pre>## app/controllers/properties_controller.rb class PropertiesController &lt; ApplicationController before_filter :authorise_action private def authorise_action case action_name when 'index', 'show', 'map_info_window' # Allowed by anyone. when 'new', 'create', 'edit', 'update', 'destroy' if is_logged_out? deny_access :notice =&gt; Phrases.login_required, :redirect_to =&gt; login_url elsif is_landlord? or is_admin? # Allowed. else deny_access :notice =&gt; Phrases.access_denied, :store_location =&gt; false end else deny_access :notice =&gt; Phrases.not_public_yet, :store_location =&gt; false, :redirect_to =&gt; :back end end end</pre> Nick nick@deadorange.com tag:refactormycode.com,2007:Code600 2008-11-11T17:10:30+00:00 2008-11-11T23:34:42+00:00 [C#] DirectoryInfo.CopyTo <p>Because the .NET Framework does not contain a function which allows you to copy a directory from one location to another, I thought I would write one:</p> <p><a href="http://gatekiller.co.uk/Post/DirectoryInfo.CopyTo" target="_blank">http://gatekiller.co.uk/Post/DirectoryInfo.CopyTo</a></p> <p>Please let me know what you think. Any refactorings to make the code more elegant would be much appreciated.</p> <p>Cheers <br />Stephen</p> <pre>public static class DirectoryInfoExtensions { public static void CopyTo(this String Source, String Destination, Boolean Overwrite) { // Hold directory information var SourceDirectory = new DirectoryInfo(Source); var DestinationDirectory = new DirectoryInfo(Destination); // Throw an error is the source directory does not exist if (SourceDirectory.Exists == false) { throw new DirectoryNotFoundException(); } // Create the destination directory if (DestinationDirectory.Exists == false) { DestinationDirectory.Create(); } // Loop through the files and copy them var SubFiles = SourceDirectory.GetFiles(); for (int i = 0; i &lt; SubFiles.Length; i++) { var NewFile = Path.Combine( DestinationDirectory.FullName, SubFiles[i].Name ); SubFiles[i].CopyTo(NewFile, Overwrite); } // Loop through the directories and call this function var SubDirectories = SourceDirectory.GetDirectories(); for (int i = 0; i &lt; SubDirectories.Length; i++) { var NewDirectory = Path.Combine( DestinationDirectory.FullName, SubDirectories[i].Name ); SubDirectories[i].CopyTo(NewDirectory, Overwrite); } } } var SourceDirectory = new DirectoryInfo(@&quot;C:\Users\&quot;); SourceDirectory.CopyTo(@&quot;C:\Users_Backup\&quot;, true);</pre> GateKiller refactormycode@gatekiller.co.uk tag:refactormycode.com,2007:Code597 2008-11-11T01:14:04+00:00 2008-11-11T05:14:29+00:00 [C#] Strip Html Comments <p>Procedural style code to strip HTML comments. No attempt was made to make this code more OO/patterned base so it could be readable/maintainable. ;)</p> <pre>public static class HtmlHelper { public static string StripHtmlComments(string html) { if (html == null) { throw new ArgumentNullException(&quot;html&quot;); } if (html.IndexOf(&quot;&lt;!&quot;, StringComparison.Ordinal) &lt; 0) { return html; } var cleanedHtml = new char[html.Length]; bool inHtmlComment = false; bool inHtmlTag = false; int cleanCount = 0; for (int i = 0; i &lt; html.Length; i++) { char current = html[i]; if (!inHtmlComment &amp;&amp; !inHtmlTag) { if (current == '&lt;') { if (i + 1 &lt; html.Length) { char nextChar = html[i + 1]; if (nextChar == '!') { inHtmlComment = true; continue; } else { if (IsEnglishLetter(nextChar)) { inHtmlTag = true; } } } } } else if(inHtmlComment) { if (current == '&gt;') { if (inHtmlComment) { inHtmlComment = false; continue; } } continue; } else if (inHtmlTag) { if (current == '&gt;') { inHtmlTag = false; } } cleanedHtml[cleanCount++] = current; } return new String(cleanedHtml, 0, cleanCount); } private static bool IsEnglishLetter(char nextChar) { return ('a' &lt;= nextChar &amp;&amp; nextChar &lt;= 'z') || ('A' &lt;= nextChar &amp;&amp; nextChar &lt;= 'Z'); } } //Unit Tests [TestMethod] public void NullStringReturnsThrowsArgumentNullException() { try { HtmlHelper.StripHtmlComments(null); Assert.Fail(); } catch (ArgumentNullException) { } } [TestMethod] public void EmptyStringReturnsEmpty() { Assert.AreEqual(string.Empty, HtmlHelper.StripHtmlComments(string.Empty)); } [TestMethod] public void StringWithoutCommentReturnsSameString() { string s = &quot;This has &lt;strong&gt;No Comments&lt;/strong&gt;!&quot;; Assert.AreEqual(s, HtmlHelper.StripHtmlComments(s)); } [TestMethod] public void StringWithOnlyCommentReturnsEmptyString() { string s = &quot;&lt;!-- this go bye bye&gt;&quot;; Assert.AreEqual(string.Empty, HtmlHelper.StripHtmlComments(s)); } [TestMethod] public void Html_WithNonDashDashComment_ReturnsEmptyString() { string s = &quot;&lt;! this go bye bye&gt;&quot;; Assert.AreEqual(string.Empty, HtmlHelper.StripHtmlComments(s)); } [TestMethod] public void StringWithTwoConsecutiveCommentsReturnsEmptyString() { string s = &quot;&lt;!-- this go bye bye&gt;&lt;!-- another comment&gt;&quot;; Assert.AreEqual(string.Empty, HtmlHelper.StripHtmlComments(s)); } [TestMethod] public void CommentWithStringBeforeReturnsString() { string s = &quot;Hello&lt;!-- this go bye bye --&gt;&quot;; Assert.AreEqual(&quot;Hello&quot;, HtmlHelper.StripHtmlComments(s)); } [TestMethod] public void CommentWithStringAfterReturnsString() { string s = &quot;&lt;!-- this go bye bye --&gt;World&quot;; Assert.AreEqual(&quot;World&quot;, HtmlHelper.StripHtmlComments(s)); } [TestMethod] public void Html_WithAngleBracketsButNotHtml_NotSripped() { string s = &quot;&lt;$)*(@&amp;$(@*&gt;&quot;; Assert.AreEqual(s, HtmlHelper.StripHtmlComments(s)); } [TestMethod] public void Html_WithCommentInterleavedWithText_RendersText() { string s = &quot;Hello &lt;!-- this go bye bye --&gt; World &lt;!--&gt; This is fun&quot;; Assert.AreEqual(&quot;Hello World This is fun&quot;, HtmlHelper.StripHtmlComments(s)); } [TestMethod] public void Html_WithHtmlTags_DoesNotStripHtml() { string s = &quot;&lt;strong&gt;Hello&lt;/strong&gt;&lt;!this go bye bye&gt;&quot;; Assert.AreEqual(&quot;&lt;strong&gt;Hello&lt;/strong&gt;&quot;, HtmlHelper.StripHtmlComments(s)); } [TestMethod] public void Html_WithCommentInAttribute_DoesNotStripAttributeValue() { string s = &quot;&lt;img alt=\&quot;&lt;!-- This should remain --&gt;\&quot; /&gt;&quot;; Assert.AreEqual(s, HtmlHelper.StripHtmlComments(s)); } [TestMethod] public void Html_WithCommentInSingleQuotedAttribute_DoesNotStripAttributeValue() { string s = &quot;&lt;img alt=\'&lt;!-- This should remain --&gt;\' /&gt;&quot;; Assert.AreEqual(s, HtmlHelper.StripHtmlComments(s)); } [TestMethod] public void Html_WithCommentInNonQuotedAttribute_DoesNotStripAttributeValue() { string s = &quot;&lt;p title=&lt;!--Thisshouldremain--&gt;Test&lt;/p&gt;&quot;; Assert.AreEqual(s, HtmlHelper.StripHtmlComments(s)); } [TestMethod] public void Html_WithCommentBetweenNonTagButLooksLikeTag_DoesStripComment() { string s = @&quot;&lt;ç123 title=&quot;&quot;&lt;!bc def&gt;&quot;&quot;&gt;&quot;; Assert.AreEqual(@&quot;&lt;ç123 title=&quot;&quot;&quot;&quot;&gt;&quot;, HtmlHelper.StripHtmlComments(s)); } </pre> Haacked haacked@gmail.com tag:refactormycode.com,2007:Code599 2008-11-11T12:30:41+00:00 2008-11-18T06:19:17+00:00 [C++] Stream ADODB recordset into a buffer <p>Can we make the code between &quot;START HERE&quot; and &quot;END HERE&quot; faster? The code is iterating thru the rows and columns of an ADODB Recordset, using Microsoft's generated wrapper classes. I'm streaming it into a buffer as a big flattened string. Can we make the flattening go faster? Notice there is already a trick for turning the BSTRs into ANSI strings (I'm only dealing with ASCII chars). Anything else?</p> <pre>// For faster converting of dates to strings char* sLeadingZeroIntegerValues[] = { &quot;00&quot;,&quot;01&quot;,&quot;02&quot;,&quot;03&quot;,&quot;04&quot;,&quot;05&quot;,&quot;06&quot;,&quot;07&quot;,&quot;08&quot;,&quot;09&quot;, &quot;10&quot;,&quot;11&quot;,&quot;12&quot;,&quot;13&quot;,&quot;14&quot;,&quot;15&quot;,&quot;16&quot;,&quot;17&quot;,&quot;18&quot;,&quot;19&quot;, &quot;20&quot;,&quot;21&quot;,&quot;22&quot;,&quot;23&quot;,&quot;24&quot;,&quot;25&quot;,&quot;26&quot;,&quot;27&quot;,&quot;28&quot;,&quot;29&quot;, &quot;30&quot;,&quot;31&quot;,&quot;32&quot;,&quot;33&quot;,&quot;34&quot;,&quot;35&quot;,&quot;36&quot;,&quot;37&quot;,&quot;38&quot;,&quot;39&quot;, &quot;40&quot;,&quot;41&quot;,&quot;42&quot;,&quot;43&quot;,&quot;44&quot;,&quot;45&quot;,&quot;46&quot;,&quot;47&quot;,&quot;48&quot;,&quot;49&quot;, &quot;50&quot;,&quot;51&quot;,&quot;52&quot;,&quot;53&quot;,&quot;54&quot;,&quot;55&quot;,&quot;56&quot;,&quot;57&quot;,&quot;58&quot;,&quot;59&quot;}; // For faster converting of dates to strings char date_buf[20] = &quot;XXXX-XX-XX XX:XX:XX&quot;; // Just some non printable ascii chars, for delimiters const string DataTable::SECTION_DELIMITER = &quot;\1&quot;; const string DataTable::ROW_DELIMITER = &quot;\2&quot;; const string DataTable::COL_DELIMITER = &quot;\3&quot;; const string DataTable::TABLE_DELIMITER = &quot;\4&quot;; const string DataTable::NAME_VALUE_DELIMITER = &quot;\5&quot;; void CDbInterface::LoadRecordsetIntoStreamAsBigString( _RecordsetPtr&amp; pRs, ostringstream&amp; ostrm) { DataTable::TypeList types; if (!pRs-&gt;EndOfFile) { int nColumns = pRs-&gt;Fields-&gt;GetCount(); // Column names for (long i = 0L; i &lt; nColumns; i++) { string name = (const char*) (_bstr_t) pRs-&gt;Fields-&gt;GetItem(i)-&gt;Name; if (i != 0) ostrm &lt;&lt; DataTable::COL_DELIMITER; ostrm &lt;&lt; name.c_str(); } ostrm &lt;&lt; DataTable::SECTION_DELIMITER; // Column types for (long i = 0L; i &lt; nColumns; i++) { ADODB::DataTypeEnum dbType = pRs-&gt;Fields-&gt;GetItem(i)-&gt;GetType(); if (i != 0) ostrm &lt;&lt; DataTable::COL_DELIMITER; DataTableDataType type; if (dbType == ADODB::DataTypeEnum::adVarWChar || dbType == ADODB::DataTypeEnum::adWChar) { type = DataTableDataType::String; } else if (dbType == ADODB::DataTypeEnum::adInteger) { type = DataTableDataType::Integer; } else if (dbType == ADODB::DataTypeEnum::adUnsignedTinyInt) { type = DataTableDataType::Bool; } else if (dbType == ADODB::DataTypeEnum::adDate) { type = DataTableDataType::Date; } ostrm &lt;&lt; type; types.push_back(type); } ostrm &lt;&lt; DataTable::SECTION_DELIMITER; // Load the rows and columns int nRow = 0; ADODB::FieldsPtr pFields = pRs-&gt;Fields; char buf[80]; ::SYSTEMTIME sysTime; _variant_t var; char* pBstr; long nBstrLen; DWORD time1 = ::GetTickCount(); while(!pRs-&gt;EndOfFile) { if (nRow != 0) ostrm &lt;&lt; DataTable::ROW_DELIMITER; for (long i = 0L; i &lt; nColumns; i++) { // For every column in every row... &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; START HERE // Can we make this even faster? if (i != 0) ostrm &lt;&lt; DataTable::COL_DELIMITER; var = pFields-&gt;GetItem(i)-&gt;GetValue(); if (V_VT(&amp;var) == VT_BSTR) { // Copy every other byte of the bstr into the stream. // That's doing an ansi conversion w/o allocating unnecessary memory pBstr = (char*) var.bstrVal; nBstrLen = *(pBstr-4); for (int i = 0; i &lt; nBstrLen; i+=2) { ostrm &lt;&lt; (char) pBstr[i]; } } else if (V_VT(&amp;var) == VT_I4 || V_VT(&amp;var) == VT_UI1 || V_VT(&amp;var) == VT_I2 || V_VT(&amp;var) == VT_BOOL) { ostrm &lt;&lt; itoa(((int)var),buf,10); } else if (V_VT(&amp;var) == VT_DATE) { ::VariantTimeToSystemTime(var,&amp;sysTime); memcpy(date_buf,itoa(sysTime.wYear,buf,10),4); memcpy(date_buf+5,sLeadingZeroIntegerValues[sysTime.wMonth],2); memcpy(date_buf+8,sLeadingZeroIntegerValues[sysTime.wDay],2); memcpy(date_buf+11,sLeadingZeroIntegerValues[sysTime.wHour],2); memcpy(date_buf+14,sLeadingZeroIntegerValues[sysTime.wMinute],2); memcpy(date_buf+17,sLeadingZeroIntegerValues[sysTime.wSecond],2); ostrm &lt;&lt; date_buf; } // End of the part we're trying to make faster... &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; END HERE else if (V_VT(&amp;var) == VT_EMPTY || V_VT(&amp;var) == VT_NULL) { if (types[i] == DataTableDataType::String) { ostrm &lt;&lt; &quot;&quot;; } else if (types[i] == DataTableDataType::Integer) { ostrm &lt;&lt; DataTableNullInteger; } else if (types[i] == DataTableDataType::Bool) { ostrm &lt;&lt; &quot;0&quot;; } else if (types[i] == DataTableDataType::Date) { ostrm &lt;&lt; &quot;&quot;; } } } pRs-&gt;MoveNext(); nRow++; } } ostrm &lt;&lt; DataTable::FINAL_DELIMITER; } </pre> ctrager.blogspot.com ctrager@yahoo.com tag:refactormycode.com,2007:Code602 2008-11-11T22:53:23+00:00 2008-11-12T00:33:11+00:00 [Haskell] Cat90 <p>Rotates text given in stdin 90 degrees. </p> <pre>main = do s &lt;- getContents putStr (unlines (reverse (rotate (lines s)))) rotate ls = if (maxLength ls) &gt; 0 then (column ls) : (rotate (dropColumn ls)) else [] maxLength ls = (maximum (map length ls)) column ls = map wholeHead ls dropColumn ls = map (drop 1) ls wholeHead cs = if (null cs) then ' ' else (head cs) </pre> jarkko jarkko.sakkinen@iki.fi tag:refactormycode.com,2007:Code605 2008-11-15T08:51:14+00:00 2008-11-15T08:51:14+00:00 [Ruby] repeated code in rspec model test <p>how do i clean up this repeated code (Stock.create &amp; Stock.new) in my rspec test</p> <pre>describe Stock do it &quot;should be valid when new&quot; do stock = Stock.new(:symbol =&gt; 'GOOG') stock.should be_valid end it &quot;should be invalid when symbol is empty&quot; do stock = Stock.new(:symbol =&gt; '') stock.should_not be_valid end it &quot;should have symbol in all uppercase&quot; do stock = Stock.create(:symbol =&gt; 'GOOG') stock.symbol.should equal(stock.symbol.upcase) stock = Stock.create(:symbol =&gt; 'goog') stock.symbol.should equal(stock.symbol.upcase) end end</pre> scottmotte.myopenid.com scott@scottmotte.com tag:refactormycode.com,2007:Code578 2008-11-05T09:30:03+00:00 2008-11-13T21:13:57+00:00 [Ruby] Re-use code for new and create actions <p>Hello,</p> <p>I have a 'people' controller to control user accounts. I want to share as much code as possible between the 'new' and 'edit' actions. I've tried to DRY it up as much as I can but in doing that I fear I might have made it more complicated. In the controller code below, the two methods 'new' and 'edit' both display a template 'user_form.html.erb', where title and form action are changed accordingly. The 'new' method submits to 'create', and the 'edit' method submits to 'update'. Errors are redisplayed via saving the user object with errors in the hash.</p> <p>I would be very grateful for and refactoring suggestions anyone might have!</p> <p>Many thanks, <br />Dave</p> <pre>## Controller [ruby_on_rails] class PeopleController &lt; ApplicationController before_filter :clean_attributes, :only =&gt; [:create, :update] # show the form to create a new user def new if flash[:user_with_errors] @user = flash[:user_with_errors] else @user = User.new end show_user_form('add user', 'create') end # show the form to edit an existing user def edit if flash[:user_with_errors] @user = flash[:user_with_errors] else @user = get_user(params[:id]) end if @user show_user_form('edit user', 'update') else flash[:error] = 'user not found' redirect_to(root_path) end end # this is the target of the 'new' action def create if request.post? user = User.new save_user(user) redirect_to(:action =&gt; 'new') end end # this is the target of the 'edit' action def update if request.post? if user = get_user(params[:id]) save_user(user) redirect_to(:action =&gt; 'edit', :id =&gt; params[:id]) else flash[:error] = 'user not found' redirect_to(root_path) end end end private # before filter to remove unwanted whitespace def clean_attributes begin [:forename, :surname, :email].each do |attribute| params[:user][attribute].squish! if params[:user][attribute] end rescue end end # show the user form (for new or edit actions) def show_user_form(title, action) @form_title = title @action = action render :action =&gt; 'user_form' end # save submitted user details def save_user(user) user.attributes = params[:user] # set administrator only attributes if current_user_is_admin? user.login = params[:user][:login] end if user.save flash[:success] = 'user saved successfully' else # blank out password for redisplay user.password = nil user.password_confirmation = nil flash[:error] = 'save failed' flash[:user_with_errors] = user end end # get the user object def get_user(id) begin user = User.find(id) rescue ActiveRecord::RecordNotFound logger.error(&quot;Attempt to access user id that doesn't exist (id: #{id})&quot;) end user end end</pre> Dave pastelvasco@gmail.com tag:refactormycode.com,2007:Code579 2008-11-05T12:14:53+00:00 2008-11-06T11:31:11+00:00 [C#] Sorting by dependencies <p>This code sorts a collection by the dependencies of its contents.</p> <p>It is passed a dictionary mapping a key to a set of keys - the dependencies of that key.</p> <p>I knocked up this code quickly and realised as I wrote it that it was likely to blow the stack on a large data set due to its recursive nature. I'd try to make it tail recursive, but the C# compiler doesn't take advantage of that yet, so it should probably be iterative. I'd be interested to see any improved solution.</p> <p></p> <pre>public static class DependencySorter&lt;T&gt; { public static IEnumerable&lt;T&gt; Sort(Dictionary&lt;T, IEnumerable&lt;T&gt;&gt; dependencies) { var visited = new Dictionary&lt;T, bool&gt;(); foreach (var key in dependencies.Keys) { visited[key] = false; } foreach (var key in dependencies.Keys) { foreach (var ordered in Search(key, dependencies, visited)) yield return ordered; } } private static IEnumerable&lt;T&gt; Search ( T key, IDictionary&lt;T, IEnumerable&lt;T&gt;&gt; dependencies, IDictionary&lt;T, bool&gt; visited ) { if (!visited[key]) { visited[key] = true; foreach (T value in dependencies[key]) { foreach (var ordered in Search(value, dependencies, visited)) { yield return ordered; } } yield return key; } } }</pre> rikkus rik@rikkus.info tag:refactormycode.com,2007:Code581 2008-11-06T22:29:37+00:00 2008-11-07T03:17:55+00:00 [Ruby] Pretty output of permission bits for a file <p>This snippet is designed to match the permission bits output of an ls -l command for a shell replacement written in Ruby.</p> <pre># [user@host ~]$ ls -l blah # -rwxr--r-- 1 user users 0 2008-11-06 15:20 foo def convert(file) output = [&quot;&quot;] File.stat(file).mode.to_s(8).slice(-3..-1).split('').each do |m| case m.to_i when 1 then output &lt;&lt; [&quot;-&quot;,&quot;-&quot;,&quot;x&quot;] when 2 then output &lt;&lt; [&quot;-&quot;,&quot;w&quot;,&quot;-&quot;] when 3 then output &lt;&lt; [&quot;-&quot;,&quot;w&quot;,&quot;x&quot;] when 4 then output &lt;&lt; [&quot;r&quot;,&quot;-&quot;,&quot;-&quot;] when 5 then output &lt;&lt; [&quot;r&quot;,&quot;-&quot;,&quot;x&quot;] when 6 then output &lt;&lt; [&quot;r&quot;,&quot;w&quot;,&quot;-&quot;] when 7 then output &lt;&lt; [&quot;r&quot;,&quot;w&quot;,&quot;x&quot;] end end output.flatten! if File.directory?(file) then output[0] = &quot;d&quot;; end if File.file?(file) then output[0] = &quot;-&quot;; end if File.symlink?(file) then output[0] = &quot;l&quot;; end if File.setuid?(file) then output[3] = &quot;s&quot;; end if File.setgid?(file) then output[6] = &quot;s&quot;; end if File.sticky?(file) if output[3] &amp;&amp; output[6] == &quot;-&quot; output[9] = &quot;T&quot; else output[9] = &quot;t&quot; end end puts output.flatten.to_s end convert('poop')</pre> ScriptFu scriptfu@gmail.com tag:refactormycode.com,2007:Code577 2008-11-05T07:13:41+00:00 2008-11-05T16:12:09+00:00 [Ruby] xml rss feed <p>Looking for a better way to define the xml.description node...which needs html embedded as CDATA, but I think it is ugly concating this way with &quot;+&quot;.</p> <p>Generates a description and a link at the bottom.</p> <p></p> <pre> for directory in @directories xml.item do xml.title &quot;#{directory.name} (PR #{directory.pagerank})&quot; //cleaner proc here? xml.description { xml.cdata! simple_format(directory.description) + simple_format(link_to directory.software.name, software_url(directory.software)) } xml.pubDate directory.created_at.to_s(:rfc822) xml.link directory_url(directory) xml.guid directory_url(directory) end end </pre> chovy.myopenid.com spam@chovy.com tag:refactormycode.com,2007:Code580 2008-11-06T07:01:36+00:00 2008-11-07T00:52:45+00:00 [Ruby] View refactoring <p>In following code ul getting repeat after showing 3 feed items in the li.</p> <pre>## List.rhtml [html_rails] &lt;ul&gt; &lt;% if @feeds[16..19] %&gt; &lt;% @feeds[16..19].each do |feed| -%&gt; &lt;li style=&quot;width:170px&quot;&gt; &lt;input name=&quot;source[&lt;%=feed.id %&gt;]&quot; type=&quot;checkbox&quot; value=&quot;&lt;%=feed.id %&gt;&quot; &quot;checked&quot; /&gt; &lt;%=feed.name %&gt; &lt;/li&gt; &lt;% end -%&gt; &lt;% end -%&gt; &lt;/ul&gt; &lt;ul&gt; &lt;% if @feeds[20..23] %&gt; &lt;% @feeds[20..23].each do |feed| -%&gt; &lt;li style=&quot;width:170px&quot;&gt; &lt;input name=&quot;source[&lt;%=feed.id %&gt;]&quot; type=&quot;checkbox&quot; value=&quot;&lt;%=feed.id %&gt;&quot; &quot;checked&quot; /&gt; &lt;%=feed.name %&gt; &lt;/li&gt; &lt;% end -%&gt; &lt;% end -%&gt; &lt;/ul&gt;</pre> DG deepak.gole8@gmail.com tag:refactormycode.com,2007:Code582 2008-11-07T04:41:48+00:00 2008-11-07T05:48:19+00:00 [Ruby] Retrieve class name only <p>Im sure there is a better way to do below:</p> <pre> # Suppose I have San::Languages::JavaScript as the 'lang' local var below # I want a string of 'JavaScript' from this example p lang.class.to_s.split('::')[2] # =&gt; JavaScript</pre> Tj Holowaychuk tj@vision-media.ca tag:refactormycode.com,2007:Code565 2008-10-27T22:00:49+00:00 2008-10-28T14:52:14+00:00 [Ruby] route spec'ing <p>I'm trying to extract a pattern from rails routes rspec'ing into a helper. </p> <p>The helper works great and makes it nice to read/write routing specs (only for :get right now) such as shown below. <br />But the &quot;interpreted_route_path&quot; part really sucks. Any better ways?</p> <pre>## This part is ugly! &gt;&gt; path =&gt; &quot;/:foo/bar/:baz&quot; &gt;&gt; params =&gt; {:foo=&gt;&quot;FOO&quot;, :baz=&gt;&quot;BAZ&quot;} &gt;&gt; path.split(&quot;/&quot;).map { |v| (params[v[1,v.length].to_sym] if !v.empty? &amp;&amp; v[0] == ':'[0]) || v }.join('/') =&gt; &quot;/FOO/bar/BAZ&quot; &gt;&gt; ## in spec/spec_helper.rb def interpreted_route_path(path, params) path.split('/').map { |v| (params[v[1,v.length].to_sym] if !v.empty? &amp;&amp; v[0] == ':'[0]) || v }.join('/') end # To check map.root: # use as: check_routing_for(:route_name =&gt; 'root', :route_path =&gt; '/', :controller =&gt; 'foo', :action =&gt; 'bar') def check_routing_for(options) route_name = options.delete(:route_name) route_path = options.delete(:route_path) controller, action = options.delete(:controller), options.delete(:action) class_eval do describe &quot;map.#{route_name}&quot; do before do @route_hash = { :controller =&gt; controller, :action =&gt; action }.merge(options) end it &quot;Routes to #{route_path}&quot; do route_for(@route_hash).should == interpreted_route_path(route_path, options) end it &quot;Recognizes #{@route_hash.inspect}&quot; do params_from(:get, interpreted_route_path(route_path, options)).should == @route_hash end end end end </pre> hellekin hellekin@gmail.com tag:refactormycode.com,2007:Code575 2008-10-31T20:52:05+00:00 2008-11-03T05:46:13+00:00 [Ruby] DRY up a controller action <p>My Neighbourhood &quot;map_filter&quot; action finds Property objects that match search criteria submitted by the user. It works, but I reckon it could be a bit shorter. Any suggestions?</p> <pre># GET /neighbourhoods/map_filter def map_filter @map_filter_errors = nil # Stores errors related to a filter request. @properties = nil # Stores the properties that match the filter constraints. # Extract the &quot;accessible&quot; attributes from the params. property_filter_attributes = AccessibleModelAttributes.extract PropertyFilter, params filtered_properties = PropertyFilter.new(property_filter_attributes).properties # If properties were returned. if filtered_properties[:properties] @properties = filtered_properties[:properties] @property_data = render_to_string( :partial =&gt; 'properties/map_properties_table', :locals =&gt; {:properties =&gt; @properties} ) @number_of_properties_found_sentence = render_to_string :partial =&gt; 'properties/number_of_properties_found' else @map_filter_errors = filtered_properties[:errors] end end </pre> Nick nick@deadorange.com