<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Aaron Gadberry &#187; Programming</title>
	<atom:link href="http://www.gadberry.com/aaron/category/computers/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.gadberry.com/aaron</link>
	<description>Help - v. helped, helpÂ·ing, helps</description>
	<lastBuildDate>Thu, 02 Sep 2010 13:42:36 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Use NULLS FIRST in TOPLink Expression API Ordering</title>
		<link>http://www.gadberry.com/aaron/2008/01/22/use-nulls-first-in-toplink-expression-api-ordering/</link>
		<comments>http://www.gadberry.com/aaron/2008/01/22/use-nulls-first-in-toplink-expression-api-ordering/#comments</comments>
		<pubDate>Wed, 23 Jan 2008 01:37:36 +0000</pubDate>
		<dc:creator>Aaron</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.gadberry.com/aaron/2008/01/22/use-nulls-first-in-toplink-expression-api-ordering/</guid>
		<description><![CDATA[There is no specific method for NULLS FIRST (default is NULLS LAST), but you can still accomplish this through the expression api. You can simply append some sql to the end of your ordering field expression and it will take care of it for you. For example, if you are ordering by the name then [...]]]></description>
			<content:encoded><![CDATA[<p>There is no specific method for NULLS FIRST (default is NULLS LAST), but you can still accomplish this through the expression api.</p>
<p>You can simply append some sql to the end of your ordering field expression and it will take care of it for you.</p>
<p>For example, if you are ordering by the name then this would put the nulls last (default):</p>
<div class="code_box"><code>query.addOrdering(builder.get("name"));
</code></div>
<p>This code could be ammended into the following to put nulls first:</p>
<div class="code_box"><code>query.addOrdering(builder.get("name").postfixSQL("NULLS FIRST"));
</code></div>
<p>It&#8217;s that easy.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.gadberry.com/aaron/2008/01/22/use-nulls-first-in-toplink-expression-api-ordering/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Find the Difference Between two Java Dates (Calendars)</title>
		<link>http://www.gadberry.com/aaron/2007/08/17/find-the-difference-between-two-java-dates-calendars/</link>
		<comments>http://www.gadberry.com/aaron/2007/08/17/find-the-difference-between-two-java-dates-calendars/#comments</comments>
		<pubDate>Fri, 17 Aug 2007 20:40:58 +0000</pubDate>
		<dc:creator>Aaron</dc:creator>
				<category><![CDATA[Computers]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.gadberry.com/aaron/2007/08/17/find-the-difference-between-two-java-dates-calendars/</guid>
		<description><![CDATA[Well the first question to ask is what unit do you want the difference in. This is one of the reasons many people stick to incremental date math instead of math returning an int. Lets say you want to do a basic age calculation. How old is Joe? His birthday is 7/29/1981. Well you could [...]]]></description>
			<content:encoded><![CDATA[<p>Well the first question to ask is what unit do you want the difference in.  This is one of the reasons many people stick to incremental date math instead of math returning an int.</p>
<p>Lets say you want to do a basic age calculation.  How old is Joe?  His birthday is 7/29/1981.  Well you could subtract 1981 from today, then determine if he had a birthday this year, which could mean comparing everything up to the milliseconds.  The problem is, such a calculation is not as accurate as it would seem.  This style method fails to preserve the validity of the passing of leap years, leap seconds, etc.  If you asked how many days old Joe is then your answer would be something like 365 * (current &#8211; 1981) + number of days this year &#8211; number of days between Jan 1 and July 29.  Well you forgot a few leap days in there, at least 5.<br />
<span id="more-106"></span><br />
I don&#8217;t know about you, but inaccurate results bug me.  So I went about researching the correct way to solve this problem.  Turns out that adding through the Calendar add method preserves these little nuances.  The way to solve this is to increment one date until it passes the second date, counting the times it is incremented.</p>
<p>What?!?  But it will take forever to count the number of days that passed between Joe&#8217;s birthday and today!  What if I needed to know the number of hours, seconds, or even worse, milliseconds?  Well we can build in some optimization just for that.</p>
<p>The method I wrote has the following signature <span class="code_line"><code>CalendarUtils.difference(Calendar c1, Calendar c2, int unit);</code></span>.  To figure out Joe&#8217;s age we would call it with something like <span class="code_line"><code>CalendarUtils.difference(birthday, today, Calendar.YEAR);</code></span>.</p>
<p>Enough with the small talk.  Here&#8217;s the code.  It happens to be part of an open source project I work on, <a href="http://code.google.com/p/jexel/">JExel</a>.  Here is the most recent, complete <a href="http://jexel.googlecode.com/svn/Expression/src/com/gadberry/utility/CalendarUtils.java">CalendarUtils.java</a>.</p>
<div class="code_box"><code>
public static long difference(Calendar c1, Calendar c2, int unit) {

	differenceCheckUnit(unit);

	Map&lt;Integer, Long&gt; unitEstimates = differenceGetUnitEstimates();

	Calendar first = (Calendar) c1.clone();
	Calendar last = (Calendar) c2.clone();

	long difference = c2.getTimeInMillis() - c1.getTimeInMillis();

	long unitEstimate = unitEstimates.get(unit).longValue();
	long increment = (long) Math.floor((double) difference / (double) unitEstimate);
	increment = Math.max(increment, 1);

	long total = 0;

	while (increment &gt; 0) {
		add(first, unit, increment);
		if (first.after(last)) {
			add(first, unit, increment * -1);
			increment = (long) Math.floor(increment / 2);
		} else {
			total += increment;
		}
	}

	return total;

}

private static Map&lt;Integer, Long&gt; differenceGetUnitEstimates() {
	Map&lt;Integer, Long&gt; unitEstimates = new HashMap&lt;Integer, Long&gt;();
	unitEstimates.put(Calendar.YEAR, 1000l * 60 * 60 * 24 * 365);
	unitEstimates.put(Calendar.MONTH, 1000l * 60 * 60 * 24 * 30);
	unitEstimates.put(Calendar.DAY_OF_MONTH, 1000l * 60 * 60 * 24);
	unitEstimates.put(Calendar.HOUR_OF_DAY, 1000l * 60 * 60);
	unitEstimates.put(Calendar.MINUTE, 1000l * 60);
	unitEstimates.put(Calendar.SECOND, 1000l);
	unitEstimates.put(Calendar.MILLISECOND, 1l);
	return unitEstimates;
}

private static void differenceCheckUnit(int unit) {
	List&lt;Integer&gt; validUnits = new ArrayList&lt;Integer&gt;();
	validUnits.add(Calendar.YEAR);
	validUnits.add(Calendar.MONTH);
	validUnits.add(Calendar.DAY_OF_MONTH);
	validUnits.add(Calendar.HOUR_OF_DAY);
	validUnits.add(Calendar.MINUTE);
	validUnits.add(Calendar.SECOND);
	validUnits.add(Calendar.MILLISECOND);

	if (!validUnits.contains(unit)) {
		throw new RuntimeException(
				"CalendarUtils.difference one of these units 
				Calendar.YEAR,
				Calendar.MONTH,
				Calendar.DAY_OF_MONTH,
				Calendar.HOUR_OF_DAY,
				Calendar.MINUTE,
				Calendar.SECOND,
				Calendar.MILLISECOND."
				);
	}
}

public static void add(Calendar c, int unit, long increment) {
	while (increment &gt; Integer.MAX_VALUE) {
		c.add(unit, Integer.MAX_VALUE);
		increment -= Integer.MAX_VALUE;
	}
	c.add(unit, (int) increment);
}

</code></div>
<p>You can find the JUnit test cases I run this method through <a href="http://jexel.googlecode.com/svn/Expression/tests/com/gadberry/utility/CalendarUtilsTests.java">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.gadberry.com/aaron/2007/08/17/find-the-difference-between-two-java-dates-calendars/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>JExel &#8211; Java Based Expression Language Parser</title>
		<link>http://www.gadberry.com/aaron/2007/07/26/jexel-java-based-expression-language-parser/</link>
		<comments>http://www.gadberry.com/aaron/2007/07/26/jexel-java-based-expression-language-parser/#comments</comments>
		<pubDate>Fri, 27 Jul 2007 03:35:02 +0000</pubDate>
		<dc:creator>Aaron</dc:creator>
				<category><![CDATA[Computers]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.gadberry.com/aaron/2007/07/26/jexel-java-based-expression-language-parser/</guid>
		<description><![CDATA[I have published a pet project of mine online recently. After looking at many different project hosting sites I resolved on google code. It seems to have a great interface and amount of space available. The project is called JExel, and is a Java based expression language parser. It&#8217;s not complex to utilize, and can [...]]]></description>
			<content:encoded><![CDATA[<p>I have published a pet project of mine online recently.  After looking at many different project hosting sites I resolved on google code.  It seems to have a great interface and amount of space available.</p>
<p>The project is called JExel, and is a Java based expression language parser.  It&#8217;s not complex to utilize, and can be the perfect plugin library for usage in your larger Java application.  JExel parses string expressions to an object result.  It comes with native boolean, math, string and date functionality.</p>
<p>A boolean expression utilization would look something like <span class="code_line"><code>Expression.evaluateToBoolean("true AND false");</code></span> and, in this case, would return a <span class="code_line"><code>new Boolean(false);</code></span>.</p>
<p>Of course there are also included methods <span class="code_line"><code>evaluateToDouble(String)</code></span> and <span class="code_line"><code>evaluateToString(String)</code></span>.</p>
<p>Additionally there is a plain <span class="code_line"><code>evaluate(String)</code></span> method that returns an Argument.  You can then call getObject() on the resulting Argument and get the actual Object result.</p>
<p>You can expand on the included operators, and write your own to accomplish your own task.  You can provide a Resolver which can resolve string variables found in the expression via your own needs.  Say you had an expression like <span class="code_line"><code>Expression.evaluateToDouble("path/to/variable + otherVariable");</code></span>.  This means if you provide a resolver then you can gain variable resolution relevant to your own project.  Maybe path/to/variable is translated into &#8220;6&#8243; and otherVariable is translated into &#8220;4&#8243;.  Then the result would be 10.</p>
<p>Have fun!  <a href="http://code.google.com/p/jexel/">Start Exploring JExel</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.gadberry.com/aaron/2007/07/26/jexel-java-based-expression-language-parser/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Inject Build Time (timestamp) Property Using Maven</title>
		<link>http://www.gadberry.com/aaron/2007/05/28/inject-build-time-timestamp-property-using-maven/</link>
		<comments>http://www.gadberry.com/aaron/2007/05/28/inject-build-time-timestamp-property-using-maven/#comments</comments>
		<pubDate>Mon, 28 May 2007 19:49:04 +0000</pubDate>
		<dc:creator>Aaron</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.gadberry.com/aaron/2007/05/28/inject-build-time-timestamp-property-using-maven/</guid>
		<description><![CDATA[In your pom.xml you have the ability to turn on resource filtering that replaces variables in resource files with actual values. These are useful for things like ${pom.name} and ${pom.version}. Your pom.xml section would look something like this&#8230; &#60;build&#62; &#60;resources&#62; &#60;resource&#62; &#60;directory&#62;src/main/resources&#60;/directory&#62; &#60;filtering&#62;true&#60;/filtering&#62; &#60;/resource&#62; &#60;/resources&#62; &#60;/build&#62; And your properties file could contain something like these [...]]]></description>
			<content:encoded><![CDATA[<p>In your pom.xml you have the ability to turn on resource filtering that replaces variables in resource files with actual values.  These are useful for things like ${pom.name} and ${pom.version}.  Your pom.xml section would look something like this&#8230;</p>
<div class="code_box"><code>&lt;build&gt;
  &lt;resources&gt;
    &lt;resource&gt;
      &lt;directory&gt;src/main/resources&lt;/directory&gt;
      &lt;filtering&gt;true&lt;/filtering&gt;
    &lt;/resource&gt;
  &lt;/resources&gt;
&lt;/build&gt;
</code></div>
<p>And your properties file could contain something like these</p>
<div class="code_box"><code># Build Time Information
APPLICATION.NAME=${pom.name}
APPLICATION.VERSION=${pom.version}</code></div>
<p><span id="more-103"></span><br />
There is a list of available properties that you can use here <a href="http://docs.codehaus.org/display/MAVENUSER/MavenPropertiesGuide">http://docs.codehaus.org/display/MAVENUSER/MavenPropertiesGuide</a></p>
<p>Onto the difficult part.  There is no automatic variable that references a current timestamp for use as a buildtime property.  I want a buildtime property available to my webapp so I can see very easily when the currently deployed version was built.</p>
<p>Here is how I accomplished it (it wasn&#8217;t that hard).<br />
There are a few steps to this.</p>
<ol>
<li>Put a placeholder in the properties file.</li>
<li>Replace the placeholder with a timestamp at build time</li>
<li>Remove the updated file to allow the file to be refreshed at the next build time</li>
</ol>
<p>Step 1: Add a property such as <span class="code_line"><code>APPLICATION.BUILDTIME=HOLDER</code></span></p>
<p>Step 2: Include an ant execution in your build.  This is not extremely difficult.  Place a plugin in the plugins tag in the POM.</p>
<div class="code_box"><code>
&lt;plugin&gt;
  &lt;artifactId&gt;maven-antrun-plugin&lt;/artifactId&gt;
  &lt;executions&gt;
    &lt;execution&gt;
      &lt;id&gt;set-build-time&lt;/id&gt;
      &lt;phase&gt;process-sources&lt;/phase&gt;
      &lt;configuration&gt;
        &lt;tasks&gt;
          &lt;tstamp&gt;
            &lt;format property="timestamp" pattern="yyyy/MM/dd HH:mm:ss z"/&gt;
          &lt;/tstamp&gt;
          &lt;replaceregexp byline="true"&gt;
            &lt;regexp pattern="APPLICATION\.BUILDTIME=HOLDER" /&gt;
            &lt;substitution expression="APPLICATION.BUILDTIME=${timestamp}" /&gt;
            &lt;fileset dir="src/main/resources/pathToPropertyFileDirectory" includes="*.properties" /&gt;
          &lt;/replaceregexp&gt;
        &lt;/tasks&gt;
      &lt;/configuration&gt;
      &lt;goals&gt;
        &lt;goal&gt;run&lt;/goal&gt;
      &lt;/goals&gt;
    &lt;/execution&gt;
  &lt;/executions&gt;
&lt;/plugin&gt;
</code></div>
<p>This will do a regular expression find and replace on HOLDER with the timestamp.</p>
<p>Step 3: I am using continuum so I must clean up my files before continuing.  I use a post cleanup method, and it looks something like this.  I put this under the profiles tag.</p>
<div class="code_box"><code>&lt;profile&gt;
  &lt;id&gt;cleanProperties&lt;/id&gt;
  &lt;build&gt;
    &lt;plugins&gt;
      &lt;plugin&gt;
        &lt;artifactId&gt;maven-antrun-plugin&lt;/artifactId&gt;
        &lt;executions&gt;
          &lt;execution&gt;
            &lt;id&gt;cleanProperties&lt;/id&gt;
            &lt;phase&gt;package&lt;/phase&gt;
            &lt;goals&gt;
              &lt;goal&gt;run&lt;/goal&gt;
            &lt;/goals&gt;
            &lt;configuration&gt;
              &lt;tasks&gt;
                &lt;delete dir="./src/main/resources/pathToPropertyFileDirectory" /&gt;
              &lt;/tasks&gt;
            &lt;/configuration&gt;
          &lt;/execution&gt;
        &lt;/executions&gt;
      &lt;/plugin&gt;
    &lt;/plugins&gt;
  &lt;/build&gt;
&lt;/profile&gt;</code></div>
<p>As a final note, do not forget to include the profile when you build your project.  The flag is -P.</p>
<p>And there you have it.  Since it is a POST cleanup you may have to build twice for it to operator properly.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.gadberry.com/aaron/2007/05/28/inject-build-time-timestamp-property-using-maven/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Changing Stylesheets Dynamically</title>
		<link>http://www.gadberry.com/aaron/2006/02/22/changing-stylesheets-dynamically/</link>
		<comments>http://www.gadberry.com/aaron/2006/02/22/changing-stylesheets-dynamically/#comments</comments>
		<pubDate>Thu, 23 Feb 2006 05:24:10 +0000</pubDate>
		<dc:creator>Paradochs</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.gadberry.com/aaron/2006/02/22/changing-stylesheets-dynamically/</guid>
		<description><![CDATA[Introduction If you are one of those select few who have multiple stylesheets for their website, then this article is for you. On the other hand, whether you know CSS or not, this might be a good way for you to learn. I know of 4 ways to change between styles dynamically in a page. [...]]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>If you are one of those select few who have multiple stylesheets for their website, then this article is for you. On the other hand, whether you know CSS or not, this might be a good way for you to learn.<br />
I know of 4 ways to change between styles dynamically in a page. They are listed below with some code examples.</p>
<p><span id="more-94"></span></p>
<h3>My Experience</h3>
<p>Originally I created my website using only HTML and tables. That meant long and ugly code, plus it was terrible to maintain. I learned enough CSS to rewrite my page using only CSS and HTML without attributes or tables. This gave me the power to have only content in my HTML, separated by &lt;div&gt; tags. When designing the HTML of a page so that it can be redesigned using CSS, throw in as many &lt;div&gt;&#8217;s as you want. Think of it like object oriented programming: You don&#8217;t want to define a whole slew of pieces all on the same level. You want a container class, sections, parts, etc. Don&#8217;t be afraid of how many &lt;div&gt;&#8217;s you have, just name them well (using ID or class).<br />
Once I had finished rewriting my page so that it looked identical to the original, I decided to overhaul the look of the page. I searched for some designs that I liked, and found a couple that I thought would work. I took the original stylesheet and modified it piece by piece to get a totally different design. This way is easier because you don&#8217;t have to rewrite the entire stylesheet class by class, just modifying, adding, and deleting attributes and values.<br />
At this point I got too excited about it and wrote a total of five styles for my page. I wanted people to see all of them, so I came up with some ways to swap between the styles. I set up a voting script so that the style with the most votes automatically becomes the default. While adding more styles is fun and you learn quite a bit about design of CSS and HTML while doing it, it becomes very difficult to add a section to your page, because you have to add it to all your stylesheets also. (In most cases).<br />
Here are the different ways I know of to change between styles dynamically.</p>
<h3>Multiple &lt;link&gt; Tags in Header</h3>
<p>If you put multiple &lt;link&gt; tags with names, Firefox will be able to switch between them using the dropdown menu. When I did this, it worked perfectly for Firefox only. IE displayed different parts of the page in different styles (obviously it didn&#8217;t work) and also there was no way to switch. I ruled out this option for now until IE catches up to Firefox. (Therefore this will never be a viable option)   :)</p>
<div class="code_box"><code>
&lt;link rel='stylesheet' type='text/css' href='first.css' title='First'&gt;
&lt;link rel='stylesheet' type='text/css' href='second.css' title='Second'&gt;
&lt;link rel='stylesheet' type='text/css' href='third.css' title='Third'&gt;
</code></div>
<h3>Using PHP and GET Variables</h3>
<p>This is the best (most stable) way that I&#8217;ve implemented so far. When a page is loaded, simply pull the GET variable &#8220;style&#8221; out of the address bar. If there isn&#8217;t one, then set the variable equal to a default style. Use that variable as the stylesheet filename.<br />
The problem with this is that you have to use PHP or some other script language to implement it. If you already are using one then it is not a problem at all. Another problem is that you have to add the <span class="code_line"><code>"?style=whatever.css"</code></span> dynamically to all of your internal links. Basically, any time you click on a link, it has to have the stylesheet GET variable at the end of the line. This can also be done with PHP, but not too easily, especially if you already are using GET variables. There is an example of code below. </p>
<div class="code_box"><code>
&lt;?php
	if(isset($_GET[style]))
		$style = $_GET[style];
	else if(!isset($_SESSION[style]))
		$style = "default.css";
	echo "
	&lt;link rel='stylesheet' type='text/css' href='$style' title='Current'&gt;
	";
?&gt;
</code></div>
<h3>Using PHP, GET Variables and Sessions</h3>
<p>This is the same concept as the idea above, but instead of having the GET variable on every single page and link, simply set up a script that, if the GET variable is set, sets a session variable with the value of the GET variable. Then when you create your &lt;link&gt; tag, you simply use the session value as the filename.<br />
The drawbacks similar to above because you have to use a scripting language to set the session variable and echo it back to the &lt;link&gt; tag. The upside is that you don&#8217;t have to change any of your links. To change between two styles all you have to have is a link with <span class="code_line"><code>href="?style=whatever.css"</code></span>. That will reload the current page with the style of whatever.css.<br />
Here&#8217;s how I implemented it. This code didn&#8217;t work very well for me, but did work sometimes.</p>
<div class="code_box"><code>
&lt;?php
	session_start();
	if(isset($_GET[style]))
		$_SESSION[style] = $_GET[style];
	else if(!isset($_SESSION[style]))
		$_SESSION[style] = "default.css";

	echo "
	&lt;link rel='stylesheet' type='text/css' href='$_SESSION[style]' title='Current'&gt;
	";
?&gt;
</code></div>
<h3>Using PHP, GET Variables and Cookies (The best and most stable way)</h3>
<p>This is the best and cleanest way I&#8217;ve found so far. There is no GET variable in every address, and it has worked perfectly for me so far. It is basically the same as the idea above with session variables. Set a cookie to the default stylesheet filename. If there is a GET variable, set the cookie to it instead. When the &lt;link&gt; is set, use the cookie variable to fill in the filename. This works great for me and hasn&#8217;t broken yet. The cookie will stay set, so when a user returns to the page, the latest style the user has chosen is displayed by default. The only minor bug is if your stylesheets change order or you add some. The index might be off and they will view a different page by default the first time they return.<br />
The cookie name can NOT be &#8220;STYLE&#8221;. Firefox accepts it, but it won&#8217;t work in IE. </p>
<div class="filename">functions.php</div>
<div class="code_box"><code>
&lt;?php
	function setCurrentStyle($styleSheets)
	{
		$styleIndexToUse = 0;

		if(!isset($_COOKIE["MYSTYLE"]))
		{
			if(isset($_SESSION["MYSTYLE"]))
			{
				$styleIndexToUse = $_SESSION["MYSTYLE"];
			}
			else
			{
				$styleIndexToUse = 0;
			}
		}
		else
		{
			$styleIndexToUse = $_COOKIE["MYSTYLE"];
		}

		echo "&lt;link href='stylesheets/$styleSheets[$styleIndexToUse][cssname]' rel='stylesheet' type='text/css' /&gt;";
	}
?&gt;
</code></div>
<p>This is the page that changes the stylesheet index. Simply create a link like <span class="code_line"><code>&lt;a href="setstyle.php?SETSTYLE=0" title="Blue Haven"&gt;Blue Haven&lt;/a&gt;</code></span>. Changing the &#8220;0&#8243; and &#8220;Blue Haven&#8221; to whatever you want the style to be.</p>
<div class="filename">setstyle.php</div>
<div class="code_box"><code>
&lt;?php

	// SET COOKIE FOR 1 YEAR
	if(isset($_REQUEST["SETSTYLE"]))
	{
		if(setcookie("testcookie",true))
		{
			setcookie("MYSTYLE",$_REQUEST["SETSTYLE"],time()+31622400);
		}
		else
		{	
			$_SESSION["MYSTYLE"]=$_REQUEST["SETSTYLE"];
		}
	}

	// RETURN TO CALLER PAGE
	header("Location: ".$_SERVER["HTTP_REFERER"]);
?&gt;
</code></div>
<h3>Conclusion</h3>
<p>These are the only ways that I have come up to switch the style of a page. Either you can have it work in Firefox only, or you&#8217;re going to have to use a few scripts. If anyone else has any good ideas, I&#8217;d be grateful and I will add them to this list. Leave them as comments or email me. Please send code if you have it also.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.gadberry.com/aaron/2006/02/22/changing-stylesheets-dynamically/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Pop up Photographs (Automatic 2D -&gt; 3D Scene Creation)</title>
		<link>http://www.gadberry.com/aaron/2006/01/26/pop-up-photographs-automatic-2d-3d-scene-creation/</link>
		<comments>http://www.gadberry.com/aaron/2006/01/26/pop-up-photographs-automatic-2d-3d-scene-creation/#comments</comments>
		<pubDate>Fri, 27 Jan 2006 00:18:08 +0000</pubDate>
		<dc:creator>Paradochs</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.gadberry.com/aaron/2006/01/26/pop-up-photographs-automatic-2d-3d-scene-creation/</guid>
		<description><![CDATA[Pop up Photographs (P.u.P.) Travis Gadberry Christopher Skelton CPSC 641(485) &#8211; Dr. John Keyser December 13, 2005 Introduction Our original plan had been to implement our own version of the SIGGRAPH paper â€œAutomatic Photo Pop-upâ€, from the 2005 SIGGRAPH proceedings. We researched ourselves into a corner, realizing that what we had taken on a project [...]]]></description>
			<content:encoded><![CDATA[<p>Pop up Photographs (P.u.P.)<br />
Travis Gadberry<br />
Christopher Skelton<br />
CPSC 641(485) &#8211; Dr. John Keyser<br />
December 13, 2005</p>
<h3>Introduction</h3>
<p>Our original plan had been to implement our own version of the SIGGRAPH paper â€œAutomatic Photo Pop-upâ€, from the 2005 SIGGRAPH proceedings.  We researched ourselves into a corner, realizing that what we had taken on a project that was going to take many, many more months to complete than the time we had to work on this project.  We decided, then, to plan out and research what we would have done if we had more time to work on this.  This paper explains the approach that we took in an attempt to implement the paper.  Even the simplified version that we had planned on still turned out to be too much to tackle in one semester.</p>
<h3>Summary</h3>
<p>The user loads the image by passing the image filename as a parameter to the executable file. The program then reads the file and sets the height and width accordingly. The image is then broken into regions with region codes. Each region makes up one polygon of the final scene. Once all the regions are created and coded, the region map is created. This is an image with the same dimensions as the original and contains the regions scan converted using a parallel view. Each region code has a different color, 0 = red, 1 = blue, and 2 = green. Then the regions are given world points based on the pixels vertically below it in the region map. Once all the regions are converted to world space, they are then drawn in the final scene and texture mapped. The user can then use the fly-through ability to view the scene from any angle.</p>
<p><span id="more-89"></span></p>
<h3>Loading an Image</h3>
<p>Since we chose OpenGL to develop this project, loading a picture became an issue.  The way we chose to load the image for processing and display was to load it as a texture and paste it onto a quad.  Since most picture are 3&#215;5 or 4&#215;6, OpenGL wouldnâ€™t like that since it only supports square textures.  So the problem was finding a way to load these pictures.  You can â€œpadâ€ a picture by adding extra information to make a square, but we chose not to do that, and try to find an image loading library.  </p>
<p>There is an open source image loading library called DevIL(DEVelopers Image Library) that supports non-square image loading for textures in a wide variety of image formats.  This seemed to be the golden ticket.  Not only did we take care of the non-square problem, but now we didnâ€™t have to worry about writing our own code to load a specific file format.  There were a few problems (mainly with VS .NET not knowing where to look for the file at compilation/linking time), but in the end it was up and running.  </p>
<p>Happy with DevIL, but still curious to see what else was out there, we kept digging around.  We discovered that OpenGL had extensions of its own that allows for textures with non-power of two dimensions, provided your video card is recent enough to support it.  They allow you to use your OpenGL code exactly like you would use it for square textures, but you specify non square dimension when creating your texture (in glTexImage2D).  The only problem with this was that we would have to write our own code to load an image.  This was easy enough to do if you wanted to load 24 bit bitmaps, since the code was pretty straightforward, but bitmaps take up a lot of space, and we had hoped to use jpgs or some other compressed format, which is why DevIL is so wonderful, because it supports those.</p>
<h3>Creating Regions Manually</h3>
<p>The most effective way to manually input the regions was to use a mouse capture function. Using OpenGL, we displayed the picture in a parallel view to the screen. We were able to save the points the mouse moved over while being clicked using built in functions of OpenGL. Every time another region is input using the mouse, the user is prompted to input the code for that region. A code of zero means that the region is flat, like the ground in the front of a picture. A code of one means that the region should be displayed vertically and is usually indicative of buildings or walls. A code of two means that it is above the code one regions, whether it be a ceiling or the sky. </p>
<h3>Creating Regions Automatically</h3>
<p>In the SIGGRAPH paper, they used an algorithm to detect â€œregionsâ€ that would be folded to make the 3d image.  Over several passes, they would create â€œsuper pixelsâ€ that were collections of similarly colored pixels.  These â€œsuper pixelsâ€ were then grouped into what they called constellations.  A statistics algorithm was then run on the constellations to find the regions to fold.  </p>
<p>We had designed an algorithm that was significantly less complex, using basic edge detection algorithms, which will be explained in brief below.</p>
<h3>Edge detection</h3>
<p>Originally, we had planned for automation across all aspects of our pop up process.  In order to do so, we needed to be able to detect edges that we wanted to â€œfoldâ€ our image.  There are various edge detection algorithms out there, such as detection of sudden color differences, contrast differences, or a blending of both. </p>
<p>We never could decide on what detection would be best due to the differences in finding edges within a single image. The edges to detect would have to be between ground-wall, wall-sky, and wall-wall. The first two would be relatively simple to implement with the same edge detection technique, but the wall-wall edge would be different. The reason behind this is that the colors on each side of the edge are almost exactly the same. This would make it very difficult to implement an effective technique just by doing edge detection. </p>
<p>The best option using edge detection was to use edges in conjunction with colors. To do this we would implement an edge detection algorithm and find the major edges in the result image. Major edges are the edges in an image that are the most likely to be the edges that are folded on. We would then use the color information to find the ground-wall edges and the wall-sky edges. We would then search the vertical space between those edges for the wall-wall edges in a separate routine. This is the only way that we could think of to possibly use edges in determining where to fold. However, we are not positive that it would work. We did not run any tests or simulations on whether or not it works on all images. </p>
<h3>Region Creation</h3>
<p>To create the regions based on these techniques is relatively simple compared to finding where to create the regions. Once the folding edges are found, each region is defined simply by connecting the edges together and getting the perimeter of the polygon surrounded. The next step is to set the region code of each region. The first step is to set the lowest polygon to be code zero, because one of the requirements of the input image is that there is ground in the foreground. The part is assigning the other region codes. For each region, starting with the lowest and ending with the highest, a code is set based on the codes below it. If there are only regions with code zero below the current region, then it is assigned a code of one. If there are regions with code zero and regions with code one directly below the current region, then it is assigned a code of one. If there are only regions with code one directly below the current region then it is a code two. These codes are the only way that we can determine which regions are ground, wall, and sky.</p>
<h3>Region Map</h3>
<p>The region map is a necessity due to the way we decided to display the regions. We researched different possible options of how to handle the display. We looked into the possibility of using a simple conversion from texture coordinates and region codes into world space, but could not find a suitable function to do the calculations correctly. We then tried to use OpenGL functions to translate and rotate. We had difficulties figuring out how to extract the axis of rotation from the vertices of a region. There were other complications also. We finally settled on the concept of the region map. The region map is an image with the same dimensions as the original image. We render the regions into a buffer using a parallel view to maintain the proportions. We set the color of each region using the associated region code. The region map is simply a scan conversion of the polygons so that the interior points can also have the region codes associated with them. </p>
<h3>Converting Regions to World Space</h3>
<p>The regions at this point are still in texture space, and we had to come up with a way to convert them to world space. We used the region map to do this. We converted each point on the perimeters of the regions one at a time. To convert a single point we used the vertical line under the point in the region map. We counted the total number of pixels that were contained in different region codes. We came up with a total number for region codes zero and one. Once those totals were calculated we used formulas to change those into world space coordinates. The number of pixels with region code zero is the rough amount that the point is moved down the Z axis. The number of pixels with region code one is the rough amount that the point is moved up the Y axis. We ignored region code two because it should never happen and inevitably the scene will be wrong anyway. Once this conversion process is done for every point on ever regionsâ€™ perimeter, they are ready to be displayed.</p>
<p>The following code is the pseudo code to convert the texture coordinates into world space coordinates. For each region code, there are different x, y, and z values calculated. </p>
<div class="code_box"><code>
For each region
{
	for each point on region j
	{
		if region is code 0
		{
			x = 7*(u *2.0 -1);
			y = -4;
			z = 7*(( v *2.0) -1)-7;
		}
		if region is code 1
		{
			ZeroCount = countBelow(u, v, 0);
			OneCount  = countBelow(u, v, 1);
			x =    7*(( ZeroCount/ImageH *2.0) -1);
			y = -4+7*(( OneCount /ImageH *2.0) -1)-7;
			if(OneCount == 0)
				y = -4;
			z = 7*(( v *2.0) -1)-7;
		}
		if region is code 2
		{
			SKY processing
		}
	}
}
</code></div>
<h3>Displaying the Scene</h3>
<p>We used OpenGL for all the display purposes. To display the scene we simply used a vertex array and used the perimeters of the regions. The regions are initially stored using texture coordinates, so texture mapping is not difficult either. We simply used the converted data as the world space coordinates and the original as the texture coordinates. We used preexisting code to implement the fly through, which we had written as part of a homework assignment before. </p>
<h3>Sky Processing</h3>
<p>There is a lot of room to develop this area of the project. The paper we discussed eliminated the sky processing and did not include it in the display. We worked on possible ways to handle the sky, including eliminating it. We came up with three other ways to produce a reasonable representation of the sky. The first was the easiest of the three, and simply forces the program to display the polygons created by the regions. This outcome would might look odd because it would seem like the sky is broken and only in certain places around the top of the building. The second was a little bit more in depth. The program would average the values of all of the pixels in code two regions. It would then create a polygon that connects to the tops of all of the buildings and color it with the average. Finding the tops of all of the buildings wouldnâ€™t be difficult. They could be found by saving the highest points of all of the code one regions. The third option that we came up with was to use a program that we read about in our research. The program takes a sample image and generates a texture which is essentially tiled with the image. The program does not simply tile the sample over and over, but generates an extrapolation of what a continued picture would look like. This would give a much better sky and would be able to create clouds, birds, and other such objects that might be in the sky. We would then use that image to texture the polygon that spans the entire top of the scene. The sky would have to be optional to include because users might not want to have it there, especially if the modifications are made to turn multiple images into a model (see future work).</p>
<h3>Future Research</h3>
<p>Generate a fly-through of an area and building. It can be used for professional use in portfolios of architects and designers, as well as personal use in showing off vacation pictures or homes. It adds more aesthetic value to simple photographs by providing a third dimension. </p>
<p>More technical possibilities are possible, such as extrapolating data about a building from a photo. Given enough photos, it would be relatively simple to create a full model of a building and the surrounding area. The same techniques could be used to recreate towns with groups of buildings.</p>
<p>This technique could also be modified to handle two or more images and create something like a layered depth image. Multiple objects at each point would make many things possible. A user could load multiple images and the program could automatically create the scenes, find similarities between them, and combine them into a single scene. The ability to create an entire texture mapped model by simply loading images of the building into the program would have many possible advantages. Architecture planning and displays would have the most obvious benefit. Other possibilities include personal use and simple model creation for use in larger scenes. </p>
<h3>Conclusion</h3>
<p>We took on this project with a simple concept in our heads. We assumed that we knew everything that we needed to be able to complete this project in its entirety. We began designing the program based on what we knew, but we soon discovered that our approach would not even come close to satisfying the requirements. We began researching the concepts that we discovered we would need to implement. It soon became clear that we would not be able to code this in the time we had. There is an amazing amount of coding involved in the creation of this program, and we did not have the resources or the time to complete it. At that point we decided to not attempt the coding at all, because we would not be able to complete anything that would have visible results. Instead we decided to research and learn about everything that we would need to know to code the project.  This project is a prime example of not judging a book by its cover.  The output is deceptively simple, covering a large amount of brilliant work on their part.  </p>
]]></content:encoded>
			<wfw:commentRss>http://www.gadberry.com/aaron/2006/01/26/pop-up-photographs-automatic-2d-3d-scene-creation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rule-Based Tic Tac Toe</title>
		<link>http://www.gadberry.com/aaron/2006/01/26/rule-based-tic-tac-toe/</link>
		<comments>http://www.gadberry.com/aaron/2006/01/26/rule-based-tic-tac-toe/#comments</comments>
		<pubDate>Thu, 26 Jan 2006 22:37:45 +0000</pubDate>
		<dc:creator>Paradochs</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.gadberry.com/aaron/2006/01/26/rule-based-tic-tac-toe/</guid>
		<description><![CDATA[Summary This program is an implementation of a rule-based AI game. The game has 5 difficulty levels based on how good you want the computer to be. It can range from making many mistakes to being impossible to beat. There is also an option for who gets to move first. Details Difficulty levels were relatively [...]]]></description>
			<content:encoded><![CDATA[<h3>Summary</h3>
<p>This program is an implementation of a rule-based AI game. The game has 5 difficulty levels based on how good you want the computer to be. It can range from making many mistakes to being impossible to beat. There is also an option for who gets to move first.</p>
<p><span id="more-84"></span></p>
<h3>Details</h3>
<p>Difficulty levels were relatively easy to create. The simple concept is the make the computer â€œforgetâ€ to check specific rules. Problems arise if you take out rules, because then there will be specific patterns of play that will constantly win. What I did to put probability into the equation is simple. I generate a random number in a large range (1-32000 approx). I then take the modulus of the random number % difficulty level. This makes my new random number in a smaller or larger range, based on the difficulty level. The harder it is set on, the larger the range of the random number. A new random number is generated and scaled for every rule. Then the test is simple. If the random number = 1 then the rule is not calculated. This gives the program a 1 / (range of random #) to fail that rule. The special case is the perfect machine. The highest difficulty level means that all rules are checked all the time. For this I simply have a Boolean flag that must be true for any rules to fail. </p>
<p>The board is simple, just an array of characters. The players take turns back and forth until someone wins or until all of the spaces are filled. There is another menu option of choosing who moves first, which is also simple to implement. </p>
<p>The OpenGL was thrown together to put a graphical interface on the program. It is simply a few cylinders in different colors. </p>
<h3>The Rules</h3>
<p>The idea of the rules behind this game is easy. There are seven rules.</p>
<ol>
<li>If you can win, take the win.</li>
<li>If you can block a win, block it.</li>
<li>If you control center, he controls a side, and itâ€™s only your second turn, take the adjacent side. This is a combo play and requires you to move in the corner between the previous side moves. </li>
<li>If he has two adjacent sides then take the corner between them.</li>
<li>If he has a corner and an opposing side, move in the other opposing side.</li>
<li>If he has opposing corners and you control the center, move in any side.</li>
<li>If no previous rule applies, take any space.</li>
</ol>
<p>Here are the pictorial representations of the rules.<br />
Codes on board</p>
<ul>
<li>O = opponent&#8217;s space</li>
<li>X = my space</li>
<li>M = my choice of move</li>
<li>A = opponent&#8217;s assumed next move</li>
<li>P = my previous move of a strategy</li>
</ul>
<p><img src="http://www.gadberry.com/aaron/wp-content/uploads/2006/01/rules.jpg"></p>
<h3>C++ Code</h3>
<div class="filename">
<a target="_blank" href="http://www.gadberry.com/aaron/wp-content/uploads/2006/01/hw7.cpp">hw7.cpp</a><br />
<a target="_blank" href="http://www.gadberry.com/aaron/wp-content/uploads/2006/01/GadTicTacToe.h">GadTicTacToe.h</a><br />
<a target="_blank" href="http://www.gadberry.com/aaron/wp-content/uploads/2006/01/GadTicTacToe.cpp">GadTicTacToe.cpp</a>
</div>
<p>This code has a few built in functions to time the sort and count the number of comparisons.<br />
This code was written and compiled successfully in Visual Studio .NET.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.gadberry.com/aaron/2006/01/26/rule-based-tic-tac-toe/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cryptarithmatic</title>
		<link>http://www.gadberry.com/aaron/2006/01/26/cryptarithmatic/</link>
		<comments>http://www.gadberry.com/aaron/2006/01/26/cryptarithmatic/#comments</comments>
		<pubDate>Thu, 26 Jan 2006 22:25:06 +0000</pubDate>
		<dc:creator>Paradochs</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.gadberry.com/aaron/2006/01/26/cryptarithmatic/</guid>
		<description><![CDATA[Original Assignment Write a program to solve a simple class of cryptarithmetic problems MORE EFFICIENTLY THAN BY BRUTE FORCE (EXHAUSTIVE SEARCH) by using deductions about even/odd, digit range, etc. For example, in the test case CADET +CORPS &#8212;&#8212;&#8212; TROOP given below your program can deduce that C]]></description>
			<content:encoded><![CDATA[<h3>Original Assignment</h3>
<p>Write a program to solve a simple class of cryptarithmetic problems MORE EFFICIENTLY THAN BY BRUTE FORCE (EXHAUSTIVE SEARCH) by using deductions about even/odd, digit range, etc.  For example, in the test case </p>
<p> CADET<br />
+CORPS<br />
&#8212;&#8212;&#8212;<br />
 TROOP</p>
<p><span id="more-79"></span></p>
<p>given below your program can deduce that C<5.  (You do not have to use this deduction; this is just an example of a deduction which would reduce the search space.) By convention, each letter stands for a different digit and there are no leading zeroes.</p>
<p>You program should read strings (hint: in C, use fgets), right justify the strings to make an addition problem, and find a solution.  If there is more than one solution, you only need to find one.  For the example in Figure 5.2, the input would be</p>
<p> TWO<br />
 TWO<br />
FOUR</p>
<p>Run your program on this example plus the following:</p>
<p>JAVA<br />
 OOP<br />
LANG</p>
<p>CADET<br />
CORPS<br />
TROOP</p>
<p> KYLE<br />
FIELD<br />
AGGIE</p>
<p>The grader will also run your project on additional problems.  You may assume the input contains only upper case letters, and no more than 10 different letters.</p>
<h3>My Solution</h3>
<p>Firstly, I did not find one answer. I found them all.<br />
Second, I found them all in under a second in every case I tried<br />
Third, parts of the code and design may not be pretty, but they went way above and beyond the requirements and the time frame I was given to code this.</p>
<h3>Data &#038; Algorithm</h3>
<p>I set up data structures to hold all of the possible values of every letter. Yes, all 26 letters. There can only be 10 unique letters in each puzzle though. </p>
<p>The next thing I did was to try and narrow down each of those lists using simple rules. The easiest rule is that if the character doesnâ€™t appear in the puzzle, it has no possible values. That eliminates at least 160 numbers in your list (16 letters * 10 numbers).</p>
<p>There are several other rules that can be stated.</p>
<h4>Rules</h4>
<ol>
<li>If the two letters added together are identical characters, the one below them must be even. That eliminates half of the numbers available for that character.
<li>If the far two characters that add together are different, but the character they add up to be is the same as one of them, the other one must be equal to 0. ( A+B=A : B=0) Note: This only works for the far right-hand column as other columns might have a carry.
<li>On the far left columns, if the answer word is longer than both the added words, the farthest left digit of the answer word is a 1.
</ol>
<p>I believe these are the only ones I implemented, but there might be more and better ones out there if you think hard enough.</p>
<p>I then order the characters from the top right to the bottom left, going down first. IE for the example with JAVA above, the order would be APGVONJL. Only count each character once and do it in the order you naturally add in. This is the order in which I solved.</p>
<p>I then did a brute force set of for loops, in which I set every letter to the numbers it could possibly be, starting the outside loop with the first letter of the solving order (above). After every time I set three characters, I test the partial results. If the numbers that are set add up, then I continue with the rest of the for loops. If is doesnâ€™t add up, then I break back down a loop and continue the iterations of the previous number. By doing this I find problems early in the assigning of numbers and incredibly reduce the amount of time needed to find all solutions. I record the number of solutions I take to completion and the number of correct answers. Because my program finds most of the problems before assigning all of the numbers, the number of completed assignments is not much greater than the number of solutions in most cases. </p>
<h3>Web Based Attempt</h3>
<p>I tried to put this on the web using a php script and html forms. I never could get it working quite right due to compiling issues on the server (ie we donâ€™t allow compiling on the server). I tried using a virtual machine with the same OS as the server, but to no triumph. If anyone has any tips on how to get it to work, let me know. </p>
<h3>Files and C++ Code</h3>
<div class="filename">
<a target="_blank" href="http://www.gadberry.com/aaron/wp-content/uploads/2006/01/assignment.txt">assignment.txt</a><br />
<a target="_blank" href="http://www.gadberry.com/aaron/wp-content/uploads/2006/01/crypto.cpp">crypto.cpp</a><br />
<a target="_blank" href="http://www.gadberry.com/aaron/wp-content/uploads/2006/01/cryptoReg.exe">cryptoReg.exe</a>
</div>
<p>This code has a few built in functions to time the sort and count the number of comparisons.<br />
This code was written and compiled successfully in Visual Studio .NET.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.gadberry.com/aaron/2006/01/26/cryptarithmatic/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Inference Engine</title>
		<link>http://www.gadberry.com/aaron/2006/01/26/inference-engine/</link>
		<comments>http://www.gadberry.com/aaron/2006/01/26/inference-engine/#comments</comments>
		<pubDate>Thu, 26 Jan 2006 22:19:54 +0000</pubDate>
		<dc:creator>Paradochs</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.gadberry.com/aaron/2006/01/26/inference-engine/</guid>
		<description><![CDATA[Statement of Problem The purpose of this assignment is to create a Horn clause solver. This solver must read in logical expressions, or rules, and then be able to determine if it is possible to prove a certain variable true or false. The structure of the input, rules maintenance, and proving algorithm is not specified. [...]]]></description>
			<content:encoded><![CDATA[<h3>Statement of Problem</h3>
<p>	The purpose of this assignment is to create a Horn clause solver. This solver must read in logical expressions, or rules, and then be able to determine if it is possible to prove a certain variable true or false. The structure of the input, rules maintenance, and proving algorithm is not specified. The significance of this problem is simple. Input can be related to percepts, and deductions can be related to actions. This program is a simple way of representing logical thinking in an AI machine. A simple conditional agent responds logically based on the rules the user/programmer inputs. Although limited, it can be very powerful if implemented correctly.</p>
<p><span id="more-71"></span></p>
<h3>Restrictions and limitations</h3>
<p>	The input for this program is assumed to be always correctly input by the user. The program checks for contradictions as the user enters new rules, and if the new rule is found to be contradictory it is ignored. This solver is more than a Horn clause solver. It can also solve most any clauses, by the inclusion of the â€œnotâ€ case. For example, â€˜aâ€™ is the same as not â€˜Aâ€™. The rules must still be inputted using the standard Horn clause format, with only one term on the right hand side and only AND operations and variables on the left. The program will check to see if the input is in a valid form. If there is an unknown character or more than one character after the implication symbol, it will return the problem and not add the rule. When the user inputs a character to prove the program can only output whether it is true, false, or maybe, but can not output how it got to that conclusion. The reason is in the next section. In some input situations, if a character is input where a number was expected, the program will exit without stating a reason. </p>
<h3>Explanation of Strategy</h3>
<p>	I used C++ for everything. I wrote a class â€œRuleâ€ to handle every clause given. It contains several constructors, a vector of chars for the left side, and a single character variable for the right side. I have two vectors of rules constantly maintained throughout the program. The main list is called rulesGiven. This is the list that the user can edit by adding new rules or removing existing ones. The other one is the inferred rules. The inferred list also contains all rules in the given list. Every time the user changes the given list, the program solves for everything that it can. When it solves that a variable is true it adds a truth rule for the character and a false rule for the conjugate variable in the inferred list. When the user inputs a character to prove, the program only has to search through the inferred list once and determine if it has proved it or not. If it hasnâ€™t proved it true or false, then it cannot be determined with the given information and will return â€˜Maybeâ€™. This is why the path of proving can not be printed. The method of proving that I used was a backward solving algorithm. The program goes down every rule in the inferred list and when one matches the right side, it recursively calls the prove function for every character on the left side. Once a rule has completed and returned true, two things happen. The characters needed to prove the original character all have truth rules, and their conjugates all have false rules. This is the most complete and quickest way Iâ€™ve found to implement the solver, and I have yet to find a set of rules that doesnâ€™t work correctly.</p>
<h3>Results and Analysis</h3>
<p>	I ran the program several times, trying to come up with different scenarios and different types of inferences. I tested the program many times, and have found no data that can not be processed correctly. The program does check for contradictions as the user inputs rules, so that filters out most of the types of problems that could arise when trying to prove something. Here are the simplified results of three test runs. Rules given are the rules that I input. Rules inferred are the rules the program created. Truths, falses, and maybes are the variables the program proved true, false or maybe, respectively. The program will return maybe for any variable it can not prove true or false, so if the user tries to prove a variable not given in any rule, it will always return maybe.</p>
<h3>Conclusions</h3>
<p>	My conclusions are simple. This program can take inputs of Horn clauses and, through deduction, prove anything and everything provable using those clauses. I am convinced that the program can handle any set of clauses, although I can not prove it as fact. I do not dismiss the possibility of there being an input set that produces erroneous results. The program is powerful and smart, with the ability to check for repetition of rules, use negated variables in proofs, and even has the ability to check for contradictions while inputting new rules. This is a very logical and robust program.<br />
Future Research<br />
	This program could be built up to be much more powerful if a few modifications were made. First, the rule class would have to be changed to handle full expressions, without designating a left or a right. With the rule class changed, a user could input any logical expressions he needs, including ands, ors, nots, and other functions. Once this is done, a parse algorithm would have to be made to be able to determine the exact meaning of each rule. This would be the hardest part of the upgrade. The algorithm would have to detect what parts are expressions, operators, variables, truths, falses, and equivalences, and then use the rule accordingly. Another upgrade would be to let users define variables with more than one character. I will not try to explain how to implement it, because I do not know how to do it at this time. The last upgrade that I can think of is to let the user create functions. The user could define a function name, variables input, and what the function does. It would then return values of the unknown variable(s) such as in prolog. This is another part that is currently beyond me, but I hope to reach the skill level required soon. </p>
<h3>Instructions</h3>
<p>Menu Appears.</p>
<ol>
<li>
Input rules by choosing option 1.</li>
<ul>
<li>Use the format â€œAB>Câ€  for  â€œA ^ B -> C â€  and  â€œAâ€ for â€œ true -> Aâ€</li>
<li>â€˜*â€™ denotes a truth, â€˜#â€™ denotes a false. These can be used in inputs also.</li>
<li>Ex: â€œ*>Aâ€   is equiv. to â€œ#>aâ€,  and â€œ#B>Câ€  can never be true.</li>
<li>Loops input until you type 0 and press enter.</li>
</ul>
<li>Print the rules by choosing option 2.</li>
<ul>
<li>This prints both the given and the inferred lists of rules.</li>
<li>Program returns to menu.</li>
</ul>
<li>Remove a given rule by choosing option 3.</li>
<ul>
<li>The given list of rules appears with the index of each rule on its left.</li>
<li>Type the index of the rule you wish to remove and press enter.</li>
<li>To exit without removing a rule, input 0.</li>
<li>Program returns to menu.</li>
</ul>
<li>Prove a character by choosing option 4.</li>
<ul>
<li>Type the character you wish to prove and press enter.</li>
<li>The computer will output whether it is true, false, or maybe.</li>
<li>Program returns to menu.</li>
</ul>
<li value=0>Program shuts down by choosing option 0.</li>
</ol>
<h3>Files and C++ Code</h3>
<div class="filename">
<a target="_blank" href="http://www.gadberry.com/aaron/wp-content/uploads/2006/01/Rule.h">Rule.h</a><br />
<a target="_blank" href="http://www.gadberry.com/aaron/wp-content/uploads/2006/01/Rule.cpp">Rule.cpp</a><br />
<a target="_blank" href="http://www.gadberry.com/aaron/wp-content/uploads/2006/01/IEngine.h">IEngine.h</a><br />
<a target="_blank" href="http://www.gadberry.com/aaron/wp-content/uploads/2006/01/IEngine.cpp">IEngine.cpp</a><br />
<a target="_blank" href="http://www.gadberry.com/aaron/wp-content/uploads/2006/01/ProjectReport.doc">ProjectReport.doc</a><br />
<a target="_blank" href="http://www.gadberry.com/aaron/wp-content/uploads/2006/01/SampleRuns.doc">SampleRuns.doc</a>
</div>
<p>This code has a few built in functions to time the sort and count the number of comparisons.<br />
This code was written and compiled successfully in Visual Studio .NET.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.gadberry.com/aaron/2006/01/26/inference-engine/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Searching: Linear Search</title>
		<link>http://www.gadberry.com/aaron/2006/01/24/linear_search/</link>
		<comments>http://www.gadberry.com/aaron/2006/01/24/linear_search/#comments</comments>
		<pubDate>Wed, 25 Jan 2006 02:40:43 +0000</pubDate>
		<dc:creator>Paradochs</dc:creator>
				<category><![CDATA[Computers]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.gadberry.com/aaron/2006/01/24/linear_search/</guid>
		<description><![CDATA[Information Order: O(n) Best Case: O(1) Average: O(n/2) Description (from wikipedia) In computer science, linear search is a search algorithm, also known as sequential search, that is suitable for searching a set of data for a particular value. It operates by checking every element of a list until a match is found. Linear search runs [...]]]></description>
			<content:encoded><![CDATA[<h3>Information</h3>
<ul>
<li>Order: O(n)</li>
<li>Best Case: O(1)</li>
<li>Average: O(n/2)</li>
</ul>
<h3>Description <a href="http://en.wikipedia.org/wiki/Linear_search" class="wikiLink">(from wikipedia)</a></h3>
<p>In computer science, linear search is a search algorithm, also known as sequential search, that is suitable for searching a set of data for a particular value.</p>
<p>It operates by checking every element of a list until a match is found. Linear search runs in O(N). If the data are distributed randomly, on average N/2 comparisons will be needed. The best case is that the value is equal to the first element tested, in which case only 1 comparison is needed. The worst case is that the value is not in the list, in which case N comparisons are needed.</p>
<p><span id="more-28"></span></p>
<h3>C++ Files and Code Listings</h3>
<div class="filename">
<a target="_blank" href="http://www.gadberry.com/aaron/wp-content/uploads/2006/01/LinearSearch.h">LinearSearch.h</a><br />
<a target="_blank" href="http://www.gadberry.com/aaron/wp-content/uploads/2006/01/LinearSearch.cpp">LinearSearch.cpp</a><br />
<a href="http://www.gadberry.com/aaron/2006/01/24/search_driver/">Driver Program for Search Code</a>
</div>
<p>This code has a few built in functions to time the sort and count the number of comparisons.<br />
This code was written and compiled successfully in Visual Studio .NET.</p>
<div class="filename">LinearSearch.h</div>
<div class="code_box"><code> /*
	Travis Gadberry
	Patrick Hesser
	Chris Ladewig

	LinearSearch.h
	21Mar05
*/

#ifndef LINEARSEARCH_H
	#define LINEARSEARCH_H

#include &lt;vector&gt;
#include &lt;time.h&gt;

using namespace std;

class LinearSearch {
public:
	LinearSearch();
	LinearSearch(int *, int);
	LinearSearch(vector&lt;int&gt;);
	~LinearSearch();
	bool search(int);

	double getSearchTime();
	int getSearchIncrements();

private:
	int * A;
	int n;
	int increments;
	double time;
};

#endif
</code></div>
<div class="filename">LinearSearch.cpp</div>
<div class="code_box"><code>/*
	Travis Gadberry
	Patrick Hesser
	Chris Ladewig

	LinearSearch.cpp
	21Mar05
*/

#include "LinearSearch.h"

using namespace std;

LinearSearch::
LinearSearch() {
	n = 1;
	A = new int[n];
	A[0] = 0;
	increments = 0;
	time = 0;
}

LinearSearch::
LinearSearch(int * array, int N) {
	n = N;
	A = new int[n];
	for(int i = 0; i &lt; n; i++)
		A[i] = array[i];
	increments = 0;
	time = 0;
}

LinearSearch::
LinearSearch(vector&lt;int&gt; V) {
	n = V.size();
	A = new int[n];
	for(int i=0; i&lt;n; i++)
		A[i] = V.at(i);
	increments = 0;
	time = 0;
}


LinearSearch::
~LinearSearch() {
	delete(A);
}

bool 
LinearSearch::
search(int key) {
	time_t t1, t2;
	t1 = clock();

	bool found = false;

	for(int i=0; i&lt;n &amp;&amp; !found; i++)
		if(increments++, key==A[i])
			found = true;


	t2 = clock();
	time = (t2 - t1)/CLOCKS_PER_SEC;
	return found;
}


int
LinearSearch::
getSearchIncrements() {
	return increments;
}


double
LinearSearch::
getSearchTime() {
	return time;
}

</code></div>
]]></content:encoded>
			<wfw:commentRss>http://www.gadberry.com/aaron/2006/01/24/linear_search/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
