Never been to DZone Snippets before?

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

About this user

Matthew Beale http://madhatted.com

« Newer Snippets
Older Snippets »
Showing 1-6 of 6 total  RSS 

vimrc for 2 space tab replacements

~/.vimrc:
set softtabstop=2
set shiftwidth=2
set tabstop=2
set expandtab

Ruby FPDF PDF_MC_Table port

My old direct port of FPDF MultiCell tables to Ruby from PHP. I'm sure there are at least 30 better ways to do this :-) (PDF::Writer is more popular now anyway)

FPDF: http://fpdf.org/en/script/script3.php
Ruby FPDF: http://brian.imxcc.com/fpdf/

require 'fpdf'

class PDF_MC_Table < FPDF
  attr_reader :widths, :aligns

  def SetWidths (w)
    # Set the array of column widths
    @widths=w;
  end

  def SetAligns (a)
    # Set the array of column alignments
    @aligns=a;
  end

  def Row (data)
    # Calculate the height of the row
    nb = 0
    0.upto(data.length - 1) do |i|
      num_lines = NbLines(@widths[i],data[i])
      nb = num_lines if num_lines > nb
    end
    h = 5 * nb
    # Issue a page break first if needed
    CheckPageBreak(h)
    # Draw the cells of the row
    0.upto(data.length - 1) do |i|
        w = @widths[i]
        a = ( (@aligns && @aligns[i]) ? @aligns[i] : 'L' )
        # Save the current position
        x = GetX()
        y = GetY()
        # Draw the border
        Rect(x,y,w,h)
        # Print the text
        MultiCell(w,5,data[i],0,a)
        # Put the position to the right of the cell
        SetXY(x+w,y)
    end
    # Go to the next line
    Ln(h)
  end

  def CheckPageBreak(h)
    # If the height h would cause an overflow, add a new page immediately
    AddPage(@CurOrientation) if GetY()+h > @PageBreakTrigger
  end

  def NbLines(w,txt)
    # Computes the number of lines a MultiCell of width w will take
    cw = @CurrentFont['cw']
    w = w - @rMargin - @x if ( w==0 )
    wmax = ( w - 2 * @cMargin ) * 1000 / @FontSize
    s = txt ? txt.gsub(/\r/,'') : ''
    nb = s.length
    nb -= 1 if ( nb > 0 and s[nb-1]==10 ) # strip a trailing \n
    sep = -1
    i = 0
    j = 0
    l = 0
    nl = 1
    while(i < nb) do
      c=s[i] #go through the string character by character
      if(c==10) #if we find a newline just skip the rest
	i += 1
        sep = -1
        j = i
        l = 0
        nl += 1
        next
      end
      sep = i if (c==' ')
      l = l + cw[c]
      if(l>wmax)
        if(sep==-1)
          if(i==j)
	    i += 1
	  end
        else
	  i = sep+1
	end
        sep = -1
        j = i
        l = 0
        nl += 1
      else
	i += 1
      end
    end
    return nl
  end
end

Barebones xHTML and CSS template pages

Ok, so this guy already did this: http://www.bigbold.com/snippets/posts/show/583 but I needed a bit more. So this is my xHTML template page (it doesn't declare xml since it makes IE kick out of standards mode):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <title>XHTML TEMPLATE</title>
  
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <meta name="description" content="THIS IS A TEMPLATE XHTML PAGE" />
  
  <link rel="stylesheet" href="main.css" type="text/css" media="screen" />
  
  <!-- <script type="text/javascript" src="prototype.js">
  </script> -->
  <script type="text/javascript" language="JavaScript"><!-- <![CDATA[
  // ]]> --></script>
</head>
<body>
  <div id="container">

  </div>
</body>
</html>


This is the accomponying CSS:

body {
  font-family :Verdana, Arial, Sans;
  font-size   :76%;
  margin      :0px; }
div#container {
  font-size   :1.0em; }

.clearfix:after {
    content: "."; 
    display: block; 
    height: 0; 
    clear: both; 
    visibility: hidden;
}

.clearfix {display: inline-table;}

/* Hides from IE-mac \*/
* html .clearfix {height: 1%;}
.clearfix {display: block;}
/* End hide from IE-mac */

Backup MySQL databases into seperate files

A cronable script for backing up all your databases as seperate files. I'd suggest limiting the backup user's access to the IP of the computer backing up, and using some sort of encryption if you're on a capable version of mysql.

#!/bin/sh
#
# MySQL backups from the Data

MOUNTED=`grep /etc/mtab -e \/mnt\/backup`
if [ "$MOUNTED" = '' ]; then
        echo "/mnt/backup is not mounted, there is no drive to backup to"
        exit 1
fi


mkdir -p /mnt/backup/cluster_sql

for i in $(echo 'SHOW DATABASES;' | mysql -ubackup -pSUPERSECRET -hData|grep -v '^Database$'); do
  mysqldump -ubackup -pSUPERSECRET -hData --opt $i > /mnt/backup/cluster_sql/$i.sql;
done;

Model.find_or_create_by_title - rails &lt; 0.14

Check it!

In our model for rails we can have a need to get the id for a title, but sometimes want to create the title on the fly (like adding a tag to something, if it's there we want the id, if it's not we want to make it and get back the id). That'd be messy in the controller, this is much nicer:

*Note - only for < 0.14 rails. Something like this became standard in rails after that.

  def Project.find_or_create_by_title(title)
    return nil if title.empty?

    if (project = Project.find( :first, :conditions => [ 'title = ?', title ] ))
      return project.id
    else
      project = Project.new
      project.title = title
      if project.save
        return project.id
      else
        @flash[:notice] = 'Sorry, a project could not be created'
        return nil
      end
    end
  end

ajax_pagination_links

Put in a helper somewhere, and use like this:
<%= ajax_pagination_links @client_pages, {:update => 'search_results', :params => {:search_query => @params[:search_query]} } %>

and just update the div your results (and the above line) are in.
       def ajax_pagination_links(paginator, options={})
         
         options.merge!(ActionView::Helpers::PaginationHelper::DEFAULT_OPTIONS) {|key, old, new| old}
         
         window_pages = paginator.current.window(options[:window_size]).pages
 
         return if window_pages.length <= 1 unless
           options[:link_to_current_page]
         
         first, last = paginator.first, paginator.last
         
         returning html = '' do
           if options[:always_show_anchors] and not window_pages[0].first?
             html << link_to_remote(first.number, :update => options[:update], :url => { options[:name] => first }.update(options[:params] ))
             html << ' ... ' if window_pages[0].number - first.number > 1
             html << ' '
           end
           
           window_pages.each do |page|
             if paginator.current == page && !options[:link_to_current_page]
               html << page.number.to_s
             else
               html << link_to_remote(page.number, :update => options[:update], :url => { options[:name] => page }.update(options[:params] ))
             end
             html << ' '
           end
           
           if options[:always_show_anchors] && !window_pages.last.last?
             html << ' ... ' if last.number - window_pages[-1].number > 1
             html << link_to_remote(paginator.last.number, :update => options[:update], :url => { options[:name] => last }.update( options[:params]))
           end
         end
       end
« Newer Snippets
Older Snippets »
Showing 1-6 of 6 total  RSS