tag:refactormycode.com,2007:refactoringsrecentallRecent refactoringsThu Nov 27 17:18:05 +0000 2008tag:refactormycode.com,2007:Refactor889512008-11-27T17:18:05+00:00[Ruby] On Displaying numbers to words.<p>Done ...cheers</p>
<pre>require 'rubygems'
require 'linguistics'
class Fixnum
def to_words
word_translation_range = 1..1_000_000
if word_translation_range.include?(self)
Linguistics::EN.numwords(self)
else
to_s
end
end
end
ra = 1..1_000_000
ra.each {|v| puts v.to_words}</pre>ytse.myopenid.comjaredtse@hotmail.comtag:refactormycode.com,2007:Refactor889412008-11-27T17:13:57+00:00[Ruby] On Displaying numbers to words.<p>You want to print numbers from 1 to 1,000,000? Just do something like this:</p>
<pre>1.upto(1_000_000) { |number| puts Linguistics::EN.numwords(number) }</pre>Adamskidooer+p@gmail.comtag:refactormycode.com,2007:Refactor889372008-11-27T17:10:29+00:00[Ruby] On Displaying numbers to words.<p>Yes this is prety much what I want to do. But shouldnt the method go inside the Range class ? And also would you mind demonstrate on how to do the iteration from 1 - 1000000</p>
<p>Thanx</p>
<pre>require 'rubygems'
require 'linguistics'
class Fixnum
def to_words
word_translation_range = 1..1_000_000
if word_translation_range.include?(self)
Linguistics::EN.numwords(self)
else
to_s
end
end
end</pre>ytse.myopenid.comjaredtse@hotmail.comtag:refactormycode.com,2007:Refactor888112008-11-27T15:42:13+00:00[Ruby] On Displaying numbers to words.
<pre># http://www.deveiate.org/projects/Linguistics/
require 'linguistics'
class Fixnum
def to_words
word_translation_range = 1..1_000_000
if word_translation_range.include?(self)
Linguistics::EN.numwords(self)
else
to_s
end
end
end</pre>Adamskidooer+p@gmail.comtag:refactormycode.com,2007:Refactor884792008-11-27T10:54:44+00:00[Ruby] On Ruby simple loop
<pre>name = 'nicholas'
(1..10).each { |i| puts i,name }
output
1
nicholas
2
nicholas
3
nicholas
4
nicholas
5
nicholas
6
nicholas
7
nicholas
8
nicholas
9
nicholas
10
nicholas
</pre>Nicholasnicholas.domnic.i@gmailc.omtag:refactormycode.com,2007:Refactor881652008-11-27T02:15:57+00:00[C#] On Filterting a List<> with a Regular Expression<p>Some advices : The way you are using the regular expression is equivalent to using the regular way to do a string comparaison. Also, I would suggest also to filter documents in your document layer by adding the name and author to your GetDocuments(username) method, I would be more efficient as your method can retrieve 500 documents from the database to finally display one or two results for exemple.</p>
<pre>List<Document> aDocuments = documentLayer.GetDocuments(username);
string docName = (string)Session["DocumentName"];
string docAuthor = (string)Session["DocumentAuthor"];
bool docNameEmpty = string.IsNullOrEmpty(docName);
bool docAuthorEmpty = string.IsNullOrEmpty(docAuthor);
if (docNameEmpty && docAuthorEmpty)
gridDocuments.DataSource = aDocuments;
else
{
List<Document> aDocumentsFilter = new List<Document>();
aDocuments.ForEach(oDoc =>
{
if ((!docNameEmpty && !docAuthorEmpty && docName == oDoc.Name && docAuthor == oDoc.Author)
|| (docNameEmpty && docAuthor == oDoc.Author)
|| (docAuthorEmpty && docName == oDoc.Name))
aDocumentsFilter.Add(oDoc);
});
gridDocuments.DataSource = aDocumentsFilter;
}
gridDocuments.DataBind();</pre>Moonshieldmonsterinthepit@hotmail.comtag:refactormycode.com,2007:Refactor880622008-11-26T23:24:45+00:00[Java] On Factoring Integers<p>The two functions, nextFactor and has nextFactor shared the common pattern I refactored into the findNextFactor() private method.
<br />You have obfuscated the while conditions a bit but I'm sure you can see that the loop laying after the two sligthy different syntax are the same.</p>
<p>Once you get this, the two method get straight simple.
<br />I added a runtime exception to cover the case of a call of nextFactor method without a previous check of hasNextFactor</p>
<p>I hope you can get through my english to the explanation :)</p>
<pre>## Quick Fix [Java]
// line 44 while condition have to change to or you don't apply the last division (but return the last factor everytime) => number don't become 1 => hasnextfactor misbehave.
while (factor <= number)
## Refactoring [Java]
public class factorGenerator
{
private int number;
private int factor;
/**
* Creates a FactorGenerator object used to determine the factor of an input value.
* @param aNum is the input value
**/
public factorGenerator(int aNum)
{
number = aNum;
factor = 2;
}
/**
* Find the next factor of a value.
* @return factor the next factor
**/
private int findNextFactor()
{
while((factor < number) && ((number%factor)!=0)) factor++;
return factor;
}
/**
* Apply the next factor of a value.
* @return factor the next factor
**/
public int nextFactor() throws RuntimeException
{
int result = findNextFactor();
if (result <= number) {
number/= result;
return result;
} else
throw new RuntimeException();
}
/**
Determine whether or not there are more factors.
@return true there are more factors
*/
public boolean hasMoreFactors()
{
return (findNextFactor()<=number);
}
}</pre>Einekimagisano@cs.unibo.ittag:refactormycode.com,2007:Refactor879892008-11-26T21:23:04+00:00[C#] On Filterting a List<> with a Regular Expression<p>Might as well make this easier on yourself with LINQ.
<br />Is there a reason you are using a regex? I threw the below together in LINQPad and it works...</p>
<pre>//I just need some values to work with.
var names = new[] { "Tom", "Dick", "Harry", "Hurry","Mary", "Jay" }.AsQueryable();
IEnumerable<Document> documents =
from n in names
select new Document
{
author = n,
name = n.Replace ("a", "").Replace ("e", "").Replace ("i", "").Replace ("o", "").Replace ("u", "")
};
documents.Dump();
System.Random r = new Random();
string documentName = r.Next(2) == 1 ? "Hrry": "";
string documentAuthor = r.Next(2) == 1 ? "Harry":"";
"Name".Dump(documentName);
"Author".Dump(documentAuthor);
//commented out this if else just for demo purposes. On the other hand
//if ((string.IsNullOrEmpty(documentName)) && (string.IsNullOrEmpty(documentAuthor)))
// {
//documents.DataSource = documents;
//documents.DataBind();
// }
// else
//{
//this should be easier to read and more efficient: less accessing of properties, fewer lines,
//fewer function calls, takes advantage of fewer comparisons due to &&
IEnumerable filteredDocuments =
from d in documents
where d.name == (string.IsNullOrEmpty(documentName) ? d.name : documentName)
&& d.author == (string.IsNullOrEmpty(documentAuthor) ? d.author : documentAuthor)
select d;
filteredDocuments.Dump();
//}
}
class Document
{
public string author;
public string name;
</pre>MattKopenid@morelightmorelight.comtag:refactormycode.com,2007:Refactor879242008-11-26T19:45:27+00:00[Ruby] On Doing a 'blank?' in named_scope<p>maybe work.</p>
<pre>named_scope :with_description, :conditions => "description IS NOT NULL and description NOT REGEXP '[[:blank:]]'</pre>kivaniokivanio@gmail.comtag:refactormycode.com,2007:Refactor849872008-11-25T08:18:52+00:00[Java] On Efficiently load a text file into a sorted String Array<p>One disadvantage with your approach is that since Sets do not allow duplicate elements, duplicate lines will be lost.</p>
<p>Alternatively, you could just add them to some kind of List (ArrayList or LinkedList will do) and then sort it.</p>
<pre>public static String[] loadFile(final String f) {
String thisLine;
final List<String> s = new ArrayList<String>();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(f));
while ((thisLine = br.readLine()) != null)
s.add(thisLine.trim());
} catch (IOException ioe) {
System.err.println("Error reading file " + f);
throw new RuntimeException(ioe);
} finally {
if(br!=null) try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Collections.sort(s);
return s.toArray(new String[s.size()]);
}</pre>footag:refactormycode.com,2007:Refactor845352008-11-24T23:32:27+00:00[C#] On Sanitize HTML<p>Here is an actual parser (written in PHP) that only accepts white listed input, <a href="http://refactormycode.com/codes/557-html-filter" target="_blank">http://refactormycode.com/codes/557-html-filter</a></p>
<pre></pre>gromgrom@zeminvaders.nettag:refactormycode.com,2007:Refactor838632008-11-24T10:54:17+00:00[Ruby] On Cheap ruby block templating<p>Nice Adam. I'm ended up using the equivalent in Merb.</p>
<pre>def row(&block)
tag :div, capture(&block), :class => 'row'
end</pre>Alistairalistairholt@gmail.comtag:refactormycode.com,2007:Refactor834302008-11-24T04:38:34+00:00[Ruby] On Cheap ruby block templating
<pre>def field_row(&block)
content_tag(:div, :class => :field_row, &block)
end</pre>Adamskidooer+p@gmail.comtag:refactormycode.com,2007:Refactor825602008-11-23T15:11:36+00:00[PHP] On Eval encoded file decoder<p>can anyone help with a procedure of decrypting this:</p>
<p></p>
<pre><?php eval(strtr(strrev(' encoded text here ')); ?></pre>mrlamemrlame@mail.rutag:refactormycode.com,2007:Refactor811692008-11-22T17:38:28+00:00[Ruby] On Cheap ruby block templating<p>I believe it is the same now in Rails 2.2. I am unsure how it was different before 2.2.</p>
<pre></pre>Jeff Bergjeff@ministrycentered.comtag:refactormycode.com,2007:Refactor811642008-11-22T17:34:22+00:00[Ruby] On Cheap ruby block templating<p>That's cool thanks. I was previously using yield. What are the advantages/disadvantages of using yield over capture(&block)?</p>
<pre></pre>Alistairalistairholt@gmail.comtag:refactormycode.com,2007:Refactor811602008-11-22T17:29:16+00:00[Ruby] On Cheap ruby block templating<p>That is the best way unless you are on Rails 2.2 (Which just got released). Check out this blog post: <a href="http://www.pathf.com/blogs/2008/10/rails-22-for-me-and-for-you/" target="_blank">http://www.pathf.com/blogs/2008/10/rails-22-for-me-and-for-you/</a></p>
<pre> def label_block(caption)
concat("<label>")
concat("<span>#{caption}</span>")
yield
concat("</label>")
end</pre>Jeff Bergjeff@ministrycentered.comtag:refactormycode.com,2007:Refactor810502008-11-22T15:48:37+00:00[Ruby] On Bindings on caller<p>Cool thanks! not overly practical I suppose but still cool</p>
<pre></pre>Tj Holowaychuktj@vision-media.catag:refactormycode.com,2007:Refactor807752008-11-22T11:12:26+00:00[Ruby] On Bindings on caller
<pre>def capitalize_args(bind)
eval("local_variables", bind).each do |var|
var = eval(var, bind)
var.capitalize! if var.is_a?(String)
var.map! { |arg| arg.is_a?(String) ? arg.capitalize : arg } if var.is_a?(Array)
end
end
def test(a, b)
capitalize_args(binding)
puts a
puts b
end
def test2(*args)
capitalize_args(binding)
puts args
end
test "hello", "world"
# => Hello
# => World
test2 "hello", 1, "world"
# => Hello
# => 1
# => World</pre>Simo Niemeläsimo.niemela@gmail.comtag:refactormycode.com,2007:Refactor795202008-11-21T15:33:06+00:00[Perl] On Apache log file sorting<p>Modified the capitalization of subroutines.</p>
<pre>#!/usr/bin/perl -w
use strict;
use Moose;
use Time::localtime;
use File::Find;
use File::Copy;
my $vmlogpath = $ARGV[0] or die "y'all didn't enter no arguments";
find(\&sort_file, $ARGV[0]);
sub sort_file {
if ( -f ) {
my $filename=$_;
$filename =~ /([0-9]{5,})/;
my $unixtime = $1 or print "Not a log file: $filename\n";
my $dirname=make_dir_name($unixtime);
unless(-e "${ARGV[0]}/${dirname}/${filename}") {
my $path=make_dir($ARGV[0], $dirname);
move_file($filename, $path);
print "$filename is the file name.\n";
print "$unixtime is the extracted unixtime.\n";
print "$dirname is the directory name.\n";
print "$path is the path.\n";
}
}
else { print "Not a plain file: $_\n"; }
}
sub move_file {
my $tehfile=$_[0];
my $tehdir=$_[1];
move($tehfile, $tehdir) or die "Could not move files!\n$!";
return 1;
}
sub make_dir {
my $currentdir=$_[0];
my $newdir=$_[1];
my $newpath="${currentdir}/${newdir}";
unless (-d $newpath) {
mkdir($newpath,755) or die "mkdir failed for $newpath: $!\n"
}
return $newpath;
}
sub make_dir_name {
my $tehunix=$_[0];
my $day_of_year=localtime(int($tehunix))->yday;
my $week_of_year=int($day_of_year / 7) + 1;
my $year=1900+localtime(int($tehunix))->year;
return $year . $week_of_year;
}</pre>hourbackhourback@gmail.comtag:refactormycode.com,2007:Refactor793242008-11-21T12:17:13+00:00[Ruby] On Shortest regular expression for matching a subdomain.<p>This ought to do it.</p>
<pre>/^(?!www\.)(?:\w+\.)*example\.com$/</pre>Daniel Schierbeckdaniel.schierbeck@gmail.comtag:refactormycode.com,2007:Refactor792462008-11-21T07:53:13+00:00[Ruby] On Shortest regular expression for matching a subdomain.<p>I would maybe consider extending URI similarly to below. 'example' is technically a subdomain of the TLD 'com' so I would maybe allow that to have a param like below, just as well 'www' is still a valid subdomain of course so maybe that logic could belong in a different method</p>
<pre>require 'uri'
module URI
class HTTP
def domains
host.split '.'
end
def tld
domains.last
end
def subdomain(level = 1)
domains[-(level + 1)] unless domains.length < level + 1
end
end
end
p URI.parse("http://something.example.com").domains
p URI.parse("http://something.example.com").tld
p URI.parse("http://something.example.com").subdomain
p URI.parse("http://something.example.com").subdomain 2
p URI.parse("http://example.com").subdomain
p URI.parse("http://example.com").subdomain 2
Outputs :
["something", "example", "com"]
"com"
"example"
"something"
"example"
nil
</pre>Tj Holowaychuktj@vision-media.catag:refactormycode.com,2007:Refactor792452008-11-21T07:32:40+00:00[C++] On Counting Sort <p>I did not understand why the code is categorized as C++ code. It is in C except the I/O functions. </p>
<pre></pre>pardus1tag:refactormycode.com,2007:Refactor792402008-11-21T06:12:08+00:00[Ruby] On Similar virtual attributes and their getters/setter
<pre>module NameAssociation
def self.extended(object)
object.instance_eval(<<-EOS, '(__NAME_ASSOCIATION__)', 1)
def #{object.proxy_owner.to_s.downcase}_name=(name)
find_or_create_by_name(name)
end
EOS
end
end
class Publication < ActiveRecord::Base
has_one :publication, :extend => NameAssociation
has_one :organization, :extend => NameAssociation
delegate :name, :name=, :to => :publication, :prefix => true
delegate :name, :name=, :to => :organization, :prefix => true
end</pre>Adamskidooer+p@gmail.comtag:refactormycode.com,2007:Refactor792382008-11-21T05:55:58+00:00[Ruby] On Similar virtual attributes and their getters/setter<p>removed string based class_eval in favor of define_method.. shorter code :)</p>
<pre>module ChildAccessor
def attr_child_accessor(obj,attr_name)
child_name = obj.name.downcase
method_name = "#{child_name}_#{attr_name.to_s}"
class_eval do
define_method method_name do
self.send(child_name).send(attr_name)
end
define_method "#{method_name}=" do |name|
self.send("#{child_name}=", obj.send("find_or_create_by_#{attr_name}", name.strip)) unless name.blank?
end
end
end
end
ActiveRecord::Base.extend ChildAccessor
class Publication < ActiveRecord::Base
attr_child_accessor Publisher, :name
attr_child_accessor Orginization, :name
end
</pre>Josh Njoshnuss@gmail.com