School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!
Welcome to Dream.In.Code
Become an Expert!

Join 340,029 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 4,087 people online right now. Registration is fast and FREE... Join Now!



  • (13 Pages)
  • +
  • 1
  • 2
  • 3
  • Last »

Best Way to Improve Your Code... A Vacation

Posted by Martyr2  Icon, 14 January 2010 - 07:12 PM

The idea of taking a sizable break is bantered around from time to time as coding lore, but does it really work? In my opinion it sure does! Newbies and experts alike underestimate the mind when it comes to problem solving and always wonder what is the fountain of youth when it comes to thinking with code clarity. Those of us who go to work to write code for others and then come home to write code for ourselves on a day in and day out basis tend to forget that we really do need a break from time to time. Oh I am not talking about the simple 15 minute break to grab a bite, you should be doing that out of habit, and I am not talking about even the day or weekend off without a single if statement. I am talking about a solid week or so of no compilers, no code, no books on computer science or even technology if you can help it. Ok, maybe the technology part is a bit too far, but you get the idea.

I am one of those people who tends to think about code even when I am not physically at a computer. I think about code when I watch TV or when I am on my way to work to write code. I think about it in the shower or when I walk near the water front. I am a bit of an addict.

Recently I took a trip back to the "motherland" of Seattle Washington, between the holidays, where I spent the better part of a full week chilling and taking in the sights. Little did I know that I was not only having fun, but I was recharging the code machine which is my mind.

Coming back home to Vancouver I slowly got back into my usual routine again of code code and more code. However, things were a bit different. Not only was I writing great code (which I tend to think I do well on any given day), but I was also problem solving extraordinarily well, even for myself. I was looking at code I had written before I left and seeing ways to improve it left and right. Refactoring and simplifying was not only shortening the code but also making it extremely bullet proof... much to my disbelief. I have been writing some extremely powerful stuff since that trip and I am now not only a believer in the occasional code break, but a new believer in the idea of longer breaks to improve the way you code.

Of course there is always the idea of too much of a good thing being bad and I am not advising taking too long of breaks. I feel that a week is really the ideal length to improve what you know without losing any of it. So if you are new or an old hat to programming, be sure you plan that vacation from time to time and STAY AWAY FROM CODE. In the end I think you will be glad you did. You may even find yourself newly motivated and enjoying the 0's and 1's a little "bit" more. I will be sure to take more of these breaks in the future!

Thanks for reading! :)

Filed in Deep Underground (misc)

Reflective N-bit Binary Gray Code Using Ruby

Posted by Martyr2  Icon, 05 December 2009 - 11:28 AM

So what is behind the theory of binary gray code? It was named after Frank Gray and is a numerical system where each successive value differs from the one before it by one bit value. It is like counting in binary, but in binary counting a step may require changing two bits. For instance going from 1 (01) to 2 (10) would involve changing the most significant value 1 to a zero and then changing the next bit to a 1. This would be a two step process. In gray code you would go from 01 to 11 and then to 10. Notice on each of these steps we only change one bit. Gray code is currently being used in the digital communications industry to clean up and error correct signals for things like your digital TV. So if your tv signals are getting smashed during an episode of the Teletubbies, it could be Frank Gray who comes to your (or Tinkie Winkie's) rescue! The theory behind it is not that hard once you understand you can only change one bit at a time. We will cover how to do produce gray code using the reflective method using our good old friend Ruby right here on the Programming underground!

<Nickelback singing their kick ass single "Code Rockstar">

Before we start, I have to admit that Ruby makes this whole process ridiculously easy. I don't think anyone can doubt the expressive power of the language. Implementing this reflective method in another language would be a bit more drawn out. My only beef with Ruby is that it is too expressive. Ruby enthusiasts often spend their time on boards arguing which of their methods are the "most compact and elegant" even though they all work equally well. You often can solve the same problems a hundred different ways.

Back to our gray code, there are many ways to do it but by far the most common is what is called "Reflected binary code" in which we use binary values only (even though you can us other base values) and follow a process of taking each bit, reversing it, prepending a 0 to the first unreflected array elements and prepending a 1 to the reflected array elements and simply concatenating them together. Below we demonstrate how this works...

// Original bits
0, 1

// Get a reverse version
1, 0

// Prepend 0 to the original bits
00, 01

// Prepend 1 to the reverse version
11, 10

// Add reverse onto new original
00, 01, 11, 10



Pretty straight forward right? As long as we follow these steps on each iteration we will be golden. The trick here is that you can do this iteratively or of course recursively. In my example below I create a recursive version which is typically the most sought after solution and the solution most asked for from any classes that may deal with an example in gray code. First thing is first and we will create a function called "graycode" and pass to it an array and the number of iterations we want to go through. Like all recursive functions, the first thing we should think about is hitting our "base case" which is the case where we need to signal to the process when we have hit the end of the road. Our end of the road is when our value passed into the function is less than 1. On each successive recursive call, we are going to decrement "n" by one so that eventually we will hit our base case of n being less than 1 and return.

For our first iteration we are going to check that our array is empty. If it is, then we are going to put in our starting bits of 0 and 1. If it is not empty we are going to go through our steps where we prepend the 0 or 1 onto each element, reverse the array (that is the reflective part) and smash it onto the end of the original array. Let's take a look at how we can accomplish this in Ruby...

# graycode takes an array and the number of iterations "n" to proceed with.
# It assumes that we have a binary array only.

def graycode(list, n)
	# base case
	if n < 1
		return
	else 
		# First iteration, fill with binary values 0 and 1. 
		# Then print the two elements
		if list.empty?
			list.push("0")
			puts 0
			list.push("1")
			puts 1, "\n"
			
		else
			# Reflective method
			# 1) Take incoming array and reverse it
			reverse = list.reverse
			
			#2) Append 0 onto each element for original list elements and print it
			list.each_index { |i| puts list[i] = "0" + list[i] }
			
			#3) Append 1 onto each element of new reverse list and print it
			reverse.each_index { |i| puts reverse[i] = "1" + reverse[i] }
			
			#4) Concatenate arrays
			list += reverse
			
			# Add a break to see each successive iteration
			puts
			
		end
		
		# Subtract 1 from n and recursively call itself until we hit base case
		graycode(list, n - 1)
	end
end

# Create array
list = Array.new

# Call our function with 3 iterations
graycode(list, 3)



This Ruby code can of course be crunched down much smaller by simply taking out several of the narrative comments and maybe even joining a few of the lines up. I wanted to stick with a very explicit setup to show you the steps we talked about before and how we are implementing them in the language.

To kick off the function we test for our base case and once reached, we simply return out of the function. If we are not at the base case yet, we go about checking if we have an empty array. If so, we fill it with our starting values and print them to the display. If we are not at the base case and we don't have an empty array, we go about getting a reflective copy of the array by reversing it. We then loop through each element of the original array and add our 0 onto the front of them. We then do the same with the reversed version but instead adding a 1. At each iteration we print out the new element to the screen. Lastly, we add the two arrays together and pass that on to the next recursive call. Of course as we do that we will have to decrement "n" so that again it will reach the base case setup at the beginning of the function.

The result should be a list of gray code values for binary...

// This is our n = 1
0
1

// This is our n = 2
00
01
11
10

// This is our n = 3
000
001
011
010
110
111
101
100



Again, not too complicated once you know the steps and work it out through the code. Ruby does a great job at creating the solution for this without having to rely on loops for reversing and concatenating like you would do in a language like C/C++. It also doesn't require you to define some new dimensions as the array grows. You could mimic this in Java or .NET however by using an expanding collection like Arraylist. So you could give that a try if you are interested in porting it over to another one of your favorite languages. Keep in mind that our implementation is also dealing with strings here and if you want to actually work on each of the values, you will need to make sure you take the appropriate action to make sure you are using the correct types.

I hope you enjoyed this little algorithm. It is nice to play around with something like this while you sip your tea or orange juice on a Saturday morning. Thanks again for reading! :)

Filed in Hack the Planet!! (Just for fun category)

Intersection of LinkedLists Using Java

Posted by Martyr2  Icon, 04 November 2009 - 09:48 PM

Yesterday a user came through the Java forum looking for help with finding the intersection of two LinkedList sets. If you were anything like I was in school, you probably had a flash back to math class and the teacher drawing Venn Diagrams up on the white board. Two circles, usually representing two sets of elements, and where they overlapped was elements shared between the sets. Maybe they even drew 3 or 4 circles and did the whole shading and crosshatching thing. You probably figured "Where the hell am I going to use this?" Well today my friend is where learning it will help you understand a programming solution. Learn how to find which elements share LinkedList sets on this entry of the Programming Underground!

<That song about loving the sound of broken glass from the movie "Little Monsters"... by far Fred Savage's finest work *chuckle*>

Now imagine you have two sets of numbers. One is 1, 2, 3 and 4. The other set is 2, 4, 6, 8, and 10. Perhaps you want to find out which elements from set A are also found in set B. Just by looking at the sets you can see that the element 4 is in both sets. Pretty simple to see that right? Well imagine that these lists were hundreds or even thousands of items long. In addition to that, imagine that you don't really know which items are in the sets. Perhaps you generated the sets based on some sort of criteria. Perhaps the elements in each set are more complex than just counting numbers. You can quickly see where our problems lie. One, we don't have the time to go through thousands of items in the list looking for what they share. Two, if we don't exactly know what are in the sets, how can we find matches? Three, what if the elements were not just numbers, but a custom object you created? How would you go about finding matching dohickies?

