DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
  • submit to reddit
        Go to /home/virtual and run:

find -type l -maxdepth 1 -name '*.*' | xargs -n 1 basename | xargs -i find /home/virtual/{}/var/www -type f -size +8192k -ls
    
        You can confirm that your database YAML file is being parsed properly with this one line shell command.

ruby -ryaml -e "File.open('config/database.yml') { |f| puts YAML.load(f).inspect }"
    
        Use this objects:

java.util.Stack (LIFO)
java.util.LinkedList (FIFO)
    
        
# put this in lib/active_record/json.rb
require 'json/lexer'
require 'json/objects'
module ActiveRecord
  module Json # :nodoc:
    DEFAULT_CONVERSIONS = { Time => [:to_s, :db] }
    def to_json(conversions = {})
      conversions = DEFAULT_CONVERSIONS.merge(conversions)
      self.attributes.keys.inject({}) do |hsh, key|
        value = self.send(key)
        hsh.merge(key => conversions[value.class] ? value.send(*conversions[value.class]) : value.to_s)
      end.to_json
    end
  end
end
 
# in environment.rb do
#require "#{RAILS_ROOT}/lib/active_record/json"
#ActiveRecord::Base.class_eval { include ActiveRecord::Json }

Doing something like 
<%= var post = @post.to_json %>
 in a javascript snippet should allow you to use the basic AR attributes such as post.title, post.summary (using the Weblog analogy).  You could also pass the json bits to a javascript function.    
        
//simple general rand function 
float randBetween(float min, float max)
{
    return llFrand(max - min) + min;
}

//uses randBetween to generate a random colour vector
//maybe a bit of overkill, but can be repurposed.

vector randColour()
{   
    vector r_colour = <randbetween 0,1), randBetween(0,1), randBetween(0,1)>;
    return r_colour;    
}
    
        The R FAQ states:
 
par(mar = c(7, 4, 4, 2) + 0.1)
plot(1 : 30, xaxt = "n",  xlab = "")
labels <- paste("Label", 1:30, sep = " ")
text(1:30, par("usr")[3] - 0.25, srt = 90, adj = 1,labels = labels, xpd = TRUE)
mtext(1, text = "X Axis Label", line = 6)

Also see Figure 1 and associated code in Paul Murrell (2003), “Integrating grid Graphics Output with Base Graphics Output�, R News, 3/2, 7–12.    
        At the prompt, type this:

defaults write com.apple.screencapture type image_format

Replace "image_format" with a file format name, like pdf, png, tiff, etc. Then to take screenshots, Cmd+Shift+4, then drag around the area you want to capture.    
        
data <- sort.data.frame(data, key = "LOC")

where the function "sort.data.frame" is as follows:

sort.data.frame <- function(x, key, ...) {
    if (missing(key)) {
        rn <- rownames(x)
        if (all(rn %in% 1:nrow(x))) rn <- as.numeric(rn)
        x[order(rn, ...), , drop=FALSE]
    } else {
        x[do.call("order", c(x[key], ...)), , drop=FALSE]
    }
}
    
        The CSV file "loc.csv" contains the following:

Module LOC
a.rb 100
b.rb 120
c.rb 54

The following R code creates the barplot image "loc.png":

data <- read.csv(file="loc.csv", sep = " ", header = TRUE, row.names = "Module")
png("loc.png", width = 640, height = 480)
barplot(data$LOC, names = rownames(data), ylim = c(0, 250), main = "Lines of code by module", ylab = "Lines of code", xlab = "Module")
dev.off()
    
        This lets you load ActionView helpers globally.

RAILS_ROOT/lib/action_view/helpers/widget_helper.rb:
module ActionView
  module Helpers
    module WidgetHelper
      # define helper methods
    end
  end
end

RAILS_ROOT/config/environment.rb:
require "#{RAILS_ROOT}/lib/action_view/helpers/widget_helper.rb"
ActionView::Base.class_eval do
  include ActionView::Helpers::WidgetHelper
end
    
        
class AccountControllerTest < Test::Unit::TestCase
  def setup
    @controller = AccountController.new
    @request    = ActionController::TestRequest.new
    @request.env['HTTPS'] = 'on'
    @response   = ActionController::TestResponse.new
  end

  def test_ssl
    assert @request.ssl?
  end
end
    
        
use Date::Manip qw(ParseDate UnixDate);

# Create an RFC822 compliant date (current time)
my $rfc822_format = "%a, %d %b %Y %H:%M %Z";
my $today         = ParseDate("Now");

my $rfc822_date   = UnixDate($today,$rfc822_format);

    
        Pass new tags followed by a table name and database handle and this function updates the table so that each tag becomes properly associated/its record created, eg:

table state:
tagname  |  relatedtags
-----------------------
blog     |  rss;personal
rss      |  blog
personal |  blog

call (table is named tags):
updateTags("blog personal friends","tags",$db);

table state:
tagname  |  relatedtags
-----------------------
blog     |  rss;personal;friends
rss      |  blog
personal |  blog;friends
friends  |  blog;personal


function updateTags($tags,$table,$db) {//category handling stuff
   include("recordExists.php");//see http://bigbold.com/snippets/posts/show/464
   $cats = explode(";",$tags);//parse tags into array cats
   foreach($cats as $cat) {//loop through cats
      $tmp = array($cat);//dummy array with cat in it
      $tmp = array_diff($cats,$tmp);//get everything in cats that is not cat
      if(!recordExists("tagname",$cat,$table,$db)) {//if there is no category by this name yet
         $tmp = implode(";",$tmp);//make tmp into semicolon-separated string
         $result = mysql_query("INSERT INTO ".$table." (tagname,relatedtags) VALUES ('$cat','$tmp')", $db) or die(mysql_error());//insert category into database
      } else {
         $result = mysql_query("SELECT relatedtags FROM ".$table." WHERE tagname='$cat'", $db) or die(mysql_error());//select already related tags
         $result = mysql_fetch_array($result);//get the result row as an array
         $result = explode(";",$result['relatedtags']);//parse relatedtags into result
         $result = array_merge($tmp,$result);//merge the cats in this $tags (without cat, hence tmp) with the ones that were in there already
         $result = array_unique($result);//strip duplicates
         $result = implode(";",$result);//make result into semicolon-separated string
         $result = mysql_query("UPDATE ".$table." SET relatedtags='$result' WHERE tagname='$cat'", $db) or die(mysql_error());//update category
      }//end if-else !recordExists
   }//end foreach cats
}//end function updateTags
    
        In mySQL (from PHP), checks for the existance of a record based on id, passing the name of the id field followed by the id to check for, the table name, and the database resource, in that order.
function recordExists($id,$idval,$table,$db) {//check for id=idval in table and return TRUE or FALSE
   $result = mysql_query("SELECT * FROM ".$table." WHERE ".$id."='".$idval."'", $db) or die(mysql_error());
   if($row = mysql_fetch_array($result)) {//if we did return a record
      return 1;
   }//end if row
   return 0;
}//end fuction recordExists
    
        
<global-forwards>
	<forward name="error" path="/WEB-INF/jsp/error.jsp"/>
</global-forwards>