Steven

Jul 092014
 

Here’s a short method to add a delimiter to a list of strings

        /**
	 * Creates a delimited list
	 * @param list The list of strings to delimit
	 * @param delimiter The string to use as a delimiter
	 * @return A delimited list
	 */
	public staatic String delimitString(final List list, String delimiter) {
		
        StringBuilder result = new StringBuilder();
        boolean addComma = false;

        for (String element : list) {

            // don't add a comma before the first
            if (addComma) {
                result.append(delimiter);
            }

            // after the first iteration, it's okay to add a comma
            addComma = true;

            result.append(element);
        }
        
        return result.toString();
    }
 Posted by at 4:01 pm
Jun 252013
 

The ‘RX’ in front of ‘List’ – R for Roycat, to differentiate from any other List, and X for extended, because I already had an RList interface. I’ll get the abstract class and a concrete class posted in the days to come.

 /**
  * A revised, updated, and extended RList interface
  * @author Steven Bolin - June 2013 - All rights reserved.
  */
 interface RXList {

  /**
   * Adds an element to the end of the list and 
   * returns the resulting list
   * @param mixed $element The element to add
   * @return mixed The resulting list
   */
  public function add($element);

  /**
   * Adds $element at the index specified by $index and returns the list
   * @param int $index The index at which to add $element
   * @param mixed The element to add at $index
   * @return mixed The resulting list
   */
  public function addAt($index, $element);

  /**
   * Adds an element to the beginning of the list and 
   * returns the resulting list
   * @param mixed $element The element to add
   * @return mixed The resulting list
   */
  public function addFirst($element);

  /**
   * Adds an element to the end of the list and 
   * returns the resulting list
   * @param mixed $element The element to add
   * @return mixed The resulting list
   */
  public function addLast($element);

  /**
   * Removes all of the elements from this list and returns
   * the resulting empty list
   * @return mixed The resulting (empty) list
   */
  public function clear();

  /**
   * Returns true if this list contains the specified element, false otherwise.
   * @param mixed $element - The element to search for.
   * @return boolean - Returns true if this list contains the specified element, 
   * false otherwise.
   */
  public function contains($element);

  /**
   * Searches the array for a given value and returns the corresponding key 
   * if successful
   * @param mixed $element The element to find
   * @return mixed Returns the index of the first occurance of $element, or
   * null if $element not found
   */
  public function findFirst($element);

  /**
   * Returns the element at the specified position in this list.
   * @param int $index - The index of the element to return.
   * @return mixed - Returns the element at the specified position in this list
   * or null if the index is out of bounds.
   * @require Index must be within bounds
   */
  public function get($index);

  /**
   * Returns the index of the first occurrence of the specified element in this 
   * list, or null if this list does not contain the element.
   * @param mixed $element - The element to get the index of.
   * @return int - Returns the index of the first occurrence of the specified 
   * element in this list, or null if this list does not contain the element.
   */
  public function indexOf($element);

  /**
   * Returns true if this list contains no elements, false otherwise.
   * @return boolean - Returns true if this list contains no elements, false 
   * otherwise.
   */
  public function isEmpty();

  /**
   * Returns an iterator over the elements in this list in proper sequence.
   * @return \RListIterator - Returns an iterator over the elements in this list 
   * in proper sequence.
   */
  public function iterator();

  /**
   * Removes the first occurrence of the specified element from this list, if 
   * it is present
   * @param mixed $element - The element to remove the first occurance of.
   * @return mixed Returns the resulting list
   */
  public function remove($element);

  /**
   * Removes the element at the index given by $index and returns the
   * resulting List. Alias for removeIndex($index)
   * @param int $index The index of the element to remove
   * @return mixed Returns the element which is being removed or null if $index 
   * is out of bounds
   */
  public function removeAt($index);

  /**
   * Removes duplicate values from the array and returns the resulting array
   * @return mixed Returns the resulting list
   */
  public function removeDuplicates();

  /**
   * Removes and returns the first element in the list.
   * @return The element being removed, or null if the list is empty.
   */
  public function removeFirst();

  /**
   * Removes the element at the specified position in this list. 
   * Alias for removeAt($index).
   * @param int $index - the index of the element to remove.
   * @return The element being removed, or null if $index is out of bounds.
   */
  public function removeIndex($index);

  /**
   * Removes and returns the last element in the list
   * @return The element which is being removed, or null if the list is empty.
   */
  public function removeLast();

  /**
   * Replaces the element at the specified position in this list with the 
   * specified element
   * @param int $index - The index at which to place element
   * @param mixed $element - The element to place at index
   */
  public function set($index, $element);

  /**
   * Returns the number of elements in the array
   * @return Returns the number of elements in the array
   */
  public function size();

  /**
   * Returns an array containing all of the elements in this list in proper 
   * sequence (from first to last element).
   * @return mixed array - Returns an array containing all of the elements in 
   * this list in proper sequence (from first to last element).
   */
  public function toArray();

  /**
   * Returns a string representation of the List.
   * @return string - Returns a string representation of the List.
   */
  public function toString();
} // End of interface
 Posted by at 9:39 am
Jun 232013
 

A wrapper class for the standard PHP array. I should probably go ahead and change this to RArrayList and make it implement the RList interface. I’ll mess with that later.

 

 

/**
 * A wrapper for standard PHP array functions plus some helper methods.                                                                                                                                                                                                                                                                                                                         
 *
 * @author Steven Bolin - April 2013 - All rights reserved.
 */
class RArray {
  
  private $array;
 
  public function __construct() {
    $this->array = array();
  }
  
  /**
   * Adds an element to the end of the array and 
   * returns the resulting array
   * @param mixed $element The element to add
   */
  public function add($element) {
    array_push($this->array, $element);
    return $this->array;
  }
  
 /**
  * Adds an element to the end of the array and 
  * returns the resulting array
  * @param mixed $element The element to add
  */
  public function addLast($element) {
    array_push($this->array, $element);
    return $this->array;
  }
  
/**
 * Adds an element to the beginning of the array and 
 * returns the resulting array
 * @param mixed $element The element to add
 */
  public function addFirst($element) {
    array_unshift($this->array, $element);
    return $this->array;
  }
  
/**
 * Returns true if the array contains $element
 * @param mixed The element for which to evaluate the array.
 */
  public function contains($element) {
    return in_array($element, $this->array);
  }
  
/**
 * Removes and returns the first element in the array.
 */
  public function removeFirst() {
    return array_shift($this->array);
  }
  
/**
 * Removes and returns the last element in the array
 */
  public function removeLast() {
    return array_pop($this->array);
  }
  
/**
 * Returns the array
 */
  public function getArray() {
    return $this->array;
  }
  
/**
 * Adds $element at the array index specified by $index and returns the array
 * @param int $index The index at which to add $element
 * @param mixed The element to add at $index
 */
  public function addAt($index, $element) {
    array_splice( $this->array, $index, 0, $element );
    return $this->array;
  }
  
/**
 * Removes the element at the array index given by $index and returns the
 * resulting array.
 * @param int $index The array index of the element to remove
 */
  public function removeAt($index) {
    array_splice($this->array, $index, 1);
    return $this->array;
  }
  
/**
 * Returns the number of elements in the array
 */
  public function size() {
    return count($this->array);
  }
  
/**
 * Searches the array for a given value and returns the corresponding key if successful
 */
  public function findFirst($element) {
    return array_search($element, $this->array);
  }
  
/**
 * Returns TRUE if the given key is set in the array. key can be any value possible for an array index.
 */
  public function isKey($key) {
    return array_key_exists($key, $this->array);
  }
  
/**
 * Removes duplicate values from the array and returns the resulting array
 */
  public function removeDuplicates() {
    $this->array = array_unique($this->array);
    return $this->array;
  }
} // End of class
 Posted by at 10:01 pm