Despite these little problems, lets see what we do know about sets. Well, we know that the most elements the result can have is the number of elements of the smaller set. Taking our example at the top, we know the most the result set will have is 4 elements. That is because set A has only 4 elements. This would mean that set A's elements are going to be completely inside set B's elements. In other words, set A is a subset of set B (or the same set if the two sets had the same number of elements).

Simple enough right? Ok, the original poster was asking about LinkedLists which contain integers only. We are going to go a bit beyond that and we are going to devise a small algorithm which can take two LinkedLists full of ANY kind of objects and find out which elements they share. Our only requirement is that the elements tell us how they can be compared to one another. In other words, the objects must implement the Comparable interface. For those who don't know about the Comparable interface, this interface says that any object which implements the interface must create a method called "compareTo" in their implementation. This method then must be able to compare itself with another element of the same type to tell us equality. For instance, the String class implements Comparable, so it has a method called compareTo which is used to compare one instance of the String class against another instance of the String class for equality. The method simply returns -1, 0 or 1 for less than, equal to, or greater than respectively. The interface is a "contract" which guarantees that any object that implements it will have the compareTo functionality to tell us equality.

We need this ability so that we can loop through one list, element by element, and look for it in the second list. Sounds pretty straight forward a nested for loop should do the trick. So lets dive right in and create a version for Strings, Integers, perhaps a custom class or two etc. If you are saying that to yourself, I suggest you hold up one second. This might be a great situation for a little Generics!

I won't go into generics too much here, but think of it as a way to make your code, well, generic. One function that could work on Strings and then turn around and be used for Integers and then whipped into working for custom objects. All this using ONE version of the algorithm. As long as the objects implement this Comparable interface, our generic algorithm should work perfectly despite the type used at that particular moment.

Now that we know the general pattern of needing a nested loop, which loops through one set and looks for matching elements in the other set, we can boilerplate design. In addition, we also know that a generic solution would be ideal for flexibility and work on multiple objects. When we are done we could also put this piece of code in our personal libraries to use for multiple projects. Sounds like a better idea than JackOfAllTrades dressing up like Blowup Doll Suzie for Halloween!

Lets show the code and then dive into the pieces afterwards...

import java.util.*;

public class Intersection {

	// Static method which takes two LinkedLists of objects (that implement the Comparable interface) and find any intersecting elements.
	// Returns a LinkedList of elements which intersect both sets.
	public static <T extends Comparable<T>> LinkedList<T> getIntersection(LinkedList<T> SetA, LinkedList<T> SetB) {
	
		// New results LinkedList
		LinkedList<T> results = new LinkedList<T>();
		
		// Loop through the first set using an iterator. 
		for (Iterator<T> it = SetA.iterator(); it.hasNext(); ) {
			T item1 = it.next();
			
			// Look for each element of the first set in the second.
			for (Iterator<T> it2 = SetB.iterator(); it2.hasNext(); ) {
				T item2 = it2.next();
				
				// Compare if the two are equal, then add them to result if they are.
				if (item1.compareTo(item2) == 0) {
				   results.add(item1);
				   break;
				}
			}
		}
		
		return results;
	}
}



Wow, lots of stuff going on here and maybe the generics in it also has you a bit shaky. No worries, take out the comments and you quickly see this thing is much smaller. Also understanding what we are doing with the Type parameters here and you will quickly see the light at the end of the tunnel. First off, we see that this is a static method called "getIntersection" which is a method of our class "Intersection". I made this static because all we really need here is two lists to compare and that itself doesn't require us to create an instance of the Intersection object to accomplish. Just like the sqrt() function doesn't need us to create a "Math" object to use.

The second thing you may notice is that we take in two LinkedLists called SetA and SetB. But what is with this <T> garbage? Well this is where the generics come in. It is called a Type Parameter and essentially it takes on the type of whatever object is passed to the function. If we pass in two LinkedLists of type String (LinkedList<String>) then T becomes "String" and everywhere you see T you could replace it with the word String (in your mind). If we pass it two Lists of Integer, T becomes Integer and you can replace T with the type Integer. Not too bad there right? Pretty simple. The last bit of generics here that we are going to explain is <T extends Compareable<T>> Again, T is going to take on the type passed to the function, that part hasn't changed. So if we have a String list, the statement will act like <String extends Comparable<String>>. This is essentially saying that all data types we pass to the function, in this case String, must implement the Comparable interface. The keyword "extends" here isn't necessarily the same version you may know from inheritance. It can mean inherits, but in this case it can also mean implements. You use the keyword "extends" in both situations, for objects and for interfaces when it comes to generics. All objects passed to our method must have a compareTo method which tells us how to compare itself with other objects of the same type.

Hopefully that was as clear as mud. Now lets try out a simple program which uses this class and show how this bad boy works...

import java.util.*;

public class IntersectionTest {
	public static void main(String args[]) {
	
		// To LinkedList sets of Integer objects (not int, int is a primative, Integer is an object)
		LinkedList<Integer> Set1 = new LinkedList<Integer>();
		LinkedList<Integer> Set2 = new LinkedList<Integer>();
		
		// Fill sets with some data
		Set1.add(1);
		Set1.add(4);
		Set1.add(3);
		
		Set2.add(3);
		Set2.add(2);
		Set2.add(4);
		
		// Call our method and give it the two LinkedLists, it returns a result LinkedList with elements that are in both sets.
		LinkedList<Integer> results = Intersection.getIntersection(Set1, Set2);
		
		// Loop through and print elements in result. We should see both elements 4 and 3 share both sets.
		for(Integer i : results) {
			System.out.println(i);
		}
		
		
		// Lets create two more sets, this time with a custom object we made called Item. Its declaration is below. 
		// Notice it implements the Comparable interface and thus has the compareTo object which takes in another item and essentially compares names for equality.
		
		LinkedList<Item> ItemSet1 = new LinkedList<Item>();
		LinkedList<Item> ItemSet2 = new LinkedList<Item>();
		
		// Fill sets with some data
		ItemSet1.add(new Item("Bannana"));
		ItemSet1.add(new Item("Watermelon"));
		ItemSet1.add(new Item("Strawberry"));
		
		ItemSet2.add(new Item("Plum"));
		ItemSet2.add(new Item("Strawberry"));
		ItemSet2.add(new Item("Tangerine"));
		ItemSet2.add(new Item("Grape"));
		
		// Again, call the SAME function but giving it two sets of our new item
		LinkedList<Item> resultsItems = Intersection.getIntersection(ItemSet1, ItemSet2);
		
		// Loop through and print elements in result. We should see only one element shares, "Strawberry".
		for(Item i : resultsItems) {
			System.out.println(i);
		}
		
	
	}
}


// Our custom class which implements the Comparable interface for Items
class Item implements Comparable<Item> {
	private String _name;
	
	public Item(String name) {
		_name = name;
	}
	
	public String toString() {
		return _name;
	}
	
	public int compareTo(Item anotherItem) {
		return _name.compareTo(anotherItem.toString());
	}
}



As you can see from our little bit of a rambling example that I first create two LinkedLists of Integer objects. I then give them to our static method (remember you call static methods by using the class name and then the method, no need to instantiate) and it returns results of the same type as what we passed in. The beauty here is that if we gave it LinkedLists of different types, SetA was Integers and SetB was Strings for instance, we would get a compile time error which is great. We don't want those errors to appear at runtime, so good to catch that error early!

After we run the first intersection, we print the results which happens to be the numbers 4 and 3. We then switch gears and create two more LinkedLists which feature our own custom object called "Item". This class implements the Comparable interface for comparing Items with one another and thus has the compareTo method. This method basically compares their names.... nothing fancy there. If our object didn't implement this interface, we would get another compile time error. We run the results through and this time only "Strawberry" appears in both sets. The results are then printed out again to show that. Here we just used the same algorithm for two different sets of objects (Integers and Items) and it gave us the elements which are contained in both sets in both situations. Pretty nifty.

Now before you go running off and "generifying" everything, keep in mind that making things too generic can also be harmful. I personally recommend using generics in situations where you really do need the flexibility and to cut down on repeat code. If you find yourself using generics everywhere just to get by with your solutions, perhaps you should take another look at how you are structuring the overall design. I have built a lot of software in my time and rarely do I find a need to use extensive generics. They have their niche and are useful for some solutions, but too much of a good thing is just as bad. Keep code short, simple and readable. That should always be your top goal.

Thank you for reading my blog! :)

Filed in Theory

Histogram Equalization Using PHP

Posted by Martyr2  Icon, 21 October 2009 - 09:44 PM

The other day someone on the board had asked about histogram equalization and it had sparked some thoughts about how it is applied to picture correction and enhancement. Then of course it hit me like a ton of bricks (ouch!), why not make this into a blog post? So here I am telling all you fine people about using PHP to equalize the histogram information in pictures. Now we all know that PHP isn't exactly the "ideal" technology to use for such a task, but that is where the fun comes in. Why not give it a try? Now we will make PHP dance like our sick little puppet and do our bidding on this entry of the Programming Underground!

