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

Remco van 't Veer http://blog.remvee.net

« Newer Snippets
Older Snippets »
Showing 11-16 of 16 total

url and xml encode to fool naive web spiders

Encode all characters to XML entities:

  def xml_encode(text)
    text.unpack('c*').map{|c|"&\##{c};"}.join
  end


Encode all characters to %00%00.. url ecoding:

  def url_encode(text)
    text.split('').map{|c|"%#{c.unpack('H2')}"}.join
  end


The following:

  <a href="<%= xml_encode("mailto:" + url_encode("somebody@somewhere.net")) %>">mail somebody</a>


yields:

  <a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;&#37;&#55;&#51;&#37;&#54;&#102;&#37;&#54;&#100;&#37;&#54;&#53;&#37;&#54;&#50;&#37;&#54;&#102;&#37;&#54;&#52;&#37;&#55;&#57;&#37;&#52;&#48;&#37;&#55;&#51;&#37;&#54;&#102;&#37;&#54;&#100;&#37;&#54;&#53;&#37;&#55;&#55;&#37;&#54;&#56;&#37;&#54;&#53;&#37;&#55;&#50;&#37;&#54;&#53;&#37;&#50;&#101;&#37;&#54;&#101;&#37;&#54;&#53;&#37;&#55;&#52;">mail somebody</a>


which works fine in a browser.

determine image size

Attributed to Sam Stephenson:
IO.read('image.png')[0x10..0x18].unpack('NN')
=> [713, 54]

Homegrown,

GIF:
IO.read('image.gif')[6..10].unpack('SS')
=> [130, 50]

BMP:
d = IO.read('image.bmp')[14..28]
d[0] == 40 ? d[4..-1].unpack('LL') : d[4..8].unpack('SS')


JPEG (slightly more complex):
class JPEG
  attr_reader :width, :height, :bits

  def initialize(file)
    if file.kind_of? IO
      examine(file)
    else
      File.open(file, 'rb') { |io| examine(io) }
    end
  end

private
  def examine(io)
    raise 'malformed JPEG' unless io.getc == 0xFF && io.getc == 0xD8 # SOI

    class << io
      def readint; (readchar << 8) + readchar; end
      def readframe; read(readint - 2); end
      def readsof; [readint, readchar, readint, readint, readchar]; end
      def next
        c = readchar while c != 0xFF
        c = readchar while c == 0xFF
        c
      end
    end

    while marker = io.next
      case marker
        when 0xC0..0xC3, 0xC5..0xC7, 0xC9..0xCB, 0xCD..0xCF # SOF markers
          length, @bits, @height, @width, components = io.readsof
          raise 'malformed JPEG' unless length == 8 + components * 3
        when 0xD9, 0xDA:  break # EOI, SOS
        when 0xFE:        @comment = io.readframe # COM
        when 0xE1:        io.readframe # APP1, contains EXIF tag
        else              io.readframe # ignore frame
      end
    end
  end
end

From my blog entry about reading JPEG.

read and parse RSS feed

require 'open-uri'

require 'rss/0.9'
require 'rss/1.0'
require 'rss/2.0'
require 'rss/parser'

url = 'http://some.host/rss.xml'
rss = RSS::Parser.parse(open(url){|fd|fd.read})
puts rss.items.collect{|item|item.title}.join("\n")


See also simple-rss at rubyforge.

Slurp InputStream to String

public static String slurp (InputStream in) throws IOException {
    StringBuffer out = new StringBuffer();
    byte[] b = new byte[4096];
    for (int n; (n = in.read(b)) != -1;) {
        out.append(new String(b, 0, n));
    }
    return out.toString();
}

find files in zip, jar, war, ear and nested archives

The following java class takes two arguments; a directory name and a regular expression. The directory is searched for files matching the regexp. Zip files (and zip-alikes) are also searched including nested zips.

import java.io.*;
import java.util.*;
import java.util.zip.*;

public class Finder {
	public static void main(String[] args) throws Exception {
		String path = args[0];
		final String expr = args[1];

		List l = new ArrayList();
		findFile(new File(path), new P() {
			public boolean accept(String t) {
				return t.matches(expr) || isZip(t);
			}
		}, l);

		List r = new ArrayList();
		for (Iterator it = l.iterator(); it.hasNext();) {
			File f = (File) it.next();
			String fn = f + "";
			if (fn.matches(expr)) r.add(fn);
			if (isZip(f.getName())) {
				findZip(fn, new FileInputStream(f), new P() {
					public boolean accept(String t) {
						return t.matches(expr);
					}
				}, r);
			}
		}

		for (Iterator it = r.iterator(); it.hasNext();) {
			System.out.println(it.next());
		}
	}

	static void findFile(File f, P p, List r) {
		if (f.isDirectory()) {
			File[] files = f.listFiles();
			for (int i = 0; i < files.length; i++) findFile(files[i], p, r);
		} else if (p.accept(f + "")) {
			r.add(f);
		}
	}

	static void findZip(String f, InputStream in, P p, List r) throws IOException {
		ZipInputStream zin = new ZipInputStream(in);

		ZipEntry en;
		while ((en = zin.getNextEntry()) != null) {
			if (p.accept(en.getName())) r.add(f + "!" + en);
			if (isZip(en.getName())) findZip(f + "!" + en, zin, p, r);
		}
	}

	static String[] ZIP_EXTENSIONS = { ".zip", ".jar", ".war", ".ear" };

	static boolean isZip(String t) {
		for (int i = 0; i < ZIP_EXTENSIONS.length; i++) {
			if (t.endsWith(ZIP_EXTENSIONS[i])) {
				return true;
			}
		}
		return false;
	}

	static interface P {
		public boolean accept(String t);
	}
}



Files are not properly closed! Don't use this class in a long running application or properly close all streams.

zebra a table

<html>
  <head>
    <script>
      function init () {
	var tables = document.getElementsByTagName("table");
	for (var i = 0; i < tables.length; i++) {
	  if (tables[i].className.match(/zebra/)) {
	    zebra(tables[i]);
	  }
	}
      }

      function zebra (table) {
	var current = "oddRow";
	var trs = table.getElementsByTagName("tr");
	for (var i = 0; i < trs.length; i++) {
	  trs[i].className += " " + current;
	  current = current == "evenRow" ? "oddRow" : "evenRow";
	}
      }
    </script>
    <style>
        tr.oddRow { background-color: green; }
        tr.evenRow { background-color: red; }
    </style>
  </head>
  <body onload="init()">
    <table class="zebra">
      <tr> <td>foo</td> <td>foo</td> <td>foo</td> </tr>
      <tr> <td>bar</td> <td>bar</td> <td>bar</td> </tr>
      <tr> <td>foo</td> <td>foo</td> <td>foo</td> </tr>
      <tr> <td>bar</td> <td>bar</td> <td>bar</td> </tr>
      <tr> <td>foo</td> <td>foo</td> <td>foo</td> </tr>
    </table>
  </body>
</html>
« Newer Snippets
Older Snippets »
Showing 11-16 of 16 total