iterator – wrapping around a class

An iterator is when you implement a abstract way of cycling through data. I have below created a internal iterator wrapper that will allow the class to implement a iterator for that class. Below the class is kinder like a stack where you place one item at the root of the stack and then place another item in a link (next item) attached to the last node of the stack (where the last item is, be it at the root if empty)

You can create a wrapper for the class externally as well, but in this instance I am creating it internally.

To start with I have created a internal class within the stack class called a Node, the Node is the item on the stack (the data inserted in a array as such). Also I created a basic class definition at the top the class so that the rest of the class knows that there is a thing called a Node, but the implementation is below.

    // forward declaration for the class structure below.
    class Node;

As said before, there is a root node that, this is where the start of the array in essence is, and the last node, where the last inserted node as placed. On each node there is a method to return the value attached to that node and also a link to the next node on the linked list.

    class Node {
    public:
	Node(const int& val) : nextNode(NULL), nodeValue(val) {}
	int& getVal() {return(nodeValue);}
	Node* nextNode;
    private:
	int nodeValue;
    };

now we have the node class setup, which means that when we add to the stack we can now place the values added to a dynamic linked list and a way to go through them. Now we just need to add values into the stacked list.

void theStack::addValue(int valueToAdd)
{
    if (rootNode == NULL)
    {
	rootNode = new Node(valueToAdd);
	lastNode = rootNode;
    }else
    {
	Node* p = new Node(valueToAdd);
	lastNode->nextNode = p;
	lastNode =p;
    }
}

this will place the new item either at the root node or attached to the next node to the last added node and then re-sets the last node added to point to where the new node, so that when another node is added it will be added in the correct place.

Here comes the iterator part.