<The Big Bang Theory TV show theme music, but with PHP cleverly put into the lyrics on occasion>

To understand this idea of histogram equalization we have to first understand what a histogram is. You may have created one in school and not even have known it. Essentially it is a bar chart of counts. The standard X and Y axis with each bar representing the count, or total number of, a particular value listed on the X axis. So if you add up the counts of each bar, you will reach the total number of elements in the set. That's all it is.

We know that images have pixels and the total number of pixels in an image is the width multiplied by the height. Straight forward right? Each pixel is a solid color but the fact that many of them sit next together with different colors and shades create things like shadows or other colors when viewed from afar. Typically a pixel's color is made up of three colors known as RGB or the amount of Red, Green and Blue in the color. Each of these values are between 0 (for black) to 255 (white). Of course this could all be elementary for you, so let me go ahead and skip to the good part.

Since each pixel essentially contains different amounts of red, green and blue we can take each of those colors and build a histogram of them... along with other factors such as hue or saturation (which I may cover in another entry later when I cover HSV values). To help illustrate this point, I have a standard picture I downloaded off the net and have shown it below. As you can see this picture is very much washed out in colors of brown, tan, beige and the colors in between. So if we break down each pixel into its basic colors, we would expect to see our histograms have a large peak in their charts. This peak represents little color variation and if we look, sure enough...

Posted Image

Posted Image

As you can see from the picture and its various histograms (one for luminosity and the others for the RGB) the counts appear to peak in the same area and around the same values.

What histogram equalization does is take that peak and flattens it out across the entire spectrum. It amplifies the lower values and weakens the higher values. We go through the picture pixel by pixel, build a histogram of the colors (here we put the values in arrays) and then run them through another algorithm called "cumulative frequency." As the name implies, we are essentially finding out how "frequent" a particular color value (and all those values below it on the scale) is in the histogram... their cumulative value. This means we sum up all the counts for each value, starting at 0, and sum up all values up to and including the Nth value. So if we are on value 5, we add up all values for 0, 1, 2, 3, 4 and 5. The result is a chart which starts off low and quickly climbs up and to the right and eventually flattens out.

So what good is this cumulative frequency chart? Well, it just so happens if we take a frequency of the color and multiply it by an alpha value (which is simply the scale of x, in our case 255, divided by the total number of pixels in the picture) we can formulate a new value for each of the red, green and blue of that pixel. But this time it will be evenly distributed across the spectrum. Here is the same picture above, but run through our script. Below it is the new histograms. Notice how they are flattened out and more equal?


Posted Image

Posted Image


Looking at the picture we still see that it is not crystal clear. It's not suppose to be. However, it does reveal new details and provides more contrast. Notice how this new picture is no longer bogged down in all sorts of beige and tan colors, but features colors like blues, whites, greens, purples, yellows etc. Also take notice how the picture now appears to be closer to something taken during a clear day. The histograms now show how each of the colors, and luminosity, are evened out quite a bit. This allows us to see things like more detail in the road and almost make out individual pebbles. The green in the trees in the background are also a bit cleaner and more vivid. The sky is cleared up and even appears to be in the morning.

So how is this witchcraft performed? PHP's image functions helps us out here. A word of warning, PHP is not exactly the fastest of languages for manipulating graphics. It is interpreted, so it is a bit slower than something like C++ or Java which are compiled and thus closer to being native to the computer making them run faster. Because of this, you will have to keep the images to reasonable sizes unless you want to wait forever to render the picture or until the script times out. Some hosts may even kill the script if it takes too long.

<?php

	// Main output function which reads the file and runs it through histogram equalization for the various color channels.
	function outputPicture($filename) {

		$reds = array();
		$blues = array();
		$greens = array();
		
		$freqr = array();
		$freqb = array();
		$freqg = array();
		
		$info = getimagesize($filename);
		
		$width = $info[0];
		$height = $info[1];
		$totalpixels = $width * $height;
		
		
		$img = imagecreatefromjpeg($filename);
		
		if ($img) {
			buildHistograms($img, $width, $height, $reds, $greens, $blues);
			buildFrequencies($reds, $greens, $blues, $freqr, $freqg, $freqb);
		}
		
		$alpha = (float)(255.0 / (float)$totalpixels);
		$newimg = @imagecreatetruecolor($width, $height);
		$color = imagecolorallocate($newimg, 255, 255, 255);
		
		for ($i = 0; $i < $height; $i++) {
			for ($j = 0; $j < $width; $j++) {
				$rgb = imagecolorat($img, $j, $i);
				$r = ($rgb >> 16) & 0xFF;
				$g = ($rgb >> 8) & 0xFF;
				$b = $rgb & 0xFF;
				
				$adjR = (int)((float)$freqr[$r] * $alpha);
				$adjG = (int)((float)$freqg[$g] * $alpha);
				$adjB = (int)((float)$freqb[$b] * $alpha);
				
				$color = imagecolorallocate($newimg, $adjR, $adjG, $adjB); 
				imagesetpixel($newimg, $j, $i, $color);
			}
		}
		
		header('Content-Type: image/jpg');
		imagejpeg($newimg, NULL, 100);
		imagedestroy($newimg);
	}
	
	
	// Fills $reds, $greens, $blues arrays with counts (histograms) based on picture $img.
	function buildHistograms($img, $width, $height, &$reds, &$greens, &$blues) {
		for ($i = 0; $i < $height; $i++) {
			for ($j = 0; $j < $width; $j++) {
				$rgb = imagecolorat($img, $j, $i);
				$r = ($rgb >> 16) & 0xFF;
				$g = ($rgb >> 8) & 0xFF;
				$b = $rgb & 0xFF;
				
				// Add counts to our histogram arrays for each color.
				$reds[$r]++;
				$greens[$g]++;
				$blues[$b]++;
			}
		}
		
		// Sort them by keys into order
		ksort($reds);
		ksort($greens);
		ksort($blues);
	}
	
	
	// Build frequency charts for all colors
	function buildFrequencies(&$arR, &$arG, &$arB, &$freqR, &$freqG, &$freqB) {
		// Loop through all values and sum counts from 0 to current column $i
		for ($i = 0; $i <= 255; $i++) {
			$sumR = 0;
			$sumG = 0;
			$sumB = 0;
			
			for ($j = 0; $j <= $i; $j++) {
				// Sums for Red, Green, Blue
				if (isset($arR[$j])) { $sumR += $arR[$j]; }
				if (isset($arG[$j])) { $sumG += $arG[$j]; }
				if (isset($arB[$j])) { $sumB += $arB[$j]; }
			}
			
			// Stash sums into frequency charts for each color
			$freqR[$i] = $sumR;
			$freqG[$i] = $sumG;
			$freqB[$i] = $sumB;
		}
	}
	
	outputPicture("stdSLR.jpg");
?>



This PHP script is setup to output a raw image file. This means you can't simply place it into the middle of a page or show any other kind of HTML/PHP output. It just shows a picture. We provide it a picture name (as seen down at the bottom of the script) and it creates several arrays to hold our histograms for RGB and each color's frequencies. It also features a function for making the histogram counts and a buildFrequencies() function which calculates the color frequencies. It uses these histograms and the frequencies to then adjust the RGB colors into new variants which are then redrawn to a new image pixel by pixel. The result is that the picture is displayed to the user altered and cleaned up.

This type of process isn't going to make all pictures instantly better. Its specialty is taking out those single high peaked histograms and equal them out. That means it works well on pictures which are bogged down in a particular color range (various oranges or various shades of red or purple etc). You can experiment with various pictures and see what kind of effects you get. Night time pictures may also reveal things in the shadows you hadn't seen before by adjusting their colors to be lighter. Lights may get more a halo effect. You might be wondering, is this what filters in Photoshop or other Adobe products do? Yup!

I have another script available where we take this process a step further in which we adjust each RGB into a HSV value (hue/saturation/value) system and thus can adjust things like brightness and some color corrections. I may share that shortly in a separate entry since it will deal with two new functions for converting RGB to HSV and back again. So until then, enjoy the script and tinker with it to you heart's content.

Thanks again for reading my blog! :)

Filed in Theory

Slot Machine Example in C++

Posted by Martyr2  Icon, 03 October 2009 - 03:20 PM

I was bored and that can be a dangerous thing. Like doodling on the phone book while you are talking on the phone, I doodle code while answering questions on DIC. Yeah, it means I have no life and yes it means I was born a coder. During this little doodle I decided to make a slot machine. But not your standard slot machine per say, but one designed a little bit more like the real thing. Sure it could have been done a little more simpler and not even using a Wheel class at all, but what fun is that? In this entry I show the creation of a slot machine from a bit more of a mechanical aspect than a purely computerized one. It should provide a small sampling of classes and how they can represent real life machines. We cover it all right here on the Programming Underground!

<Kris Allen (American Idol) singing "Apologize" but from the perspective of a n00b asking for help with a sloppy for loop>

