DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

The Latest Popular Topics

article thumbnail
Java: RegEx: Splitting A Space-, Comma-, And Semi-colon Separated List
// Greedy RegEx quantifier used // X+ = X, one or more times // [\\s,;]+ = one or more times of either \s , or ; String test_data = "hello world, this is a test, ;again"; _logger.debug("Source: " + test_data); for (String tag : test_data.split("[\\s,;]+")) { _logger.debug("Received tag: [" + tag + "]"); }
August 5, 2007
by Snippets Manager
· 38,145 Views · 1 Like
article thumbnail
Java: Lucene: Simple In-Memory Search Example
// Adapted from http://javatechniques.com/blog/lucene-in-memory-text-search-example // Works with present APIs in Lucene 2.1.0 /** * A simple example of an in-memory search using Lucene. */ import java.io.IOException; import java.io.StringReader; import org.apache.lucene.search.Hits; import org.apache.lucene.search.Query; import org.apache.lucene.document.Field; import org.apache.lucene.search.Searcher; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.document.Document; import org.apache.lucene.store.RAMDirectory; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.analysis.standard.StandardAnalyzer; public class InMemoryExample { public static void main(String[] args) { // Construct a RAMDirectory to hold the in-memory representation // of the index. RAMDirectory idx = new RAMDirectory(); try { // Make an writer to create the index IndexWriter writer = new IndexWriter(idx, new StandardAnalyzer(), true); // Add some Document objects containing quotes writer.addDocument(createDocument("Theodore Roosevelt", "It behooves every man to remember that the work of the " + "critic, is of altogether secondary importance, and that, " + "in the end, progress is accomplished by the man who does " + "things.")); writer.addDocument(createDocument("Friedrich Hayek", "The case for individual freedom rests largely on the " + "recognition of the inevitable and universal ignorance " + "of all of us concerning a great many of the factors on " + "which the achievements of our ends and welfare depend.")); writer.addDocument(createDocument("Ayn Rand", "There is nothing to take a man’s freedom away from " + "him, save other men. To be free, a man must be free " + "of his brothers.")); writer.addDocument(createDocument("Mohandas Gandhi", "Freedom is not worth having if it does not connote " + "freedom to err.")); // Optimize and close the writer to finish building the index writer.optimize(); writer.close(); // Build an IndexSearcher using the in-memory index Searcher searcher = new IndexSearcher(idx); // Run some queries search(searcher, "freedom"); search(searcher, "free"); search(searcher, "progress or achievements"); searcher.close(); } catch (IOException ioe) { // In this example we aren’t really doing an I/O, so this // exception should never actually be thrown. ioe.printStackTrace(); } catch (ParseException pe) { pe.printStackTrace(); } } /** * Make a Document object with an un-indexed title field and an indexed * content field. */ private static Document createDocument(String title, String content) { Document doc = new Document(); // Add the title as an unindexed field… doc.add(new Field("title", title, Field.Store.YES, Field.Index.NO)); // …and the content as an indexed field. Note that indexed // Text fields are constructed using a Reader. Lucene can read // and index very large chunks of text, without storing the // entire content verbatim in the index. In this example we // can just wrap the content string in a StringReader. doc.add(new Field("content", new StringReader(content))); return doc; } /** * Searches for the given string in the "content" field */ private static void search(Searcher searcher, String queryString) throws ParseException, IOException { // Build a Query object QueryParser parser = new QueryParser("content", new StandardAnalyzer()); Query query = parser.parse(queryString); // Search for the query Hits hits = searcher.search(query); // Examine the Hits object to see if there were any matches int hitCount = hits.length(); if (hitCount == 0) { System.out.println("No matches were found for \"" + queryString + "\""); } else { System.out.println("Hits for \"" + queryString + "\" were found in quotes by:"); // Iterate over the Documents in the Hits object for (int i = 0; i < hitCount; i++) { Document doc = hits.doc(i); // Print the value that we stored in the "title" field. Note // that this Field was not indexed, but (unlike the // "contents" field) was stored verbatim and can be // retrieved. System.out.println(" " + (i + 1) + ". " + doc.get("title")); } } System.out.println(); } }
May 15, 2007
by Snippets Manager
· 6,171 Views
article thumbnail
Java DOM : Creating An XML Document From XML File
// description of your code here try { // // Create the XML Document // DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.parse(filePath); // ... } catch (Exception e) { // ... }
May 14, 2007
by Snippets Manager
· 19,202 Views
article thumbnail
How To Convert A String With A Date To A Calendar
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); Date date = sdf.parse(strDate); Calendar cal = Calendar.getInstance(); cal.setTime(date);
May 8, 2007
by Snippets Manager
· 160,467 Views · 3 Likes
article thumbnail
Draw, Plot 2d Line In C# (csharp) - Bresenham's Line Algorithm
based on wikipedia public interface ISetPixel { void SetPixel(Point point); } public partial class Algorithms2D { public delegate void SetPixel(Point point); public static void Line(Point p0,Point p1,G plot) where G:ISetPixel { int x0=p0.X; int y0=p0.Y; int x1=p1.X; int y1=p1.Y; bool steep=abs(y1-y0)>abs(x1-x0); if (steep) { swap(ref x0,ref y0); swap(ref x1,ref y1); } if (x0>x1) { swap(ref x0,ref x1); swap(ref y0,ref y1); } int deltax=x1-x0; int deltay=abs(y1-y0); int error=-deltax/2; int ystep; int y=y0; if (y00) { y=y+ystep; error=error-deltax; } } } struct CSetPixel:ISetPixel { public CSetPixel(SetPixel setPixel) { this.setPixel=setPixel; } SetPixel setPixel; #region ISetPixel Members public void SetPixel(Point point) { setPixel(point); } #endregion } public static void Line(Point p0,Point p1,SetPixel plot) { Line(p0,p1,new CSetPixel(plot)); } private static int abs(int p) { return Math.Abs(p); } private static void swap(ref T x0,ref T y0) { T z=x0; x0=y0; y0=z; } } unit tests (c# 3.0): [TestFixture] public class Line { [Test] public void LineDiagonal() { List l = new List(); Algorithms2D.Line(new Point(0,0),new Point(3,3),z=>l.Add(z)); Assert.AreEqual(3, l.Count); Assert.AreEqual(new Point(0, 0), l[0]); Assert.AreEqual(new Point(1, 1), l[1]); Assert.AreEqual(new Point(2, 2), l[2]); } [Test] public void Line45() { List l = new List(); Algorithms2D.Line(new Point(0, 0),new Point(6, 3), z => l.Add(z)); Assert.AreEqual(6, l.Count); Assert.AreEqual(new Point(0, 0), l[0]); Assert.AreEqual(new Point(1, 0), l[1]); Assert.AreEqual(new Point(2, 1), l[2]); Assert.AreEqual(new Point(3, 1), l[3]); Assert.AreEqual(new Point(4, 2), l[4]); Assert.AreEqual(new Point(5, 2), l[5]); } }
April 26, 2007
by Snippets Manager
· 4,014 Views
article thumbnail
Range() In Java
A range is a very handy feature of programing languages like Python. * range( 10 ) -> 0 1 2 3 4 5 6 7 8 9 * range( 5, 10 ) -> 5 6 7 8 9 * range( 0, 10, 3 ) -> 0 3 6 9 * range( '0', '9' ) -> 012345678 With an extended for loop it is possible to use such a feature too: /* * This project is made available under the terms of the BSD license, more information can be found at * http://www.opensource.org/licenses/bsd-license.html * * Copyright (c) 2007. Christian Ullenboom (http://www.tutego.com/) and contributors. All rights reserved. */ package com.tutego; import java.util.Iterator; /** * Class that generates immutable sequences (ranges) as Iterable * objects. A range represents a start (0 if not given), an stop (mandatory) and * an optional step (1 by default). The start value is included in the range, * the stop value is exclusive. Every range is handled by an Iterable * which can by used in an extended for loop. * * * for ( int i : range( 0, 10, 3 ) ) * System.out.print( i + " " ); // 0 3 6 9 * * * @author Christian Ullenboom (tutego) * @version 1.0 */ public class Range { public static Iterable range( final int start, final int stop, final int step ) { if ( step <= 0 ) throw new IllegalArgumentException( "step > 0 isrequired!" ); return new Iterable() { public Iterator iterator() { return new Iterator() { private int counter = start; public boolean hasNext() { return counter < stop; } public Integer next() { try { return counter; } finally { counter += step; } } public void remove() { } }; } }; } public static Iterable range( final int start, final int stop ) { return range( start, stop, 1 ); } public static Iterable range( final int stop ) { return range( 0, stop, 1 ); } } This is an example: package com.tutego; import static com.tutego.Range.range; public class RangeDemo { public static void main( String[] args ) { for ( int i : range( 10 ) ) System.out.print( i + " " ); System.out.println(); for ( int i : range( 5, 10 ) ) System.out.print( i + " " ); System.out.println(); for ( int i : range( 0, 10, 3 ) ) System.out.print( i + " " ); System.out.println(); for ( int i : range( '0', '9' ) ) System.out.print( (char) i ); System.out.println(); String[] a = { "Mary", "had", "a", "little", "lamb" }; for ( int i : range(a.length ) ) System.out.printf( "%d %s%n", i, a[i] ); } }
April 24, 2007
by Snippets Manager
· 32,537 Views · 1 Like
article thumbnail
Get MD5 Hash In A Few Lines Of Java
1 import java.security.*; 2 import java.math.*; 3 4 public class MD5 { 5 public static void main(String args[]) throws Exception{ 6 String s="This is a test"; 7 MessageDigest m=MessageDigest.getInstance("MD5"); 8 m.update(s.getBytes(),0,s.length()); 9 System.out.println("MD5: "+new BigInteger(1,m.digest()).toString(16)); 10 } 11 }
March 18, 2007
by Greg Miller
· 45,968 Views · 2 Likes
article thumbnail
JavaScript: Programmatically Click The Form Submit Button
// Programmatically Click the Form Submit Button // by using the 'click()' method submitTags : function() { var btnSubmitTags = document.getElementById( TagsHelperConfig.FORM_TAGS_ENTRY_SUBMIT_BUTTON_ID ); // Programmatically click the submit button btnSubmitTags.click(); }
March 6, 2007
by Snippets Manager
· 12,372 Views · 3 Likes
article thumbnail
Add A Jar File To Java Load Path At Run Time
import java.net.URL; import java.io.IOException; import java.net.URLClassLoader; import java.net.MalformedURLException; public class JarFileLoader extends URLClassLoader { public JarFileLoader (URL[] urls) { super (urls); } public void addFile (String path) throws MalformedURLException { String urlPath = "jar:file://" + path + "!/"; addURL (new URL (urlPath)); } public static void main (String args []) { try { System.out.println ("First attempt..."); Class.forName ("org.gjt.mm.mysql.Driver"); } catch (Exception ex) { System.out.println ("Failed."); } try { URL urls [] = {}; JarFileLoader cl = new JarFileLoader (urls); cl.addFile ("/opt/mysql-connector-java-5.0.4/mysql-connector-java-5.0.4-bin.jar"); System.out.println ("Second attempt..."); cl.loadClass ("org.gjt.mm.mysql.Driver"); System.out.println ("Success!"); } catch (Exception ex) { System.out.println ("Failed."); ex.printStackTrace (); } } }
February 23, 2007
by Snippets Manager
· 31,555 Views
article thumbnail
Retrieving All Parameters to a Java Servlet
Here's a really simple code snippet for retrieving parameters to a Java servlet.
February 10, 2007
by Snippets Manager
· 27,180 Views · 2 Likes
article thumbnail
Algorithm For Calculating The Date Of Easter Sunday
/// /// Algorithm for calculating the date of Easter Sunday /// (Meeus/Jones/Butcher Gregorian algorithm) /// http://en.wikipedia.org/wiki/Computus#Meeus.2FJones.2FButcher_Gregorian_algorithm /// /// A valid Gregorian year /// Easter Sunday public static DateTime EasterDate(int year) { int Y = year; int a = Y % 19; int b = Y / 100; int c = Y % 100; int d = b / 4; int e = b % 4; int f = (b + 8) / 25; int g = (b - f + 1) / 3; int h = (19 * a + b - d - g + 15) % 30; int i = c / 4; int k = c % 4; int L = (32 + 2 * e + 2 * i - h - k) % 7; int m = (a + 11 * h + 22 * L) / 451; int month = (h + L - 7 * m + 114) / 31; int day = ((h + L - 7 * m + 114) % 31) + 1; DateTime dt = new DateTime(year, month, day); return dt; } Easter Monday = Easter Sunday + 1 Ascension Day = Easter Sunday + 39 Pentecost Sunday = Easter Sunday + 49 Pentecost Monday = Easter Sunday + 50
September 27, 2005
by Snippets Manager
· 14,969 Views
  • Previous
  • ...
  • 571
  • 572
  • 573
  • 574
  • 575
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook
×