Jun 102013
 

This class formats a string to line break at a specific character position. It can also limit the number of rows of
the string. There are probably already better ways of doing this, but this filled my needs and makes for a good future
reference for me.

 

package bolin;

import java.io.Serializable;
import java.util.Scanner;

/**
 * This class provides functionality for formatting a String to a specific number of characters
 * per row and a specific number of rows.
 * @author Steven Bolin
 */
public class MyMessageFormatter implements MessageFormatter, Serializable {

	private static final long serialVersionUID = 1L;
	private String unformattedMessage;
	private Integer maxLineLength;
	private String formattedMessage;
	private Integer maxLineCount;
	private boolean limitLineCount;

	/**
	 * Initializes the MessageFormatter with the message argument and the max line
	 * length of 65 characters.
	 * 
	 * @param message
	 *          The message to be formatted.
	 */
	public MyMessageFormatter (String message) {
		this.unformattedMessage = message;
		this.maxLineLength = 65;
		this.maxLineCount = 196;
		this.limitLineCount(false);
		this.formattedMessage = null;
	}

	/**
	 * Initializes the MessageFormatter to an empty state. Max line length 
	 * defaults to 65 characters.
	 */
	public MyMessageFormatter () {
		this.unformattedMessage = "";
		this.setMaxLineLength(65); // 65 is an arbitrary choice for default. 
		this.formattedMessage = null;
		this.setMaxLineCount(0);
		this.limitLineCount(false);
	}

	/**
	 * Formats message to where lines are no more than lineLength characters long
	 * and makes all characters upper case
	 * 
	 * @param message
	 * @return Returns formatted message where lines are no more than lineLength
	 *         characters long and makes all characters upper case
	 */
	private String formatMessage(String message) {
		// There is probably a lot of room for improvement to this method, but having
		// gotten it to work as desired.

		if (this.maxLineLength <= 0) {
			message = "";
		} else {
			Character c = null; 				// The character being inspected
			Integer messageLength = message.length();	// The length of the message being formatted
			String line = "";				// Essentially a character buffer used to build each line
			Integer lineLimit = this.maxLineLength + 1;	// The length of the line. One more than maxLineLength to
                                                                        // evaluate the char after maxLinelength
			String revisedMessage = "";			// Used to build the formatted message.

			// If the message is shorter than the maxLineLength, then just leave it alone.
			if (message.length() < this.maxLineLength) {
				revisedMessage = message;
			} else {

				// Otherwise, inspect each character looking for \n or \c and/or adding \n as required
				for (int i = 0; i < messageLength; i++) {

					c = message.charAt(i);
					line = line + c;

					// If the line already ends with a newline, then add it to the revised msg
					if (c.equals('\n') || c.equals('\r')) {
						revisedMessage = revisedMessage + line;
						line = "";

					} else {
						// otherwise, check if the buffer (line) is full and add the newline
						if (line.length() == lineLimit) {
							line = line.substring(0, this.maxLineLength) + '\n'; 	// Keep all but the last char and replace the last char with newline
							revisedMessage = revisedMessage + line;			// Add it to the revised msg
							line = "";	// Clear the buffer
							i--;	// Decrement i to re-inspect that last character.
						}
					}
				}
				revisedMessage = revisedMessage + line;		// Add the remaining content of the buffer to the revised msg
			}

			message = revisedMessage;    // Update message to the revised version
		}

		// If the number of lines to the message is to be limited, then do so now
		if (this.limitLineCount) {
			message = this.limitRows(message);
		}

		// Return the uppercase version of the revised message.
		return message.toUpperCase();
	}

	/**
	 * Limits the number of rows to the number set by this.maxLines. It will
	 * return a String with the message truncated at the maxLines number of rows.
	 * 
	 * @param message
	 *          The message to limit the number of rows for
	 * @return It will return a String with the message truncated at the maxLines
	 *         number of rows.
	 */
	private String limitRows(String message) {
		Scanner scanner = new Scanner(message);
		Integer count = 0;
		String result = "";

		if ((count < this.maxLineCount) && scanner.hasNextLine()) {
			result = result + scanner.nextLine();
			count++;
		}

		while ((count < this.maxLineCount) && scanner.hasNextLine()) { 			
                  result = result + "\n" + scanner.nextLine();
  		  count++; 		
                }
 		scanner.close();
 		return result;
 	}

 	@Override
 	public Integer getLineCount() {
 		Scanner scanner = new Scanner(this.formatMessage(unformattedMessage));
 		Integer count = 0;
 		while (scanner.hasNextLine()) {
 			count++;
 			scanner.nextLine();
 		}
 		scanner.close();

 		String message = this.formatMessage(unformattedMessage);
 		count = message.length() > 0 ? 1 : 0;
		for(int i=0; i< message.length(); i++) {
		  if(message.charAt(i) == '\n') {
		    count++;
		  }
		}

		return count;
	}

	@Override
	public void setUnformattedMessage(String message) {
		this.unformattedMessage = message;
	}

	@Override
	public Integer getMaxLineLength() {
		return maxLineLength;
	}

	@Override
	public void setMaxLineLength(Integer lineLength) {
		this.maxLineLength = (lineLength < 0) ? 0 : lineLength;
	}

	@Override
	public String getFormattedMessage() {
		this.formattedMessage = this.formatMessage(unformattedMessage);
		return formattedMessage;
	}

	@Override
	public Integer characterCount() {
		return this.formatMessage(unformattedMessage).length();
	}

	@Override
	public Integer getMaxLineCount() {
		return maxLineCount;
	}

	@Override
	public void setMaxLineCount(Integer maxLineCount) {
		this.maxLineCount = maxLineCount;
	}

	@Override
	public void limitLineCount(boolean limitLineCount) {
		this.limitLineCount = limitLineCount;
	}

	@Override
	public void setLimitLineCount(boolean limitLineCount) {
		this.limitLineCount = limitLineCount;
	}

} // End of class
 Posted by at 4:22 pm
Apr 232013
 

The adapter pattern is aka a wrapper. This makes sense when you see the code. It’s used to ‘adapt’ one interface to another interface. Not that you would ever design a system this way, but it serves to demonstrate the pattern; maybe you are maintaining some code poorly written code and you need to adapt it to work with your well designed code; example code below:

 

Existing interface and concrete class:

interface Child {

  public void babble();

  public void crawl();

}

 

class Toddler implements child {

  public Toddler() {
  }

  public void babble() {
    System.out.println("babble, babble, babble");
  }

  public void crawl() {
    System.out.println("Crawl, crawl, crawl");
  }
} // end of class

Okay, now you have to adapt it to the Human interface via the ChildAdapter concrete class.

interface Human {

  public void speak();

  public void walk();
}

 

class ChildAdapter implements Human {

  private Child child;

  public ChildAdapter (Child child) {
    this.child = child;
  }

  public void speak() {
    child.babble();
  }

  public void walk() {
    child.crawl();
  }
} // end of class
 Posted by at 8:12 am
