Never been to DZone Snippets before?

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

« Newer Snippets
Older Snippets »
Showing 1-10 of 24 total  RSS 

DOM Parser Demo Code

//above class will search a movie/actor/producer name & will accordingly print other
//details
import javax.swing.text.html.parser.DocumentParser;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.util.*;
public class Movie_XML implements Movie
{

ArrayList<MovieDB> movies = new ArrayList<MovieDB>();

public ArrayList<MovieDB> searchByActorName(String nm,String key)
{
try
{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse("movie.xml");
NodeList nodeList = null;

if(key.equalsIgnoreCase("actor"))
nodeList = doc.getElementsByTagName("actor");
else if(key.equalsIgnoreCase("movie"))
nodeList = doc.getElementsByTagName("name");
else
nodeList = doc.getElementsByTagName("producer");

Node temp = null, parent=null;
NodeList childs = null;
for(int i=0;i<nodeList.getLength();i++)
{
temp = nodeList.item(i);
if(temp.getTextContent().equalsIgnoreCase(nm))
{
parent = temp.getParentNode();
childs = parent.getChildNodes();
MovieDB mDB = new MovieDB();
for(int j=0;j<childs.getLength();j++)
{
Node nd = childs.item(j);
if(nd.getNodeType() == Node.ELEMENT_NODE)
{
String name = nd.getNodeName();
//System.out.println(name);
if(name.equalsIgnoreCase("id"))
{
mDB.setId(nd.getTextContent());
}
if(name.equalsIgnoreCase("name"))
{
mDB.setName(nd.getTextContent());
}
if(name.equalsIgnoreCase("producer"))
{
mDB.setProducer(nd.getTextContent());
}
if(name.equalsIgnoreCase("director"))
{
mDB.setDirector(nd.getTextContent());
}
if(name.equalsIgnoreCase("music_director"))
{
mDB.setMusic_director(nd.getTextContent());
}
if(name.equalsIgnoreCase("actor"))
{
mDB.setActor(nd.getTextContent());
}
if(name.equalsIgnoreCase("actress"))
{
mDB.setActress(nd.getTextContent());
}
}
}
movies.add(mDB);
}
}
return movies;
}
catch(Exception e)
{
throw new CustomException("err in Searching by actor name",e);
}
}
}


//this class will call the above class by sending appropriate parmeters

import java.util.*;
import java.io.*;
public class XMLDemo
{
public static void main(String[] args)
{
try
{
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
while(true)
{
System.out.println("\n Enter the Choice : ");
System.out.println(" 1 : Search By Actor Name : ");
System.out.println(" 2 : Search By Movie Name : ");
System.out.println(" 3 : Search By Producer Name : ");
System.out.println(" 4 : Quit : ");
try
{
int ch = Integer.parseInt(br.readLine());
switch(ch)
{
case 1 :
System.out.println("Enter Actor Name : ");
String actorName = br.readLine();
search(actorName,"actor");
break;
case 2 :
System.out.println("Enter Movie Name");
String movieName = br.readLine();
search(movieName,"movie");
break;
case 3 :
System.out.println("Enter Producer Name");
String producerName = br.readLine();
search(producerName,"producer");
break;
case 4 :
System.out.println("Exiting");
System.exit(0);
default :
System.out.println("Invalid Choice !");
}
}
catch(Exception e)
{
System.out.println("Invalid Choice !");
}
}//end of while
}
catch(Exception e)
{
//e.printStackTrace();
throw new CustomException("err in main",e);
}
}

static void search(String name,String key)
{
try
{
ArrayList<MovieDB> movies = new ArrayList<MovieDB>();
Movie_XML obj = new Movie_XML();
movies = obj.searchByActorName(name,key);
int i =0;
System.out.println();
for(i=0;i<movies.size();i++)
{
MovieDB mDB = movies.get(i);
System.out.println("ID : "+mDB.getId());
System.out.println("Name : "+mDB.getName());
System.out.println("Producer : "+mDB.getProducer());
System.out.println("Director : "+mDB.getDirector());
System.out.println("Music : "+mDB.getMusic_director());
System.out.println("Actor : "+mDB.getActor());
System.out.println("Actress : "+mDB.getActress());
}
System.out.println(i+" Record Found!");
}
catch(Exception e)
{
throw new CustomException("err in byActor",e);
}
}
}

