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

                    
mysql -uroot -p
mysql> CREATE DATABASE staff_hieraki;
mysql> GRANT ALL PRIVILEGES ON staff_hieraki.* TO staff@localhost IDENTIFIED BY 'password-goes-here' WITH GRANT OPTION;
                
                    Preview what you type in an input or a textarea out of them (in a html tag, like a p, hx...)

Seen here: http://amuchamu.bitacoras.com/archivos/2005/02/17/previsualizacion_de_comentarios (spanish explain).

javascript code:

function preview(id1, id2){
	  		var NewText = document.getElementById(id1).value;
	  		splitText = NewText.split(/\n/).join("<br />");
	  		var DivElement = document.getElementById(id2);
	  		DivElement.innerHTML = splitText;
}


html code:

<form action="#">
<label>Name:</label>
<input type="text" id="nombre" onkeyup="preview('name', 'preview-name');" />

<label>Phone:</label>
<input type="text" id="phone" onkeyup="preview('phone', 'preview-phone');" />
</form>

<h2>Preview</h2>
<dl>
	<dt>Name:</dt>
	<dd id="preview-name"></dd>
	<dt>Phone:</dt>
	<dd id="preview-phone"></dd>

</dl>
                
                    This function transforms an HTTP request path (ie, $_SERVER['PATH_INFO']) into its canonical form, removing empty path elements and relative path elements (//, /./, /../). It assumes that there is a trailing slash on the path if it's a directory.

function canonical_path($path) {
    $canonical = preg_replace('|/\.?(?=/)|','',$path);
    while (($collapsed = preg_replace('|/[^/]+/\.\./|','/',$canonical,1)) !== $canonical) {
        $canonical = $collapsed;
    }
    $canonical = preg_replace('|^/\.\./|','/',$canonical);
    return $canonical;
}
                
                    The following code is for loading Velocity resources (i.e. Velocity files) from a web application's ServletContext.

import java.io.InputStream;

import javax.servlet.ServletContext;

import org.apache.commons.collections.ExtendedProperties;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.resource.Resource;
import org.apache.velocity.runtime.resource.loader.ResourceLoader;

public class WebAppResourceLoader extends ResourceLoader {

    private static ServletContext context = null;

    public void init(ExtendedProperties extendedProperties) {

    }

    private static ServletContext getServletContext() {
        return context;
    }

    public static void setServletContext(ServletContext context) {
        WebAppResourceLoader.context = context;
    }

    /**
     * @see org.apache.velocity.runtime.resource.loader.ResourceLoader#getResourceStream(java.lang.String)
     */
    public InputStream getResourceStream(String name)
            throws ResourceNotFoundException {
        InputStream result = null;

        if (name == null || name.length() == 0) {
            throw new ResourceNotFoundException("No template name provided");
        }

        try {
            if (!name.startsWith("/"))
                name = "/" + name;

            result = getServletContext().getResourceAsStream(name);
        } catch (NullPointerException npe) {
            throw new ResourceNotFoundException("ServletContext not found");
        } catch (Exception fnfe) {
            throw new ResourceNotFoundException(fnfe.getMessage());
        }

        return result;
    }

    public boolean isSourceModified(Resource arg0) {
        return false;
    }

    public long getLastModified(Resource arg0) {
        return 0;
    }

}

Then to initialize Velocity:

    WebAppResourceLoader.setServletContext(servletContext);
    Properties props = new Properties();
    props.setProperty("resource.loader", "webapp");
    props.setProperty("webapp.resource.loader.description", 
        "Load from the ServletContext");
    props.setProperty("webapp.resource.loader.class",
        "package.WebAppResourceLoader");
    Velocity.init(props);

From then on out you can use #parse directives such as:

#parse("/WEB-INF/something.vm")
                
                    
EXPLAIN SELECT ... WHERE ...
Explain will tell you if your index work as you thought.

(I forgot to login in the last two snippets)                
                    Here is a quick way to convert database records to XML using XML::Simple.

#!/usr/bin/perl

use warnings;
use strict;
use XML::Simple;
use DBI;

my $dbh = DBI->connect('DBI:mysql:MYDATABASE','user','password')
  or die DBI->errstr;

# Get an array of hashes
my $recs = $dbh->selectall_arrayref('SELECT * FROM contents',{ Columns => {} });

# Convert to XML where each hash element becomes an XML element
my $xml = XMLout( {record => $recs}, NoAttr => 1 );

print $xml;

$dbh->disconnect;

For a table with fields named "id", "entry", and "modified", the output would be:

<opt>
  <record>
    <id>1</id>
    <entry>1932 - 1939</entry>
    <modified>2005-04-15 22:24:44</modified>
  </record>
  <record>
    <id>2</id>
    <entry>Yet another entry</entry>
    <modified>2005-04-15 22:25:00</modified>
  </record>
  <record>
    <id>3</id>
    <entry>More stuff here</entry>
    <modified>2005-04-15 22:25:13</modified>
  </record>
</opt>
                
                    You can use curl on the command line to do a POST to an endpoint. 

echo '<doc><item>Some content.</item></doc>' | curl -X POST -H 'Content-type: text/xml' -d @- http://example.com/restapi

This is handy for adding web services to applications that do not do web services but can do command lines--FileMaker for example.                
                    This will replace your H1 tag with a 100px by 100px logo.
Users with CSS disabled will see whatever is in 
<h1>Company Inc.</h1>
users with CSS will see the Company Inc. logo
to use this, add  this to your stylesheet:
h1 {
	text-indent: -100em;
	overflow: hidden;
	background: url(logo.png) no-repeat;
	height: 100px;
	width: 100px;
	}
                
                    module MetaBottle
  def self.make(x)
    Class.new do
      define_method(:bottle) do
        case x
        when 0 then "no more bottles"
        when 1 then "1 bottle"
        else        "#{x} bottles"
        end + " of beer"
      end
      define_method(:bottle_minus_one) do
        case x - 1
        when 0 then "no more bottles"
        when 1 then "1 bottle"
        else        "#{x} bottles"
        end + " of beer"
      end
      define_method(:to_s) do
        return <<T
#{bottle} on the wall, #{bottle},
take one down, pass it around,
#{bottle_minus_one} on the wall.\n
T
      end
    end
  end
end

(1..99).map { |x| MetaBottle.make(x) }.reverse_each do |bottle_class|
  bottle = bottle_class.new
  puts bottle
end
                
                    
javascript:q=document.getSelection();for(i=0;i<frames.length;i++){q=frames[i].document.getSelection();if(q)break;}if(!q)void(q=prompt('Statistically Improbable Phrase:',''));if(q)location.href='http://www.amazon.com/gp/phrase/'+escape(q)+'/ref=sip_bod_0/103-6410487-8187016'