Apr 212013
 

The coffee example is my favorite example. In my opinion, it clearly demonstrates the decorator pattern. Below is the coffee example code, copied from Wikipedia.

// The abstract Coffee class defines the functionality of Coffee implemented by decorator
public abstract class Coffee {
    public abstract double getCost(); // returns the cost of the coffee
    public abstract String getIngredients(); // returns the ingredients of the coffee
}
// extension of a simple coffee without any extra ingredients
public class SimpleCoffee extends Coffee {
    public double getCost() {
        return 1;
    }

    public String getIngredients() {
        return "Coffee";
    }
}
// abstract decorator class - note that it extends Coffee abstract class
public abstract class CoffeeDecorator extends Coffee {
    protected final Coffee decoratedCoffee;
    protected String ingredientSeparator = ", ";

    public CoffeeDecorator (Coffee decoratedCoffee) {
        this.decoratedCoffee = decoratedCoffee;
    }

    public double getCost() { // implementing methods of the abstract class
        return decoratedCoffee.getCost();
    }

    public String getIngredients() {
        return decoratedCoffee.getIngredients();
    }
}
// Decorator Milk that mixes milk with coffee
// note it extends CoffeeDecorator
class Milk extends CoffeeDecorator {
    public Milk (Coffee decoratedCoffee) {
        super(decoratedCoffee);
    }

    public double getCost() { // overriding methods defined in the abstract superclass
        return super.getCost() + 0.5;
    }

    public String getIngredients() {
        return super.getIngredients() + ingredientSeparator + "Milk";
    }
}
// Decorator Whip that mixes whip with coffee
// note it extends CoffeeDecorator
class Whip extends CoffeeDecorator {
    public Whip (Coffee decoratedCoffee) {
        super(decoratedCoffee);
    }

    public double getCost() {
        return super.getCost() + 0.7;
    }

    public String getIngredients() {
        return super.getIngredients() + ingredientSeparator + "Whip";
    }
}
// Decorator Sprinkles that mixes sprinkles with coffee
// note it extends CoffeeDecorator
class Sprinkles extends CoffeeDecorator {
    public Sprinkles (Coffee decoratedCoffee) {
        super(decoratedCoffee);
    }

    public double getCost() {
        return super.getCost() + 0.2;
    }

    public String getIngredients() {
        return super.getIngredients() + ingredientSeparator + "Sprinkles";
    }
}
public class Main {

    public static final void main(String[] args) {
        Coffee c = new SimpleCoffee();
        System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());

        c = new Milk(c);
        System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());

        c = new Sprinkles(c);
        System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());

        c = new Whip(c);
        System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());

        // Note that you can also stack more than one decorator of the same type
        c = new Sprinkles(c);
        System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());
    }

}

The output of this program is given below:

Cost: 1.0; Ingredients: Coffee
Cost: 1.5; Ingredients: Coffee, Milk
Cost: 1.7; Ingredients: Coffee, Milk, Sprinkles
Cost: 2.4; Ingredients: Coffee, Milk, Sprinkles, Whip
Cost: 2.6; Ingredients: Coffee, Milk, Sprinkles, Whip, Sprinkles
 Posted by at 10:28 pm
Apr 152013
 

This is one of the best concise explanations of the Model-View-Controller pattern I’ve run across. I can’t remember where I found it, so sadly I can’t give credit where credit is due.

 

MVC

Model: The model contains the server business logic code. This usually involves the reading and writing to a database in addition to some pre- or post-processing. For example: ‘A user enters a comment, but before we insert it into the database, we need to do a spam check with akismet.com; if it passes we can do the insert.’

View: This is where you present the output to the user in a particular format, most often HTML markup, although it can be the JSON or XML format. For example: ‘We need to display all the comments for a forum topic, the model fetches all the comments and are then read and formatted by the view.’

Controller: The controller is essentially the manager. It first intercepts the URL, then calls the correct models and views before presenting it to the browser, mobile device or an API caller. For example: ‘In displaying all the comments for a topic, the controller makes the actual call to the model and then passes the model data to the view, which then generates the HTML output. This generated view is then shown to the calling browser by the controller.’

 Posted by at 9:55 am
Mar 252013
 

As it says in the javadoc below, this class facilitates access to the resource properties. For the Java src “resources” package, this class will parse the “.properties” file of the name given in the constructor. There is definitely room for improvement in this, specifically in that the path is hard coded into the method “loadProperties”. In any case, modify it as needed.

package bolin;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * This class facilitates access to the resource properties.
 * @author Steven P. Bolin - Mar 25, 2013
 */
 public class PropertyReader {

 private String resourceName;
 private Properties prop;

/**
 * Constructor
 * @param resourceName - the name of the resource file to access. This file is
 * a file located in the resources source package.
 * Pre-requisite - resourceName != null and is a valid filename of a file located
 * in the resources source folder
 */
 public PropertyReader(String resourceName) {
   this.resourceName = resourceName;
   this.prop = new Properties();
   this.loadProperties();
 }

/**
 * Returns the property value for the property associated with propertyName or
 * null if no match is found
 * @param propertyName - The name (key) of the property to be returned.
 * @return Returns the property value for the property associated with propertyName or
 * null if no match is found
 */
 public String get(String propertyName) {
   String result = (propertyName == null) ? null : prop.getProperty(propertyName);
   return result;
 }

 // TODO: Update and correct the exception catch
 private void loadProperties() {
   InputStream in = this.getClass().getClassLoader().getResourceAsStream("resources/"+this.resourceName);
   try {
     this.prop.load(in);
   } catch (IOException e) {
     System.err.println("Failed to access "+this.resourceName+". ");
   }
 }
} // End of class

 

 

 Posted by at 12:00 am
Mar 212013
 

This class provides functionality for retrieving the X509 certificate and certificate details from the HttpServletRequest.

 

package bolin;

import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.util.Date;
import javax.faces.context.FacesContext;
import javax.security.auth.x500.X500Principal;
import javax.servlet.http.HttpServletRequest;

/**
 * This class provides utility to extract X509Certificate data, specifically 
 * subject name and cert serial, from the HttpServletRequest.
 * @author Steven P. Bolin - Mar 21, 2013
 */
public class CertificatePlucker {

  private HttpServletRequest request;
  private X509Certificate cert;    // The certificate we are interested in.

  public CertificatePlucker() {

    this.request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
    X509Certificate[] certs = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");

    if(certs != null) {
      //TODO: It should be the first cert, but this needs to be confirmed that it is always the case. - sbolin
      this.cert = certs[0];
    } else if (certs == null || certs.length == 0) {
      this.cert = null;
      System.err.println("Certificates supplied are null or empty :" + (certs == null));
      // TODO: log this when logging functionality is decided upon - sbolin
    }
  }

  /**
   * Returns true if the current date is after the getValidFromDate and before
   * the getExpirationDate, false otherwise. If cert = null, then returns false;
   */
  public boolean isValidDate() {

  	boolean isValidDate = false;

  	if(this.cert != null) {
  		// if the cert exists, then re-initialize to true.
  		isValidDate = true;

  		// The validity is checked and handled by catching the exceptions.
  		// This is the designed functionality of cert.checkValidity
  		try {      
  			cert.checkValidity();
  		} catch (CertificateExpiredException ex) {
  			isValidDate = false;
  			// TODO: Log this when logging functionality is decided upon - sbolin
  		} catch (CertificateNotYetValidException ex) {
  			isValidDate = false;
  			// TODO: Log this when logging functionality is decided upon. - sbolin
  		}
  	}

  	return isValidDate;
  }

