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

Snippets

  • submit to reddit

Recent Snippets

                    This is in models/tag.rb

def find_all_with_count
    self.find_by_sql("SELECT t.*, COUNT(pt.post_id) AS count FROM tags t, posts_tags pt WHERE pt.tag_id = t.id GROUP BY t.id ORDER BY count DESC;")
end
This is a basic non-specific overview of all tags, as you would see on Snippets' front page. So:

@tag_info = Tag.find_all_with_count
@tag_info.each { |t| .. you now have t.name, t.count, etc .. }
                
                    
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
blacklist_builder.py
Get the entries from a blacklist
and print them to standard output
"""
import urllib2, re
latest = urllib2.urlopen("http://www.unknowngenius.com/blog/blacklist/")
prefix = 'RewriteEngine  on'
suffix = 'RewriteRule /(.*) / [F,L]'
str = [prefix]
begin = "RewriteCond %{HTTP_REFERER} ^.*"
for line in latest:
	print '.',
	str.append(begin + re.sub('(\s#:url:|\s#:regex-url:|\s#:rbl:)', ".*$ [OR,NC]", line))
str.append(suffix)
file('.htaccess', 'w').write('\n'.join(str))


Use of list to speed up.

Added prefix and suffix to make it a complete rewrite.                
                    
perl -ne '@a=split"";for(@a){printf"%02x ",ord;print"\n"unless++$c % 20}' sample.txt
                
                    This rather long winded Perl subroutine returns an array of numbers expanded from a list such as 34,35,36,42-56,98-150. There are plenty of other ways to do this (eval comes to mind).

 sub expand {                                                              
  my $range = shift;            
  my @result; 
$range =~ s/[^\d\-\,]//gs; #remove extraneous characters
 my @items = split(/,/,$range);    
  foreach (@items){                 
    m/^\d+$/ and push(@result,$_) and next;  my ($start,$finish) = split /-/;   push(@result,($start .. $finish)) if $start < $finish;                    
  }                                 
  return @result;                        
 } 
                
                    Here is a quick way in Perl to read lines from a file regardless of whether it is Unix, Mac, or DOS.

my @lines = split(/\012\015?|\015\012?/,(join '',<FILE>));
                
                    Here's a cheap hack to convert UTF8 curly quotes to ASCII (but try to use CPAN module instead of this if you can).

 $xml =~ s/\xe2\x80\x99/\'/gs;
 $xml =~ s/\xe2\x80\x98/\'/gs;
 $xml =~ s/\xe2\x80\x9c/\"/gs;
 $xml =~ s/\xe2\x80\x9d/\"/gs;
                
                    This code requires JavaMail.  Specifically it requires mailapi.jar and smtp.jar from the JavaMail distribution (available at http://java.sun.com/) as well as activation.jar from the JavaBeans Activation Framework (available at http://java.sun.com/beans/glasgow/jaf.html).

Properties props = new Properties();
props.put("mail.smtp.host", "your-smtp-host.com");
Session session = Session.getDefaultInstance(props, null);

MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setContent(message, "text/plain");

Transport.send(msg);
                
                    Writer implementation which provides a means for writing directly to a JTextArea.

import java.io.Writer;
import java.io.IOException;

import javax.swing.JTextArea;

/** A implementation of the java.io.Writer class which facilitates writing to a JTextArea via a stream.
    
    <p><b>Note:</b> There appears to be bug in the Macintosh implementation of 
    the JDK 1.1 where a PrintWriter writing to this class will not include the 
    correct line feeds for display in a JTextArea.  There is a simple test of
    the "java.version" system property which, if it starts with the String "1.1"
    will cause newlines to be written each time the buffer is flushed.</p>
    
    @author Anthony Eden
*/

public class JTextAreaWriter extends Writer{
    
    private boolean closed = false;
    private JTextArea textArea;
    private StringBuffer buffer;

    /** Constructor.
    
        @param textArea The JTextArea to write to.
    */

    public JTextAreaWriter(JTextArea textArea){
        setTextArea(textArea);
    }
    
    /** Set the JTextArea to write to.
    
        @param textArea The JTextArea
    */
    
    public void setTextArea(JTextArea textArea){
        if(textArea == null){
            throw new IllegalArgumentException("The text area must not be null.");
        }
        this.textArea = textArea;
    }
    
    /** Close the stream. */

    public void close(){
        closed = true;
    }
    
    /** Flush the data that is currently in the buffer.
    
        @throws IOException
    */
    
    public void flush() throws IOException{
        if(closed){
            throw new IOException("The stream is not open.");
        }
        // the newline character should not be necessary.  The PrintWriter
        // should autmatically put the newline, but it doesn't seem to work
        textArea.append(getBuffer().toString());
        if(System.getProperty("java.version").startsWith("1.1")){
            textArea.append("\n");
        }
        textArea.setCaretPosition(textArea.getDocument().getLength());
        buffer = null;
    }
    
    /** Write the given character array to the output stream.
    
        @param charArray The character array
        @throws IOException
    */
    
    public void write(char[] charArray) throws IOException{
        write(charArray, 0, charArray.length);
    }
    
    /** Write the given character array to the output stream beginning from
        the given offset and proceeding to until the given length is reached.
    
        @param charArray The character array
        @param offset The start offset
        @param length The length to write
        @throws IOException
    */
    
    public void write(char[] charArray, int offset, int length) throws IOException{
        if(closed){
            throw new IOException("The stream is not open.");
        }
        getBuffer().append(charArray, offset, length);
    }
    
    /** Write the given character to the output stream.
    
        @param c The character
        @throws IOException
    */
    
    public void write(int c) throws IOException{
        if(closed){
            throw new IOException("The stream is not open.");
        }
        getBuffer().append((char)c);
    }
    
    /** Write the given String to the output stream.
    
        @param string The String
        @throws IOException
    */
    
    public void write(String string) throws IOException{
        if(closed){
            throw new IOException("The stream is not open.");
        }
        getBuffer().append(string);
    }
    
    /** Write the given String to the output stream beginning from the given offset 
        and proceeding to until the given length is reached.
    
        @param string The String
        @param offset The start offset
        @param length The length to write
        @throws IOException
    */
    
    public void write(String string, int offset, int length) throws IOException{
        if(closed){
            throw new IOException("The stream is not open.");
        }
        getBuffer().append(string.substring(offset, length));
    }
    
    // protected methods
    
    /** Get the StringBuffer which holds the data prior to writing via
        a call to the 
flush()
 method.  This method should
        never return null.
        
        @return A StringBuffer
    */
    
    protected StringBuffer getBuffer(){
        if(buffer == null){
            buffer = new StringBuffer();
        }
        return buffer;
    }

}
                
                    
    /**
     * Convert the byte array to an int.
     *
     * @param b The byte array
     * @return The integer
     */
    public static int byteArrayToInt(byte[] b) {
        return byteArrayToInt(b, 0);
    }

    /**
     * Convert the byte array to an int starting from the given offset.
     *
     * @param b The byte array
     * @param offset The array offset
     * @return The integer
     */
    public static int byteArrayToInt(byte[] b, int offset) {
        int value = 0;
        for (int i = 0; i < 4; i++) {
            int shift = (4 - 1 - i) * 8;
            value += (b[i + offset] & 0x000000FF) << shift;
        }
        return value;
    }
                
                    
    public static byte[] intToByteArray(int value) {
        byte[] b = new byte[4];
        for (int i = 0; i < 4; i++) {
            int offset = (b.length - 1 - i) * 8;
            b[i] = (byte) ((value >>> offset) & 0xFF);
        }
        return b;
    }