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

                    
ActiveRecord::Base.connection.select_one('select sum(quantity) from table').to_i
arrayofhashes = ActiveRecord::Base.connection.select_all('select * from table')
                
                    
>> for i in [1]
>>   puts i
>> end.any? or puts "empty!"
1
=> true
>> for i in [ ]
>>   puts i
>> end.any? or puts "empty!"
empty!
=> nil

short circuit evaluation is not intutitive? try this.

>> class Array
>>   alias :__empty? :empty?
>>   def empty?
>>     yield if __empty? and block_given?
>>     __empty?
>>   end
>> end
=> nil
>> for i in [1]
>>   puts i
>> end.empty? { puts "empty!" }
1
=> false
>> for i in [ ]
>>   puts i
>> end.empty? { puts "empty!" }
empty!
=> true
                
                    I needed a Ruby Hash class that could extract a random key from the keys that have not been extracted before. Plus that the class should be re-entrant... 

I found baby's class, but it was not working (at least not in Ruby 1.8.x). I made it work (slight changes), and I added the keys_not_used to make it work faster (baby's random would cycle almost forever on large lists). But I would say all credit should go to the original author, who did all the hard work. 

Without further ado, here is the new version:
class RandomHash < Hash 

   @keys_used = nil 
  
   def random_key 
      if @keys_used == nil then
         @keys_used = Hash.new 
      else
         @keys_used = Hash.new if @keys_used.size == self.size
      end
      
      if (@keys_used.size == 0) then
         pos = rand(self.size)
         key = self.keys[pos]
      else
         @keys_not_used = Hash.new
     	 self.keys.each{ |key|
         	if (! @keys_used.include?(key)) then
            	    @keys_not_used[key] = 1
         	end
	     }
	     pos = rand(@keys_not_used.size)
	     key = @keys_not_used.keys[pos]
	  end
	  
      @keys_used[key] = 1
      return key 
   end 
end 

# Test code
$sources = Hash.new
$RandomSources = RandomHash.new

begin

   (1..10).each{ |val|
      $sources["#{val}"] = 1
   }
   
   $sources.each { |src|
      puts "Src=#{src}"
      $RandomSources[src] = 1
   }

   RandomKeys = Hash.new
   (0..$sources.length).each{ |index| # one more than all values
      key = $RandomSources.random_key
      print "Extracted #{key} ... It's a"
      if (!RandomKeys.has_key?(key)) then
         puts " NEW key!"
         RandomKeys[key] = 1
      else
         puts "n OLD key!"
      end
   }
end
                
                    
<%
On Error Resume Next

If err.Number <> 0 Then
  Response.Write "Number = " & err.Number & "<p>"
  Response.Write "Description = " & err.Description & "<p>"
  Response.Write "Source = " & err.Source
  err.Clear
End If
%>
                
                    
XML:
<addresses>
  <address>
    <name>Robert Jones</name>	
    <street>Cedar Park Way</street>
    <city>Atlanta</city>
    <postcode>30083</postcode>
  </address>
</addresses>

XSLT:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
     version="1.0">

  <xsl:output method="text"/>

  <xsl:template match="addresses">
    <xsl:apply-templates>
      <xsl:sort select="name"/>
    </xsl:apply-templates>
  </xsl:template>

  <xsl:template match="address">
	<!-- Name -->
	<p ><strong><xsl:value-of select="name"/></strong> </p>

	<!--Address-->
	<xsl:variable name="street" select="street"/>
	<xsl:if test="string($street)">
		<p ><strong>Address<br/></strong>
		<xsl:value-of select="$street" /><br/>
		<xsl:value-of select="postcode"/> <xsl:value-of select="city"/>
		</p>
	</xsl:if>  
  </xsl:template>

</xsl:stylesheet>
                
                    Grep a bunch of jars for a certain package or class or expression:

find /path/to/directory -type f -name '*.jar' -print0 | xargs -n1 -0i sh -c 'jar tf "{}" | grep -q query && echo "{}"'

E.g.

find ~/soft/java/maven-repository -type f -name '*.jar' -print0 | xargs -n1 -0i sh -c 'jar tf "{}" | grep -q org.apache && echo "{}"'
                
                    This BigDecimalFormatter tries to parse the text as BigDecimal for the current locale. It uses the BigDecimal(String) constructor to keep the number of decimals from the text.

public class BigDecimalFormatter extends NumberFormatter {
    public Object stringToValue(String text) throws ParseException {
        if("".equals(text.trim())) {
             return null;
         }
         char ds = getDefaultLocaleDecimalSeparator();

         try {
             String val = text;
             if(ds != '.') {
                 val = val.replace(".", "").replace(ds, '.');
             }
             return new BigDecimal(val);
         } catch(NumberFormatException e) {
             return null;
         }
    }

    public String valueToString(Object value) throws ParseException {
        return super.valueToString(value);
    }

    private char getDefaultLocaleDecimalSeparator() {
          DecimalFormatSymbols symbols = new DecimalFormat("0").getDecimalFormatSymbols();
          char ds = symbols.getDecimalSeparator();
          return ds;
      }

}

public class BigDecimalFormatterFactory extends JFormattedTextField.AbstractFormatterFactory {
    public JFormattedTextField.AbstractFormatter getFormatter(JFormattedTextField tf) {
        return new BigDecimalFormatter();
    }
}

Use it like this:

bigdecimalfield.setFormatterFactory(new BigDecimalFormatterFactory());
                
                    To create a borderless JButton in swing use the following:

JButton taskButton = new JButton(action);
taskButton.setBorder(BorderFactory.createEmptyBorder(2,2,2,2));
taskButton.setHorizontalAlignment(JButton.LEADING); // optional
taskButton.setBorderPainted(false);
taskButton.setContentAreaFilled(false);

This is useful for "hyperlink" style buttons or "task buttons".
                
                    To change all .htm files in a folder to .html files:

for f in *.htm; do mv $f `basename $f .htm`.html; done;
                
                    Go back to your previous directory:

cd -

Go to a new directory and push the current one onto a stack:

pushd /newdirectory

Pop a directory from the stack and go to it:

popd