  /**
   * Returns the subject name of the Certificate
   * if the certificate is null, returns null.
   * @return Returns the subject name of the Certificate
   * if the certificate is null, returns null
   * @pre-condition The certificate subject is a name of the format ...redacted
   * @post-condition The name of the certificate is returned in the format ...redacted
   */
  public String getName() {
	  String subject = null;

	  if(this.cert != null) {

		  X500Principal certificatePrincipal = cert.getSubjectX500Principal();
		  subject = certificatePrincipal.getName().substring(0, certificatePrincipal.getName().indexOf(","));
		  String[] parts = subject.split("=");

		  if(parts != null && parts.length == 2) {
			  subject = parts[1];
		  } else {
			  subject = null;
		  }
	  }
	  return subject;
  }

  /**
   * Returns the serialNumber value from the certificate, if the certificate is null, returns null
   * @return Returns the serialNumber value from the certificate, if the certificate is null, returns null
   */
  public String getSerial() {
  	String serial = null;
  	if(this.cert != null) {
      serial = cert.getSerialNumber().toString();
  	}
    return serial;
  }

  /**
   * Returns the Date that the certificate validity ends, if the certificate is null, returns null
   * @return Returns the Date that the certificate validity ends, if the certificate is null, returns null
   */
  public Date getExpirationDate() {
  	Date date = null;
  	if(this.cert != null) {
  		date = cert.getNotAfter();
  	}
  	return date;
  }

  /**
   * Returns the Date that the certificate validity begins, if the certificate is null, returns null
   * @return Returns the Date that the certificate validity begins., if the certificate is null, returns null
   */
  public Date getValidFromDate() {
  	Date date = null;
  	if(this.cert != null) {
  		date = cert.getNotBefore();
  	}
  	return date;
  }

} // end of class

 

 

 Posted by at 12:00 am
Jan 252013
 

This notion of Single Entry, Single Exit (SESE) comes from languages with explicit resource management, like C and assembly. In C, code like this will leak resources:

void f()
{
  resource res = acquire_resource();  // think malloc()
  if( f1(res) )
    return; // leaks res
  f2(res);
  release_resource(res);  // think free()
}

In such languages, you basically have three options:

  • Replicate the cleanup code.
    Ugh. Redundancy is always bad.
  • Use a goto to jump to the cleanup code.
    This requires the cleanup code to be the last thing in the function. (And this is why some argue thatgoto has its place. And it has indeed – in C.)
  • Introduce a local variable and manipulate control flow through that.
    The disadvantage is that control flow manipulated through syntax (think breakreturnif,while) is much easier to follow than control flow manipulated through the state of variables (because those variables have no state when you look at the algorithm).

In assembly it’s even weirder, because you can jump to any address in a function when you call that function, which effectively means you have an almost unlimited number of entry points to any function. (Sometimes this is helpful. Such thunks are a common technique for compilers to implement the thispointer adjustment necessary for calling virtual functions in multiple-inheritance scenarios in C++.)

When you have to manage resources manually, exploiting the options of entering or exiting a function anywhere leads to more complex code, and thus to bugs. Therefore, a school of thought appeared that propagated SESE, in order to get cleaner code and less bugs.


However, when a language features exceptions, (almost) any function might be exited prematurely at (almost) any point, so you need to make provisions for premature return anyway. (I think finally is mainly used for that in Java and using in C#; C++ instead employs RAII.) Once you have done this, youcannot fail to clean up after yourself due to an early return statement, so what is probably the strongest argument in favor of SESE has vanished.

That leaves readability. Of course, a 200 LoC function with half a dozen return statements sprinkled randomly over it is not good programming style and does not make for readable code. But such a function wouldn’t be easy to understand without those premature returns either.

So in languages where resources are not or should not be managed manually, there is little or no value in adhering to the old SESE convention. OTOH, as I have argued above, SESE often makes code more complex. So it is a dinosaur that (except for C) does not fit well into most of today’s languages. Instead of helping the understandability of code, it hinders it.


So why do Java programmers stick to this? I don’t know, but from my (outside) POV, Java took a lot of conventions from C (where they make sense) and applied them to its OO world (where they are useless or outrightly bad), where it now sticks to them, no matter what the costs. (Like the convention to define all your variables at the beginning of the scope.)

But programmers stick to all kinds of strange notations for irrational reasons. (Deeply nested structural statements – “arrowheads” – were, in languages like Pascal, once seen as beautiful code.) Applying pure logical reasoning to this seems to fail to convince the majority of them to deviate from their established ways. So the best way to change such habits is probably to teach them early on to do what’s best, not what’s conventional. You, being a programming teacher, have it in your hand. :)

 

This “article” copied from a comment at stackexchange.com: http://programmers.stackexchange.com/a/118717

 Posted by at 10:58 am
Jan 242013
 

In web.xml, set “facelets.SKIP_COMMENTS” parameter to “true“.

<context-param>
    <param-name>facelets.SKIP_COMMENTS</param-name>
    <param-value>true</param-value>
</context-param>

Now, JSF removes anything in the page that is contained in <!– –>.

 

Alternately, see http://www.roseindia.net/jsf/remove.shtml

to do it this way:

try <ui:remove>This line will be removed</ui:remove>

 Posted by at 3:37 pm
Jan 102013
 

Copied from http://blog.cedarsoft.com/2010/11/setting-java-library-path-programmatically/

When messing around with JNI, one have to set the “java.library.path” accordingly. Unfortunately the only way is to add a system property *before* the application is started:

java -Djava.library.path=/path/to/libs

same as

java -Djava.library.path=C:\Java\ljwgl\libs org.mypackage.MyProgram
Changing the system property later doesn’t have any effect, since the property is evaluated very early and cached.
But the guys over at jdic discovered a way how to work around it. It is a little bit dirty – but hey, those hacks are the reason we all love Java…

System.setProperty( "java.library.path", "/path/to/libs" );

Field fieldSysPath = ClassLoader.class.getDeclaredField( "sys_paths" );
fieldSysPath.setAccessible( true );
fieldSysPath.set( null, null );

Explanation

At first the system property is updated with the new value. This might be a relative path – or maybe you want to create that path dynamically.

The Classloader has a static field (sys_paths) that contains the paths. If that field is set to null, it is initialized automatically. Therefore forcing that field to null will result into the reevaluation of the library path as soon as loadLibrary() is called…

 Posted by at 3:00 pm
Dec 202012
 

A linked list implementation in PHP. I need to look into whether I need a destructor or not.

 

  include_once("rc/collections/RListIterator.php");
  include_once("rc/collections/RAbstractList.php");
/**
 * An RList implemented as a linked list.
 *
 * @author Steven Bolin - December 2012 - All rights reserved
 */
final class RLinkedList extends RAbstractList implements RList {

  private $head; // The first link
  private $tail; // The latest link
  private $size; // The size of the list

  public function __construct() {
    $this->head = new RLinkedListNode(null);
    $this->tail = $this->head;
    $this->size = 0;
  }