//this class will hold the details of the movie(id,name,---)

import java.util.*;
public class MovieDB
{
private String id,name,year;
private ArrayList<String> actor,actress;
private String director,producer,music_director;

public MovieDB()
{
actor = new ArrayList<String>();
actress = new ArrayList<String>();
}

public void setId(String id)
{
this.id = id;
}

public void setName(String name)
{
this.name = name;
}

public void setYear(String year)
{
this.year = year;
}

public void setDirector(String director)
{
this.director = director;
}

public void setProducer(String producer)
{
this.producer = producer;
}

public void setMusic_director(String music_director)
{
this.music_director = music_director;
}

public void setActor(String actor)
{
this.actor.add(actor);
}

public void setActress(String actress)
{
this.actress.add(actress);
}

public String getId()
{
return id;
}

public String getName()
{
return name;
}

public String getProducer()
{
return producer;
}

public String getDirector()
{
return director;
}

public String getMusic_director()
{
return music_director;
}

public ArrayList<String> getActor()
{
return actor;
}

public ArrayList<String> getActress()
{
return actress;
}
}


//movie interface

import java.util.*;
public interface Movie
{
public ArrayList<MovieDB> searchByActorName(String nm,String key);
}

DOM Parser Demo Code

//above class will search a movie/actor/producer name & will accordingly print other
//details
import javax.swing.text.html.parser.DocumentParser;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.util.*;
public class Movie_XML implements Movie
{

ArrayList<MovieDB> movies = new ArrayList<MovieDB>();

public ArrayList<MovieDB> searchByActorName(String nm,String key)
{
try
{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse("movie.xml");
NodeList nodeList = null;

if(key.equalsIgnoreCase("actor"))
nodeList = doc.getElementsByTagName("actor");
else if(key.equalsIgnoreCase("movie"))
nodeList = doc.getElementsByTagName("name");
else
nodeList = doc.getElementsByTagName("producer");

Node temp = null, parent=null;
NodeList childs = null;
for(int i=0;i<nodeList.getLength();i++)
{
temp = nodeList.item(i);
if(temp.getTextContent().equalsIgnoreCase(nm))
{
parent = temp.getParentNode();
childs = parent.getChildNodes();
MovieDB mDB = new MovieDB();
for(int j=0;j<childs.getLength();j++)
{
Node nd = childs.item(j);
if(nd.getNodeType() == Node.ELEMENT_NODE)
{
String name = nd.getNodeName();
//System.out.println(name);
if(name.equalsIgnoreCase("id"))
{
mDB.setId(nd.getTextContent());
}
if(name.equalsIgnoreCase("name"))
{
mDB.setName(nd.getTextContent());
}
if(name.equalsIgnoreCase("producer"))
{
mDB.setProducer(nd.getTextContent());
}
if(name.equalsIgnoreCase("director"))
{
mDB.setDirector(nd.getTextContent());
}
if(name.equalsIgnoreCase("music_director"))
{
mDB.setMusic_director(nd.getTextContent());
}
if(name.equalsIgnoreCase("actor"))
{
mDB.setActor(nd.getTextContent());
}
if(name.equalsIgnoreCase("actress"))
{
mDB.setActress(nd.getTextContent());
}
}
}
movies.add(mDB);
}
}
return movies;
}
catch(Exception e)
{
throw new CustomException("err in Searching by actor name",e);
}
}
}


//this class will call the above class by sending appropriate parmeters