To start with the internal part of the class, the internal iterator wrapper as such, we use the iterator class to extend/implement the iterator functions that we have to implement for the iterator aspects to work, here I am using the forward_iterator_tag as part of the parameter to the iterator and also we are returning a int value (which is what the stack is implementing as a linked list of integers, if you want to return another type just put in what ever your return type is.

  class Iterator : public iterator<forward_iterator_tag, int>

here are function/methods of a iterator to allow the stack iterator to go through the linked list (array of integers).

  class Iterator : public iterator<forward_iterator_tag, int>
  {
    private: 
      // the intP is a integer pointer
	Node* intP;
    public:
	Iterator(Node* p) : intP(p) {}
	~Iterator() {}
 
	// assignment 
	Iterator& operator=(const Iterator& otherValue);
	// equal or not equal to
	bool operator==(const Iterator& otherValue);
	bool operator != (const Iterator& otherValue);
	// increment the pointer to the next value
	Iterator& operator++();
	// increment the pointer to the next next etc value
	Iterator& operator++(int);
 
	// return type here is a int because that is what I said at the top of the class setup
	// e.g. iterator<forward_iterator_tag, int>
	int& operator*();
   };

of course we need to know when the begin and the end of the linked list is, this is the root and the last nodes, for a iterator to know where to start and end when you are going from start to end with using a iterator style of coding. Here is a way of using the iterator to loop through the values added, below is code that setups up the stack (theStack) class with some values (5,10,3), and then using a for loop to go through the values within the linked list (this is where the iterator part comes in)

    theStack stacky;
 
    stacky.addValue(5);
    stacky.addValue(10);
    stacky.addValue(3);
 
    printf("Value in the stack was\n");
    for (theStack::Iterator theIterator= stacky.begin(); theIterator != stacky.end(); theIterator++)
    {
	// (int) wrapping the return value into a int type, *theIterator getting the pointered to value
	printf("%d\n", ((int)*theIterator));
    }

in the full source code below is the implementations of the iterator and the stack

#include <iostream>
#include <iterator>
#include <stdio.h>
 
using namespace std;
 
class theStack
{
    private:
    // forward declaration for the class structure below.
    class Node;
 
    // the pointers to the root nodes and the last node on the stack as such.
    Node* rootNode;
    Node* lastNode;
 
  public:
      theStack(): rootNode(NULL), lastNode(NULL) {}
      ~theStack() { delete rootNode; }
 
      // add objects to the DrawingObject
      void addValue(int valueToAdd);
 
 
  class Iterator : public iterator<forward_iterator_tag, int>
  {
    private: 
      // the intP is a integer pointer
	Node* intP;
    public:
	Iterator(Node* p) : intP(p) {}
	~Iterator() {}
 
	// assignment 
	Iterator& operator=(const Iterator& otherValue);
	// equal or not equal to
	bool operator==(const Iterator& otherValue);
	bool operator != (const Iterator& otherValue);
	// increment the pointer to the next value
	Iterator& operator++();
	// increment the pointer to the next next etc value
	Iterator& operator++(int);
 
	// return type here is a int because that is what I said at the top of the class setup
	// e.g. iterator<forward_iterator_tag, int>
	int& operator*();
   };
 
   // the begin and end of the iterator look up
   Iterator begin();
   Iterator end();
 
   //  here we define the Node class
  private:
    class Node {
    public:
	Node(const int& val) : nextNode(NULL), nodeValue(val) {}
	int& getVal() {return(nodeValue);}
	Node* nextNode;
    private:
	int nodeValue;
    };
 
};
 
int main(int argc, char **argv) {
    theStack stacky;
 
    stacky.addValue(5);
    stacky.addValue(10);
    stacky.addValue(3);
 
    printf("Value in the stack was\n");
    for (theStack::Iterator theIterator= stacky.begin(); theIterator != stacky.end(); theIterator++)
    {
	// (int) wrapping the return value into a int type, *theIterator getting the pointered to value
	printf("%d\n", ((int)*theIterator));
    }
    return 0;
}
 
 
void theStack::addValue(int valueToAdd)
{
    if (rootNode == NULL)
    {
	rootNode = new Node(valueToAdd);
	lastNode = rootNode;
    }else
    {
	Node* p = new Node(valueToAdd);
	lastNode->nextNode = p;
	lastNode =p;
    }
}
 
 
// the definitions of the class theStack
// Iterator class implementations 
theStack::Iterator& theStack::Iterator::operator=(const Iterator& otherValue)
{
  intP = otherValue.intP;
  return (*this);
}
 
bool theStack::Iterator::operator==(const Iterator& otherValue)
{
    return (intP == otherValue.intP);
}
 
bool theStack::Iterator::operator != (const Iterator& otherValue)
{
    return (intP != otherValue.intP);
}
 
// increment the pointer to the next value
theStack::Iterator& theStack::Iterator::operator++()
{
    if (intP != NULL)
      intP = intP->nextNode;
    return (*this);
}
 
// if the loop has a increment by more than 1 then just increment the value still by one.
// if you are implementing another stack then you could get to the next next next etc nodes
theStack::Iterator& theStack::Iterator::operator++(int)
{
    if (intP != NULL)
      intP = intP->nextNode;
    return (*this);
}
 
int& theStack::Iterator::operator*()
{
    return(intP->getVal());
}
 
theStack::Iterator theStack::begin()
{
  return(Iterator(rootNode));
}
 
theStack::Iterator theStack::end()
{
  return(Iterator(NULL));
}

Output would be

Value in the stack was
5
10
3

Loading a image on the fly

In flash you can load images from a remote server on-the-fly whilst the flash is running within the browser, here I am going to show how to load a image into a Image tag.

To start off you need to setup the environment to compile up the flash code into SWF file, (here is a previous tutorial where I have created the development environment for flash in creating the classic hello world)

As a side note, the image that I am loading I have taken from the openclipart website and it is off a laptop which I have made slightly smaller to load into the embed object within the HTML (web) page.

To start off, we first create a flash tag of Image (mx is the subscript as such of the flash library) with having the id of imageLoad, we can access the tag within the actual code, and then create a Button which once clicked calls a function called “loadImageIntoImageBlock” the event that is attached to the function is what happened to call this function which would be a mouse event.

	<mx:Image x="30" y="30" id="imageLoad" />
	<mx:Button label="Click here to load image" click="loadImageIntoImageBlock(event)" />

and now when the Button has been clicked we just need to call the function, which is below, the imageLoad is the ID name from the mx:Image above and then just need to alter the source to the image that is in the same place as the swf file.

private function loadImageIntoImageBlock(e:MouseEvent):void {
	imageLoad.source = 'johnny_automatic_laptop.png';
}

that is about it, here is the full source code, if you call this imageload.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
	<mx:Image x="30" y="30" id="imageLoad" />
	<mx:Button label="Click here to load image" click="loadImageIntoImageBlock(event)" />
	<mx:Script>
		<![CDATA[
			private function loadImageIntoImageBlock(e:MouseEvent):void {
				imageLoad.source = 'johnny_automatic_laptop.png';
			}
		]]>
	</mx:Script>
</mx:Application>

I always place my swf files within a bin directory, so if you create a bin directory where the above imageLoad.mxml file is and then run this (once your development environment is setup e.g. the PATH variable to find the mxmlc executable file), once that is place you can compile up the code into a swf by

mxmlc imageload.mxml -output ./bin/imageload.swf

which places the imageLoad.swf into the bin directory that was created.

Here is the web page code that will load the imageLoad.swf into a web page, if you save this as loadingimage.html within the same bin directory as above with the ‘johnny_automatic_laptop.png’ image within the same bin directory you can then open up the html page within your favourite web browser (Firefox) and then click on the button and it will load in the image. hey presto

<html>
<body>
<embed src="imageload.swf" width="560" height="560">
</body>
</html>

upstart – emit – start on network

I have been reading some of the funky things in ubuntu implementations that has been happening in the distribution. One of the things that I like is the upstart, this changes the way that init (the process of the computer system from boot to console/GUI for creating the different runlevels ).

In essence, it replaces the /sys/init daemon which handles the start up and shutting down, looking after tasks/services during boot/running and shutdown.

One of the things that is great is that the upstart will “emit” and signal to other services to “start on” when that signal has been emitted, to demonstrate this when a network card is activated for the Ethernet (for example) in the “/etc/network/if-up.d/upstart”

initctl emit -n net-device-up \

which basically says when a network device because in a state of up emit a signal, the state of being up is when the device is active. Then in the /etc/init/mountall-net.conf file

description     "Mount network filesystems"
 
start on net-device-up

is listening for the emitted signal of net-device-up and thus the upstart will start the networking filesystems.

Another example is within the /etc/init/mountall.conf there is the emitting of a signal

mountall.conf:emits virtual-filesystems

the signal is virtual-filesystems which is then picked up with the udev.conf with the

start on virtual-filesystems

since udev is a virtual filesystem in the /dev and /sys directories.

I find the stuff that Canonical is doing with the ubuntu linux distribution is just great.

ArrayList and ListIterator

An ArrayList is basically a array of objects that are managed within a List interface. This basically means that Java will do the management of the List and you just need to either add to that list/change the values/remove items.

The way that the ArrayList is defined is using the Generics syntax, since a ArrayList can be of any type.

ArrayList<String> names = new ArrayList<String>();

this will create a object called “names” that have a array of type String and to add names to the array you use the “add” method, the “add” method can either just have the ArrayList type (in this case a String) as a single parameter or a index into the ArrayList with the ArrayList type again.. e.g.

// normal add
names.add("Genux");
// adding at a set point
names.add("1","Genux at point 1");

to remove at a set point, there is a method called “remove” that will either take a index point or a class (e.g. will compare against a class within the ArrayList to see if there is anything that equals, if so remove from the ArrayList), in the example below I am just going to use the index point to remove from the ArrayList

names.remove(0);

you can also alter any of the names within the ArrayList with using the method “set”, here I am altering the index point 0 within the array to have the String value of “Genux new start”

names.set(0,"Genux new start");

The ListIterator is when you can iterate through a List (interface implemented object e.g ArrayList), to iterate through a list you basically go from one to the next to the next etc. the ArrayList object called names has a method that will return the list iterator object for the ListIterator to go through, the hasNext method within the ListIterator returns true if there is another value/object after the present one, the “next” method within the ListIterator returns a value/object of the type of ListIterator and then goes to the next value within the List, here is some code that uses the above that uses the hasNext and next methods.

ListIterator<String> arrayListIt = names.listIterator();
while (arrayListIt.hasNext())
{
	System.out.println("Names :"+ arrayListIt.next());
}

here is the source code in full, if you save as “ArrayListTutorial.java”

import java.util.ArrayList;
import java.util.ListIterator;
 
public class ArrayListTutorial {
 
	public static void main(String[] args) {
			ArrayList<String> names = new ArrayList<String>();
			// add names in a standard way, placing on the end in this case the start position = 0 
			names.add("Genux");
			// adding a set point
			names.add(1,"Genux at point 1");
 
			System.out.println("Starting point of the Array of names");
 
			// a ListIterator is a template (e.g. can use any type String/Integer etc) 
			// that will loop through a List object (in this case the ArrayList has implemented a List interface)
			ListIterator<String> arrayListIt = names.listIterator();
			while (arrayListIt.hasNext())
			{
				System.out.println("Names :"+ arrayListIt.next());
			}
 
			System.out.println("Alerting the starting name");
			// change the start of the array list e.g. point 0
			names.set(0,"Genux new start");
 
			// loop through the array list with a iterator
			arrayListIt = names.listIterator();
			while (arrayListIt.hasNext())
			{
				System.out.println("Names :"+ arrayListIt.next());
			}
 
			System.out.println("Removing index 0 from the ArrayList of names");
			names.remove(0);
			// loop through the array list with a iterator
			arrayListIt = names.listIterator();
			while (arrayListIt.hasNext())
			{
				System.out.println("Names :"+ arrayListIt.next());
			}
	}
}

and the output would be

Starting point of the Array of names
Names :Genux
Names :Genux at point 1
Alerting the starting name
Names :Genux new start
Names :Genux at point 1
Removing index 0 from the ArrayList of names
Names :Genux at point 1

to compile if you save the java code above as “ArrayListTutorial.java”

javac ArrayListTutorial.java
java ArrayListTutorial

PHP SOAP server and .NET Client

On a previous post, it was the other way around a .NET SOAP server and a PHP client and this one is a PHP SOAP server talking to a .NET client. I am using a similar PHP SOAP Server output as before, but having to alter the return type to a complexType instead of a normal PHP SOAP server type.

The basic WSDL generation is very similar to the previous SOAP post, apart from parameter passed the Zend_Soap_AutoDiscover which is “Zend_Soap_Wsdl_Strategy_ArrayOfTypeComplex”, which creates the start of the newer return complexTypes.

if(isset($_GET['wsdl'])) {
    $autodiscover = new Zend_Soap_AutoDiscover('Zend_Soap_Wsdl_Strategy_ArrayOfTypeComplex');
    $autodiscover->setClass('QuoteOfTheDay');
    $autodiscover->handle();

here is the new return type for the function to return, it is a class that has public variable that is a string (you define as “” which sets up a string in PHP)

// the return class type
class theQuote {
// have a return value of type string
/** @var string */
  public $getTheQuote="";
}

and then just alter the phpDoc notation for the auto discovery with the Zend SOAP to create a return of theQuote class as above and alter the return variable to the class., below I have included the new WSDL output generated.

  /* phpdoc notation to return a complex type (a class) */
  /**
  * @return theQuote
  */
 function getQuote($quote) {
    $theQuoteR = new theQuote();
    /* just encase the string is in uppercase*/
    $symbol = strtolower($quote);
    /* if there is a quote for the day requested */
    if (isset($this->quotes[$quote])) {
      $theQuoteR->getTheQuote=$this->quotes[$quote];
      return $theQuoteR;
    } else {
      /* else error with default response*/
      $theQuoteR->getTheQuote=$this->quotes["monday"];
      return $theQuoteR;
    }
  }

here is the full source code for the PHP SOAP server

<?php
/* setup the including path for the zend library framework */
ini_set('include_path', '/usr/share/php/libzend-framework-php/');
 
//****************************************************
// Zend Framework 1.8
include_once 'Zend/Loader/Autoloader.php';
require_once "Zend/Soap/Server.php";
require_once "Zend/Soap/AutoDiscover.php";
$loader = Zend_Loader_Autoloader::getInstance();
$loader->setFallbackAutoloader(true);
$loader->suppressNotFoundWarnings(false);
//****************************************************
 
if(isset($_GET['wsdl'])) {
    $autodiscover = new Zend_Soap_AutoDiscover('Zend_Soap_Wsdl_Strategy_ArrayOfTypeComplex');
    $autodiscover->setClass('QuoteOfTheDay');
    $autodiscover->handle();
} else {
    $soap = new Zend_Soap_Server("http://localhost/projects/webservice/zend_soap_server_net.php?wsdl"); // this current file here
    $soap->setClass('QuoteOfTheDay');
    $soap->handle();
}
 
// the return class type
class theQuote {
// have a return value of type string
/** @var string */
  public $getTheQuote="";
}
 
class QuoteOfTheDay {
 
  /* the quotes to be used from within the function getQuote */
  private $quotes = array("monday" => "Monday's child is fair of face", "tuesday"=>"Tuesday's child is full of grace","wednesday" =>"Wednesday's child is full of woe",
  "thursday" =>"Thursday's child has far to go", "friday" => "Friday's child is loving and giving", "saturday" =>"Saturday's child works hard for a living",
  "sunday" =>"But the child who is born on the Sabbath Day - Is bonny and blithe and good and gay");  
 
  /* phpdoc notation to return a complex type (a class) */
  /**
  * @return theQuote
  */
 function getQuote($quote) {
    $theQuoteR = new theQuote();
    /* just encase the string is in uppercase*/
    $symbol = strtolower($quote);
    /* if there is a quote for the day requested */
    if (isset($this->quotes[$quote])) {
      $theQuoteR->getTheQuote=$this->quotes[$quote];
      return $theQuoteR;
    } else {
      /* else error with default response*/
      $theQuoteR->getTheQuote=$this->quotes["monday"];
      return $theQuoteR;
    }
  }
}
 
?>

Here is the newer WSDL output (snipped) from the new PHP SOAP server that creates a complexType return type for the .NET environment to be able to use.

<types>
-
<xsd:schema targetNamespace="http://localhost/projects/webservice/zend_soap_server_net.php">
-
<xsd:complexType name="theQuote">
-
<xsd:all>
<xsd:element name="getTheQuote" type="xsd:string"/>
</xsd:all>
</xsd:complexType>
</xsd:schema>
</types>
-
<portType name="QuoteOfTheDayPort">
-
<operation name="getQuote">
<documentation>@return theQuote</documentation>
<input message="tns:getQuoteIn"/>
<output message="tns:getQuoteOut"/>
</operation>
</portType>

Here is the .NET client

Since we have a new WSDL generation, will need to generate a newer DLL that will allow the .NET to use the class structure. Please note I am using mono as my .NET environment, so if you are using .NET in Windows then you could either include the WSDL within the Visual Studio or use very similar commands as below.

wsdl2 http://localhost/projects/webservice/zend_soap_server_net.php?wsdl
gmcs QuoteOfTheDayService.cs /t:library /r:System.Web.Services

which will generate the QuoteOfTheDayService.dll and with the code below

using System;
 
namespace codingfriendssoap
{
    class Test_Php_Soap
    {
 
static public void Main()
{
  QuoteOfTheDayService quoteService = new QuoteOfTheDayService();
 
  Console.WriteLine("mondays quote " + quoteService.getQuote("monday").getTheQuote);
}
    }
}

to compile that you once again I am using mono so these are the commands that I am using, but with .NET framework in Windows the commands may be different to compile the program e.g. (mcc)

gmcs web_service_client_php.cs /r:QuoteOfTheDayService.dll

the /r includes the dll generated of the above generated PHP SOAP server this is the output

mondays quote Monday's child is fair of face

here is the XML response from the PHP SOAP server, which includes getTheQuote return wrapped around the theQuote class.

<SOAP-ENV:Body><ns1:getQuoteResponse><return xsi:type="ns1:theQuote"><getTheQuote xsi:type="xsd:string">Monday's child is fair of face</getTheQuote></return></ns1:getQuoteResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>

iPhone – Linux – iTunes it works

I have been using gtkPod and also amarok, but sometimes I just missed that iTunes interface to sync with my iPhone 3GS (16GB).

Well, with using the virtual box ( you will need to get the Sun version and not the OSE (open source edition) because the Sun edition has the USB parts)

Then I booted up the virtualbox with a Windows OS, and installed the iTunes I was able to sort out my iPhone in the apple way!!.

It is still kinder annoying that apple are not making iTunes for Linux, but with this setup at least I am able to still use the iTunes interface with my phone and sync correctly.

Soap Client calling .NET Web service

Since Web Service Description Language (WSDL) is to be used between language so that a PHP program can call a .NET web service or the other way around. So here we create a PHP Soap Client that will call the .Net Web service created from a previous post (Web Service).

As before with the soap client for a PHP server (PHP server previous post) we just need to link to the WSDL output of the .NET web service as below

$client = new SoapClient("http://localhost/csharp/web_service.asmx?wsdl")

so if you tried to call the function / web method.

echo $client->Add(2,3);

The error would be

Catchable fatal error: Object of class stdClass could not be converted to string in

this does not mean that much or really point to where the problem is, the actual problem is not the passing parameters (even through they are in a complex format) but the return from the $client object, because .NET returns a array object as such, so if you

print_r($client->Add(2,3));

the output would be

stdClass Object ( [AddResult] => 0 )

thus to gain access to the actual result you would need to reference the first part of the returned array named AddResult

echo $client->Add(2,3)->AddResult;

but the parameters being passed are not!!, so if you look at the WSDL file generated from the .NET web service it has

      <xs:element name="Add">
        <xs:complexType>
          <xs:sequence>
            <xs:element minOccurs="1" maxOccurs="1" name="a" type="xs:int"/>
            <xs:element minOccurs="1" maxOccurs="1" name="b" type="xs:int"/>
          </xs:sequence>
        </xs:complexType>

complex types and thus if you try to pass in parameters to the function Add (as the web service client does) as a normal PHP way it is not passing in the numeric values from the php code, the reason for this PHP has to specify the actual names of the passing parameters within a array.. as

print_r( $client->Add(array("a" => "5", "b" =>"2")));

which displays a better result for us..

stdClass Object ( [AddResult] => 7 )

So the best way to remember is that if you are calling a .NET WSDL web service, then always pass in a array with the WSDL function parameters within a index array and the return result is always function name + Result (AddResult)

echo $client->Add(array("a" => "5", "b" => "2"))->AddResult;

So here is the full code to pull back the code with some debugging information.

<?php
  // create a connection to the local host mono .NET pull back the wsdl to get the functions names
  // and also the parameters and return values
  $client = new SoapClient("http://localhost/csharp/web_service.asmx?wsdl",
    array(
      "trace"      => 1,		// enable trace to view what is happening
      "exceptions" => 0,		// disable exceptions
      "cache_wsdl" => 0) 		// disable any caching on the wsdl, encase you alter the wsdl server
  );
 
  // get a response from the WSDL zend server function getQuote for the day monday
  print_r( $client->Add(array("a" => "5", "b" =>"2")));
 
  // display what was sent to the server (the request)
  echo "<p>Request :".htmlspecialchars($client->__getLastRequest()) ."</p>";
  // display the response from the server
  echo "<p>Response:".htmlspecialchars($client->__getLastResponse())."</p>";
?>