  /**
   * Inserts the specified element at the specified position in this list
   * @param int $index - The index at which to enter the element
   * @param mixed $element - The element to add to the List
   */
  public function addAt($index, $element) {
    if($index >= 0 && $index <= $this->size && $element !== null) {
      $count = 0;
      $currentNode = $this->head;
      while($count < $index) {         $currentNode = $currentNode->next();
        $count++;
      }
      $newNode = new RLinkedListNode($element);
      $newNode->setNext($currentNode->next());
      $currentNode->setNext($newNode);
      $this->size++;
    }
  }

  /**
   * Removes all of the elements from this list.
   */
  public function clear() {
    $this->head = $this->tail;
    $this->size = 0;
  }

  /**
   * Returns the element at the specified position in this list.
   * @param int $index - The index of the element to return.
   * @return mixed - Returns the element at the specified position in this list.
   */
  public function get($index) {
    $result = null;
    if($this->indexInRange($index) && is_numeric($index)) {
      $count = 0;
      $currentNode = $this->head;
      while($count <= $index) {         $currentNode = $currentNode->next();
        $count++;
      }
      $result = $currentNode->value();
    }
    return $result;
  }

  /**
   * Returns an iterator over the elements in this list in proper sequence.
   * @return \RListIterator - Returns an iterator over the elements in this list 
   * in proper sequence.
   */
  public function iterator() {
    return new RListIterator($this);
  }

  /**
   * Removes the element at the specified position in this list.
   * @param int $index - the index of the element to remove.
   */
  public function removeIndex($index) {
    if($this->indexInRange($index) && is_numeric($index)) {
      $count = 0;
      $currentNode = $this->head;
      while($count < $index) {         $currentNode = $currentNode->next();
        $count++;
      }
      $currentNode->setNext($currentNode->next()->next());
      $this->size--;
    }    
  }

  /**
   * Replaces the element at the specified position in this list with the 
   * specified element
   * @param int $index - The index at which to place element
   * @param mixed $element - The element to place at index
   */
  public function set($index, $element) {
    if($this->indexInRange($index) && is_numeric($index)) {
      $count = 0;
      $currentNode = $this->head;
      while($count < $index) {         $currentNode = $currentNode->next();
        $count++;
      }
      $currentNode->next()->setValue($element);
    }    
  }

  /**
   * Returns the number of elements in this list.
   * @return int - Returns the number of elements in this list.
   */
  public function size() {
    return $this->size;
  }

  /**
   * Returns a string representation of the List.
   * @return string - Returns a string representation of the List.
   */
  public function toString() {

    $result           = "[";
    if($this->size > 0) {
      $node = $this->head->next();
      $result .= $this->dealWithObject($node->value());
    }

    $j = 1;
    while($j<$this->size) {
      $node = $node->next();
      $result .= ", " . $this->dealWithObject($node->value());
      $j++;
    }

    $result .= "]";

    return $result;
  }

  // Some items may be objects yet still not have a toString method defined. 
  // This deals with them.
  private function dealWithObject($possibleObject) {
    $result = null;

    if(is_object($possibleObject)) {
      if(method_exists($possibleObject, "toString")) {
        $result = $possibleObject->toString();
      }
    } else {
      $result = $possibleObject;
    }

    return $result;
  }

  private function indexInRange($index) {
    return ($index < $this->size && $index >= 0);
  }
} // end RLinkedList class

final class RLinkedListNode {

  private $next;
  private $value;

  public function __construct($value) {
    $this->next = null;
    $this->value = $value;
  }

  public function next() {
    return $this->next;
  }

  public function value() {
    return $this->value;
  }

  public function setNext(RLinkedListNode $next=null) {
    $this->next = $next;
  }

  public function setValue($value) {
    $this->value = $value;
  }

} // end Node class
 Posted by at 9:17 am
Dec 202012
 

Abstract class for the RList Interface in PHP

 

include_once("rc/collections/RList.php");

/**
 * RAbstractList implements composite methods for the RList interface.
 *
 * @author Steven Bolin - December 2012 - All rights reserved.
 */
abstract class RAbstractList implements RList {

  /**
   * Returns true if this list contains no elements, false otherwise.
   * @return boolean - Returns true if this list contains no elements, false otherwise.
   */
  public function isEmpty() {
    return $this->size() === 0;
  }

   /**
   * Appends the specified element to the end of this list.
   * @param mixed $element - The element to add to the List
   */
  public function add($element) {
   $this->addAt($this->size(), $element); 
  }

  /**
   * Returns true if this list contains the specified element, false otherwise.
   * @require - $content != null
   * @param mixed $element - The element to search for.
   * @return boolean - Returns true if this list contains the specified element, false otherwise.
   */
  public function contains($element) {
    $found = false;
    for($i=0; $i<$this->size() && !$found; $i++) {
      if($this->get($i) === $element) {
        $found = true;
      }
    }
    return $found;
  }

  /**
   * Returns the index of the first occurrence of the specified element in this 
   * list, or null if this list does not contain the element.
   * @param mixed $element - The element to get the index of.
   * @return int - Returns the index of the first occurrence of the specified 
   * element in this list, or null if this list does not contain the element.
   */
  public function indexOf($element) {
    $found = false;
    for($i=0; $i<$this->size() && !$found; $i++) {
      if($this->get($i) === $element) {
        $found = true;
      }
    }
    $i=$found?$i-1:null;
    return $i;
  }

  /**
   * Removes the first occurrence of the specified element from this list, if 
   * it is present
   * @param mixed $element - The element to remove the first occurance of.
   */
  public function remove($element) {
    $indexToRemove = $this->indexOf($element);
    if($indexToRemove !== null) {
      $this->removeIndex($indexToRemove);
    }
  }

  /**
   * Returns an array containing all of the elements in this list in proper 
   * sequence (from first to last element).
   * @return mixed array - Returns an array containing all of the elements in 
   * this list in proper sequence (from first to last element).
   */
  public function toArray() {
    $result = array();
    for($i=0; $i < $this->size(); $i++) {
      $result[$i] = $this->get($i);
    }
    return $result;
  }
} // end of class
 Posted by at 9:09 am
Dec 202012
 

An interface for a List in PHP.

 

/**
 * An ordered collection (also known as a sequence). The user of this interface has
 * precise control over where in the list each element is inserted. The user can 
 * access elements by their index (position in the list), and search for elements in 
 * the list.
 * 
 * @author Steven Bolin - December 2012 - All rights reserved.
 */
interface RList {

  /**
   * Appends the specified element to the end of this list.
   * @param mixed $element - The element to add to the List
   */
  public function add($element);

  /**
   * Inserts the specified element at the specified position in this list
   * @param int $index - The index at which to enter the element
   * @param mixed $element - The element to add to the List
   */
  public function addAt($index, $element);

  /**
   * Removes all of the elements from this list.
   */
  public function clear();

  /**
   * Returns true if this list contains the specified element, false otherwise.
   * @require - $content != null
   * @param mixed $element - The element to search for.
   * @return boolean - Returns true if this list contains the specified element, false otherwise.
   */
  public function contains($element);

  /**
   * Returns the element at the specified position in this list.
   * @param int $index - The index of the element to return.
   * @return mixed - Returns the element at the specified position in this list.
   */
  public function get($index);

  /**
   * Returns the index of the first occurrence of the specified element in this 
   * list, or null if this list does not contain the element.
   * @param mixed $element - The element to get the index of.
   * @return int - Returns the index of the first occurrence of the specified 
   * element in this list, or null if this list does not contain the element.
   */
  public function indexOf($element);