import java.util.*;
import java.io.*;
public class XMLDemo
{
public static void main(String[] args)
{
try
{
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
while(true)
{
System.out.println("\n Enter the Choice : ");
System.out.println(" 1 : Search By Actor Name : ");
System.out.println(" 2 : Search By Movie Name : ");
System.out.println(" 3 : Search By Producer Name : ");
System.out.println(" 4 : Quit : ");
try
{
int ch = Integer.parseInt(br.readLine());
switch(ch)
{
case 1 :
System.out.println("Enter Actor Name : ");
String actorName = br.readLine();
search(actorName,"actor");
break;
case 2 :
System.out.println("Enter Movie Name");
String movieName = br.readLine();
search(movieName,"movie");
break;
case 3 :
System.out.println("Enter Producer Name");
String producerName = br.readLine();
search(producerName,"producer");
break;
case 4 :
System.out.println("Exiting");
System.exit(0);
default :
System.out.println("Invalid Choice !");
}
}
catch(Exception e)
{
System.out.println("Invalid Choice !");
}
}//end of while
}
catch(Exception e)
{
//e.printStackTrace();
throw new CustomException("err in main",e);
}
}

static void search(String name,String key)
{
try
{
ArrayList<MovieDB> movies = new ArrayList<MovieDB>();
Movie_XML obj = new Movie_XML();
movies = obj.searchByActorName(name,key);
int i =0;
System.out.println();
for(i=0;i<movies.size();i++)
{
MovieDB mDB = movies.get(i);
System.out.println("ID : "+mDB.getId());
System.out.println("Name : "+mDB.getName());
System.out.println("Producer : "+mDB.getProducer());
System.out.println("Director : "+mDB.getDirector());
System.out.println("Music : "+mDB.getMusic_director());
System.out.println("Actor : "+mDB.getActor());
System.out.println("Actress : "+mDB.getActress());
}
System.out.println(i+" Record Found!");
}
catch(Exception e)
{
throw new CustomException("err in byActor",e);
}
}
}

//this class will hold the details of the movie(id,name,---)

import java.util.*;
public class MovieDB
{
private String id,name,year;
private ArrayList<String> actor,actress;
private String director,producer,music_director;

public MovieDB()
{
actor = new ArrayList<String>();
actress = new ArrayList<String>();
}

public void setId(String id)
{
this.id = id;
}

public void setName(String name)
{
this.name = name;
}

public void setYear(String year)
{
this.year = year;
}

public void setDirector(String director)
{
this.director = director;
}

public void setProducer(String producer)
{
this.producer = producer;
}

public void setMusic_director(String music_director)
{
this.music_director = music_director;
}

public void setActor(String actor)
{
this.actor.add(actor);
}

public void setActress(String actress)
{
this.actress.add(actress);
}

public String getId()
{
return id;
}

public String getName()
{
return name;
}

public String getProducer()
{
return producer;
}

public String getDirector()
{
return director;
}

public String getMusic_director()
{
return music_director;
}

public ArrayList<String> getActor()
{
return actor;
}

public ArrayList<String> getActress()
{
return actress;
}
}


//movie interface

import java.util.*;
public interface Movie
{
public ArrayList<MovieDB> searchByActorName(String nm,String key);
}

dbg - debuging routine

A handy little routine to debug autoit scripts

   1  
   2  dbg("Log this message")
   3  Func dbg($msg, $error=@error, $extended=@extended, $ScriptLineNumber=@ScriptLineNumber)
   4      Local $out = "(" & $ScriptLineNumber & ")(" & $error & ")(" & $extended & ") := " & $msg 
   5      ;Output to application attaching a console to the script engine
   6      ConsoleWrite($msg & @CRLF)
   7      ;Output to debugger (dbgview.exe)
   8      DllCall("kernel32.dll", "none", "OutputDebugString", "str", $out)
   9  EndFunc

Generate combinations

Code generates all the combinations of n elements choosing k elements.

See this for definition.