So as I have already said, this little project was just something to play around with. It turned out kinda nice, so I thought I would share it. But what did I mean about it being mechanical in nature? Well, if you have ever played a real slot machine, not the digital ones they have in casinos now, you would see a metal case with a series of wheels. Typically it would be three wheels with pictures on them. When you put your money in and pull the handle the wheels would be set into motion. They would spin and then the first wheel would stop, followed by the second and then the third. After they have all stopped, the winnings are determined and you are paid out in coinage or credits.

I thought, why not be a bit mechanical in this slot machine design and create the wheels as a class called "Wheel" and give it the ability to spin independently of the other wheels? Have the wheel keep track of which picture (or in our case number) is flying by and report the results to the actual slot machine class. I could have done this mechanism without the need of a wheel at all and instead load up an array and have it randomly pick a number from the wheel. Little slimmer, little more efficient but wouldn't show much programming theory.

What do we gain by recreating these Wheel classes and spinning them independently? Well, you gain a slight bit of flexibility. Independently we are able to control the speed of the spinning if we wanted to, we are able to grasp the idea of the wheel as a concept in our mind and manipulate it. We could easily built in features like if the wheel lands on a certain number it will adjust itself. Like some slots in Vegas, if you land on lets say a rocket in the center line, the machine would see the rocket and correct the wheel to spin backwards 1 spot (in the direction of the rocket as if the rocket was controlling the wheel). We could spin one wheel one way and another wheel another. We could inherit from that wheel and create a specialized wheel that does a slew of new different behaviors. All encapsulated into one solid object making the actual Machine class oblivious to the trickery of the wheel itself... encapsulation at its finest!

The machine class we create will contain 3 pointers. Each to one of the wheels. The machine itself will be in charge of a few different tasks. Taking money, issuing and removing credits, determining when to spin, telling each of the wheels to spin and checking our winnings based on some chart we create. It has enough on its plate than worrying about the wheels and reading their values.

So lets start with our Wheel class and its declaration/implementation...

wheel.h

#include <time.h>
using namespace std;

class Wheel {
public:
	Wheel();
	void spin();
	int* read();

private:
	int slots[9];
	int internalPtr;
};


// Constructor
Wheel::Wheel() {
	srand((int)time(NULL));

	internalPtr = (rand() % 9);

	for (int i = 0; i < 9; i++) {
		slots[i] = i + 1;
	}
}


// Spin the internal pointer around spins times.
void Wheel::spin() {
	int spins = (rand() % 50) + 10;

	for (int i = 0; i < spins; i++) {
		internalPtr++;

		if (internalPtr > 8) { internalPtr = 0; }
	}
}


// Read the wheel for its values and return 3 values in an array
int* Wheel::read() {
	int prev = internalPtr - 1;
	int next = internalPtr + 1;

	if (prev < 0) { prev = 8; }
	if (next > 8) { next = 0; }

	int* values = new int[3];

	// Get values from wheel for pointer and before/after pointer.
	values[0] = slots[prev];
	values[1] = slots[internalPtr];
	values[2] = slots[next];

	return values;
}
	



As you can see the wheel itself is not a difficult concept to envision. The bulk of the work is in the read() method. Here we simply read the values from our internal array of integers (the values on the wheel) and return those values as an array of the three integers... representing the visible column. This column will then be loaded into our 2-Dimensional Array back in the Machine class. The 2D array represents the view or screen by which the user sees the results. Remember that the user never gets to see the entire wheel. Only the 3 consecutive values on the face of the wheel.

Here is how it may look in the real world. We have our machine with the three wheels and our 2D array called "Screen" which acts as our viewing window. Each wheel will report its values and those values will be put into the screen...

Posted Image

Below is our machine class...

machine.h

#include "wheel.h"

// Class declaration for our slot machine.
class Machine {
public:
	enum Image {
		orange = 1,
		watermelon,
		luckyseven,
		lemon,
		bar,
		doublebar,
		triplebar,
		cherry,
		plum
	};

	Machine();
	~Machine();
	void spin();
	void bet(int);
	void insertcoin();
	void insertbill(double);
	void printscreen();


private:
	void loadscreen(int, int*);
	void checkwinnings();
	int checkline(int line[3]);
	int credits;
	int betAmount;
	int screen[3][3];

	Wheel *wheels[3];
};


// Constructor
Machine::Machine() {
	credits = 0;
	betAmount = 0;

	wheels[0] = new Wheel();
	wheels[1] = new Wheel();
	wheels[2] = new Wheel();

	// Initialize screen
	for (int i = 0; i < 3; i++) {
		for (int j = 0; j < 3; j++) {
			screen[i][j] = 0;
		}
	}
}


// Destructor
Machine::~Machine() {
	delete(wheels[0]);
	delete(wheels[1]);
	delete(wheels[2]);
}


// Spins the wheels and calls the loading of each wheel's results.
// Then calls to check for winnings.
void Machine::spin() {
	if (betAmount > 0) {
		wheels[0]->spin();
		wheels[1]->spin();
		wheels[2]->spin();

		int *column1 = wheels[0]->read();
		int *column2 = wheels[1]->read();
		int *column3 = wheels[2]->read();


		loadscreen(0, column1);
		loadscreen(1, column2);
		loadscreen(2, column3);

		printscreen();
		checkwinnings();

		betAmount = 0;


		delete [] column1;
		delete [] column2;
		delete [] column3;

		column1 = column2 = column3 = NULL;

	}
	else { cout << "Please make a bet before spinning." << endl; }
}


// Loads a wheel into the respective column of the screen
void Machine::loadscreen(int col, int *wheelcolumn) {
	for (int i = 0; i < 3; i++) {
		screen[i][col] = wheelcolumn[i];
	}
}


// Simply prints the screen
void Machine::printscreen() {
	for (int i = 0; i < 3; i++) {
		for (int j = 0; j < 3; j++) {
			cout << screen[i][j] << " ";
		}
		cout << endl;
	}
}


// Bet function takes the number of lines the user wants to bet on (3 horizontal, 2 diagonals)
// and checks if they have enough credits to bet that much.
void Machine::bet(int lines) {
	if ((lines < 1) || (lines > 5)) {
		cout << "You may only bet between 1 and 5 lines. Please try again." << endl;
	}
	else if ((credits - lines) < 0) {
		cout << "You have " << credits << " credits available. Try adding more money." << endl;
	}
	else {
		betAmount = lines;
		credits -= betAmount;
	}
}


// Adds a credit
void Machine::insertcoin() {
	credits++;

	cout << "You now have " << credits << " credits." << endl;
}


// Adds multiple credits based on the bill denomination.
void Machine::insertbill(double billAmount) {
	if ((billAmount >= 1.00) && (billAmount <= 20.00)) {
		int newcredits = (int)(billAmount / .25);
		credits += newcredits;
		
		cout << "You now have " << credits << " credits." << endl;
	}
}


// Checks lines for wins and adds credits earned.
void Machine::checkwinnings() {
	int lineValues[3];
	int winnings = 0;

	// Check line middle line
	if (betAmount >= 1) {
		for (int i = 0; i < 3; i++) {
			lineValues[i] = screen[1][i];
		}

		winnings += checkline(lineValues);
	}

	// Check line top line
	if (betAmount >= 2) {
		for (int i = 0; i < 3; i++) {
			lineValues[i] = screen[0][i];
		}

		winnings += checkline(lineValues);
	}

	// Check bottom line
	if (betAmount >= 3) {
		for (int i = 0; i < 3; i++) {
			lineValues[i] = screen[2][i];
		}

		winnings += checkline(lineValues);
	}

	// Check left to right diagonal
	if (betAmount >= 4) {
		for (int i = 0; i < 3; i++) {
			lineValues[i] = screen[i][i];
		}

		winnings += checkline(lineValues);
	}

	// Check right to left diagonal
	if (betAmount == 5) {
		for (int i = 2; i >= 0; i--) {
			lineValues[i] = screen[i][i];
		}

		winnings += checkline(lineValues);
	}	

	if (winnings > 0) {
		cout << "You won " << winnings << " credits!" << endl;
		credits += winnings;
	}
	else {
		cout << "Sorry, you did not win anything." << endl;
	}

	cout << "You have " << credits << " credits left." << endl << endl;
}


// Determines the winning sequences. 
// 3 of a kind wins something
// Two cherries and something else wins as does two luckysevens and something else.
int Machine::checkline(int line[3]) {
	if (line[0] == this->luckyseven && line[1] == this->luckyseven && line[2] == this->luckyseven) { return 1000; }
	if (line[0] == this->watermelon && line[1] == this->watermelon && line[2] == this->watermelon) { return 800; }
	if (line[0] == this->triplebar && line[1] == this->triplebar && line[2] == this->triplebar) { return 600; }
	if (line[0] == this->doublebar && line[1] == this->doublebar && line[2] == this->doublebar) { return 500; }
	if (line[0] == this->bar && line[1] == this->bar && line[2] == this->bar) { return 400; }
	if (line[0] == this->cherry && line[1] == this->cherry && line[2] == this->cherry) { return 375; }
	if (line[0] == this->orange && line[1] == this->orange && line[2] == this->orange) { return 350; }
	if (line[0] == this->plum && line[1] == this->plum && line[2] == this->plum) { return 300; }
	if (line[0] == this->luckyseven && line[1] == this->luckyseven) { return 200; }
	if (line[0] == this->cherry && line[1] == this->cherry) { return 50; }
	if (line[0] == this->lemon && line[1] == this->lemon && line[2] == this->lemon) { return 5; }


	return 0;
}