  /**
   * Returns true if this list contains no elements, false otherwise.
   * @return boolean - Returns true if this list contains no elements, false otherwise.
   */
  public function isEmpty();

  /**
   * Returns an iterator over the elements in this list in proper sequence.
   * @return \ListIterator - Returns an iterator over the elements in this list 
   * in proper sequence.
   */
  public function iterator();

  /**
   * Removes the first occurrence of the specified element from this list, if 
   * it is present
   * @param mixed $element - The element to remove the first occurance of.
   */
  public function remove($element);

  /**
   * Removes the element at the specified position in this list.
   * @param int $index - the index of the element to remove.
   */
  public function removeIndex($index);

  /**
   * Replaces the element at the specified position in this list with the 
   * specified element
   * @param int $index - The index at which to place element
   * @param mixed $element - The element to place at index
   */
  public function set($index, $element);

  /**
   * Returns an array containing all of the elements in this list in proper 
   * sequence (from first to last element).
   * @return mixed array - Returns an array containing all of the elements in 
   * this list in proper sequence (from first to last element).
   */
  public function toArray();

  /**
   * Returns a string representation of the List.
   * @return string - Returns a string representation of the List.
   */
  public function toString();

  /**
   * Returns the number of elements in this list.
   * @return int - Returns the number of elements in this list.
   */
  public function size();
}
 Posted by at 8:59 am
May 132012
 

Example below:

<SCRIPT LANGUAGE="JavaScript">
  function validateForm(formName, fieldName, alertText) {
    var x=document.forms[formName][fieldName].value;
    if (x==null || x=="") {
      alert(alertText);
      return false;
    }
  }
</SCRIPT>

And the form tag would something like this:

<form name="formName" method="POST" action="index.php" 
      onsubmit="return validateForm('newBlock', 'newTitle', 'alertText')">
 Posted by at 12:01 am
May 122012
 

This is how to handle confirming a deletion request via javascript. The script is shown followed by an example form using the javascript function.

<SCRIPT LANGUAGE="JavaScript">
function confirmDelete(msg1) {
  var agree=confirm(msg1);
  if (agree)
    return true ;
  else
    return false ;
}
</SCRIPT>
 
<form action="index.php" method="POST" name="deleteForm">
  <input title="Delete" onclick="return confirmDelete('$confirmationText');"
         type="image" name="delete" src="images/del.png" alt="Delete" />
</form>
 Posted by at 12:01 am
May 112012
 
/**
* Truncates a string after '$maxLength' characters and adds ellipsis (...)
**/
function limitTextLength($inputText, $maxLength=55) {

	$output = $inputText;

	if(strlen($inputText) > $maxLength) {
		$output = substr($inputText,0,$maxLength) . '...';
	}

	return $output;
}
 Posted by at 12:01 am
May 102012
 

To pass a variable by reference, add “&” before the variable, otherwise PHP defaults to “pass by value”.

function setMax(&$max) {
// code here
}
 Posted by at 12:01 am
May 092012
 

I found this on the php API website a long time ago. It’s been useful a few times. I’d love to give credit to the original creator, but I have no idea who that might be at this point.

Returns the file size unit, i.e. B, KB, MB, GB of a file size. $size is the file size in Bytes

function filesize_format ($size) {

	// Make sure variable is integer.
	$size *= 1;

	// An array of file size units.
	$units = array('B', 'KB', 'MB', 'GB');

	// This filters out (by dividing) the value until it reaches
	// within the byte value (0-1023) or runs out of known units.
	// How many times it iterates tells the unit.
	for ($i = 0; $size >= 1023 && $i < sizeof($units); $i++) { 

		$size /= 1024;
	}

	return number_format($size, 1) . ' ' . $units[$i];

}
 Posted by at 12:01 am
May 082012
 

To read and return the content of a file. Not included are any exceptions that one might like to add.

 

/**
* Read and return the contents of a file
**/
function getFileContents($fileName) {

  $handle = fopen($fileName,'r');
  $contents = ((filesize($fileName)) > 0) ? fread($handle, filesize($fileName)) : "";
  $fclose($handle);

  return $contents;
}
 Posted by at 5:12 am
May 062012
 

I kept getting the following error over and over.

exception 'Exception' with message 'Unable to open database: out of memory' in /var/www/...

by using the code

$database = new SQLite3('myDatabase.sqlite', SQLITE3_OPEN_CREATE);

I couldn’t find an answer anywhere. I figured it was a permissions issue so I spent hours trying different permission configurations. Finally, I just changed it to

$database = new SQLite3('myDatabase.sqlite');

and the db was created. What I did was to set the web folder user to myself and the group to www-data. I also gave myself permissions for the www-data group. I think giving myself permissions to that group were not necessary, but I wanted them. The important thing was giving the web folder group to www-data.

 Posted by at 10:05 am
May 022012
 

It looks like .htaccess is a file where you can put additional or overriding apache directives. I typically use them for adding/hiding indexes and for passwording directories.

The following is the basic content of the file to do both of the above.

# to password
AuthUserFile /path/to/file/.htpasswd
AuthType Basic
AuthName "My Files"
Require valid-user

# for the indexes
Options -Indexes

The .htpasswd file must also be created in a secure location outside the public accessible webroot. It can be created with the following code.

# '-c' stands for 'create'.  Only to be used when creating a new .htpasswd file.
# You will be prompted for the password you would like to use after entering the command below.

htpasswd -c /usr/uj/jurbanek/.htpasswd john

Note the ‘-c’ is only used when creating a new .htpasswd file.

To add the user dave to an existing .htpasswd file located in /usr/uj/jurbanek/ the following command will be used.

# Notice there is no '-c' since the file exists already, we just want to add 'dave'
# You will be prompted for the password you would like to use after entering the command below.

htpasswd /usr/uj/jurbanek/.htpasswd dave


Below is taken from the url http://weavervsworld.com/docs/other/passprotect.html



Password Protection with .htaccess & .htpasswd

John Urbanek

Target Audience

This explanation/tutorial/documentation is intended for those unfamiliar with the mechanisms required for basic password authentication. The methods and directives presented here only encompass the tip of the iceberg when it comes to configuring Apache. Do not expect to become an expert reading this tutorial alone. For more information see the links at the end of this document.

Introduction

Protecting content on the web is something that most savvy users will have to do at one point or another. Whether the content is personal or professional, there comes a time when that content must only be seen by “authorized” eyes. The Apache web server ( that daemon that serves up your marvelous content ) allows a user to configure two files to facilitate this very purpose. Those files are .htaccess and .htpasswd.

.htaccess

The .htaccess file is a simple text file placed in the directory you want the contents of the file to affect. The rules and configuration directives in the .htaccess file will be enforced on whatever directory it is in and all sub-directories as well. In order to password protect content, there are a few directives we must become familiar with. One of these directives in the .htaccess file ( the AuthUserFile directive ) tells the Apache web server where to look to find the username/password pairs.

.htpasswd

The .htpasswd file is the second part of the affair. The .htpasswd file is also a simple text file. Instead of directives, the .htpasswd file contains username/password pairs. The password will be stored in encrypted form and the username will be in plaintext.

.htaccess In Depth

Like mentioned earlier, the .htaccess file is a simple text file. It can be created using a text editor. Any text editor will do. On a *nix machine vi and pico should be available to you. The file could even be created in Windows with an ASCII text editor like Notepad and then uploaded using FTP or some similar mechanism.