See this for explanation.

   1  
   2  #include <stdio.h>
   3  
   4  /* Prints out a combination like {1, 2} */
   5  void printc(int comb[], int k) {
   6  	printf("{");
   7  	int i;
   8  	for (i = 0; i < k; ++i)
   9  		printf("%d, ", comb[i] + 1);
  10  	printf("\b\b}\n");
  11  }
  12  
  13  /*
  14  	next_comb(int comb[], int k, int n)
  15  		Generates the next combination of n elements as k after comb
  16  
  17  	comb => the previous combination ( use (0, 1, 2, ..., k) for first)
  18  	k => the size of the subsets to generate
  19  	n => the size of the original set
  20  
  21  	Returns: 1 if a valid combination was found
  22  		0, otherwise
  23  */
  24  int next_comb(int comb[], int k, int n) {
  25  	int i = k - 1;
  26  	++comb[i];
  27  	while ((i >= 0) && (comb[i] >= n - k + 1 + i)) {
  28  		--i;
  29  		++comb[i];
  30  	}
  31  
  32  	if (comb[0] > n - k) /* Combination (n-k, n-k+1, ..., n) reached */
  33  		return 0; /* No more combinations can be generated */
  34  
  35  	/* comb now looks like (..., x, n, n, n, ..., n).
  36  	Turn it into (..., x, x + 1, x + 2, ...) */
  37  	for (i = i + 1; i < k; ++i)
  38  		comb[i] = comb[i - 1] + 1;
  39  
  40  	return 1;
  41  }
  42  
  43  int main(int argc, char *argv[]) {
  44  	int n = 5; /* The size of the set; for {1, 2, 3, 4} it's 4 */
  45  	int k = 3; /* The size of the subsets; for {1, 2}, {1, 3}, ... it's 2 */
  46  	int comb[16]; /* comb[i] is the index of the i-th element in the
  47  			combination */
  48  
  49  	/* Setup comb for the initial combination */
  50  	int i;
  51  	for (i = 0; i < k; ++i)
  52  		comb[i] = i;
  53  
  54  	/* Print the first combination */
  55  	printc(comb, k);
  56  
  57  	/* Generate and print all the other combinations */
  58  	while (next_comb(comb, k, n))
  59  		printc(comb, k);
  60  
  61  	return 0;
  62  }
  63  

Permutations

Generates all permutation of n. Uses the naive (stupid) "let's generate all imaginable possibilities and see which are permutations" algorithm.

Time: O(n!)

   1  
   2  #include <stdio.h>
   3  
   4  int next(int v[], int n) {
   5  	int i = n - 1;
   6  	v[i] = v[i] + 1;
   7  	while ((i >= 0) && (v[i] > n)) {
   8  		v[i] = 1;
   9  		i--;
  10  		if(i >= 0)
  11  			v[i]++;
  12  	}
  13  
  14  	if (i < 0)
  15  		return 0;
  16  	return 1;
  17  }
  18  
  19  void printv(int v[],int n) {
  20  	int i;
  21  
  22  	for (i = 0; i < n; i++)
  23  		printf("%d", v[i]);
  24  	printf("\n");
  25  }
  26  
  27  int is_perm(int v[], int n) {
  28  	int i, j;
  29  
  30  	for (i = 0; i < n; i++)
  31  		for (j = i + 1; j < n; j++)
  32  			if (v[i] == v[j])
  33  				return 0;
  34  
  35  	return 1;
  36  }
  37  
  38  int main(int argc, char *argv[]) {
  39  	int v[128];
  40  	int n = 6;
  41  	int i;
  42  	for(i = 0; i <= n; i++)
  43  		v[i] = i + 1;
  44  
  45  	while (next(v,n))
  46  		if (is_perm(v,n))
  47  			printv(v,n);
  48  
  49  	return 0;
  50  }

The Qeens Problem

