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

                    TrashCanMorph subclass: #SmartTrashCanMorph
	instanceVariableNames: ''
	classVariableNames: ''
	poolDictionaries: ''
	category: 'SqueakRos'

initialize
	"Initialize the receiver's graphics, name, and balloon-help"
	super initialize.
	self image: TrashPicOn;
		 offImage: TrashPic;
		 pressedImage: TrashPicOn.
	self setNameTo: 'SmartTrash'.
	self setBalloonText: 'Drag some morph here . Removes all morph of same class'

acceptDroppingMorph: aMorph event:  evt 
 ActiveWorld submorphs copy do: [:each | (each class  == aMorph class ) ifTrue: [each delete]].

                
                    This needs more work to be complete.  Will it ever be useful?

public class MixinTest
{
  /*
   * The Demo
   */
  interface Chimera extends Lion, Goat, Serpent, Animal {}

  public static void main(String[] args)
  {
    Chimera chimera = (Chimera) MixinFactory.create(Chimera.class, new AnimalImpl());
    System.out.println("The Chimera: ");
    chimera.roar();
    chimera.stomp();
    chimera.slither();
    chimera.action("Sing a song");
  }

  /*
   * The Interfaces
   */
  public interface Lion
  {
    void roar();
  }

  public interface Goat
  {
    void stomp();
  }

  public interface Serpent
  {
    void slither();
  }

  public interface Animal
  {
    void action(String description);
  }

  /*
   * The Implementations
   */
  public static class LionImpl implements Lion
  {
    private Animal animal;

    public LionImpl(Animal animal)
    {
      this.animal = animal;
    }

    public void roar()
    {
      animal.action("Roars with lion head");
    }
  }

  public static class GoatImpl implements Goat
  {
    private Animal animal;

    public GoatImpl(Animal animal)
    {
      this.animal = animal;
    }

    public void stomp()
    {
      animal.action("Stomps with goat foot");
    }
  }

  public static class SerpentImpl implements Serpent
  {
    private Animal animal;

    public SerpentImpl(Animal animal)
    {
      this.animal = animal;
    }

    public void slither()
    {
      animal.action("Slithers with serpent tail");
    }
  }

  public static class AnimalImpl implements Animal
  {
    public void action(String description)
    {
      System.out.println(description);
    }
  }

  /*
   * The Guts
   */
  public static class MixinFactory
  {
    private static class MixinInvocationHandler implements InvocationHandler
    {
      private Map implMap = new HashMap();
      public MixinInvocationHandler(Class clazz, Object core)
      {
        for (int i = 0; i < clazz.getInterfaces().length; i++)
        {
          Class anInterface = clazz.getInterfaces()[i];
          try
          {
            Class delegateClass = Class.forName(anInterface.getName()+"Impl");
            Constructor delegateConstructor = findBestMatchConstrustor(delegateClass, core.getClass());
            if(delegateConstructor != null)
            {
              implMap.put(anInterface, delegateConstructor.newInstance(new Object[] {core}));
            }
            else
            {
              implMap.put(anInterface, core);
            }
          }
          catch(Exception e)
          {
            throw new RuntimeException(e);
          }
        }
      }
      public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
      {
        Object delegate = implMap.get(method.getDeclaringClass());
        return delegate.getClass().getDeclaredMethod(method.getName(), method.getParameterTypes()).invoke(delegate, args);
      }
      private static Constructor findBestMatchConstrustor(Class delegateClass, Class coreClass)
      {
        if(coreClass == null)
        {
          return null;
        }
        try
        {
          return delegateClass.getConstructor(new Class[] {coreClass});
        }
        catch (NoSuchMethodException e)
        {
          Class[] interfaces = coreClass.getInterfaces();
          for (int i = 0; interfaces != null && i < interfaces.length; i++)
          {
            Class interfaceClass = interfaces[i];
            Constructor delegateConstructor = findBestMatchConstrustor(delegateClass, interfaceClass);
            if(delegateConstructor != null)
            {
              return delegateConstructor;
            }
          }
          Constructor delegateConstructor = findBestMatchConstrustor(delegateClass, coreClass.getSuperclass());
          if(delegateConstructor != null)
          {
            return delegateConstructor;
          }
        }
        return null;
      }
    }
    public static Object create(Class clazz, Object core)
    {
      return Proxy.newProxyInstance(clazz.getClassLoader(), new Class [] {clazz}, new MixinInvocationHandler(clazz, core));
    }
  }
}
                
                    
function QueryString(path)
  {
  	this.path = path;
	this.toString = function()
	{
		result = this.path + "?";
		for(element in this)
		{
			if(typeof this[element] != 'function' && element != 'path')
			{
				result += element + "=" + this[element] + "&";
			}
		}
		return result;
	}
	
	this.toLink = function(text)
	{
		return "<a href=\"" + this.toString() + "\">" + text + "</a>";
	}
  }


Now i can get rid of mess link this:
url = '/pictures/crop?id=<%= @picture.id  %>' +
				'&w=' + dd_picturer.w + 
				'&h=' + dd_picturer.h +
				'&sx=' + (dd_crop.x - dd_picturer.x) + '&sy=' + 
				(dd_crop.y - dd_picturer.y) + '&ex=' +
				 dd_crop.w + '&ey=' + dd_crop.h;

And make it readable like this:

myObj = new QueryString("http://codebehind.dk");
  myObj.w = 100;
  myObj.rx = 1000;
  myObj.ry = 1000;
  ...
  ...
  document.writeln(myObj.toLink("codebehind.dk"));

                
                    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);