This looks like a lot of code but really it is not if you look at each function. Most of them are very very simple to understand. We have a spin method which essentially spins each of the wheels, reads their values back from the Wheel class into a pointer (representing each column), then they are loaded into the 2D array one column at a time (our view screen), printed for the user to see the results and lastly the winnings are checked. The checkwinnings() method determines which rows to check based on the amount of the bet. If they chose 1 line, it checks for winning combinations on the middle row only. If they choose 2 lines, it checks the middle and top lines, 3 line bet checks all three horizontal rows, 4 line bet checks the first diagonal as well and 5 line bet checks both diagonals in addition to the lines.

How does it check the lines? Well each line is given to the checkline() helper function which compares the 3 values of the line against an enumerated type of various symbols. Here we are just assigning a symbol against each numbered value to help the programmer determine which numbers correspond to which winning combos. For instance, luckyseven represents the number 3 in the enumeration. So if it runs across a line with 3 number 3s, then it knows it hit the grand jackpot and credits the player 1000. This method makes things easy because if we ever wanted to change the win patterns later, we could change the enum and checkline method to do so. We could also build in multiple types of symbols and even let the user choose what slot machine game they want to go by. It becomes very flexible and is a testament to great design!

Lastly we can put some tests together just to show some the various aspects of how this thing works and how the programmer can use the classes...

slotmachine.cpp

#include <iostream>
#include "machine.h"
using namespace std;

int main() {

	// Create our slot machine
	Machine *slotmachine = new Machine();

	// Insert a five
	slotmachine->insertbill(5.00);

	// Plus a coin for good luck
	slotmachine->insertcoin();

	// Go for it all and bet five lines
	// Then spin!
	slotmachine->bet(5);
	slotmachine->spin();

	// Win or lose, lets bet five lines again
	// Then spin!
	slotmachine->bet(5);
	slotmachine->spin();


	// Ok, we had enough of the slot machine.
	delete(slotmachine);

	return 0;
}



This simply inserts a 5 dollar bill and a coin for good luck. Then bets 5 lines and spins. Despite the outcome we go and bet five lines again and spin once more. Hopefully we win something this time around! But either way, those are the classes for you and I hope you like them. As always, all code here on the Programming Underground is in the public domain and free for the taking (just don't cause a mess in isle 3, I am tired of running out there for cleanup). Thanks for stopping by and reading my blog. :)

Filed in Hack the Planet!! (Just for fun category)

Simple Queue Using Text File in PHP

Posted by Martyr2  Icon, 19 September 2009 - 09:59 AM

When talking about any kind of server-side language, like PHP or ASP, you will often find the term "database" not too far behind. It is the preferred choice for storing data on the web after all. Another option is to use a text file. The problem with text files is that they are not typically secure, can be easily read, and don't offer any of the features like referential integrity (relationships). However, one thing that files do have is the ability to quickly modify data that doesn't need to be secure, can be easily viewed or perhaps isn't related to any other data. Who really cares if someone sees a text file listing a bunch of article topics or shouts from a publicly viewed shoutbox? As long as they can't modify the content directly, no problem. For this reason they are great for logs, list data, even sources of information for other services to use. So flat files have their place and I will show you how we can use one to store a queue of article topics between script executions in PHP right here on the Programming Underground!

<Britney Spears singing Circus, not caring who sees her data... just like a text file on the web>

What is a queue? Well it is essentially a data structure where you have a list of data (a collection) that is kept in order and the data added to it is added to the top of the list and data removed comes from the bottom of the list. You may know this as a FIFO or First In First Out data structure. To help you think of how this works imagine a line of people standing outside of a video game retailer. They are all wanting to be the first to get a new game that is launching that day. Those who add themselves first to the line are the ones that will get the video game first and are the ones that leave first to go play it. "First come first served." I suggest you look up the term FIFO on the web for any further information on these types of systems. These types of structures are encountered all the time in programming and so it is helpful to know how they work and try implementing a few of them in your creations. Unless of course your creation leads to the end of humanity, then in that case don't try them!

In our example below we use a simple text file on our web server to keep a list of titles for some articles. I used this system in one of my projects recently to keep track of titles I have already shown to the public. When I select a new title, I want to check this list to make sure that the title hasn't already been shown (in the last 75 topics) and to pick another title in case of a repeat. Whenever I determine that a title has not been shown yet, I can add it to the front of the text file list. If at any time that list grows beyond 75 items, I also want to trim the list down by removing a title from the end of the list (the oldest title).

The result is that I have a text file keeping track of the last 75 article titles I have shown the public and no more. In addition, since the list essentially trims itself with a limit, I don't have to worry about going and cleaning out the text file at some later date. It keeps itself in check. You could use such a system to easily log bits of information that you may want to view later, keep for later access by a script (persistence), or serve as a data source for other applications. All this without the file taking up massive resources in your database and without a lot of query execution.

Let's check it out below....

<?php

// Title Manager class (essentially a queue) that uses a simple text file for storage
class TitleManager {
	private $filename = "titlemanager.txt";
	private $queueLimit = 75;
	private $titles;
	
	// Upon creation, load up our titles from the file
	public function __construct() {
		$this->titles = array();
		$this->loadTitles();
	}
	

	private function loadTitles() {
		if (file_exists($this->filename)) {
			$this->titles = file($this->filename, FILE_SKIP_EMPTY_LINES);
		}
	}
	
	// Add a title to the queue and if we are at our limit, drop one off the end.
	public function enqueue($strTitle) {
		if (!empty($strTitle)) {
			array_unshift($this->titles, $strTitle . "\n"); 
			
			if (count($this->titles) > $this->queueLimit) {
				$this->dequeue();
			}	
		}
	}
	
	// Remove a title item from the end of our list
	public function dequeue() {
		if (count($this->titles) > 0) {
			return trim(array_pop($this->titles));
		}
		return "";
	}
	
	// Save the contents of our array back to the file.
	public function save() {				
		if (file_put_contents($this->filename, $this->titles)) {
			return true;
		}
		return false;
	}


	// Check if an item is already in our list. 
	// Note: We could have also used in_array here instead of a loop.
	public function isTitlePresent($strTitle = "") {
		if (!empty($strTitle)) {
			foreach ($this->titles as $title) {
				$trimmedTitle = trim($title);
				$strTitle = trim($strTitle);
				if (strtolower($strTitle) == strtolower($trimmedTitle)) { return true; }
			}
			
			return false;
		}
		return -1;
	}
	
	
	// Mainly a debug function to print our values to screen.
	public function printValues() {
		foreach ($this->titles as $value) {
			echo "$value<br/>";
		}
	}
}
?>



I have wrapped all this functionality up into a small class called "TitleManager" which has a few main methods. Upon creation of this class it references a file in the local directory which I called "titlemanager.txt". You could have made this a dynamic setting that you pass in through the constructor, but I knew I wasn't really going to use this for anything else in the foreseeable future. So to be lazy I made it a hardcoded name. If I wanted to change it later, it wouldn't be hard to do anyways. In addition to this constructor, I created a few methods called enqueue() for adding items to the top of the list, dequeue() for removing items from the end of the list, save() for basically dumping the array contents back out to the file, isTitlePresent() a boolean function to check if a title is already found in our list and printValues() a debug function to show the contents currently being managed by the class.

The methods are not complicated and using PHP's great file handling functions, like file() and file_put_contents(), I can easily bring the file in and out of a PHP array. Creating the class will load up the file (if it exists) and put the titles into an array for us. We can add and remove using the enqueue() and dequeue() methods as we see fit, then save() them back to the file.

One place you could use this class is for website event logging. You could keep track of the last X number of events that happen on a website. The only place this would really need some modification, if you were to use it for logging, is the isTitlePresent() function. This would probably become a useless function given that you would not really want to check if an event had already occurred. Each event would be unique to itself and already have a unique timestamp associated with it. But other than that, it should prove very useful to you.

Implementing something like this through a database would involve executing select queries, reading into an array, making updates and deletes as appropriate and could all become very messy for a simple FIFO system. So if you need something basic and simple for handling logging or keeping track of a list that you don't mind people reading at any point, this may be your answer.

Feel free to help yourself to the code and modify it as you see fit. As with all code on the programming underground, it is in the public domain and can be used for academic or commercial purposes. Enjoy and thanks again for reading! :)

Filed in Basics

Bit.ly Class for shortening URLs in VB.NET and C#

Posted by Martyr2  Icon, 21 August 2009 - 09:59 PM

So I was tinkering around with some code and thought "Hey, wouldn't it be great to create a class that could be used to tie into bit.ly's API for shortening URLs?" After having this thought I also thought "I am hungry" so went to get some lunch. Then when I came back, I got to work putting together a quick class that a programmer could use in their projects for submitting long URLs for bit.ly to shorten up. I created it in two .NET languages so that it would be more versatile and save some programmers from having to port it from one language to the other. Now lets get shortening on this episode of the Programming Underground!