Prints all valid ways to arrange n qeens on a n x n chessboard so that the qeens don't attack each other.

   1  
   2  #include <iostream>
   3  #include <vector>
   4  
   5  typedef std::vector< int > Vect;
   6  typedef std::vector< Vect > List;
   7  
   8  const int n = 12;
   9  
  10  bool checkRow(const Vect &v, int k) {
  11  	for (int i = k - 1; i >= 0; --i)
  12  		if (v[k] == v[i])
  13  			return false;
  14  
  15  	return true;
  16  }
  17  
  18  bool checkDiag(const Vect &v, int k) {
  19  	for (int i = k - 1; i >= 0; --i)
  20  		if (k - i == abs(v[k] - v[i]))
  21  			return false;
  22  	
  23  	return true;
  24  }
  25  
  26  List filter(List l, int k) {
  27  	List r;
  28  	for (List::const_iterator it = l.begin(); it != l.end(); ++it) {
  29  		if (checkRow(*it, k) && checkDiag(*it, k))
  30  			r.push_back(*it);
  31  	}
  32  	
  33  	return r;
  34  }
  35  
  36  List qeens(int k) {
  37  	if (0 == k) {
  38  		List l;
  39  		l.push_back(Vect());
  40  		return l;
  41  	}
  42  	
  43  	List l = qeens(k - 1);
  44  	List r;
  45  	for (List::iterator it = l.begin(); it != l.end(); ++it) {
  46  		for (int newRow = 1; newRow <= n; ++newRow) {
  47  			Vect v(*it);
  48  			v.push_back(newRow);
  49  			r.push_back(v);
  50  		}
  51  	}
  52  	
  53  	r = filter(r, k - 1);
  54  	
  55  	return r;
  56  }
  57  
  58  void printS(List l) {
  59  	for (List::const_iterator it = l.begin(); it != l.end(); ++it) {
  60  		for (Vect::const_iterator jt = it->begin(); jt != it->end(); ++jt)
  61  			std::cout << *jt << " ";
  62  		std::cout << std::endl;
  63  	}
  64  }
  65  
  66  int main(int argc, char *argv[]) {
  67  	List l = qeens(n);
  68  	
  69  	printS(l);
  70  	
  71  	return 0;
  72  }
  73  

Quicksort

Qucksort written in C. Uses the Hoare partition algorithm.

   1  
   2  typedef struct {
   3  	int len;
   4  	int elem[50240];
   5  } vector;
   6  
   7  void printv(char *str, vector v) {
   8  	printf("%s", str);
   9  	int i = 0;
  10  	for (; i < v.len; ++i)
  11  		printf("%d ", v.elem[i]);
  12  	printf("\n");
  13  }
  14  
  15  #define MAX(a, b) ((a > b) ? (a) : (b))
  16  #define MIN(a, b) ((a < b) ? (a) : (b))
  17  
  18  int partition(vector *v, int p, int r) {
  19  	int x;
  20  	if (p + 3 < r)
  21  		x = MIN(v->elem[p], MAX(v->elem[p+1], v->elem[p+2]));
  22  	else
  23  		x = v->elem[p];
  24  	
  25  	int i = p - 1;
  26  	int j = r + 1;
  27  	while (1) {
  28  		do {
  29  			--j;
  30  		} while (v->elem[j] > x);
  31  		do {
  32  			++i;
  33  		} while (v->elem[i] < x);
  34  
  35  		if (i < j) {
  36  			int aux = v->elem[j];
  37  			v->elem[j] = v->elem[i];
  38  			v->elem[i] = aux;
  39  		} else
  40  			return j;			
  41  	}
  42  }
  43  
  44  void quicksort_real(vector *v, int p, int r) {
  45  	if (p < r) {
  46  		int q = partition(v, p, r);
  47  		quicksort_real(v, p, q);
  48  		quicksort_real(v, q + 1, r);
  49  	}
  50  }
  51  
  52  void quicksort(vector *v) {
  53  	printf("Quicksort...\n");
  54  	quicksort_real(v, 0, v->len - 1);
  55  }