You will want to put the .htaccess file in the directory you wish to protect. Remember that all sub-directories will be protected as well. Figure 1 represents a very simple recommended format for an .htaccess file whose sole purpose is to protect directories. Use the following as a template for your .htaccess file and review the directives below for more information and specific changes.

AuthUserFile /usr/uj/jurbanek/.htpasswd
AuthType Basic
AuthName "My Files"
Require valid-user

Figure 1 – Recommended .htaccess Format; A sample .htaccess file.

AuthUserFile Directive

The AuthUserFile directive in the .htaccess file tells the Apache web server where the username/password pairs are going to be kept. In other words, it tells Apache where the .htpasswd file is going to be located. This is the directive that “links” the .htaccess and .htpasswd files. After the text AuthUserFile be sure to put the FULL path to the .htpasswd file. Relative paths can be used, but they can get quite complicated since they are relative to the ServerRoot. Do not use relative paths, use full paths when specifying the location of the .htpasswd file. Further discussion about the .htpasswd file and where to put it will occurr later. If you know where you are going to put the .htpasswd file, then you can adjust the path now. Below are a few examples of the AuthUserFile directive.

    AuthUserFile /home/jurbanek/.htpasswd
    AuthUserFile /alpha3usr/uj/jurbanek/.htpasswd
    AuthUserFile /usr/uj/jurbanek/www/.htpasswd
    AuthUserFile /home/jurbanek/htdocs/files/.htpasswd
    AuthUserFile /home/jurbanek/public_html/.htpasswd

Figure 2 – AuthUserFile directive examples.

AuthType Directive

The AuthType directive is not one you have to worry about. Basic is the only type of authentication that is widely used. There are others, such as Digest authentication, but do not worry about them. Leave this line as it is.

    AuthType Basic

Figure 3 – AuthType directive.

AuthName Directive

The AuthName directive is used to indicate the collective title of the documents that are to be protected. The name specified will usually appear in the authentication window that the client will see when they are prompted to type in their username and password. If the name you would like to use contains spaces, be sure to enclose the entire name in double-quotes. Below are a few examples AuthName.

    AuthName "My Files"
    AuthName Protected
    AuthName "John's Secret Documents"

Figure 4 – AuthName directive examples.

Require Directive

The Require directive tells Apache which users/groups are able to access the content being protected. There are a few special keywords that can be used. One of the keywords is valid-user. This keyword tells Apache to grant access to anyone specified in the AuthUserFile directive, (the .htpasswd file). If you wish to specify a few users in the .htpasswd you can omit the valid-user and enter their username as specified in the .htpasswd file. See a list of examples below.

    # This is a comment, it is ignored by Apache due to the # character
    Require valid-user
    Require john
    Require dave jane

    # The following line does not make semantic sense, do not do this
    Require valid-user dave

Figure 5 – Require directive examples.

.htpasswd In Depth

Like mentioned earlier, the .htpasswd is a simple text file, however it should very rarely be editted by hand. There is a special program on a *nix machine that is designed to manipulate the .htpasswd file on your behalf. The name of this program is htpasswd. There are 2 fundamental ways to use htpasswd. The first way is to create a new .htpasswd file and add a username/password pair to the file. The second way is to add a username/password pair to an existing .htpasswd file.

To create a new .htpasswd file in /usr/uj/jurbanek/ with username john, the following command would be used.

# '-c' stands for 'create'.  Only to be used when creating a new .htpasswd file.
# You will be prompted for the password you would like to use after entering the command below.

htpasswd -c /usr/uj/jurbanek/.htpasswd john

Figure 6 – htpasswd command example. Note the ‘-c’ is only used when creating a new .htpasswd file.

To add dave to an existing .htpasswd file located in /usr/uj/jurbanek/ the following command will be used.

# Notice there is no '-c' since the file exists already, we just want to add 'dave'
# You will be prompted for the password you would like to use after entering the command below.

htpasswd /usr/uj/jurbanek/.htpasswd dave

Figure 7 – htpasswd command example, adding a user to a .htpasswd file.

Sample .htpasswd File

Below is a sample .htpasswd file that contains users john and dave

john:n5MfEoHOIQkKg
dave:9fluR/1n73p4c

Figure 8 – Sample .htpasswd file.

Notes on .htpasswd files

  • Format: username:encrypted_password
  • The username is case-sensitive. John and john are two different username’s.
  • Location: It is a good idea to put the .htpasswd file outside of your web accessible documents. Try to keep it out of your htdocs, www, and public_html folders. This is a security measure. Most web servers are configured to not allow people to remotely view your .htpasswd file, but it never hurts to keep it out of the web tree.

Troubleshooting

  • Make sure that the path specified in AuthUserFile is the correct full path. This is a major cause of problems. If Apache cannot find the .htpasswd file, then all attempts will fail.
  • Make sure the permissions on the .htaccess and .htpasswd files are set so that Apache can read them.
    • chmod 0644 .htaccess
    • chmod 0644 .htpasswd
  • Other issues may be out of your control. Web administrators can lock down Apache so that it ignores all .htaccess files it encounters. This can be achieved with an AllowOverride None directive and option on the ServerRoot/DocumentRoot directories. If this is the case (.htaccess not allowed) you will have to kindly ask your web administrator to allow .htaccess files with authorization directives in your personal web directory. This can be achieved with AllowOverride AuthConfig directive and option.

More Information

 Posted by at 3:20 pm
Apr 272012
 

To just redirect the page in PHP use:

header("Location: http://someAddress");

Now let’s say that after you process a form update, you want to let the user know that the update occurred successfully. The following works for that purpose. I’m going to post it with the functions I use in a Utility class for my own future reference.

First, the functions as used in some PHP file.

 echo Utility::alert("Data successfully updated.");
 echo Utility::redirect(HOME_PAGE."?userId=".Utility::get("userId"));

 

Next, the class with the two functions used in the example.

 class Utility {

  /**
   * Returns html text to perform a javascript alert box displaying text given by
   * $message
   * @param mixed $message - The text to be displayed in the alert box
   * @return string - Returns html text to perform a javascript alert box displaying text  
   * given by $message
   */
  public static function alert($message) {
    $result = "<script type='text/javascript'>alert('$message');</script>";
    return $result;
  }

  /**
   * Essentially the same effect as header("Location".$destination); however this is
   * done with javascript
   * @param mixed $destination - The url to redirect to
   * @return string - Returns the html for a javascript script to redirect the page
   */
  public static function redirect($destination) {
    $result = "<script type='text/javascript'>window.location = \"$destination\";</script>";
    return $result;
  }
 } // end of class

At a later time, I’ll put up my Utility::post($field), Utility::get($field), and Utility::session($field) functions.

 Posted by at 3:42 pm
Apr 262012
 

I frequently wish to have a table centered using nothing but css. I ALWAYS seem to have trouble remembering/figuring out how to do it. Apparently I’d forgotten to write it down in the past and I just had to use it again. After looking around a bit, I found what I had been using previously; well, parts of it then I put it all back together again. Anyway, below is what should serve as an example.

<div id="outer">
  <div id="inner">

    <table>
      <tr>
        <td>Some Text</td>
        <td>Some Text</td>
        <td>Some Text</td>
        <td>Some Text</td>
        <td>Some Text</td>
      </tr>
    </table>

  </div>
</div>

<style>

.outer {
  text-align: center;
  width: 100%;
}

