tag:refactormycode.com,2007:codesrecentRecent codesFri Dec 05 11:46:21 +0000 2008tag:refactormycode.com,2007:Code6532008-12-05T11:42:04+00:002008-12-05T11:46:21+00:00[Ruby] Photograhy methods<p>Any comments, corrections, refactorings or suggestions would be fantastic, thanks.
<br />Hopefully we might have some photography nuts out there too :)</p>
<pre># camera related
def frame_diagonal(frame_horizontal, frame_vertical)
@frame_diagonal = Math.sqrt((frame_horizontal**2) + (frame_vertical**2))
end
def focal_length_multiplier(frame_diagonal_1, frame_diagonal_2)
@focal_length_multiplier = frame_diagonal_1 / frame_diagonal_2
end
def circle_of_confusion(frame_diagonal)
@circle_of_confusion = frame_diagonal / 1730
end
# lens related
def hyperfocal_distance(focal_length, f_number, circle_of_confusion)
@hyperfocal_distance = ((focal_length**2) / (f_number * circle_of_confusion)) + focal_length
end
def near_distance(focus_distance, hyperfocal_distance, focal_length)
@near_distance = (focus_distance * (hyperfocal_distance - focal_length)) / (hyperfocal_distance + focus_distance - 2 * focal_length)
end
def far_distance(focus_distance, hyperfocal_distance, focal_length)
@far_distance = (focus_distance * (hyperfocal_distance - focal_length)) / (hyperfocal_distance - focus_distance)
end
def total_distance(near_distance, far_distance)
@total_distance = far_distance - near_distance
end
def magnification(focal_length, focus_distance)
@magnification = focal_length/(focus_distance - focal_length)
end
def fov_rectilinear_horizontal(frame_horizontal, focal_length, magnification)
@fov_rectilinear = 2 * Math.arctan(frame_horizontal/(focal_length * 2 * (magnification+1)))
end
def fov_rectilinear_vertical(frame_vertical, focal_length, magnification)
@fov_rectilinear = 2 * Math.arctan(frame_vertical/(focal_length * 2 * (magnification+1)))
end
def fov_rectilinear_diagonal(frame_diagonal, focal_length, magnification)
@fov_rectilinear = 2 * Math.arctan(frame_diagonal/(focal_length * 2 * (magnification+1)))
end
def f_number_to_aperture_diameter(focal_length, f_number)
@aperture_diameter = focal_length / f_number
end
# exposure related
def exposure_value(f_number, shutter_speed)
@exposure_value = Math.logn(2, (f_number**2 / shutter_speed))
end
# math related
def Math.logn(x, n)
Math.log(x) / Math.log(n)
end
def Math.arctan(x)
Math.atan2(x, 1.0)
end</pre>sfusion.myopenid.comsfusion@gmail.comtag:refactormycode.com,2007:Code6522008-12-05T11:36:17+00:002008-12-05T11:36:17+00:00[Java] Read/download images from an URL<p>Hi guys,
<br />This code downloads some images from the given URL to the hard drive.
<br />In my case I know the URL of the images and the number images of each folder :).</p>
<pre>import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
public class ImagesDownloader {
public static void main(String[] args) throws IOException {
getImages("cars", "bikes", "motors");
}
private static void getImages(String... folders) throws IOException {
String imagesRootPath = "http://www.mysite.com/images";
for (String folder : folders) {
for (int i = 1; i < 31; i++) {
URL url = new URL(String.format("%s/%s/%d.gif", imagesRootPath, folder, i));
InputStream in = url.openStream();
OutputStream out = new BufferedOutputStream(new FileOutputStream(String.format("images/%s/%d.gif", folder, i)));
for (int b; (b = in.read()) != -1; ) {
out.write(b);
}
out.close();
in.close();
System.out.println(String.format("Image %d.gif from folder %s has been successfully downloaded.", i, folder));
}
}
}
}
</pre>Hbiloowaarheid08@gmail.comtag:refactormycode.com,2007:Code6282008-11-27T13:45:53+00:002008-11-27T17:18:05+00:00[Ruby] Displaying numbers to words.<p>Is it possible to refactore this code in order to display numbers to words from 1 - 1000000 only.</p>
<pre>module Verbal
module English
module Numbers
EXPONENT_EN = {
0 => '',
3 => 'thousand',
6 => 'million',
9 => 'billion',
12 => 'trillion',
15 => 'quadrillion',
18 => 'quintillion',
21 => 'sextillion'
}
NUMBERS_EN = {
0 => 'zero',
1 => 'one',
2 => 'two',
3 => 'three',
4 => 'four',
5 => 'five',
6 => 'six',
7 => 'seven',
8 => 'eight',
9 => 'nine',
10 => 'ten',
20 => 'twenty',
30 => 'thirty',
40 => 'fourty',
50 => 'fifty',
60 => 'sixty',
70 => 'seventy',
80 => 'eighty',
90 => 'ninety',
11 => 'eleven',
12 => 'twelve',
13 => 'thirteen',
14 => 'fourteen',
15 => 'fifteen',
16 => 'sixteen',
17 => 'seventeen',
18 => 'eighteen',
19 => 'nineteen'
}
def to_words(value)
raise 'value must be an integer' unless value.is_a?(Integer)
@exponent = Verbal::Core::exponent(value)
@extracted_exponents = Verbal::Core::process_thousands(value)
@in_words = ''
@extracted_exponents.each do |e, v|
@in_words << "#{process_hundreds(v, e, @exponent)} #{EXPONENT_EN[e]} "
end
return @in_words.strip.squeeze(' ')
end
def process_hundreds(value, current_exponent, value_exponent)
raise 'value should be in range: 0.999' unless (0..999).include?(value)
if value > 100
hundreds_count = value / 100
if value % 100 == 0
return NUMBERS_EN[hundreds_count] + ' hundred'
else
prefix = "#{(value_exponent != 0 && current_exponent == 0) ? ' and ': ''}"
return NUMBERS_EN[hundreds_count] + ' hundred ' + process_tens(value % 100, prefix)
end
else
prefix = "#{(value_exponent != 0 && current_exponent == 0) ? ' and ': ''}"
return process_tens(value % 100, prefix)
end
end
def process_tens(value, prefix)
raise 'value should be in range: 0..99' unless (0..99).include?(value)
return prefix + NUMBERS_EN[value] if value < 9
return prefix + NUMBERS_EN[(value / 10) * 10] if (value % 10) == 0
if (11..19).include?(value)
return prefix + NUMBERS_EN[value]
else
return prefix + NUMBERS_EN[(value / 10) * 10] + '-' + NUMBERS_EN[value % 10]
end
end
module_function :to_words, :process_hundreds, :process_tens
end
end
end</pre>ytse.myopenid.comjaredtse@hotmail.comtag:refactormycode.com,2007:Code6272008-11-27T04:21:57+00:002008-11-27T04:21:57+00:00[Python] Williams Words<p>For my blog: <a href="http://www.cmurphycode.blogspot.com" target="_blank">http://www.cmurphycode.blogspot.com</a></p>
<p>A little project via Kottke (<a href="http://www.kottke.org/08/11/williams-poems" target="_blank">http://www.kottke.org/08/11/williams-poems</a>), that I thought would be easy and fun. No need to actually refactor unless you're truly bored- I'm just experimenting with using this as a place to share code. </p>
<pre>import sys
#input into this structure
words = {}
#strings generated go here
gen = []
#input word
word = ""
#final output
final = []
#first arg = word to parse, second arg = wordlist name, optional, third arg = (generated word) minimum length, optional
arglength = len(sys.argv)
if arglength > 1:
word = sys.argv[1]
else:
print "Please specify an input file"
quit()
if arglength > 2:
list = sys.argv[2]
else:
print "Using default wordlist.txt"
list = "wordlist.txt"
if arglength > 3:
cutoff = int(sys.argv[3])
else:
print "Using default cutoff of 1 letter"
cutoff = 1
#create output file based on the word we're generating
outFile = "output-" + word + ".txt"
out = open(outFile, 'w')
#create input file
f = open(list,'r')
#file is one word per line, strip out the endline character, and throw in a dictionary
for line in f:
line = line.strip()
if len(line) > cutoff:
words[line] = 1
#recurse calculates all the substrings forward, is exponential
#input: current string, base string
#example: spray => recurse("s","pray"), recurse("","pray")
def recurse(current, string):
if string == "":
return
gen.append(current)
gen.append(str(current + string[:1]))
recurse(current, string[1:])
recurse(str(current + string[:1]), string[1:])
#check the generated strings for words
#input: string list, word list
def checkOverlap(gen, words):
for item in gen:
#these are just strings, so lets check if they're words
if item in words:
#ignoring duplicates as we go
if item not in final:
final.append(item)
#start recursion on the input word
recurse("", word)
#given the generated strings, find the words
checkOverlap(gen, words)
#sort the output
final.sort()
#write the output
for item in final:
out.write(item)
out.write('\n')
print "Output written to " + outFile</pre>cmurphycode.blogspot.comtag:refactormycode.com,2007:Code6262008-11-26T19:01:18+00:002008-11-26T19:45:34+00:00[Ruby] Doing a 'blank?' in named_scope<p>Can you do a .blank? in a named_scope? (MySQL)</p>
<pre>named_scope :with_description, :conditions => "description IS NOT NULL and trim(description) != ''"
</pre>Jojopotts@gmail.comtag:refactormycode.com,2007:Code6252008-11-26T17:30:38+00:002008-11-26T23:24:46+00:00[Java] Factoring Integers<p>After taking all the factors of 60 (2, 2, 3, 5), when I invoke hasMoreFactors(), it should return false, cause there are no other factors beyond that 5, yet I can only get it to return true. Any ideas?</p>
<pre>/**
This class generates all the factors of a number.
*/
public class FactorGenerator
{
private boolean answer;
private int factor, number;
/**
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;
}
/**
Determine whether or not there are more factors.
@return true there are more factors
*/
public boolean hasMoreFactors()
{
answer = true;
while(number % factor != 0 && answer == true)
{
if (factor >= number)
{
answer = false;
}
factor++;
}
return answer;
}
/**
Calculate the next factor of a value.
@return factor the next factor
*/
public int nextFactor()
{
while(factor < number)
{
if(number%factor == 0)
{
number/= factor;
break;
}
else
factor++;
}
return factor;
}
}
</pre>Kellyscothkellyscoth@gmail.comtag:refactormycode.com,2007:Code6222008-11-25T16:33:17+00:002008-11-27T02:15:58+00:00[C#] Filterting a List<> with a Regular Expression<p>Have the below code which filters a generic list for certain values. I haven't considered using a predicates to achieve the same effect,</p>
<p>Thanks</p>
<pre> List<Document> documents = documentLayer.GetDocuments(username);
List<Document> filteredDocuments = new List<Document>();
string documentName = (string)Session["DocumentName"];
string documentAuthor = (string)Session["DocumentAuthor"];
if ((string.IsNullOrEmpty(documentName)) && (string.IsNullOrEmpty(documentAuthor)))
{
documents.DataSource = documents;
documents.DataBind();
}
else
{
foreach (Document document in documents)
{
string name = document.Name;
string author = document.Author;
if (!(string.IsNullOrEmpty(documentName)) && !(string.IsNullOrEmpty(documentAuthor)))
{
if ((Regex.IsMatch(name, documentName)) && (Regex.IsMatch(author, documentAuthor)))
{
filteredDocuments.Add(document);
}
}
else if (string.IsNullOrEmpty(documentName))
{
if (Regex.IsMatch(author, documentAuthor))
{
filteredDocuments.Add(document);
}
}
else if (string.IsNullOrEmpty(documentAuthor))
{
if (Regex.IsMatch(name, documentName))
{
filteredDocuments.Add(document);
}
}
}
documents.DataSource = filteredDocuments;
documents.DataBind();
}</pre>mantis7.myopenid.comtag:refactormycode.com,2007:Code6212008-11-25T14:08:00+00:002008-11-26T21:24:30+00:00[Ruby] Converting Textile to S5<p>I'd like to take a bunch of textile and turn it into an s5 file.
<br />I was trying to use rubular to isolate blocks of text, but couldn't get just the seperate blocks isolated... Went to looping and ended up with this monstrosity.
<br />There has to be a better way.</p>
<p>example regex trial over at <a href="http://www.rubular.com/regexes/4983" target="_blank">http://www.rubular.com/regexes/4983</a>
<br />closer, but eliminate any more special characters and you get chaos
<br /><a href="http://www.rubular.com/regexes/4986" target="_blank">http://www.rubular.com/regexes/4986</a>
</p>
<pre>/* sample input
h1. Introduction
* s5 is way cool, but I think in textile
* textile is easy to write
* it would be great to take a bunch of textile and transform it instantly into an s5 presentation
h1. Regular Expressions
* they are difficult for multiple lines
* http://www.rubular.com/ helps, but I can't narrow it down to the simple bits.
* let's go shopping or use loops
h1. Looping
* redcloth does the hard work
* you just need to surround the redcloth output with <div class=slide> </div>
* this code smells so bad
h1. You
* please make sense of this
*/
def convert_from_textile_to_s5(fin)
slide = ""
File.open(fin) do | file_in|
lines = file_in.readlines
i=0
while i < lines.length
if lines[i][0..2] == "h1."
puts '<div class="slide">'
puts RedCloth.new(lines[i]).to_html
while i+1 < lines.length && lines[i+1][0,1]=='*'
slide += lines[i+1]
i+=1
end
puts RedCloth.new(slide).to_html
slide = ""
puts '</div>'
end
i+=1
end
end
end</pre>MattKopenid@morelightmorelight.comtag:refactormycode.com,2007:Code6202008-11-25T07:04:17+00:002008-11-25T08:18:54+00:00[Java] Efficiently load a text file into a sorted String Array<p>Has full "finally" blocks, passes findBugs check, should be speedy using TreeSet. Useful for loading data files.</p>
<pre>public static String[] loadFile(final String f) {
String thisLine;
final SortedSet<String> s = new TreeSet<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();
}
}
return s.toArray(new String[s.size()]);
}</pre>firesalamander.myopenid.combenjaminhill@gmail.comtag:refactormycode.com,2007:Code6192008-11-22T15:50:01+00:002008-11-24T10:54:18+00:00[Ruby] Cheap ruby block templating<p>Hello all. I've got the following code which I'm using in a Rails helper atm. It seems there a few ways to do this so does anyone know which is the best way?</p>
<pre>def field_row(options={}, &block)
concat("<div class="field_row">", block.binding)
concat(capture(&block), block.binding)
concat("</div>", block.binding)
end
# called with something like...
<% field_row do %>
<%= text_field blah blah blah %>
<% end %></pre>Alistairalistairholt@gmail.comtag:refactormycode.com,2007:Code6182008-11-22T06:16:53+00:002008-11-22T15:48:37+00:00[Ruby] Bindings on caller<p>I dont really have a need for this but i was trying to figure it out and was curious this sort of thing could be accomplished with bindings.</p>
<pre>def test(a, b)
capitalize_args
puts a # => Hello
puts b # => World
end
test "hello", "world"</pre>Tj Holowaychuktj@vision-media.catag:refactormycode.com,2007:Code6172008-11-22T02:27:39+00:002008-11-22T02:27:39+00:00[Ruby] Initial script execution very slow and skewing results<p>Below is a little snippit of a quick response time monitor I was playing around with, works fine BUT when executed the first time everything performs really slowly and skews the duration by 3 to 4 seconds.. after that every execution works as expected.</p>
<pre>def monitor(uri)
Thread.new(uri) do |uri|
begin
start = Time.now
res = open uri
duration = (Time.now - start).abs
puts " %0.3f | %s | %s" % [duration, res.status.join(' '), uri]
rescue
puts " 0.000 | 404 Not Found | %s" % [uri]
end
end.queue
end</pre>Tj Holowaychuktj@vision-media.catag:refactormycode.com,2007:Code6162008-11-22T02:16:09+00:002008-11-22T02:16:09+00:00[Ruby] suppress ERB newlines<p>Just plain-jane ERB. What does rails do differently to allow <% -%> and <%= -%> ? to get below to actually format correctly I have to place the erb tags in a gross manor.. initializing ERB with <> or ></p>
<pre>
NAME:
<%= @name %>
DESCRIPTION:
<%= @description %>
SYNOPSIS:
<%= @syntax %>
<% unless @examples.empty? %>
EXAMPLES:
<% @examples.each do |example| %>
# <%= example[:description] %>
<%= example[:command] %>
<% end %>
<% end %>
<% unless @options.empty? %>
OPTIONS:
<% @options.each do |option| %>
<%= option[:args].join(', ') %>
<% end %>
<% end %>
</pre>Tj Holowaychuktj@vision-media.catag:refactormycode.com,2007:Code6142008-11-20T22:09:32+00:002008-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 << ":pdp_#{semester}_semester"; (1..5).each{ |n| select << "pdp_#{semester}_semesters.objetive_#{n} AS #{semester}_objetive_#{n}" }}
[select, joins].each { |x| x.join(', ') }</pre>Ceritiumceritium@gmail.comtag:refactormycode.com,2007:Code6132008-11-20T13:42:18+00:002008-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 < 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>foxdemonermin@nomail.comtag:refactormycode.com,2007:Code6122008-11-19T22:23:15+00:002008-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>/// <summary>
/// Test to see if the type can be XML serialized
/// </summary>
/// <param name="objectToTest"></param>
/// <returns></returns>
private static bool CanBeXmlSerialized(Type objectToTest)
{
Type[] interfaces = objectToTest.GetInterfaces();
bool containsIXmlSerializable = interfaces.Contains(typeof(IXmlSerializable));
return containsIXmlSerializable || objectToTest.IsSerializable;
}</pre>sbehnke.myopenid.comtag:refactormycode.com,2007:Code6112008-11-19T21:53:29+00:002008-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]
<div id="slideshow" style="background:#FFF">
<h2 class="slideshowTitle">Around the World with Language</h2>
<nexus:component classid="nexus/components/AssetQuery" code="/System/Components/nexusComponents.jar" root="$node.path/slides" levelsdeep="0"
filter="A.AssetType='slide' AND((A.StartDate is null) OR (A.StartDate <= current timestamp)) AND ((A.ExpireDate >= current timestamp) OR (A.ExpireDate is null))" max="1" orderonmetadata="pageListPriority" orderbycode="1A">
<div id="slide0" name="slide" style="display:block;">
<h3 class="slideTitle">$node.contribution("title")</h3>
<div class="slideImage" width="30%">$node.contribution("image")</div>
<p class="slideCaption">$node.contribution("caption")</p>
</div>
</nexus:component>
<nexus:component classid="nexus/components/AssetQuery" code="/System/Components/nexusComponents.jar" root="$node.path/slides" levelsdeep="0"
filter="A.AssetType='slide' AND((A.StartDate is null) OR (A.StartDate <= current timestamp)) AND ((A.ExpireDate >= current timestamp) OR (A.ExpireDate is null))" skip="1" orderonmetadata="pageListPriority" orderbycode="1A">
<div id="slide$node.recordnumber" name="slide" style="display:none;">
<h3 class="slideTitle">$node.contribution("title")</h3>
<div class="slideImage" width="30%">$node.contribution("image")</div>
<p class="slideCaption">$node.contribution("caption")</p>
</div>
</nexus:component>
<p id="controls"><a href="javascript:prevslide()">Previous</a> <a href="javascript:nextslide()">Next</a></p>
</div>
## Javascript [javascript]
var slideNum = 0;
var slides = new Array();
slides = document.getElementsByName("slide");
function nextslide() {
if (slideNum < 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 > 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>tbesedatbeseda@gmail.comtag:refactormycode.com,2007:Code6102008-11-19T18:48:58+00:002008-11-21T12:17:15+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>/(?<part>(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>troethomt.thomsen@judoo.dktag:refactormycode.com,2007:Code6092008-11-19T05:23:59+00:002008-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
"Expensive operation"
end
cache_method :something_else, :for => 2.hours
end
inst = Something.new
# Empty cache
inst.something_else
# Primed cache
inst.something_else</pre>Tj Holowaychuktj@vision-media.catag:refactormycode.com,2007:Code6082008-11-19T00:45:07+00:002008-11-19T00:48:25+00:00[JavaScript] Tab-Switching in jQuery<p>Is there a better way?</p>
<pre>## showcase.html [HTML]
<div id="showcase">
<ul class="nav">
<li><a href="#example" class="selected">Example</a></li>
<li><a href="#another">Another</a></li>
</ul>
<div class="first item" id="example">
This is the first item. By default it's shown.
</div>
<div class="item" id="another">
This is another item. By default it's hidden.
</div>
</div>
## showcase.css [css]
#showcase .item {
display: none;
}
#showcase .first {
display: block;
}
## showcase.js [javascript]
$(document).ready(function() {
var selected = $("#showcase .first"); // First is selected by default
$("#showcase .nav a").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>Aupajopete@metanation.comtag:refactormycode.com,2007:Code6072008-11-18T16:22:53+00:002008-11-21T15:33:06+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 "y'all didn't enter no arguments";
find(\&sortFile, $ARGV[0]);
sub sortFile {
if ( -f ) {
my $filename=$_;
$filename =~ /([0-9]{5,})/;
my $unixtime = $1 or print "Not a log file: $filename\n";
my $dirname=makeDirName($unixtime);
unless(-e "${ARGV[0]}/${dirname}/${filename}") {
my $path=makeDir($ARGV[0], $dirname);
moveFile($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 moveFile {
my $tehfile=$_[0];
my $tehdir=$_[1];
move($tehfile, $tehdir) or die "Could not move files!\n$!";
return 1;
}
sub makeDir {
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 makeDirName {
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:Code6062008-11-18T12:33:54+00:002008-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 < min) {
if (tmp < min) {
if (max < tmp) {
tmp = max;
max = min;
min = tmp;
}
else { // max < min && tmp < min && tmp <= max
max = min;
min = tmp;
}
}
else { // max < min && min <= tmp
min = max;
max = tmp;
}
}
else { // min <= max
if (tmp < min)
min = tmp;
else // min <= max && min <= tmp
if (max < tmp)
max = tmp;
}</pre>Tien Dungdungtn@gmail.comtag:refactormycode.com,2007:Code6052008-11-15T08:51:14+00:002008-11-15T08:51:14+00:00[Ruby] repeated code in rspec model test<p>how do i clean up this repeated code (Stock.create & Stock.new) in my rspec test</p>
<pre>describe Stock do
it "should be valid when new" do
stock = Stock.new(:symbol => 'GOOG')
stock.should be_valid
end
it "should be invalid when symbol is empty" do
stock = Stock.new(:symbol => '')
stock.should_not be_valid
end
it "should have symbol in all uppercase" do
stock = Stock.create(:symbol => 'GOOG')
stock.symbol.should equal(stock.symbol.upcase)
stock = Stock.create(:symbol => 'goog')
stock.symbol.should equal(stock.symbol.upcase)
end
end</pre>scottmotte.myopenid.comscott@scottmotte.comtag:refactormycode.com,2007:Code6032008-11-12T02:16:38+00:002008-11-12T19:17:03+00:00[Ruby] A simple factorial program.<p>I'm quite new to Ruby, and I'm currently reading "Why's (Poignant) Guide to Ruby." 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, "argument must be a positive integer"
elsif n < 0
raise ArgumentError, "argument must be a positive integer"
end
factorial = 1
for i in 1...n
factorial *= i + 1
end
factorial
end
</pre>lordzoner.myopenid.commorgan.michael@me.comtag:refactormycode.com,2007:Code6022008-11-11T22:53:23+00:002008-11-12T00:33:11+00:00[Haskell] Cat90<p>Rotates text given in stdin 90 degrees. </p>
<pre>main = do s <- getContents
putStr (unlines (reverse (rotate (lines s))))
rotate ls = if (maxLength ls) > 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>jarkkojarkko.sakkinen@iki.fi