Strange square

For n = 8, builds
1 1 1 1 1 1 1 0
1 1 1 1 1 1 0 0
1 1 1 1 1 0 1 0
1 1 1 1 0 0 0 0
1 1 1 0 1 1 1 0
1 1 0 0 1 1 0 0
1 0 1 0 1 0 1 0
0 0 0 0 0 0 0 0

The algorithm, for a n x n matrix is:
1. Split the matrix into 4 matrices of the same size
2. Complete the top-left one with 1
3. Repeat for each of the other 3 matrices.

   1  
   2  #include <stdio.h>
   3  #include <stdlib.h>
   4  
   5  int n;
   6  int **T;
   7  
   8  void printM() {
   9  	int i,
  10  		j;
  11  	printf("\n");
  12  	for (i = 0; i < n; ++i) {
  13  		for (j = 0; j < n; ++j)
  14  			printf("%d ", T[i][j]);
  15  		printf("\n");
  16  	}
  17  }
  18  
  19  void fill(int x1, int y1, int x2, int y2) {
  20  	printf("%d %d %d %d\n", x1, y1, x2, y2);
  21  	//getchar();
  22  	
  23  	if (x1 == x2) {
  24  		//T[x1][y1] = 1;
  25  		return;
  26  	}
  27  	
  28  	int i,
  29  		j;
  30  	int xm = (x1 + x2) / 2;
  31  	int ym = (y1 + y2) / 2;
  32  	for (i = y1; i <= ym; ++i)
  33  		for (j = x1; j <= xm; ++j)
  34  			T[i][j] = 1;
  35  	
  36  	fill(x1, ym + 1, xm, y2);
  37  	fill(xm + 1, y1, x2, ym);
  38  	fill(xm + 1, ym + 1, x2, y2);
  39  }
  40  
  41  int main(int argc, char *argv[]) {
  42  	n = 8;
  43  	T = (int**)malloc(n * sizeof(int*));
  44  	int i;
  45  	for (i = 0; i < n; ++i)
  46  		T[i] = (int*)malloc(n * sizeof(int));
  47  	
  48  	int j;
  49  	for (i = 0; i < n; ++i)
  50  		for (j = 0; j < n; ++j)
  51  			T[i][j] = 0;
  52  	
  53  	fill(0, 0, n - 1, n - 1);
  54  	printM();
  55  	
  56  	return 0;
  57  }

C - Simple Example GTK

// gcc file.c -o file.o `pkg-config --libs --cflags gtk+-2.0`

   1  
   2  #include <gtk/gtk.h>
   3  #include <stdlib.h>
   4  
   5  void displayUI()
   6  {
   7  	GtkWidget* mainWindow = gtk_window_new(GTK_WINDOW_TOPLEVEL);
   8  
   9  	gtk_window_set_default_size(GTK_WINDOW(mainWindow), 400, 300);
  10  	gtk_window_set_title(GTK_WINDOW(mainWindow), "GTK Simple Example");
  11  	gtk_window_set_position(GTK_WINDOW(mainWindow), GTK_WIN_POS_CENTER_ALWAYS);
  12  
  13  	gtk_signal_connect(GTK_OBJECT(mainWindow), "destroy", G_CALLBACK(gtk_main_quit), NULL);
  14  
  15  	gtk_widget_show_all(mainWindow);
  16  }
  17  
  18  int main(int argc, char *argv[])
  19  {
  20  	gtk_init(&argc, &argv);
  21  
  22  	displayUI();
  23  
  24  	gtk_main();
  25  
  26  	return EXIT_SUCCESS;
  27  }

Ruby - Sostituire elementi

// Sostituisce "old" con "new" in tutti i file

   1  
   2  ruby .i.bak -pe 'sub "old", "new"' *
« Newer Snippets
Older Snippets »
Showing 1-10 of 24 total  RSS