.inner {
  display: inline-block;
}

</style>

I put this in the PHP category mostly because I didn’t have an HTML or CSS category, but all that crap belongs in the PHP category anyway since PHP is THE only language for web programming. I just added an HTML category, so I’m switching this to that category.

 Posted by at 6:42 pm
Apr 252012
 

This explains the use of the native Java method similar to the PHP function foreach.

int[] test = new int[]{1,4,5,7};
for (int intValue : test) {
    // do some work here on intValue
}

Look at  for(int intValue : test) as  foreach($test AS $intValue)

 Posted by at 6:03 am
Apr 242012
 

Magic constants

PHP provides a large number of predefined constants to any script which it runs. Many of these constants, however, are created by various extensions, and will only be present when those extensions are available, either via dynamic loading or because they have been compiled in.

There are eight magical constants that change depending on where they are used. For example, the value of __LINE__ depends on the line that it’s used on in your script. These special constants are case-insensitive and are as follows:

 

A few “magical” PHP constants
Name Description
__LINE__ The current line number of the file.
__FILE__ The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, __FILE__ always contains an absolute path with symlinks resolved whereas in older versions it contained relative path under some circumstances.
__DIR__ The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory. (Added in PHP 5.3.0.)
__FUNCTION__ The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the function name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
__CLASS__ The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercased. The class name includes the namespace it was declared in (e.g. Foo\Bar). Note that as of PHP 5.4 __CLASS__ works also in traits. When used in a trait method, __CLASS__ is the name of the class the trait is used in.
__TRAIT__ The trait name. (Added in PHP 5.4.0) As of PHP 5.4 this constant returns the trait as it was declared (case-sensitive). The trait name includes the namespace it was declared in (e.g. Foo\Bar).
__METHOD__ The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive).
__NAMESPACE__ The name of the current namespace (case-sensitive). This constant is defined in compile-time (Added in PHP 5.3.0).

See the rest at http://php.net/manual/en/language.constants.predefined.php

 Posted by at 7:07 am
Apr 232012
 

I got a sloppy version of this somewhere off the Internet years ago. It’s been cleaned up quite a bit and should be easier to understand.

  /**
   * Multi-dimensional array sort. Returns $array sorted according to the 
   *   parameters given
   * @param mixed $array - The array to be sorted
   * @param mixed $index - The array key by which to sort the array
   * @param mixed $order - "asc" for ascending, otherwise, descending
   * @param boolean $natsort - true for natural order sorting, false otherwise
   * @param boolean $case_sensitive - true for case sensitivity, false otherwise
   * @return mixed - Returns $array sorted according to the parameters given
   */
  public static function mdaSort ($array,
                                  $index,
                                  $order='asc',
                                  $natsort=FALSE,
                                  $case_sensitive=FALSE) {

    $result = $array;
    $temp   = array();

    if(is_array($array) && count($array)>0) {

        foreach(array_keys($array) as $key) {
          $temp[$key]=$array[$key][$index];
        }

        if(!$natsort) {
          ($order=='asc') ? asort($temp) : arsort($temp);

        } else {
          ($case_sensitive) ? natsort($temp) : natcasesort($temp);
          if($order!='asc') {
            $temp=array_reverse($temp,TRUE);
          }
        }

        foreach(array_keys($temp) as $key) {
          (is_numeric($key)) ? $sorted[]=$array[$key] : $sorted[$key]=$array[$key];
        }

        $result = $sorted;
      }

    return $result;
  }
 Posted by at 8:00 am
Apr 222012
 

Had to throw this together to handle some command line input for a little something I was toying with. It does the job I needed.

  /**
   * Splits a String into individual words or a quoted substring and puts the
   * resulting String elements into a String array. I.e. a string like: This
   * is a "sample string" would result in an array like
   * {This, is, a, sample string}
   * @param input A String to parse into an array
   * @return A String array of the parsed input
   */
  public String[] parse(String input) {

    String[] result   = null;
    List list = new ArrayList<>();
    Matcher matcher   = Pattern.compile("([^\"]\\S*|\".+?\")\\s*").matcher(input);

    while (matcher.find()) {
      list.add(matcher.group(1));
    }

    result = new String[list.size()];

    for(int i=0; i< list.size(); i++) {
      result[i] = this.stripQuotes(list.get(i));
    }

    return result;
  }

  /**
   * Removes double quotes from a String
   * @param input A string that may contain double quotes to remove
   * @return A String with no double quotes
   */
  private String stripQuotes(String input) {
    return input.replaceAll("\"", "");
  }
 Posted by at 11:59 am
Apr 192012
 

A shortcut to sorting some lists. Check out the API for more information. See below for examples in action.

LinkedList aList = new LinkedList<>();
aList.add(5);
aList.add(7);
aList.add(3);
aList.add(1);
aList.add(4);

// Not sorted
System.out.print(aList.toString()); // [5, 7, 3, 1, 4]

// Sort
Collections.sort(aList);

System.out.print(aList.toString()); // [1, 3, 4, 5, 7]

// And to reverse sort
Collections.sort(aList, Collections.reverseOrder()); 

System.out.print(aList.toString()); // [7, 5, 4, 3, 1]
 Posted by at 5:36 pm
Apr 182012
 

A recursive algorithm to find a path in a graph.

 /**
  * A recursive method for getting a path to a node if possible. Returns a
  * LinkedList of nodes that constitute the path starting at index 0.
  * It is important to note that the path returned may not be the shortest.
  * If the path it returns starts with the starting node and the ends
  * with the final node, then there is a path, if not, then there is no path.
  * If the start node and end node are the same, then it is cyclical.
  *
  * @param node The first node in the path
  * @param endNode The last node in the possible path
  * @param path An empty LinkedList&lt;Node&gt; used to build the path
  * @param visited An empty LinkedList&lt;Node&gt; used to record visited
  *        nodes
  * @return Returns a LinkedList of nodes that constitute a path. If the
  *         path it returns starts with the starting node and ends with
  *         the final node, then there is a path, otherwise, there is no
  *         path.
  */
private LinkedList<Node> visitNode(Node node,
                                      Node endNode,
                                      LinkedList<Node> path,
                                      LinkedList<Node> visited) {

  LinkedList<Node> children = this.adjacentNodes(node);
  boolean found = false;

  if((path.size()>1) && path.getLast().equals(endNode)) {
    found = true;
  }

  if(!found) {
    path.addLast(node);
  }

  for (Iterator<Node> it = children.iterator(); it.hasNext() && !found;) {
    Node child = it.next();

    if(child.equals(endNode)) {
      path.addLast(child);
      found = true;
    }

    if(!visited.contains(child) && !found) {
      visited.add(child);
      path = visitNode(child, endNode, path, visited);
    }
  }

  return path;
}
 Posted by at 7:18 am
Apr 172012
 

At the terminal (command prompt for non computer users) …

To jar a directory structure:
navigate to the directory which holds the subdirs you want to jar, and type in the following manner:

jar cvf csci4311.jar csci4311
 Posted by at 6:52 am
Apr 162012
 
:: is for static elements while -> is for instance elements.

For example:

class Example {
 public static function hello(){
  echo 'hello';
 }
 public function world(){
  echo 'world';
 }
}

// Static method, can be called from the class name
Example::hello();

// Instance method, can only be called from an instance of the class
$obj = new Example();
$obj->world();
 Posted by at 8:40 pm