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

                    These routes allow URLs like tags/whatever/whatever/whatever to put 'whatever', 'whatever', and 'whatever' into the @params[:tags] array, etc.

map.connect '', :controller => "posts", :action => "index"
map.connect 'tags/*tags', :controller => 'tag', :action => 'show'
map.connect 'user/:user', :controller => 'user', :action => 'show'
map.connect 'user/:user/tags/*tags', :controller => 'tag', :action => 'show'

                
                    With this code, create "next generation" bookmarklets.

The good points are that :
- the code is remotely loaded (so updatable and more simply testable)
- you have no length limitation 
- you can dispatch the code in various libaries

To disable the browser cache, we've added a random parameter in the the last javascript url. For performance, it's better to not disable the cache but it's very useful when testing.


baseurl = 'http://example.com/bookmarklet/';

var scripts = new Array(

baseurl + 'date.js',
baseurl + 'encoding.js',
baseurl + 'http.js',
baseurl + 'bookmarklet.js?x=' + Math.floor(Math.random() * 9999)

);

for (i=0;i<scripts.length;i++) {

var x = document.getElementsByTagName('head').item(0);
var o = document.createElement('script');

if (typeof o != 'object') o = document.standardCreateElement('script');
o.setAttribute('src', scripts[i] );
o.setAttribute('type','text/javascript');
x.appendChild(o);

}

Past the code above in a bookmarklet crunchinator to generate the bookmarklet. http://ted.mielczarek.org/code/mozilla/bookmarklet.html

Not fully tested. It may have some issues.                
                    
/*
 * create a new DOM element with (optionally) specified className, CSS and text/html content
 * if text contains any markup, it's used as innerHTML value - else a child text node is attached
 * if there's also a parent node given, the new element will be appended as child node
 */
function createStyledElement(tag, parent, cls, css, txt) {
    var el = document.createElement(tag);
    if(cls) el.className = cls;
    if(css) for(var s in css) el.style[s]=css[s];
    if(txt) {
        if (txt.indexOf('<')!=-1) el.innerHTML=txt;
        else el.appendChild(document.createTextNode(txt));
    }
    if(parent) parent.appendChild(el);
    return el;
}

// usage example...
// 1st define some style params
var style1={
    background: '#def',
    color: '#f00',
    padding: '0.5em',
    border: '1px black dotted'
};

createStyledElement(
  'div',
  document.getElementsByTagName('body').item(0),
  null,
  style1,
  'hello <em>world</em>!'
);
                
                    Using SnippetCompiler (http://www.sliver.com) a lot, I needed a template which has the nUnit components started... Here it is.

using System;
using System.Collections;
using NUnit.Framework;

#region entry point
public class EntryClass
{
	public static void Main()
	{
		NewClass t = new NewClass();
	}

}
#endregion entry point

// To test, select Build|Build To File... then point nunit's guii at the resultant dll


// Class we will build up for testing
public class NewClass
{
    // Sample Method which is tested
    public int MyMethod(int firstNumber, int secondNumber)
    {
        return firstNumber + secondNumber;
    }
}


// Class that does the nunit testing ([TestFixture] tells nunit it's the test class)
[TestFixture]
public class MyNewClassTestClass
{    
        // Method for testing the method in the class above ([Test] tells nunit this is a test method)
		[Test]
		public void MyMethodTest() 
		{
            // create an instance of the class
			NewClass obj_newClass = new NewClass();
            
            // Verify assertion
			Assertion.Assert(obj_newClass.MyMethod(10, 20) == 30);
		}    

} 

                
                    This RegEx should return all the Wiki Words (i.e. any word in Camel Case):

[^A-Za-z]*([A-Z][a-z]+[A-Z][a-z]+([A-Z][a-z]+)*)[^A-Za-z]*
                
                    This will recursively traverse the entire directory tree from the current directory down and compress every file.

for /r %V IN (*) DO gzip -9v "%V"
this will recursively traverse the entire directory tree from the current directory down and uncompress every file.

for /r %V IN (*.gz) DO gzip -dv "%V"
make sure you have gzip in your path.                
                    
def scale_crop
.......
   	
# Open the image-file
	   	img = Image.read(picture_name).first
		scale_image = img.scale(scale_width,scale_height )
		crop_image = scale_image.crop(left_x, left_y, right_x, right_y)
		@response.headers["Content-Type"] = "image/jpeg"
		render_text do |response|
            		print crop.to_blob
   		end
end
                
                    Returns a random key from your hash, but won't repeat until it's done every one.  (I was using this to help quiz myself.)
class Hash
  @keys_used = []

  def random_key
    @keys_used = [] if @keys_used.size == self.size
    key = self.keys[rand(self.size)]
    while @keys_used.include?(key)
      key = self.keys[rand(self.size)]
    end
    @keys_used << key
    return key
  end
end
                
                    
| w s p |

w := SystemWindow new.
s := ScrollPane new.
p := PasteUpMorph new.
p extent: 1000@1000.
s scroller addMorph: p.
w addMorph: s frame: (0@0 corner: 1@1).
w openInWorld.
                
                    | oldContent newContent |
oldContent _ nil.
[[Smalltalk at: #Stop ifAbsent:[true]] whileTrue: [
newContent _ 'http://minnow.cc.gatech.edu/squeak/recent' asUrl
retrieveContents contents.
(oldContent ~= newContent) ifTrue:[
(FMSound majorChordOn: FMSound flute1 from: #c4) play.
oldContent _ newContent
].
(Delay forSeconds:  30) wait.
]] forkAt: Processor userBackgroundPriority