<The movie 'Avatar' theme music, but with a dash of Felica Day singing 'Wanna date my avatar'>

The idea behind our class is that we are going to first create the object with a default login and API key or provide our own. By calling the method "Shorten" and giving it a nice long URL we are going to...

1) Contact bit.ly using their API URL
2) Fetch the result from bit.ly in XML format
3) Parse that XML to fetch the "shotUrl" element
4) Return that element's value to the caller of the method

The whole process is pretty straight forward. Being that we are counting on an external source that may or may not respond, could provide a bad response, or just plain ignore us we have to build in a few error handling traps. We want to make sure this class works even if the underlying API isn't. Let's start with the VB.NET version of this class and then we will move on to the C# version. These classes can be placed in their own class file and called from anywhere in the project.

Imports System.Text
Imports System.Xml
Imports System.IO
Imports System.Net

Public Class bitly
	Private loginAccount As String
	Private apiKeyForAccount As String

	Private submitPath As String = "http://api.bit.ly/shorten?version=2.0.1&format=xml"
	Private errorStatus As Integer = 0
	Private errorStatusMessage As String = ""


	' Constructors (overloaded and chained)
	Public Sub New()
		Me.New("bitlyapidemo", "R_0da49e0a9118ff35f52f629d2d71bf07")
	End Sub


	Public Sub New(ByVal login As String, ByVal APIKey As String)
		loginAccount = login
		apiKeyForAccount = APIKey

		submitPath &= "&login=" & loginAccount & "&apiKey=" & apiKeyForAccount
	End Sub


	' Properties to retrieve error information.
	Public ReadOnly Property ErrorCode() As Integer
		Get
			Return errorStatus
		End Get
	End Property

	Public ReadOnly Property ErrorMessage() As String
		Get
			Return errorStatusMessage
		End Get
	End Property


	' Main shorten function which takes in the long URL and returns the bit.ly shortened URL
	Public Function shorten(ByVal url As String) As String

		errorStatus = 0
		errorStatusMessage = ""

		Dim doc As XmlDocument
		doc = buildDocument(url)

		If Not doc.DocumentElement Is Nothing Then

			Dim shortenedNode As XmlNode = doc.DocumentElement.SelectSingleNode("results/nodeKeyVal/shortUrl")

			If Not shortenedNode Is Nothing Then

				Return shortenedNode.InnerText

			Else

				getErrorCode(doc)

			End If
		Else

			errorStatus = -1
			errorStatusMessage = "Unable to connect to bit.ly for shortening of URL"
		End If

		Return ""

	End Function


	' Sets error code and message in the situation we receive a response, but there was
	' something wrong with our submission.
	Private Sub getErrorCode(ByVal doc As XmlDocument)

		Dim errorNode As XmlNode = doc.DocumentElement.SelectSingleNode("errorCode")
		Dim errorMessageNode As XmlNode = doc.DocumentElement.SelectSingleNode("errorMessage")

		If Not errorNode Is Nothing Then

			errorStatus = Convert.ToInt32(errorNode.InnerText)
			errorStatusMessage = errorMessageNode.InnerText
		End If
	End Sub


	' Builds an XmlDocument using the XML returned by bit.ly in response 
	' to our URL being submitted
	Private Function buildDocument(ByVal url As String) As XmlDocument

		Dim doc As New XmlDocument

		Try

			' Load the XML response into an XML Document and return it.
			doc.LoadXml(readSource(submitPath + "&longUrl=" + url))
			Return doc

		Catch e As Exception

			Return New XmlDocument()
		End Try
	End Function


	' Fetches a result from bit.ly provided the URL submitted
	Private Function readSource(ByVal url As String) As String
		Dim client As New WebClient

		Try

			Using reader As New StreamReader(client.OpenRead(url))
				' Read all of the response
				Return reader.ReadToEnd()
				reader.Close()
			End Using

		Catch e As Exception
			Throw e
		End Try

	End Function

End Class



The class is made up of two constructors. One which takes no parameters (providing defaults) and another which takes two parameters representing the login account and API key provided by bit.ly (if you signed up for an account with them). Either way this should work for you even if you don't have an account. In addition to the constructors, we provide two properties that can be used to retrieve an error code and error message in the event that something terrible and horrible happens. You can use these to check and see what is going on. We also specify the shorten public method which is the main method of the class and takes in the long URL. When this method finished, it will provide the caller a short URL string returned by bit.ly.

There is a small supporting cast of private helper functions which take separate jobs of communicating with bit.ly, building an XmlDocument using the XML response returned from the bit.ly API and another to yank out any error codes and messages in the rare chance that any are found.

readSource() is responsible for connecting to the web source, getting a stream to the API, submitting our aggregated URL string and reading the XML using the ReadToEnd() method of the StreamReader class. It returns this string to the caller which is the buildDocument() method. This method is responsible for taking the XML source string, placing it into an XmlDocument class and parsing out the nodes using XPath. We are looking for the element "shortUrl" here to retrieve the short URL returned from bit.ly.

All this is also done in our C# version shown below...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Net;
using System.IO;

namespace bitly
{
	/// <summary>
	/// This class connects to bit.ly for URL shortening.
	/// 
	/// Class contains an overloaded constructor to take in a personal login and api key
	/// </summary>
  
	class bitly
	{
		private string loginAccount;
		private string apiKeyForAccount;
		private string submitPath = @"http://api.bit.ly/shorten?version=2.0.1&format=xml";
		private int errorStatus = 0;
		private string errorMessage = "";


		/// <summary>
		/// Default constructor which will login with demo credentials
		/// </summary>
		/// <returns>A bitly class object</returns>
		public bitly(): this("bitlyapidemo", "R_0da49e0a9118ff35f52f629d2d71bf07")
		{
			
		}


		/// <summary>
		/// Overloaded constructor that takes a bit.ly login and apikey (if applicable)
		/// </summary>
		/// <returns>A bitly class object</returns>
		public bitly(string login, string APIKey)
		{
			loginAccount = login;
			apiKeyForAccount = APIKey;

			submitPath += "&login=" + loginAccount + "&apiKey=" + apiKeyForAccount;
		}


		// Properties to retrieve error information.
		public int ErrorCode
		{
			get { return errorStatus; }
		}

		public string ErrorMessage
		{
			get { return errorMessage; }
		}


		/// <summary>
		/// Shortens a provided URL
		/// </summary>
		/// <param name="url">A URL</param>
		/// <returns>A shortened bit.ly URL String</returns>
		public string shorten(string url)
		{
			errorStatus = 0;
			errorMessage = "";

			XmlDocument doc = buildDocument(url);

			if (doc.DocumentElement != null)
			{
				XmlNode shortenedNode = doc.DocumentElement.SelectSingleNode("results/nodeKeyVal/shortUrl");

				if (shortenedNode != null)
				{
					return shortenedNode.InnerText;
				}
				else
				{
					errorCode(doc);
				}
			}
			else
			{
				this.errorStatus = -1;
				this.errorMessage = "Unable to connect to bit.ly for shortening of URL";
			}

			return "";

		}


		// Sets error code and message in the situation we receive a response, but there was
		// something wrong with our submission.
		private void errorCode(XmlDocument doc)
		{
			XmlNode errorNode = doc.DocumentElement.SelectSingleNode("errorCode");
			XmlNode errorMessage = doc.DocumentElement.SelectSingleNode("errorMessage");

			if (errorNode != null)
			{
				this.errorStatus = Convert.ToInt32(errorNode.InnerText);
				this.errorMessage = errorMessage.InnerText;
			}
		}
		   
	 
		// Builds an XmlDocument using the XML returned by bit.ly in response 
		// to our URL being submitted
		private XmlDocument buildDocument(string url)
		{
			XmlDocument doc = new XmlDocument();

			try
			{
				// Load the XML response into an XML Document and return it.
				doc.LoadXml(readSource(submitPath + "&longUrl=" + url));
				return doc;
			}
			catch (Exception e)
			{
				return new XmlDocument();
			}
		}


		// Fetches a result from bit.ly provided the URL submitted
		private string readSource(string url)
		{
			WebClient client = new WebClient();

			try
			{
				using (StreamReader reader = new StreamReader(client.OpenRead(url)))
				{
					// Read all of the response
					return reader.ReadToEnd();
					reader.Close();
				}
			}
			catch (Exception e)
			{
				throw e;
			}
		}
	}
}



As you can see this is almost identical to the VB.NET version but with the minor syntax changes. Again we open up our connection, retrieve the string XML response, parse that XML using XPath and return the shortUrl element's data to the caller. We could then use this class as we would for any class anywhere in the project. Place it in the button and use code similar to...

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
		Dim b As New bitly

		MessageBox.Show(b.shorten("http://www.cnn.com"))
End Sub



Not too bad huh? With this nifty little class you can quickly and easily use it to build applications which may need to submit URL's for shortening. Perhaps your own twitter client or for anything that would need simple URL's instead of long ones. Have fun playing and tinkering with this code. It is in the public domain, as all code on the Programming Underground is, so if a five finger discount is your specialty... enjoy! Thanks for reading! :)

Filed in Hack the Planet!! (Just for fun category)

Reading and Updating an Access Database in C#

Posted by Martyr2  Icon, 06 August 2009 - 06:36 PM

Almost on a daily basis we run across posts that ask about using a .NET language to read and update a database. Oh it might have a slight variation like "How do I load a value from a database into a textbox?" or "How do I read a database into _______ control and then update the database?" So I figured I would put a few little snippets here to show you some ways it can be done. We will work on reading a simple column (name) from an Access Database table (Employees) and stick those names into a listbox for selection. While there are many ways to do these things, I simply create 3 different ways that you can play with below. At the end we will cover a quick way to make a nice update to the database. So grab a drink, kick off your shoes and lets play with some snippets here on the Programming Underground!

<If twitter had a theme song, add a dash a carnage to it and that would probably be the theme song>

So how do we get this stupid name column out of our table "Employees" of the access database and into a control? Well, we have to do a few simple things. One is to connect to the database, another thing is to query the database for the info and lastly we put that info into our source control... this case is our listbox. Connecting to the database is pretty straight forward and really starts out with picking the right connection object from the System.Data namespace to target out database. Since Access can be "accessed" through the OLEDB setup we can use the OleDbConnection class for that. All we need now is to give it a connection string. This is nothing but a string that tells the class where to find the database, what driver (or DSN) to use, any username and passwords to login to the database, and any security features we will need to implement for our access. One great place to find connection string data for tons of different databases is at connectionstrings.com.

I am using a local instance of an access database that doesn't require any real credentials to access. All we need is to tell it which driver to use and where to find the database file. If this had been a database like MySQL located on another server, we would have to specify IP address info as well as port. But lets keep the example small people!

So first we bring in the System.Data.OleDb namespace so we get to use OleDbConnection as well as other classes you will see later. Then we give it the connection string and open the connection...

// Form level variable for our connection
OleDbConnection connection;

// Constructor
public Form1()
{
	 connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\example.mdb;Persist Security Info=False");
	 InitializeComponent();
}



Notice in our code above we create a new OleDbConnection and give it a connection string to tells it where to find example.mdb and to use our OLEDB 4.0 driver. Nothing much to see here other than how to create the class and use a connection string to tell the connection where to find the database.

Since we now have a database connection made, we have a few choices on how to query and load our data. I will show each method here. Some have their advantages and disadvantages, so be sure to research which one might fit your needs the most. The first example will be to use a DataAdapter class and its fill method to load it into a DataSet. Think of this method like using a hose to fill up a bucket. The DataAdapter will use our connection (a well???) and pump info into our DataSet which will be our bucket. Once we have it in the bucket, we can use the data independent of the connection or adapter. This example will use the DataSet to "bind" to the listbox and empty its contents into the listbox control.

private void button1_Click(object sender, EventArgs e)
{
	 // Create our adapter and give it a query for the database using the connection object.
	 OleDbDataAdapter dataAdapter = new OleDbDataAdapter("select name from employees", connection);

	 // Here is our "bucket"
	 DataSet ds = new DataSet();

	 // Turn on the hose and fill the bucket with the results of our query. We will then label this particular set of results as "employees"
	 dataAdapter.Fill(ds, "employees");

	 // Tell our listbox to use this table of results from the dataset. 
	 // Both the info it shows and the value of the items will be the employee's name column.
	 listBox1.DataSource = ds;
	 listBox1.DisplayMember = "employees.name";
	 listBox1.ValueMember = "employees.name";
}



Not too bad right? The only trick here is that we bind the database to the listbox and tell the listbox to use the name column as both the names we display to the user as well as the value each item has. So if we see "John" in the listbox, the value of that item will also be "John". We could have given it a different value than what it shows. Just like you can give each option item in HTML select boxes a different value than its actual list item name. The advantage of this method is that it is a quick "dump all the info here" method. It is also good in that it is directly tied to the dataset itself. So if we modify the dataset, the listbox automatically changes as well. The disadvantage is that it can get a bit tricky to update the dataset itself unless you have a good picture of how that dataset is setup. Keep in mind that this would be altering the dataset data, not the database.

The second method I will show you is again using a dataset but this time we will loop through it to load the listbox. This method is good for times where you want to modify each value before adding it to the listbox.

private void button1_Click(object sender, EventArgs e)
{
	 // Again our data adapter is going to be our hose, same query
	 OleDbDataAdapter dataAdapter = new OleDbDataAdapter("select name from employees", connection);

	 // Our "bucket"
	 DataSet ds = new DataSet();

	 // Fill the bucket with the results of the query and give it the name "employees"
	 dataAdapter.Fill(ds, "employees");

	 // Loop through the rows of the only table in the DataSet
	 // Now keep in mind that the info in a DataSet can contain multiple tables of data and each table has columns and rows like a spreadsheet.
	 // So here we ask it to get the first table (aka Employees) and loop through each DataRow. We use the row to access the column "name" and add that value to the listbox.
	 foreach (DataRow dataRow in ds.Tables[0].Rows)
	 {
		  listBox1.Items.Add(dataRow["name"].ToString());
	 }
}



Slightly different than the first method, differing only by how we load the data. We could alter the tables in the DataSet directly before looping through it, but sometimes beginners find it easier to just loop through it like this and before displaying. Like if we wanted to make sure that each name is properly capitalized we could do that before adding it to the listBox1.Items.

The last method here for selecting data is using a command object and fetching what is called a "Reader". This method is especially common because the command object is very flexible and good not only for select queries, but for updates, inserts and delete queries as well. Very versatile! We will use it again to show you a simple update in a second. Another beautiful thing about using a Reader to move through data is because they are "forward only". Since you can only move to the next record at a time and can't go back, .NET has to dedicate less resources to managing the internal record pointer and can speed up access. This means it is great for any situation where you simply want to loop through the values quickly and easily without needing to go back. Nice for report displays etc. Of course this is also the disadvantage, we can't simply go to the previous record if we wanted to. We could reset the pointer, but then that would kill the speed here.

// Our command object which again uses the connection string and a connection object
OleDbCommand cmd = new OleDbCommand("select name from employees", connection);
			
// Our reader is going to fetch our results
OleDbDataReader reader = cmd.ExecuteReader();

// Determine if the reader actually has rows
if (reader.HasRows)
{
	 // Loop through the reader real fast and add the first string column it has (our name column)
	 while (reader.Read())
	 {
		  listBox1.Items.Add(reader.GetString(0));
	 }
}



Again this is faster than the other methods and you will certainly see a difference when it comes to loading larger lists of data. Since we don't really have to go back and forth through the data, we can use the reader here to quickly speed through the list of names and spit them into the listbox. There are other Execute statements that you can use with the command object including ExecuteScalar for single values and ExecuteNonQuery which we will now use to execute any statement which is not a "query" statement. That is, any SQL that is not a select (aka insert, update and delete).

private void updateDatabase()
{
	 // Create a command object, give it a connection object, give it a query to update our database where name equals 'John'
	 OleDbCommand cmd = new OleDbCommand();
	 cmd.Connection = connection;
	 cmd.CommandText = "update employees set name = 'Jonathan' where name = 'John'";

	 // Now simply execute it!
	 cmd.ExecuteNonQuery();
}



The function above is very simple and straight forward. We simply make a new command object, give it the connection (make sure it is open first) and an update query for the commandtext. We then call the ExecuteNonQuery() method to make the update happen. The database will then be updated anywhere the name equals "John".... it will become "Jonathan".

If we were to use one of the other methods again to read this database table back to us, we would see that the Access database Employees table would be modified. Again, very simple and straight forward. This isn't the only way to do these queries and you may see other examples of doing it. However, if you are working with Access and only need to do something real quick, this example should serve you well.

NOTE: A word on security here, make sure you always validate the information coming in from the user before using them in any kind of database query. For more information on doing this securely, please look up "Parameters" collection which is part of the command object. This, along with a nicely setup query string, can help you avoid nasty people injecting bad code into your database. As always, treat all user input as dirty input!

Use the examples above to experiment with reading and updating/inserting/deleting records from Access databases. You will quickly be able to build some great applications which utilize databases for your own small projects. For more advanced features, I suggest you take an extra hard look at the command, connection and dataset classes. These are the building blocks for using databases in .NET.

Enjoy and thanks for reading! :)

Filed in Basics

Playing and Thottling Sound Clips in Java

Posted by Martyr2  Icon, 26 July 2009 - 10:57 AM

A user recently came up with an interesting project today that frankly I had never really played around with too much... playing sound clips using Java's AudioSystem. The problem he was having was two fold actually. How does one go about throttling a sound (preventing the user from triggering the sound multiple times so that they overlap themselves and causing a scrambled mess that sounds like spirits you would hear on the TV from poltergeist) and prevent Java from eating up memory doing it as well. So on this entry of the programming underground I will talk a bit about what was going on and show you an example I created to help solve both situations. All this and more right here on the Programming Underground!

<Microsoft's ding.wav played over and over to the point someone brings out a gun and puts an end to it>

So as I had said, the problem was two fold. First we have the issue of the sound overlapping on itself. This was because he was playing the clip (whether it be the same clip or could be another) before the last play was finished. This create two separate objects playing two different clips at the same time. It just so happens he wanted this clip to play when the user entered a certain area of screen coordinates. In my example, I use a simple play button to trigger the play instead. What we need to do to remedy this is first setup a flag test situation which will let us know if the current clip is currently active in playback. Based on this test, we can choose whether or not to let the sound play again. In this circumstance, we don't want the user to be able to play the sound a second time if the first one is not finished. Now we could easily make a queue here where we queue up the playing if we wanted to keep track of every time the user wants to play the sound, but this would get very cumbersome and may eat more memory if the user decides to just play the sound 10,000 times.

The trick here, and the piece that he was looking for, was the isActive() method of the DataLine interface. He could have also used isRunning() to do the same thing. We just need to know if the line is actually active. Either one will work. Since he was playing a Clip, an inherited interface of the DataLine interface, it inherited the isActive() method. This method returns a boolean to tell if the current sound clip is currently in playback or capture mode. This test is the flag condition we need to determine when a user can do a playback of the sound (as I will show you below in a moment) and when.

The second problem was a memory leak that was happening because he would start each of these overlapping clips, but would not close them. The way he had originally put it not only was he starting multiple clips at once, that would overlap, but they were also not being closed. The memory was left there idle after its sounds was played. But what is a good way to close these clips? Well, the elegant way is to listen for when the clip actually stops. So not only are we throttling how often the clip plays, but also closing it properly each time it is done playing. To listen for when it stops playing, we used a LineListener.

The LineListener is a listener which listens to the underlying line of the the sound clip used by the AudioSystem classes. Think of it is like a line of communication or stream. While the sound is being played, this stream is active. When the stream is first started it lets all LineListener's (it has registered with it) know that the line is starting. It also keeps them informed any time the state of that clip changes. This is a great way to listen for the start of a sound clip, the end and when it enters other modes.

Below is the example I have put together to demonstrate all this. Keep in mind that this is just a sample that is demonstrating the two solutions simultaneously.

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import javax.sound.sampled.*; // For sound handling
import javax.sound.sampled.LineEvent.Type.*; // For LineEvent types used in listener

public class PlaySoundSample extends JFrame implements ActionListener, LineListener {
	JButton play;
	
	// Audio variables
	File soundFile;
	Clip clip;
	AudioInputStream soundIn;
	AudioFormat format;
	DataLine.Info info;

	public PlaySoundSample() {
		setTitle("PlaySound Example");
		setSize(300,300);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
	
		play = new JButton("Play");
		play.addActionListener(this);
		
		// Add play button to the bottom portion of the frame (so we could possibly put visualizer or something in the top half???)
		add(play,BorderLayout.SOUTH);
		
		
		// Configure our variables for playing
		format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, AudioSystem.NOT_SPECIFIED, 16, 2, 4, AudioSystem.NOT_SPECIFIED, true);
		info = new DataLine.Info(Clip.class, format);

		// Our test file, be sure to change this to your own sounds or load it dynamically
		soundFile = new File("c:\\test.wav");
	
	}
	
	
	public static void main(String[] args) {
		PlaySoundSample playSound = new PlaySoundSample();
		
		playSound.setVisible(true);
	}

	
	// Listens for when the play button is pressed (Part of the ActionListener)
	public void actionPerformed(ActionEvent e) {
		try {
			// Play the sound if it is currently not set to playing a clip or that clip is not ACTIVELY PLAYING the sound.
			if ((clip == null) || (!clip.isActive())) {
				soundIn = AudioSystem.getAudioInputStream(soundFile);
				
				// Get the Data line for our clip, open it using the audio input stream from the actual sound file (loading the sound file into the clip)
				// Then start it
				clip = (Clip)AudioSystem.getLine(info);
				clip.open(soundIn);
				clip.start();
				
				// Attach line listener to the clip
				clip.addLineListener(this);
			}
		}
		catch (Exception ex) {
			System.out.println("There was an error!");
		}

	}
	
	// Listens for when the clip has stopped playing and closes it. (Part of the LineListener)
	public void update(LineEvent event) {
		if (event.getType().equals(LineEvent.Type.STOP)) { 
			clip.close();
		}
	}
}



This code essentially builds a quick little JFrame with a play button that lurks across the bottom. I used the play button to quickly activate the playing of a clip for testing purposes. As you can see from the ActionListener's actionPerformed method, we simply check if the clip is either null (being played the first time) or is not active. If either case is true, we can go about setting up the clip for another play and play it. One line I want to point out here is that we attach the LineListener to this clip so that we can listen to its states of play as the clip progresses. Any time the clip changes its state, it will let our listener know.

The second part that is of interest is the update method of our LineListener. This update event is the event notified when our clip changes state. When it changes state, the clip will send the update event a LineEvent object which we can use to evaluate what type of state actually happened. Here we are listening for a STOP event. We could easily expand this to listen for start events as well as others if you wanted to. But when we detect the clip has stopped, we close the clip and free its resources. Now the clip is ready for another pass and we are throttling and freeing the memory properly.

But anyways, I thought it was an interesting little project and certainly something worth discussing on the blog today. Feel free to take whatever code out of this you wish and use it for your own projects. Just like everything on the Programming Underground, we won't stiff you like big brother governments would. Knowledge is a free commodity as far as I am concerned. Enjoy and thanks for reading! :)

Filed in Theory

Adding to Event Logs with VB.NET

Posted by Martyr2  Icon, 18 July 2009 - 01:16 PM

Damn! What the hell happened to that application I was running? One minute I am viewing the pictures of my trip to the playboy mansion and another minute I am having to shut down the app. It is seriously not cool! Now only if there was a way I can record some of my applications activity for windows to see later. Perhaps describing why my application decided to take a dump on me would help the situation. Oh wait, there is! The Windows event logs! There we can record messages for users to view after the fact. I will show you how to make a standard VB.NET application access these logs, the types of logs there are and how to go about viewing them through XP. We cover the topic on this entry of the Programming Underground!

<Gene Simmons Theme music but where he says Family Jewels, he says Programming Tools>

So first lets cover how we even get to the event logs so that we can see our applications magic in action. On Windows XP, you can go to Start >> Settings >> Control Panel >> Performance and Maintenance >> Administrative Tools >> Event Viewer. Here you should see several types of events that are being logged on your system. It is a good idea to visit this viewer once in awhile to make sure things are running as they should and no big error messages are being generated. The logs you should see is Application, Security, System and Internet Explorer.

Each one of these covers different types of events. One is for applications (where we will put our events), security is for logins, System is for windows system processes and then of course one for Internet Explorer (bleh!). It is important to remember these types because they correspond to the types of logs you will see in the "Log" property of our EventLog control in our project.

Since we are creating an application, it makes sense that we would put application messages in the applications log. So start a new project in VB.NET. In the control toolbox you will see a control "EventLog" which should be located under the Components sub menu of the toolbox. Dragging this control onto the form will put it in the projects tray (that location where other controls like datasets, timers, and imagelists go). Once we have that in our project, we can configure it by selecting it and going to the properties window. There will be a few fields here we will want to change. The first is the Log field, which we discussed above, is the type of logging we are going to be doing. We can set this to the Application log. The second field is the "Source" field which is the name that is going to be given to the source of the message in the logs. Here I put "My Application". Any time the application logs an entry, it will say that it came from "My Application" as the source. Make sure to keep this short and descriptive so that when you see the error, you know what the source actually means. Lastly, give the control a good standard name. I will leave mine as EventLog1 just to make it generic.

Ok, so we are now all configured. How do we use it to log into the event logs? Simple! There is a method called "WriteEntry" which will take a string as our message along with 8 other overloads that you can play with. Some of them will take eventIDs, others will take event types etc. I encourage you to make sure that the message is very precise and includes any error numbers that may help users understand what is actually going on. You want them to know why your application had to close or why it was important that the message be logged. You don't want to be logging EVERYTHING into the log, but key crucial messages may be helpful.

In the code below we use a simple button event to write our message into the log...

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
		' Write two entries, one is a standard info entry, the other is a warning that our application is hostile!
		EventLog1.WriteEntry("Our application generated an entry in the application log!")
		EventLog1.WriteEntry("Warning: Our application is hostile!", System.Diagnostics.EventLogEntryType.Warning)
End Sub



So as you can see, writing to the log is not hard and we can easily customize the message to be an error, warning, or just informational message to name a few. We can include event IDs that may or may not correspond to Windows event IDs and can add whatever information we want to the message field. Perhaps we have an info dump or just to let the user know that we started a service on their computer.

After we run the code above, we can go look in the log viewer to see if we see our messages....

Posted Image

And there we go, we see our events recorded in the event logs for applications and one is our warning. That is all there is to it. Of course since this is a .NET application you could use both VC++ and C# to do something similar. You could even create this control on the fly and configure it through code. Ideally only one event log class would be needed and you could configure it to log all your activities to the different logs. Play around with it and see what you can do with it. Just don't flood the user's logs with useless information. Keep in mind that many people won't be seeing your messages on a regular basis unless something is going wrong. So don't put application critical information in it unless you have no choice.

Thanks for reading! :)

Filed in Basics

  • (13 Pages)
  • +
  • 1
  • 2
  • 3
  • Last »


Live Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month