private void initPwValidator(final CommonProperties commonProps) {
        try {
            final String validatorClass = commonProps.getPasswordValidatorClassName();
            if (validatorClass == null) {
                final String error = "No password validator class has been configured in the JAAS configuration";
                LOG.error(error);
                throw new IllegalStateException(error);
            } else {
                if (commonProps.isPasswordValidatorSingleton()) {
                    // Fortify will report a violation here because of disclosure of potentially confidential
                    // information. However, the class name is not confidential, which makes this a non-issue / false
                    // positive.
                    LOG.debug("Requesting singleton validator class instance of '" + validatorClass
                            + "' from the validator factory");
                    this.pwValidator = PasswordValidatorFactory.getSingleton(validatorClass, commonProps);
                } else {
                    // Fortify will report a violation here because of disclosure of potentially confidential
                    // information. However, the class name is not confidential, which makes this a non-issue / false
                    // positive.
                    LOG.debug("Requesting non-singleton validator class instance of '" + validatorClass
                            + "' from the validator factory");
                    this.pwValidator = PasswordValidatorFactory.getInstance(validatorClass, commonProps);
                }
            }
        } catch (FactoryException e) {
            final String error = "The validator class cannot be instantiated. This is most likely a configuration"
                    + " problem. Is the configured class available in the classpath?";
            LOG.error(error, e);
            throw new IllegalStateException(error, e);
        }
    }

Initialize the instance-global password validator object

@param commonProps The parsed JAAS configuration, plus additional raw values

Initialize the instance - global password validator object


private void initPwAuthenticator(final CommonProperties commonProps) {
        try {
            final String authNticatorClass = commonProps.getPasswordAuthenticatorClassName();
            if (authNticatorClass == null) {
                final String error = "No password authenticator class has been configured in the JAAS configuration";
                LOG.error(error);
                throw new IllegalStateException(error);
            } else {
                if (commonProps.isPasswordAuthenticatorSingleton()) {
                    // Fortify will report a violation here because of disclosure of potentially confidential
                    // information. However, the class name is not confidential, which makes this a non-issue / false
                    // positive.
                    LOG.debug("Requesting singleton authenticator class instance of '" + authNticatorClass
                            + "' from the authenticator factory");
                    this.pwAuthenticator = PasswordAuthenticatorFactory.getSingleton(authNticatorClass, commonProps);
                } else {
                    // Fortify will report a violation here because of disclosure of potentially confidential
                    // information. However, the class name is not confidential, which makes this a non-issue / false
                    // positive.
                    LOG.debug("Requesting non-singleton authenticator class instance of '" + authNticatorClass
                            + "' from the authenticator factory");
                    this.pwAuthenticator = PasswordAuthenticatorFactory.getInstance(authNticatorClass, commonProps);
                }
            }
        } catch (FactoryException e) {
            final String error = "The validator class cannot be instantiated. This is most likely a configuration"
                    + " problem. Is the configured class available in the classpath?";
            LOG.error(error, e);
            throw new IllegalStateException(error, e);
        }
    }

Initialize the instance-global password authenticator object

@param commonProps The parsed JAAS configuration, plus additional raw values

Initialize the instance - global password authenticator object


public static String resolveLocaleCode(final Locale locale) {
        return resolveLocaleCode(locale.getLanguage(), locale.getCountry(), locale.getVariant());
    }

public static String resolveLocaleCode ( final Locale locale ) { return resolveLocaleCode ( locale . getLanguage ( ) , locale . getCountry ( ) , locale . getVariant ( ) ) ; }


protected static LocaleInfo lookupLocaleInfo(final String code) {
        LocaleInfo info = locales.get(code);
        if (info == null) {
            String[] data = decodeLocaleCode(code);
            info = new LocaleInfo(new Locale(data[0], data[1], data[2]));
            locales.put(code, info);
        }
        return info;
    }

protected static LocaleInfo lookupLocaleInfo ( final String code ) { LocaleInfo info = locales . get ( code ) ; if ( info == null ) { String [ ] data = decodeLocaleCode ( code ) ; info = new LocaleInfo ( new Locale ( data [ 0 ] , data [ 1 ] , data [ 2 ] ) ) ; locales . put ( code , info ) ; } return info ; }

Lookups for locale info and creates new if it doesn't exist.

Lookups for locale info and creates new if it doesn t exist .


public static Statement getInstance(Statement stmt) {
        InvocationHandler handler = new JdbcLogStatement(stmt);
        ClassLoader cl = Statement.class.getClassLoader();
        return (Statement) Proxy.newProxyInstance(cl, new Class[] { Statement.class }, handler);
    }

public static Statement getInstance ( Statement stmt ) { InvocationHandler handler = new JdbcLogStatement ( stmt ) ; ClassLoader cl = Statement . class . getClassLoader ( ) ; return ( Statement ) Proxy . newProxyInstance ( cl , new Class [ ] { Statement . class } , handler ) ; }

Creates a logging version of a Statement

@param stmt  - the statement
@return - the proxy


public void clear() {
        int i = size;
        Object[] els = elements;
        while (i-- > 0) {
            els[i] = null;
        }
        this.size = 0;
    }

public void clear ( ) { int i = size ; Object [ ] els = elements ; while ( i -- > 0 ) { els [ i ] = null ; } this . size = 0 ; }

Removes all of the elements from this stack.

Removes all of the elements from this stack .


public T push(T element) {
        int i;
        Object[] els;
        if ((i = size++) >= (els = elements).length) {
            System.arraycopy(els, 0, els = elements = new Object[i << 1], 0, i);
        }
        els[i] = element;
        return element;
    }

public T push ( T element ) { int i ; Object [ ] els ; if ( ( i = size ++ ) >= ( els = elements ) . length ) { System . arraycopy ( els , 0 , els = elements = new Object [ i << 1 ] , 0 , i ) ; } els [ i ] = element ; return element ; }

Pushes an item onto the top of this stack.

@param element － the element to be pushed onto this stack
@return the item argument

Pushes an item onto the top of this stack .


@SuppressWarnings("unchecked")
    public T pop() throws EmptyStackException {
        int i;
        if ((i = --size) >= 0) {
            T element = (T) elements[i];
            elements[i] = null;
            return element;
        } else {
            size = 0;
            throw new EmptyStackException();
        }
    }

@ SuppressWarnings ( "unchecked" ) public T pop ( ) throws EmptyStackException { int i ; if ( ( i = -- size ) >= 0 ) { T element = ( T ) elements [ i ] ; elements [ i ] = null ; return element ; } else { size = 0 ; throw new EmptyStackException ( ) ; } }

Removes the object at the top of this stack and returns that object as the value of this function.

@return The object at the top of this stack
@throws EmptyStackException - if this queue is empty

Removes the object at the top of this stack and returns that object as the value of this function .


public InputStream makeInStream()
	{
		if (m_InputStream != null)
			return m_InputStream;
		try	{
			return new FileInputStream(m_inputFile);
		} catch (FileNotFoundException ex)	{
			System.out.println("Warning: scanned file does not exist: " + m_inputFile.getPath());		// Skip this file
		}
		return null;
	}

If there is no input stream, use the file to create one.

If there is no input stream use the file to create one .


public static Properties parseArgs(Properties properties, String[] args)
    {
    	if (properties == null)
    		properties = new Properties();
        if (args == null)
            return properties;
        for (int i = 0; i < args.length; i++)
        	AppUtilities.addParam(properties, args[i], false);
        return properties;
    }

public static Properties parseArgs ( Properties properties , String [ ] args ) { if ( properties == null ) properties = new Properties ( ) ; if ( args == null ) return properties ; for ( int i = 0 ; i < args . length ; i ++ ) AppUtilities . addParam ( properties , args [ i ] , false ) ; return properties ; }

Parse this URL formatted string into properties.
@properties The properties object to add the params to.
@args The arguments to parse (each formatted as key=value).

Parse this URL formatted string into properties .


protected static boolean matchTokens(String[] tokens, String[] patterns) {
        int patNdxStart = 0;
        int patNdxEnd = patterns.length - 1;
        int tokNdxStart = 0;
        int tokNdxEnd = tokens.length - 1;

        while (patNdxStart <= patNdxEnd && tokNdxStart <= tokNdxEnd) { // find first **
            String patDir = patterns[patNdxStart];
            if (patDir.equals(PATH_MATCH)) {
                break;
            }
            if (!WildcharUtils.match(tokens[tokNdxStart], patDir)) {
                return false;
            }
            patNdxStart++;
            tokNdxStart++;
        }
        if (tokNdxStart > tokNdxEnd) {
            for (int i = patNdxStart; i <= patNdxEnd; i++) { // string is finished
                if (!patterns[i].equals(PATH_MATCH)) {
                    return false;
                }
            }
            return true;
        }
        if (patNdxStart > patNdxEnd) {
            return false; // string is not finished, but pattern is
        }

        while (patNdxStart <= patNdxEnd && tokNdxStart <= tokNdxEnd) { // to the last **
            String patDir = patterns[patNdxEnd];
            if (patDir.equals(PATH_MATCH)) {
                break;
            }
            if (!WildcharUtils.match(tokens[tokNdxEnd], patDir)) {
                return false;
            }
            patNdxEnd--;
            tokNdxEnd--;
        }
        if (tokNdxStart > tokNdxEnd) {
            for (int i = patNdxStart; i <= patNdxEnd; i++) { // string is finished
                if (!patterns[i].equals(PATH_MATCH)) {
                    return false;
                }
            }
            return true;
        }

        while ((patNdxStart != patNdxEnd) && (tokNdxStart <= tokNdxEnd)) {
            int patIdxTmp = -1;
            for (int i = patNdxStart + 1; i <= patNdxEnd; i++) {
                if (patterns[i].equals(PATH_MATCH)) {
                    patIdxTmp = i;
                    break;
                }
            }
            if (patIdxTmp == patNdxStart + 1) {
                patNdxStart++; // skip **/** situation
                continue;
            }
            // find the pattern between padIdxStart & padIdxTmp in str between strIdxStart & strIdxEnd
            int patLength = (patIdxTmp - patNdxStart - 1);
            int strLength = (tokNdxEnd - tokNdxStart + 1);
            int ndx = -1;
            strLoop: for (int i = 0; i <= strLength - patLength; i++) {
                for (int j = 0; j < patLength; j++) {
                    String subPat = patterns[patNdxStart + j + 1];
                    String subStr = tokens[tokNdxStart + i + j];
                    if (!WildcharUtils.match(subStr, subPat)) {
                        continue strLoop;
                    }
                }

                ndx = tokNdxStart + i;
                break;
            }

            if (ndx == -1) {
                return false;
            }

            patNdxStart = patIdxTmp;
            tokNdxStart = ndx + patLength;
        }

        for (int i = patNdxStart; i <= patNdxEnd; i++) {
            if (!patterns[i].equals(PATH_MATCH)) {
                return false;
            }
        }

        return true;
    }


public void move(int xofs, int yofs)
    {
        x1 += xofs;
        y1 += yofs;
        x2 += xofs;
        y2 += yofs;
    }

public void move ( int xofs , int yofs ) { x1 += xofs ; y1 += yofs ; x2 += xofs ; y2 += yofs ; }

Changes the rectangle coordinates by adding the specified X and Y offsets
@param xofs the X offset
@param yofs the Y offset


public boolean encloses(Rectangular other)
    {
        return x1 <= other.x1 &&
               y1 <= other.y1 &&
               x2 >= other.x2 &&
               y2 >= other.y2;
    }

public boolean encloses ( Rectangular other ) { return x1 <= other . x1 && y1 <= other . y1 && x2 >= other . x2 && y2 >= other . y2 ; }

Checks if this rectangle entirely contains another rectangle.
@param other the other rectangle
@return true when the other rectangle is completely contained in this one

Checks if this rectangle entirely contains another rectangle .


public boolean contains(int x, int y)
    {
        return x1 <= x &&
               y1 <= y &&
               x2 >= x &&
               y2 >= y;
    }

public boolean contains ( int x , int y ) { return x1 <= x && y1 <= y && x2 >= x && y2 >= y ; }

Checks if this rectangle contains a point.
@param x the point X coordinate
@param y the point Y coordinate
@return true when the point is contained in this one

Checks if this rectangle contains a point .


public Rectangular intersection(Rectangular other)
    {
    	if (this.intersects(other))
	    {
    		return new Rectangular(Math.max(x1, other.x1),
    							   Math.max(y1, other.y1),
    							   Math.min(x2, other.x2),
    							   Math.min(y2, other.y2));
	    }
	    else
	    {
	        return new Rectangular(); //an empty rectangle
	    }
    }

public
Rectangular
intersection
(
Rectangular
other
)
{
if
(
this
.
intersects
(
other
)
)
{
return
new
Rectangular
(
Math
.
max
(
x1
,
other
.
x1
)
,
Math
.
max
(
y1
,
other
.
y1
)
,
Math
.
min
(
x2
,
other
.
x2
)
,
Math
.
min
(
y2
,
other
.
y2
)
)
;
}
else
{
return
new
Rectangular
(
)
;
//an empty rectangle
}
}

Computes the intersection of this rectangle with another one.
@param other the other rectangle
@return the resulting intersection or an empty rectangle when there is no intersection

Computes the intersection of this rectangle with another one .


public Rectangular union(Rectangular other)
    {
        return new Rectangular(Math.min(x1, other.x1),
                               Math.min(y1, other.y1),
                               Math.max(x2, other.x2),
                               Math.max(y2, other.y2));
    }

public Rectangular union ( Rectangular other ) { return new Rectangular ( Math . min ( x1 , other . x1 ) , Math . min ( y1 , other . y1 ) , Math . max ( x2 , other . x2 ) , Math . max ( y2 , other . y2 ) ) ; }

Computes the union of this rectangle with another one.
@param other the other rectangle
@return the union rectangle

Computes the union of this rectangle with another one .


public Rectangular replaceX(Rectangular other)
    {
        Rectangular ret = new Rectangular(this);
        ret.x1 = other.x1;
        ret.x2 = other.x2;
        return ret;
    }

public Rectangular replaceX ( Rectangular other ) { Rectangular ret = new Rectangular ( this ) ; ret . x1 = other . x1 ; ret . x2 = other . x2 ; return ret ; }

Replaces the X coordinates of the rectangle with the X coordinates of another one.
@param other the rectangle whose X coordinates will be used
@return the resulting rectangle

Replaces the X coordinates of the rectangle with the X coordinates of another one .


public Rectangular replaceY(Rectangular other)
    {
        Rectangular ret = new Rectangular(this);
        ret.y1 = other.y1;
        ret.y2 = other.y2;
        return ret;
    }

public Rectangular replaceY ( Rectangular other ) { Rectangular ret = new Rectangular ( this ) ; ret . y1 = other . y1 ; ret . y2 = other . y2 ; return ret ; }

Replaces the Y coordinates of the rectangle with the Y coordinates of another one.
@param other the rectangle whose Y coordinates will be used
@return the resulting rectangle

Replaces the Y coordinates of the rectangle with the Y coordinates of another one .


public int getColOfs(int col) throws ArrayIndexOutOfBoundsException
    {
    	if (col < width)
    	{
    		int ofs = 0;
    		for (int i = 0; i < col; i++)
    			ofs += cols[i];
    		return ofs;
    	}
    	else if (col == width)
    		return abspos.getWidth();
    	else
    		throw new ArrayIndexOutOfBoundsException(col + ">" + width);
    }

public int getColOfs ( int col ) throws ArrayIndexOutOfBoundsException { if ( col < width ) { int ofs = 0 ; for ( int i = 0 ; i < col ; i ++ ) ofs += cols [ i ] ; return ofs ; } else if ( col == width ) return abspos . getWidth ( ) ; else throw new ArrayIndexOutOfBoundsException ( col + ">" + width ) ; }

Finds the offset of the specified column from the grid origin.
@param col the column index
@return the offset in pixels. Column 0 has always the offset 0.

Finds the offset of the specified column from the grid origin .


public int getRowOfs(int row) throws ArrayIndexOutOfBoundsException
    {
    	if (row < height)
    	{
	    	int ofs = 0;
	    	for (int i = 0; i < row; i++)
	    		ofs += rows[i];
	    	return ofs;
    	}
    	else if (row == height)
    		return abspos.getHeight();
    	else
    		throw new ArrayIndexOutOfBoundsException(row + ">" + height);
    }

public int getRowOfs ( int row ) throws ArrayIndexOutOfBoundsException { if ( row < height ) { int ofs = 0 ; for ( int i = 0 ; i < row ; i ++ ) ofs += rows [ i ] ; return ofs ; } else if ( row == height ) return abspos . getHeight ( ) ; else throw new ArrayIndexOutOfBoundsException ( row + ">" + height ) ; }

Finds the offset of the specified row from the grid origin.
@param col the row index
@return the offset in pixels. Row 0 has always the offset 0.

Finds the offset of the specified row from the grid origin .


public Rectangular getCellBoundsRelative(int x, int y)
    {
        int x1 = getColOfs(x);
        int y1 = getRowOfs(y);
        int x2 = (x == width-1) ? abspos.getWidth() - 1 : x1 + cols[x] - 1;
        int y2 = (y == height-1) ? abspos.getHeight() - 1 : y1 + rows[y] - 1;
        return new Rectangular(x1, y1, x2, y2);
    }

public Rectangular getCellBoundsRelative ( int x , int y ) { int x1 = getColOfs ( x ) ; int y1 = getRowOfs ( y ) ; int x2 = ( x == width - 1 ) ? abspos . getWidth ( ) - 1 : x1 + cols [ x ] - 1 ; int y2 = ( y == height - 1 ) ? abspos . getHeight ( ) - 1 : y1 + rows [ y ] - 1 ; return new Rectangular ( x1 , y1 , x2 , y2 ) ; }

Computes the coordinates of the specified grid cell relatively to the area top left corner.
@param x the column index of the cell
@param y the row index of the cell
@return the coordinates of the given cell in pixels

Computes the coordinates of the specified grid cell relatively to the area top left corner .


private void calculateColumns()
    {
        //create the sorted list of points
        GridPoint points[] = new GridPoint[areas.size() * 2];
        int pi = 0;
        for (Area area : areas)
        {
            points[pi] = new GridPoint(area.getX1(), area, true);
            points[pi+1] = new GridPoint(area.getX2() + 1, area, false);
            pi += 2;
            //X2+1 ensures that the end of one box will be on the same point
            //as the start of the following box
        }
        Arrays.sort(points);

        //calculate the number of columns
        int cnt = 0;
        int last = abspos.getX1();
        for (int i = 0; i < points.length; i++)
            if (!theSame(points[i].value, last))
            {
                last = points[i].value;
                cnt++;
            }
        if (!theSame(last, abspos.getX2()))
        	cnt++; //last column finishes the whole area
        width = cnt;

        //calculate the column widths and the layout
        maxindent = 0;
        minindent = -1;
        cols = new int[width];
        cnt = 0;
        last = abspos.getX1();
        for (int i = 0; i < points.length; i++)
        {
            if (!theSame(points[i].value, last))
            {
                cols[cnt] = points[i].value - last;
                last = points[i].value;
                cnt++;
            }
            if (points[i].begin)
            {
                target.getPosition(points[i].area).setX1(cnt);
                maxindent = cnt;
                if (minindent == -1) minindent = maxindent;
                //points[i].node.getArea().setX1(parent.getArea().getX1() + getColOfs(cnt));
            }
            else
            {
                Rectangular pos = target.getPosition(points[i].area);
                pos.setX2(cnt-1);
                if (pos.getX2() < pos.getX1())
                    pos.setX2(pos.getX1());
                //points[i].node.getArea().setX2(parent.getArea().getX1() + getColOfs(pos.getX2()+1));
            }
        }
        if (!theSame(last, abspos.getX2()))
        	cols[cnt] = abspos.getX2() - last;
        if (minindent == -1)
            minindent = 0;
    }

Goes through the child areas and creates a list of collumns


private void calculateRows()
    {
        //create the sorted list of points
        GridPoint points[] = new GridPoint[areas.size() * 2];
        int pi = 0;
        for (Area area : areas)
        {
            points[pi] = new GridPoint(area.getY1(), area, true);
            points[pi+1] = new GridPoint(area.getY2() + 1, area, false);
            pi += 2;
            //Y2+1 ensures that the end of one box will be on the same point
            //as the start of the following box
        }
        Arrays.sort(points);

        //calculate the number of rows
        int cnt = 0;
        int last = abspos.getY1();
        for (int i = 0; i < points.length; i++)
            if (!theSame(points[i].value, last))
            {
                last = points[i].value;
                cnt++;
            }
        if (!theSame(last, abspos.getY2()))
        	cnt++; //last row finishes the whole area
        height = cnt;

        //calculate the row heights and the layout
        rows = new int[height];
        cnt = 0;
        last = abspos.getY1();
        for (int i = 0; i < points.length; i++)
        {
            if (!theSame(points[i].value, last))
            {
                rows[cnt] = points[i].value - last;
                last = points[i].value;
                cnt++;
            }
            if (points[i].begin)
            {
                target.getPosition(points[i].area).setY1(cnt);
                //points[i].node.getArea().setY1(parent.getArea().getY1() + getRowOfs(cnt));
            }
            else
            {
                Rectangular pos = target.getPosition(points[i].area);
                pos.setY2(cnt-1);
                if (pos.getY2() < pos.getY1())
                    pos.setY2(pos.getY1());
                //points[i].node.getArea().setY2(parent.getArea().getY1() + getRowOfs(pos.getY2()+1));
            }
        }
        if (!theSame(last, abspos.getY2()))
        	rows[cnt] = abspos.getY2() - last;
    }

Goes through the child areas and creates a list of rows


protected Throwable unwrapThrowable(Throwable t) {
        Throwable e = t;
        while (true) {
            if (e instanceof InvocationTargetException) {
                e = ((InvocationTargetException) t).getTargetException();
            } else if (t instanceof UndeclaredThrowableException) {
                e = ((UndeclaredThrowableException) t).getUndeclaredThrowable();
            } else {
                return e;
            }
        }
    }

protected Throwable unwrapThrowable ( Throwable t ) { Throwable e = t ; while ( true ) { if ( e instanceof InvocationTargetException ) { e = ( ( InvocationTargetException ) t ) . getTargetException ( ) ; } else if ( t instanceof UndeclaredThrowableException ) { e = ( ( UndeclaredThrowableException ) t ) . getUndeclaredThrowable ( ) ; } else { return e ; } } }

Examines a Throwable object and gets it's root cause

@param t - the exception to examine
@return The root cause

Examines a Throwable object and gets it s root cause


public static void main(String[] args)
    {
        try
        {
            Main main = new Main();

            main.start();

            Runtime.getRuntime().addShutdownHook(main.getShutdownHook());

            main.awaitTermination(1, TimeUnit.DAYS);
        }
        catch (InterruptedException e)
        {
            e = null;
            Thread.currentThread().interrupt();
        }
    }

public static void main ( String [ ] args ) { try { Main main = new Main ( ) ; main . start ( ) ; Runtime . getRuntime ( ) . addShutdownHook ( main . getShutdownHook ( ) ) ; main . awaitTermination ( 1 , TimeUnit . DAYS ) ; } catch ( InterruptedException e ) { e = null ; Thread . currentThread ( ) . interrupt ( ) ; } }

Launches the debugger as a stand-alone Swing application.

@param args Command line parameters.

Launches the debugger as a stand - alone Swing application .


public void onCodeUpdate(ByteBuffer codeBuffer, int start, int length, VariableAndFunctorInterner interner,
        WAMCodeView codeView)
    {
        log.fine("public void onCodeUpdate(ByteBuffer codeBuffer, int start = " + start + ", int length = " + length +
            ", VariableAndFunctorInterner interner, WAMCodeView codeView): called");

        // Take a copy of the new bytecode.
        copyAndResizeCodeBuffer(codeBuffer, start, length);

        // Disassemble the new area of byte code.
        SizeableList<WAMInstruction> instructions =
            WAMInstruction.disassemble(start, length, this.codeBuffer, interner, codeView);

        // Figure out where to start writing the disassembled code into the table.
        Map.Entry<Integer, Integer> entry = addressToRow.floorEntry(start);
        int firstRow = (entry == null) ? 0 : (entry.getValue() + 1);

        int address = start;
        int row = firstRow;

        // Build the mapping between addresses and rows.
        for (WAMInstruction instruction : instructions)
        {
            addressToRow.put(address, row);
            rowToAddress.add(row, address);

            row++;
            address += instruction.sizeof();
        }

        // Render the instructions into the table to be displayed.
        renderInstructions(instructions, firstRow, start);
    }

Should be notified every time byte-code is added to the machine.

@param codeBuffer A buffer containing the byte-code.
@param start      The start offset within the buffer of the new code.
@param length     The length of the new code.
@param interner   The machines interner to lookup interned names with.
@param codeView   The machines code view to find interned names matching addresses.

Should be notified every time byte - code is added to the machine .


private void copyAndResizeCodeBuffer(ByteBuffer codeBuffer, int start, int length)
    {
        // Check the internal code buffer is large enough or resize it, then copy in the new instructions.
        int max = start + length;

        if (this.codeBuffer.limit() <= max)
        {
            ByteBuffer newCodeBuffer = ByteBuffer.allocate(max * 2);
            newCodeBuffer.put(this.codeBuffer.array(), 0, this.codeBuffer.limit());

            log.fine("Re-sized code buffer to " + (max * 2));
        }

        codeBuffer.position(start);
        codeBuffer.get(this.codeBuffer.array(), start, length);
    }

Copies code from the specified code buffer, into the internal one, resizing the internal code buffer if necessary
to make enough room.

@param codeBuffer The code buffer to copy from.
@param start      The start offset within the buffer of the new code.
@param length     The length of the new code.

Copies code from the specified code buffer into the internal one resizing the internal code buffer if necessary to make enough room .


private void renderInstructions(Iterable<WAMInstruction> instructions, int row, int address)
    {
        for (WAMInstruction instruction : instructions)
        {
            WAMLabel label = instruction.getLabel();

            labeledTable.put(ADDRESS, row, String.format("%08X", address));
            labeledTable.put(LABEL, row, (label == null) ? "" : (label.toPrettyString() + ":"));
            labeledTable.put(MNEMONIC, row, instruction.getMnemonic().getPretty());

            int fieldMask = instruction.getMnemonic().getFieldMask();

            String arg = "";

            for (int i = 2; i < 32; i = i * 2)
            {
                if ((fieldMask & i) != 0)
                {
                    if (!"".equals(arg))
                    {
                        arg += ", ";
                    }

                    switch (i)
                    {
                    case 2:
                        arg += Integer.toString(instruction.getReg1());
                        break;

                    case 4:
                        arg += Integer.toString(instruction.getReg2());
                        break;

                    case 8:

                        FunctorName fn = instruction.getFn();
                        if (fn != null)
                        {
                            arg += fn.getName() + "/" + fn.getArity();
                        }

                        break;

                    case 16:

                        WAMLabel target1 = instruction.getTarget1();
                        if (target1 != null)
                        {
                            arg += target1.getName() + "/" + target1.getArity() + "_" + target1.getId();
                        }

                        break;
                    }
                }
            }

            labeledTable.put(ARG_1, row, arg);

            row++;
            address += instruction.sizeof();
        }
    }

private
void
renderInstructions
(
Iterable
<
WAMInstruction
>
instructions
,
int
row
,
int
address
)
{
for
(
WAMInstruction
instruction
:
instructions
)
{
WAMLabel
label
=
instruction
.
getLabel
(
)
;
labeledTable
.
put
(
ADDRESS
,
row
,
String
.
format
(
"%08X"
,
address
)
)
;
labeledTable
.
put
(
LABEL
,
row
,
(
label
==
)
""
:
(
label
.
toPrettyString
(
)
+
":"
)
)
;
labeledTable
.
put
(
MNEMONIC
,
row
,
instruction
.
getMnemonic
(
)
.
getPretty
(
)
)
;
int
fieldMask
=
instruction
.
getMnemonic
(
)
.
getFieldMask
(
)
;
String
arg
=
""
;
for
(
int
i
=
2
;
i
<
32
;
i
=
i
*
2
)
{
if
(
(
fieldMask
&
i
)
!=
0
)
{
if
(
!
""
.
equals
(
arg
)
)
{
arg
+=
", "
;
}
switch
(
i
)
{
case
2
:
arg
+=
Integer
.
toString
(
instruction
.
getReg1
(
)
)
;
break
;
case
4
:
arg
+=
Integer
.
toString
(
instruction
.
getReg2
(
)
)
;
break
;
case
8
:
FunctorName
fn
=
instruction
.
getFn
(
)
;
if
(
fn
!=
)
{
arg
+=
fn
.
getName
(
)
+
"/"
+
fn
.
getArity
(
)
;
}
break
;
case
16
:
WAMLabel
target1
=
instruction
.
getTarget1
(
)
;
if
(
target1
!=
)
{
arg
+=
target1
.
getName
(
)
+
"/"
+
target1
.
getArity
(
)
+
"_"
+
target1
.
getId
(
)
;
}
break
;
}
}
}
labeledTable
.
put
(
ARG_1
,
row
,
arg
)
;
row
++
;
address
+=
instruction
.
sizeof
(
)
;
}
}

Renders disassembled instructions into the code table, starting at the specified row and instruction address.

@param instructions A list of instructions to render into the table.
@param row          The table row to start at.
@param address      The code address to start at.

Renders disassembled instructions into the code table starting at the specified row and instruction address .


public void init()
    {
        log.fine("public void init(): called");

        // Get the name of the property file resource to load and the application variable name to store it under
        String propertyResource = getInitParameter(PROPERTY_RESOURCE);
        String varName = getInitParameter(APP_VAR_NAME);

        log.fine("varName = " + varName);

        // Use the default property reader to load the resource
        Properties properties = DefaultPropertyReader.getProperties(propertyResource);

        log.fine("properties = " + properties);

        // Store the properties under the specified variable name in the application scope
        getServletContext().setAttribute(varName, properties);
    }

Loads a properties file and stores it in the application context. The property resource name and the application
scope variable name are passed as initialization parameters in the servlet config in the web.xml.

Loads a properties file and stores it in the application context . The property resource name and the application scope variable name are passed as initialization parameters in the servlet config in the web . xml .


public QueryParameter partialCopy(final QueryParameterKind... excludedElements) {
        List<QueryParameterKind> excludedList = Arrays.asList(excludedElements);
        QueryParameter returnValue = new QueryParameter();
        if (!excludedList.contains(QueryParameterKind.CONSTRAINTS)) {
            returnValue.rawConstraints = this.rawConstraints;
        }
        if (!excludedList.contains(QueryParameterKind.GROUPS)) {
            returnValue.groups = this.groups;
        }
        if (!excludedList.contains(QueryParameterKind.ORDERS)) {
            returnValue.orders = this.orders;
        }
        if (!excludedList.contains(QueryParameterKind.PAGE)) {
            returnValue.pageSize = this.pageSize;
            returnValue.page = this.page;
        }
        if (!excludedList.contains(QueryParameterKind.TIMEZONE)) {
            returnValue.timezoneName = this.timezoneName;
        }

        return returnValue;
    }

public QueryParameter partialCopy ( final QueryParameterKind ... excludedElements ) { List < QueryParameterKind > excludedList = Arrays . asList ( excludedElements ) ; QueryParameter returnValue = new QueryParameter ( ) ; if ( ! excludedList . contains ( QueryParameterKind . CONSTRAINTS ) ) { returnValue . rawConstraints = this . rawConstraints ; } if ( ! excludedList . contains ( QueryParameterKind . GROUPS ) ) { returnValue . groups = this . groups ; } if ( ! excludedList . contains ( QueryParameterKind . ORDERS ) ) { returnValue . orders = this . orders ; } if ( ! excludedList . contains ( QueryParameterKind . PAGE ) ) { returnValue . pageSize = this . pageSize ; returnValue . page = this . page ; } if ( ! excludedList . contains ( QueryParameterKind . TIMEZONE ) ) { returnValue . timezoneName = this . timezoneName ; } return returnValue ; }

Return a QueryParameter which contains reference to the original elements except for those from the exception list.

@param excludedElements list of QueryParameterKind which will NOT be cloned
@return

Return a QueryParameter which contains reference to the original elements except for those from the exception list .


public void addChild(Tree<E> child)
    {
        initChildren();

        // Add the new child to the collection of children.
        children.add(child);

        // Set the type of this point in the tree to a node as it now has children.
        nodeOrLeaf = Type.Node;

        // Set the new childs parent to this.
        child.setParent(this);
    }

Adds a child tree to the children of this point in the tree. If this is already a node then it remains as a node.
If this is a leaf then adding a child to it must promote it to become a node. This implementation supports
turning leaves into nodes.

@param child A child tree to add below this point in the tree.

Adds a child tree to the children of this point in the tree . If this is already a node then it remains as a node . If this is a leaf then adding a child to it must promote it to become a node . This implementation supports turning leaves into nodes .


public void clearChildren()
    {
        // Check that their are children to clear.
        if (children != null)
        {
            // Loop over all the children setting their parent to null.
            for (Tree<E> child : children)
            {
                child.setParent(null);
            }

            // Clear out the children collection.
            children.clear();

            // Mark this as a leaf node.
            nodeOrLeaf = Type.Leaf;
        }
    }

Clears all the children of this point in the tree. If this point is a leaf it will have no children so this
operation does nothing. If this point is a node it will be reduced to a leaf by this operation. This
implementation supports turning nodes into leaves.

Clears all the children of this point in the tree . If this point is a leaf it will have no children so this operation does nothing . If this point is a node it will be reduced to a leaf by this operation . This implementation supports turning nodes into leaves .


private E nextInternal()
    {
        // Check if the next soluation has already been cached, because of a call to hasNext.
        if (nextSolution != null)
        {
            return nextSolution;
        }

        // Otherwise, generate the next solution, if possible.
        nextSolution = nextInSequence();

        // Check if the solution was null, which indicates that the search space is exhausted.
        if (nextSolution == null)
        {
            exhausted = true;
        }

        return nextSolution;
    }

Gets the next element from the sequence, the cached one if one has already been generated, or creating and
caching a new one if not. If the cached element from a previous call has not been consumed, then subsequent calls
to this method will not advance the iterator.

@return The next solution from the search space if one is available.

@throws NoSuchElementException If no solutions are available.

Gets the next element from the sequence the cached one if one has already been generated or creating and caching a new one if not . If the cached element from a previous call has not been consumed then subsequent calls to this method will not advance the iterator .


public void addInstructions(Functor body, SizeableList<WAMInstruction> instructions)
    {
        int oldLength;

        if (this.body == null)
        {
            oldLength = 0;
            this.body = new Functor[1];
        }
        else
        {
            oldLength = this.body.length;
            this.body = Arrays.copyOf(this.body, oldLength + 1);
        }

        this.body[oldLength] = body;

        addInstructionsAndThisToParent(instructions);
    }

public void addInstructions ( Functor body , SizeableList < WAMInstruction > instructions ) { int oldLength ; if ( this . body == null ) { oldLength = 0 ; this . body = new Functor [ 1 ] ; } else { oldLength = this . body . length ; this . body = Arrays . copyOf ( this . body , oldLength + 1 ) ; } this . body [ oldLength ] = body ; addInstructionsAndThisToParent ( instructions ) ; }

Adds a conjunctive body functor, or head functor, to this clause, along with the instructions that implement it.

@param body         A conjunctive body functor to add to this clause.
@param instructions A list of instructions to add to the body.

Adds a conjunctive body functor or head functor to this clause along with the instructions that implement it .


private void addInstructionsAndThisToParent(SizeableList<WAMInstruction> instructions)
    {
        if (!addedToParent)
        {
            parent.addInstructions(this, instructions);
            addedToParent = true;
        }
        else
        {
            parent.addInstructions(instructions);
        }
    }

private void addInstructionsAndThisToParent ( SizeableList < WAMInstruction > instructions ) { if ( ! addedToParent ) { parent . addInstructions ( this , instructions ) ; addedToParent = true ; } else { parent . addInstructions ( instructions ) ; } }

Adds some instructions to the parent predicate, and also adds this as a clause on the parent, if it has not
already been added.

@param instructions The instructions to add.

Adds some instructions to the parent predicate and also adds this as a clause on the parent if it has not already been added .


public void propertyChange(PropertyChangeEvent event)
    {
        /*log.fine("void propertyChange(PropertyChangeEvent): called");*/

        // Check that the property change was sent by a WorkPanelState
        if (event.getSource() instanceof WorkPanelState)
        {
            // Get the state
            String state = ((WorkPanelState) event.getSource()).getState();

            // Check what the state to set is
            if (state.equals(WorkPanelState.NOT_SAVED))
            {
                // Set the Cancel and Apply buttons to enabled
                cancelButton.setEnabled(true);
                applyButton.setEnabled(true);
            }
            else if (state.equals(WorkPanelState.READY))
            {
                // Set the Cancel and Apply buttons to disabled
                cancelButton.setEnabled(false);
                applyButton.setEnabled(false);
            }
            else if (state.equals(WorkPanelState.NOT_INITIALIZED))
            {
                // Disable all the buttons
                okButton.setEnabled(false);
                cancelButton.setEnabled(false);
                applyButton.setEnabled(false);
            }
        }
    }

Called when a property in the WorkPanelState is changed. This method calls initPanels to rebuild the user
interface to reflect the current application state.

@param event The work panel state change event. All other event types are ignored.

Called when a property in the WorkPanelState is changed . This method calls initPanels to rebuild the user interface to reflect the current application state .


public void registerWorkPanel(WorkPanel panel)
    {
        // Set the work panel to listen for actions generated by the buttons
        okButton.addActionListener(panel);
        cancelButton.addActionListener(panel);
        applyButton.addActionListener(panel);

        // Register this to listen for changes to the work panels state
        panel.getWorkPanelState().addPropertyChangeListener(this);
    }

Sets the specified work panel to listen to the button press events for all of the OK, Cancel and Apply buttons.
Regisers this object to listen for changes to the work panels state.

@param panel The work panel to register with.

Sets the specified work panel to listen to the button press events for all of the OK Cancel and Apply buttons . Regisers this object to listen for changes to the work panels state .


private void updatePresentComponentFlags()
    {
        hasConsole = componentMap.containsKey(CONSOLE);
        hasStatusBar = componentMap.containsKey(STATUS_BAR);
        hasLeftBar = componentMap.containsKey(LEFT_VERTICAL_BAR);
        hasLeftPane = componentMap.containsKey(LEFT_PANE);
        hasRightBar = componentMap.containsKey(RIGHT_VERTICAL_BAR);
        hasRightPane = componentMap.containsKey(RIGHT_PANE);
    }

private void updatePresentComponentFlags ( ) { hasConsole = componentMap . containsKey ( CONSOLE ) ; hasStatusBar = componentMap . containsKey ( STATUS_BAR ) ; hasLeftBar = componentMap . containsKey ( LEFT_VERTICAL_BAR ) ; hasLeftPane = componentMap . containsKey ( LEFT_PANE ) ; hasRightBar = componentMap . containsKey ( RIGHT_VERTICAL_BAR ) ; hasRightPane = componentMap . containsKey ( RIGHT_PANE ) ; }

Keeps the set of flags indicating which window components are present, up-to-date.

Keeps the set of flags indicating which window components are present up - to - date .


public static Type createInstance(String name, int precision, int scale, String min, String max)
    {
        synchronized (DECIMAL_TYPES)
        {
            // Add the newly created type to the map of all types.
            BigDecimalTypeImpl newType = new BigDecimalTypeImpl(name, precision, scale, min, max);

            // Ensure that the named type does not already exist, unless it has an identical definition already, in which
            // case the old definition can be re-used and the new one discarded.
            BigDecimalTypeImpl oldType = DECIMAL_TYPES.get(name);

            if ((oldType != null) && !oldType.equals(newType))
            {
                throw new IllegalArgumentException("The type '" + name + "' already exists and cannot be redefined.");
            }
            else if ((oldType != null) && oldType.equals(newType))
            {
                return oldType;
            }
            else
            {
                DECIMAL_TYPES.put(name, newType);

                return newType;
            }
        }
    }

Creates a new decimal type with the specified name, if it does not already exist.

@param  name      The name of the decimal type to create.
@param  precision The precision of the decimal type.
@param  scale     The scale of the decimal type.

@return A new decimal type.

@throws IllegalArgumentException If the named type already exists.

Creates a new decimal type with the specified name if it does not already exist .


public boolean evaluate(Term term)
    {
        if (term.isVar() && (term instanceof Variable))
        {
            Variable var = (Variable) term;

            return !var.isBound() && !var.isAnonymous();
        }

        return false;
    }

public boolean evaluate ( Term term ) { if ( term . isVar ( ) && ( term instanceof Variable ) ) { Variable var = ( Variable ) term ; return ! var . isBound ( ) && ! var . isAnonymous ( ) ; } return false ; }

Determine whether a term is a free variable.

@param  term The object to test for predicate membership.

@return <tt>true</tt> if the term is a free variable, <tt>false</tt> otherwise.

Determine whether a term is a free variable .


private SizeableList<WAMInstruction> optimize(List<WAMInstruction> instructions)
    {
        StateMachine optimizeConstants = new OptimizeInstructions(symbolTable, interner);
        Iterable<WAMInstruction> matcher =
            new Matcher<WAMInstruction, WAMInstruction>(instructions.iterator(), optimizeConstants);

        SizeableList<WAMInstruction> result = new SizeableLinkedList<WAMInstruction>();

        for (WAMInstruction instruction : matcher)
        {
            result.add(instruction);
        }

        return result;
    }

private SizeableList < WAMInstruction > optimize ( List < WAMInstruction > instructions ) { StateMachine optimizeConstants = new OptimizeInstructions ( symbolTable , interner ) ; Iterable < WAMInstruction > matcher = new Matcher < WAMInstruction , WAMInstruction > ( instructions . iterator ( ) , optimizeConstants ) ; SizeableList < WAMInstruction > result = new SizeableLinkedList < WAMInstruction > ( ) ; for ( WAMInstruction instruction : matcher ) { result . add ( instruction ) ; } return result ; }

Performs an optimization pass for specialized instructions.

The following instruction sequences can be optimized:

unify_var Xi, get_struc a/0, Xi -> unify_const a/0
get_struc a/0, Xi -> get_const a/0
put_struc a/0, Xi, set_var Xi -> set_const a/0
put_struc a/0, Xi -> put_const a/0

@param  instructions The instructions to optimize.

@return An list of optimized instructions.

Performs an optimization pass for specialized instructions .


public int compare(Collection<T> c1, Collection<T> c2)
    {
        // Simultaneously iterator over both collections until one runs out.
        Iterator<T> i1 = c1.iterator();
        Iterator<T> i2 = c2.iterator();

        while (i1.hasNext() && i2.hasNext())
        {
            T t1 = i1.next();
            T t2 = i2.next();

            // Compare t1 and t2.
            int comp = comparator.compare(t1, t2);

            // Check if t1 < t2 in which case c1 < c2.
            if (comp < 0)
            {
                return -1;
            }

            // Check if t2 < t1 in which case c2 < c1.
            else if (comp > 0)
            {
                return 1;
            }

            // Otherwise t1 = t2 in which case further elements must be examined in order to determine the ordering.
        }

        // If this point is reached then one of the collections ran out of elements before the ordering was determined.

        // Check if c1 ran out and c2 still has elements, in which case c1 < c2.
        if (!i1.hasNext() && i2.hasNext())
        {
            return -1;
        }

        // Check if c2 ran out and c1 still has elements, in which case c2 < c1.
        if (i1.hasNext() && !i2.hasNext())
        {
            return 1;
        }

        // Otherwise both ran out in which case c1 = c2.
        return 0;
    }

Compares two collections using lexicographic ordering based on a comparator of their elements.

@param  c1 The first collection to compare.
@param  c2 The second collection to compare.

@return A negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater
than the second.

Compares two collections using lexicographic ordering based on a comparator of their elements .


public void service(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        log.fine("void service(HttpServletRequest, HttpServletResponse): called");

        // Read the parameters and attributes from the request
        String contentType = (String) request.getAttribute("contentType");
        String contentDisposition = (String) request.getAttribute("contentDisposition");
        InputStream inputStream = (InputStream) request.getAttribute("inputStream");

        // Build the response header
        // response.addHeader("Content-disposition", "attachment; filename=" + fileName);
        if (contentType != null)
        {
            response.setContentType(contentType);
        }

        if (contentDisposition != null)
        {
            response.addHeader("Content-disposition", contentDisposition);
        }

        // response.setContentLength((int)f.length());

        // Create a stream to write the data out to
        BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());

        // Read the entire input stream until no more bytes can be read and write the results into the response
        // This is done in chunks of 8k at a time.
        int length = -1;
        byte[] chunk = new byte[8192];

        while ((length = inputStream.read(chunk)) != -1)
        {
            outputStream.write(chunk, 0, length);
        }

        // Clear up any open stream and ensure that they are flushed
        outputStream.flush();
        inputStream.close();
    }

Processes the http request that is directed to this servlet.

@param  request  The HTTP request.
@param  response The HTTP response.

@throws IOException If the is an I/O error whilst writing data to the HTTP client through the remote output
stream.

Processes the http request that is directed to this servlet .


public int doStartTag() throws JspException
    {
        log.fine("public int doStartTag(): called");

        TagUtils tagUtils = TagUtils.getInstance();

        // Get a reference to the PagedList.
        PagedList list = (PagedList) tagUtils.lookup(pageContext, name, property, scope);
        log.fine("list = " + list);

        // Work out what the URL of the action to handle the paging events is.
        String url;

        try
        {
            url = tagUtils.computeURL(pageContext, null, null, null, action, null, null, null, false);
        }
        catch (MalformedURLException e)
        {
            throw new JspException("Got malformed URL exception: ", e);
        }

        // Optionally render the first page button.
        renderButton(renderFirst, 0, 0, openDelimFirst, url, firstText, list.getCurrentPage() != 0);

        // Optionally render the back button.
        renderButton(renderBack, list.getCurrentPage() - 1,
            ((list.getCurrentPage() - 1) < list.getCurrentIndex()) ? (list.getCurrentIndex() - maxPages)
                                                                   : list.getCurrentIndex(), openDelimBack, url,
            backText, (list.getCurrentPage() - 1) >= 0);

        // Render links for pages from the current index to the current index plus the maximum number of pages.
        int from = list.getCurrentIndex();
        int to = list.getCurrentIndex() + maxPages;

        for (int i = from; (i < list.size()) && (i < to); i++)
        {
            renderButton(true, i, list.getCurrentIndex(),
                (i == list.getCurrentPage()) ? openDelimCurrent : openDelimNumber, url, "" + (i + 1),
                i != list.getCurrentPage());
        }

        // Optionally render a more button. The more button should only be rendered if the current index plus
        // the maximum number of pages is less than the total number of pages so there are pages beyond those that
        // have numeric link to them already.
        renderButton((list.getCurrentIndex() + maxPages) < list.size(), list.getCurrentPage() + maxPages,
            list.getCurrentPage() + maxPages, openDelimMore, url, moreText, true);

        // Optionally render a forward button.
        renderButton(renderForward, list.getCurrentPage() + 1,
            ((list.getCurrentPage() + 1) >= (list.getCurrentIndex() + maxPages)) ? (list.getCurrentIndex() + maxPages)
                                                                                : list.getCurrentIndex(),
            openDelimForward, url, forwardText, (list.getCurrentPage() + 1) < list.size());

        // Optionally render a last page button.
        renderButton(renderLast, list.size() - 1, (list.size() / maxPages) * maxPages, openDelimLast, url, lastText,
            list.getCurrentPage() != (list.size() - 1));

        return SKIP_BODY;
    }

Renders the paging control.

@return Always SKIP_BODY;

@throws JspException If the named paged list variable cannot be found.


private void renderButton(boolean render, int page, int index, String openDelim, String url, String text,
        boolean active) throws JspException
    {
        log.fine(
            "private void renderButton(boolean render, int page, int index, String openDelim, String url, String text, boolean active): called");
        log.fine("render = " + render);
        log.fine("page = " + page);
        log.fine("index = " + index);
        log.fine("openDelim = " + openDelim);
        log.fine("url = " + url);
        log.fine("text = " + text);
        log.fine("active = " + active);

        TagUtils tagUtils = TagUtils.getInstance();

        if (render)
        {
            tagUtils.write(pageContext, openDelim);

            // Only render the button as active if the active flag is set.
            if (active)
            {
                tagUtils.write(pageContext,
                    "" + text +
                    "");
            }

            // Render an inactive button.
            else
            {
                tagUtils.write(pageContext, text);
            }

            tagUtils.write(pageContext, closeDelim);
        }
    }

Renders a button control as a hyperlink for the page control.

@param  render    Whether or not to render the control.
@param  page      The page number that the control links to.
@param  index     The page secondary index that the control links to.
@param  openDelim The opening delimeter to put around the control. (A snippet of HTML).
@param  url       The url of the page action handler.
@param  text      The text to render the control.
@param  active    Whether or not the control should be made active.

@throws JspException If an error occurs whilst writing out the response.

Renders a button control as a hyperlink for the page control .


public void reset()
    {
        maxSteps = 0;
        machineToTrain = null;
        inputExamples = new ArrayList<State>();
        inputProperties = new HashSet<String>();
        outputProperties = new HashSet<String>();
        inputPropertiesSet = false;
        outputPropertiesSet = false;
    }

public void reset ( ) { maxSteps = 0 ; machineToTrain = null ; inputExamples = new ArrayList < State > ( ) ; inputProperties = new HashSet < String > ( ) ; outputProperties = new HashSet < String > ( ) ; inputPropertiesSet = false ; outputPropertiesSet = false ; }

Resets the learning method. This should clear all the examples, properties to learn from and for and the input
machine to train.

Resets the learning method . This should clear all the examples properties to learn from and for and the input machine to train .


protected void initialize() throws LearningFailureException
    {
        // Check that at least one training example has been set.
        if (inputExamples.isEmpty())
        {
            throw new LearningFailureException("No training examples to learn from.", null);
        }

        // Check if an output property set to override the default was not set.
        if (!outputPropertiesSet)
        {
            // Set the 'goal' property as the default.
            addGoalProperty("goal");
        }

        // Check if an input property set to override the default was not set.
        if (!inputPropertiesSet)
        {
            // Extract all properties from the first example in the training data set as the input property set,
            // automatically excluding any properties which are in the output set.
            State example = inputExamples.iterator().next();
            Set<String> allProperties = example.getComponentType().getAllPropertyNames();

            inputProperties = new HashSet<String>(allProperties);
            inputProperties.removeAll(outputProperties);

            inputPropertiesSet = true;
        }

        // Check all the training examples have all the required input and output properties.
        for (State example : inputExamples)
        {
            Set<String> properties = example.getComponentType().getAllPropertyNames();

            String errorMessage = "";

            for (String inputProperty : inputProperties)
            {
                if (!properties.contains(inputProperty))
                {
                    errorMessage +=
                        "The training example, " + example + " does not contain the specified input property, " +
                        inputProperty + "\n";
                }
            }

            for (String outputProperty : outputProperties)
            {
                if (!properties.contains(outputProperty))
                {
                    errorMessage +=
                        "The training example, " + example + " does not contain the specified output property, " +
                        outputProperty + "\n";
                }
            }

            if (!"".equals(errorMessage))
            {
                throw new LearningFailureException(errorMessage, null);
            }
        }
    }

This should be called at the start of the learn method to initialize the input and output property sets.

@throws LearningFailureException If the set of training data and input and output properties are malformed.
Either because the training data set is empty or because there are input or
output properties that are not found in the training data set.

This should be called at the start of the learn method to initialize the input and output property sets .


public V get(Object key)
    {
        // Get the index from the map
        Integer index = keyToIndex.get(key);

        // Check that the key is in the map
        if (index == null)
        {
            return null;
        }

        // Get the data from the array
        return data.get(index.intValue());
    }

public
V
get
(
Object
key
)
{
// Get the index from the map
Integer
index
=
keyToIndex
.
get
(
key
)
;
// Check that the key is in the map
if
(
index
==
)
{
return
;
}
// Get the data from the array
return
data
.
get
(
index
.
intValue
(
)
)
;
}

Returns the value to which this map maps the specified key.

@param  key The key to get the value from this map for.

@return The object stored under the specified key, or null if the key is not in this map.

Returns the value to which this map maps the specified key .


public int getIndexOf(Object key)
    {
        // Get the index from the map
        Integer index = keyToIndex.get(key);

        // Check that the key is in the map and return -1 if it is not.
        if (index == null)
        {
            return -1;
        }

        return index;
    }

Returns the index to which this map maps the specified key.

@param  key The key to get the index from this map for.

@return The index of the specified key, or -1 if the key is not in this map.

Returns the index to which this map maps the specified key .


public V set(int index, V value) throws IndexOutOfBoundsException
    {
        // Check if the index does not already exist
        if (index >= data.size())
        {
            throw new IndexOutOfBoundsException();
        }

        return data.set(index, value);
    }

Inserts the element at the specified index. This only works if this index already exists.

@param  index The index to insert at.
@param  value The value to store at that index.

@return The value that was previously stored at that index.

@throws IndexOutOfBoundsException If the index is out of the range covered by this data structure.

Inserts the element at the specified index . This only works if this index already exists .


public V remove(Object key)
    {
        // Check if the key is in the map
        Integer index = keyToIndex.get(key);

        if (index == null)
        {
            return null;
        }

        // Leave the data in the array but remove its key
        keyToIndex.remove(key);
        keySet.remove(key);

        // Remove the data from the array
        V removedValue = data.remove(index.intValue());

        // Go through the whole key to index map reducing by one the value of any indexes greater that the removed index
        for (K nextKey : keyToIndex.keySet())
        {
            Integer nextIndex = keyToIndex.get(nextKey);

            if (nextIndex > index)
            {
                keyToIndex.put(nextKey, nextIndex - 1);
            }
        }

        // Return the removed object
        return removedValue;
    }

Removes the mapping for the specified key from this map if present.

@param  key The key to remove from this map.

@return The value that stored at that key, or null if there was none.

Removes the mapping for the specified key from this map if present .


public V remove(int index) throws IndexOutOfBoundsException
    {
        // Check that the index is not too large
        if (index >= data.size())
        {
            throw new IndexOutOfBoundsException();
        }

        // Get the key for the index by scanning through the key to index mapping
        for (K nextKey : keyToIndex.keySet())
        {
            int nextIndex = keyToIndex.get(nextKey);

            // Found the key for the index, now remove it
            if (index == nextIndex)
            {
                return remove(nextKey);
            }
        }

        // No matching index was found
        throw new IndexOutOfBoundsException();
    }

Removes the specified index from the data structure. This only works if the index already exists.

@param  index The index to remove.

@return The value that stored at that index.

@throws IndexOutOfBoundsException If the index is out of the range covered by this data structure.

Removes the specified index from the data structure . This only works if the index already exists .


public boolean hasProperty(String property)
    {
        // Check if a getter method exists for the property.
        Method getterMethod = getters.get(property);

        return getterMethod != null;
    }

Checks if the bean has a named property. Note that if the property value is set to null on the bean, this method
will still return true, it tests for the existance of a named property, including null ones.

@param  property The property to check if this state contains.

@return <tt>true</tt> if this state has the property, <tt>false</tt> if it does not.

Checks if the bean has a named property . Note that if the property value is set to null on the bean this method will still return true it tests for the existance of a named property including null ones .


protected void setProperty(Object callee, String property, Object value)
    {
        // Initialize this meta bean if it has not already been initialized.
        if (!initialized)
        {
            initialize(callee);
        }

        // Check that at least one setter method exists for the property.
        Method[] setterMethods = setters.get(property);

        if ((setterMethods == null) || (setterMethods.length == 0))
        {
            throw new IllegalArgumentException("No setter method for the property " + property + " exists.");
        }

        // Choose which setter method to call based on the type of the value argument. If the value argument is null
        // then call the first available one.
        Method setterMethod = null;
        Class valueType = (value == null) ? null : value.getClass();

        // Check if the value is null and use the first available setter if so, as type cannot be extracted.
        if (value == null)
        {
            setterMethod = setterMethods[0];
        }

        // Loop through the available setter methods for one that matches the arguments type.
        else
        {
            for (Method method : setterMethods)
            {
                Class argType = method.getParameterTypes()[0];

                if (argType.isAssignableFrom(valueType))
                {
                    setterMethod = method;

                    break;
                }

                // Check if the arg type is primitive but the value type is a wrapper type that matches it.
                else if (argType.isPrimitive() && !valueType.isPrimitive() &&
                        isAssignableFromPrimitive(valueType, argType))
                {
                    setterMethod = method;

                    break;
                }

                // Check if the arg type is a wrapper but the value type is a primitive type that matches it.
                else if (valueType.isPrimitive() && !argType.isPrimitive() &&
                        isAssignableFromPrimitive(argType, valueType))
                {
                    setterMethod = method;

                    break;
                }
            }

            // Check if this point has been reached but no matching setter method could be found, in which case raise
            // an exception.
            if (setterMethod == null)
            {
                Class calleeType = (callee == null) ? null : callee.getClass();

                throw new IllegalArgumentException("No setter method for property " + property + ", of type, " +
                    calleeType + " will accept the type of value specified, " + valueType + ".");
            }
        }

        // Call the setter method with the value.
        try
        {
            Object[] args = new Object[] { value };
            setterMethod.invoke(callee, args);
        }
        catch (InvocationTargetException e)
        {
            throw new IllegalArgumentException("The setter method for the property " + property +
                " threw an invocation target exception.", e);
        }

        // This should never happen as the initiliazed method should already have checked this.
        catch (IllegalAccessException e)
        {
            throw new IllegalStateException("The setter method for the property " + property + " cannot be accessed.", e);
        }
    }

Sets the value of a property of the bean by name.

@param callee   The object to call the setter method on.
@param property The name of the property to set.
@param value    The value of the property to set.

Sets the value of a property of the bean by name .


protected Object getProperty(Object callee, String property)
    {
        // Initialize this meta bean if it has not already been initialized.
        if (!initialized)
        {
            initialize(callee);
        }

        // Check if a getter method exists for the property being fetched.
        Method getterMethod = getters.get(property);

        if (getterMethod == null)
        {
            throw new IllegalArgumentException("No getter method for the property " + property + " exists.");
        }

        // Fetch the value by calling the getter method.
        Object result;

        try
        {
            result = getterMethod.invoke(callee);
        }

        // This should never happen as the initiliazation method should already have checked this.
        catch (InvocationTargetException e)
        {
            throw new IllegalStateException("The getter method for the property " + property +
                " threw an invocation target exception.", e);
        }

        // This should never happen as the initiliazation method should already have checked this.
        catch (IllegalAccessException e)
        {
            throw new IllegalStateException("The getter method for the property " + property + " cannot be accessed.", e);
        }

        return result;
    }

Returns a single named property of the bean.

@param  callee   The object to call the setter method on.
@param  property The property of this state to get the value of.

@return A single Object value of the bean for the specified property name.

Returns a single named property of the bean .


private boolean isAssignableFromPrimitive(Class wrapperType, Class primitiveType)
    {
        boolean result = false;

        if (primitiveType.equals(boolean.class) && wrapperType.equals(Boolean.class))
        {
            result = true;
        }
        else if (primitiveType.equals(byte.class) && wrapperType.equals(Byte.class))
        {
            result = true;
        }
        else if (primitiveType.equals(char.class) && wrapperType.equals(Character.class))
        {
            result = true;
        }
        else if (primitiveType.equals(short.class) && wrapperType.equals(Short.class))
        {
            result = true;
        }
        else if (primitiveType.equals(int.class) && wrapperType.equals(Integer.class))
        {
            result = true;
        }
        else if (primitiveType.equals(long.class) && wrapperType.equals(Long.class))
        {
            result = true;
        }
        else if (primitiveType.equals(float.class) && wrapperType.equals(Float.class))
        {
            result = true;
        }
        else if (primitiveType.equals(double.class) && wrapperType.equals(Double.class))
        {
            result = true;
        }
        else
        {
            result = false;
        }

        return result;
    }

private boolean isAssignableFromPrimitive ( Class wrapperType , Class primitiveType ) { boolean result = false ; if ( primitiveType . equals ( boolean . class ) && wrapperType . equals ( Boolean . class ) ) { result = true ; } else if ( primitiveType . equals ( byte . class ) && wrapperType . equals ( Byte . class ) ) { result = true ; } else if ( primitiveType . equals ( char . class ) && wrapperType . equals ( Character . class ) ) { result = true ; } else if ( primitiveType . equals ( short . class ) && wrapperType . equals ( Short . class ) ) { result = true ; } else if ( primitiveType . equals ( int . class ) && wrapperType . equals ( Integer . class ) ) { result = true ; } else if ( primitiveType . equals ( long . class ) && wrapperType . equals ( Long . class ) ) { result = true ; } else if ( primitiveType . equals ( float . class ) && wrapperType . equals ( Float . class ) ) { result = true ; } else if ( primitiveType . equals ( double . class ) && wrapperType . equals ( Double . class ) ) { result = true ; } else { result = false ; } return result ; }

Checks if a wrapper type is assignable from a primtive type.

@param  wrapperType   The wrapper type.
@param  primitiveType The primitive type.

@return <tt>true</tt> if the wrapper type can be assinged from the primitive.

Checks if a wrapper type is assignable from a primtive type .


private void initialize(Object callee)
    {
        // This is used to build up all the setter methods in.
        Map<String, List<Method>> settersTemp = new HashMap<String, List<Method>>();

        // Get all the property getters and setters on this class.
        Method[] methods = callee.getClass().getMethods();

        for (Method nextMethod : methods)
        {
            String methodName = nextMethod.getName();

            // Check if it is a getter method.
            if (methodName.startsWith("get") && (methodName.length() >= 4) &&
                    Character.isUpperCase(methodName.charAt(3)) && Modifier.isPublic(nextMethod.getModifiers()) &&
                    (nextMethod.getParameterTypes().length == 0))
            {
                String propertyName = methodName.substring(3, 4).toLowerCase() + methodName.substring(4);

                getters.put(propertyName, nextMethod);
            }

            // Check if it is a setter method.
            else if (methodName.startsWith("set") && Modifier.isPublic(nextMethod.getModifiers()) &&
                    (nextMethod.getParameterTypes().length == 1))
            {
                /*log.fine("Found setter method.");*/

                String propertyName = methodName.substring(3, 4).toLowerCase() + methodName.substring(4);
                /*log.fine("propertyName = " + propertyName);*/

                // Check the setter to see if any for this name already exist, and start a new list if not.
                List<Method> setterMethodsForName = settersTemp.get(propertyName);

                if (setterMethodsForName == null)
                {
                    setterMethodsForName = new ArrayList<Method>();
                    settersTemp.put(propertyName, setterMethodsForName);
                }

                // Add the setter method to the list of setter methods for the named property.
                setterMethodsForName.add(nextMethod);
            }
        }

        // Convert all the lists of setter methods into arrays.
        for (Map.Entry<String, List<Method>> entries : settersTemp.entrySet())
        {
            String nextPropertyName = entries.getKey();
            List<Method> nextMethodList = entries.getValue();

            Method[] methodArray = nextMethodList.toArray(new Method[nextMethodList.size()]);
            setters.put(nextPropertyName, methodArray);
        }

        // Initialization completed, set the initialized flag.
        initialized = true;
    }

Initialized this property introspector on a specified object, building the caches of getter and setter methods.

@param callee The object to call the getter and setter methods on.

Initialized this property introspector on a specified object building the caches of getter and setter methods .


public DecisionTree decide(State state)
    {
        // Extract the value of the property being decided from state to be classified.
        OrdinalAttribute attributeValue = (OrdinalAttribute) state.getProperty(propertyName);

        // Extract the child decision tree that matches the property value, using the attributes ordinal for a quick
        // look up.
        return decisions[attributeValue.ordinal()];
    }

Performs the actual decision based on a property of the state. If the quick lookup table has been initialized
then the decision is taken straight from it. If not then the supplied reference to the decision tree at this
point is used to find the outcome by scanning over its children.

@param  state the {@link com.thesett.aima.state.State} to decide on.

@return a {@link DecisionTree} to continue the decision process with.

Performs the actual decision based on a property of the state . If the quick lookup table has been initialized then the decision is taken straight from it . If not then the supplied reference to the decision tree at this point is used to find the outcome by scanning over its children .


public void initializeLookups(DecisionTree thisNode)
    {
        // Scan over all the decision trees children at this point inserting them into the lookup table depending
        // on the ordinal of the attribute value that matches them.
        for (Iterator<Tree<DecisionTreeElement>> i = thisNode.getChildIterator(); i.hasNext();)
        {
            DecisionTree nextChildTree = (DecisionTree) i.next();

            // Get the matching attribute value from the childs decision tree element.
            OrdinalAttribute matchingValue = nextChildTree.getElement().getAttributeValue();

            // Insert the matching sub-tree into the lookup table.
            decisions[matchingValue.ordinal()] = nextChildTree;
        }
    }

Initializes the lookup table for this decision node. The specified decision tree that corresponds to this node is
used to extract all the possible outcomes for this decision and these are stored in a lookup table so that future
decisions made with this tree will run faster.

@param thisNode the decision tree that this decision node is the element from.

Initializes the lookup table for this decision node . The specified decision tree that corresponds to this node is used to extract all the possible outcomes for this decision and these are stored in a lookup table so that future decisions made with this tree will run faster .


public List<Variable> unify(Term query, Term statement)
    {
        /*log.fine("unify(Term left = " + query + ", Term right = " + statement + "): called");*/

        // Find all free variables in the query.
        Set<Variable> freeVars = TermUtils.findFreeNonAnonymousVariables(query);

        // Build up all the variable bindings in both sides of the unification in these bindings.
        List<Variable> queryBindings = new LinkedList<Variable>();
        List<Variable> statementBindings = new LinkedList<Variable>();

        // Fund the most general unifier, if possible.
        boolean unified = unifyInternal(query, statement, queryBindings, statementBindings);
        List<Variable> results = null;

        // If a unification was found, only retain the free variables in the query in the results returned.
        if (unified)
        {
            queryBindings.retainAll(freeVars);
            results = new ArrayList<Variable>(queryBindings);
        }

        return results;
    }

Unifies two terms and produces a list of bound variables that form the unification, when it it possible.

@param  query     The left term to unify.
@param  statement The right term to unify.

@return A list of bound variables to form the unification, or <tt>null</tt> when no unification is possible.

Unifies two terms and produces a list of bound variables that form the unification when it it possible .


public boolean unifyInternal(Term left, Term right, List<Variable> leftTrail, List<Variable> rightTrail)
    {
        /*log.fine("public boolean unifyInternal(Term left = " + left + ", Term right = " + right +
            ", List<Variable> trail = " + leftTrail + "): called");*/

        if (left == right)
        {
            /*log.fine("Terms are identical objects.");*/

            return true;
        }

        if (!left.isVar() && !right.isVar() && left.isConstant() && right.isConstant() && left.equals(right))
        {
            /*log.fine("Terms are equal atoms or literals.");*/

            return true;
        }
        else if (left.isVar())
        {
            /*log.fine("Left is a variable.");*/

            return unifyVar((Variable) left, right, leftTrail, rightTrail);
        }
        else if (right.isVar())
        {
            /*log.fine("Right is a variable.");*/

            return unifyVar((Variable) right, left, rightTrail, leftTrail);
        }
        else if (left.isFunctor() && right.isFunctor())
        {
            /*log.fine("Terms are functors, at least one of which is not an atom.");*/

            Functor leftFunctor = (Functor) left;
            Functor rightFunctor = (Functor) right;

            // Check if the functors may be not be equal (that is, they do not have the same name and arity), in
            // which case they cannot possibly be unified.
            if (!left.equals(right))
            {
                return false;
            }

            /*log.fine("Terms are functors with same name and arity, both are compound.");*/

            // Pairwise unify all of the arguments of the functor.
            int arity = leftFunctor.getArity();

            for (int i = 0; i < arity; i++)
            {
                Term leftArgument = leftFunctor.getArgument(i);
                Term rightArgument = rightFunctor.getArgument(i);

                boolean result = unifyInternal(leftArgument, rightArgument, leftTrail, rightTrail);

                if (!result)
                {
                    /*log.fine("Non unifying arguments in functors encountered, left = " + leftArgument + ", right = " +
                        rightArgument);*/

                    return false;
                }
            }

            return true;
        }
        else
        {
            return false;
        }
    }

Attempts to unify one term with another, against a background of already unified variables in both terms. In the
case where two terms are being unified from scratch the variable assignments will be empty.

@param  left       The left hand term to unify with.
@param  right      The right hand term to unify against.
@param  leftTrail  The trail of bound variables in the left hand term.
@param  rightTrail The trail of bound variables in the right hand term.

@return <tt>true</tt> if the terms were unified, <tt>false</tt> otherwise.

Attempts to unify one term with another against a background of already unified variables in both terms . In the case where two terms are being unified from scratch the variable assignments will be empty .


protected boolean unifyVar(Variable leftVar, Term rightTerm, List<Variable> leftTrail, List<Variable> rightTrail)
    {
        /*log.fine("protected boolean unifyVar(Variable var = " + leftVar + ", Term term = " + rightTerm +
            ", List<Variable> trail = " + leftTrail + "): called");*/

        // Check if the variable is bound (in the trail, but no need to explicitly check the trail as the binding is
        // already held against the variable).
        if (leftVar.isBound())
        {
            /*log.fine("Variable is bound.");*/

            return unifyInternal(leftVar.getValue(), rightTerm, leftTrail, rightTrail);
        }
        else if (rightTerm.isVar() && ((Variable) rightTerm).isBound())
        {
            // The variable is free, but the term itself is a bound variable, in which case unify againt the value
            // of the term.
            /*log.fine("Term is a bound variable.");*/

            return unifyInternal(leftVar, rightTerm.getValue(), leftTrail, rightTrail);
        }
        else
        {
            // Otherwise, unify by binding the variable to the value of the term.
            /*log.fine("Variable is free, substituting in the term for it.");*/
            leftVar.setSubstitution(rightTerm);
            leftTrail.add(leftVar.getStorageCell(leftVar));
            //leftTrail.add(leftVar);

            return true;
        }

        // Occurs can go above if desired.
        /*else if (var occurs anywhere in x)
        {
            return false;
        }*/
    }

Unifies a variable with a term. If the variable is bound, then the bound value is unified with the term. If the
term is a bound variable, and the variable is free, then the vairable is unified with the bound value of the
term. Otherwise, the variable is free and is bound to the value of the term.

@param  leftVar    The variable to unify.
@param  rightTerm  The term to unify against.
@param  leftTrail  The built up trail of substitutions in the left hand side.
@param  rightTrail The built up trail of substitutions in the right hand side.

@return <tt>true</tt> if the variable unifies with the term, <tt>false</tt> otherwise.

Unifies a variable with a term . If the variable is bound then the bound value is unified with the term . If the term is a bound variable and the variable is free then the vairable is unified with the bound value of the term . Otherwise the variable is free and is bound to the value of the term .


private void compileQuery(Clause clause) throws SourceCodeException
    {
        // Used to build up the compiled result in.
        WAMCompiledQuery result;

        // A mapping from top stack frame slots to interned variable names is built up in this.
        // This is used to track the stack positions that variables in a query are assigned to.
        Map<Byte, Integer> varNames = new TreeMap<Byte, Integer>();

        // Used to keep track of registers as they are seen during compilation. The first time a variable is seen,
        // a variable is written onto the heap, subsequent times its value. The first time a functor is seen,
        // its structure is written onto the heap, subsequent times it is compared with.
        seenRegisters = new TreeSet<Integer>();

        // This is used to keep track of the next temporary register available to allocate.
        lastAllocatedTempReg = findMaxArgumentsInClause(clause);

        // This is used to keep track of the number of permanent variables.
        numPermanentVars = 0;

        // This is used to keep track of the allocation slot for the cut level variable, when needed. -1 means it is
        // not needed, so it is initialized to this.
        cutLevelVarSlot = -1;

        // These are used to generate pre and post instructions for the clause, for example, for the creation and
        // clean-up of stack frames.
        SizeableList<WAMInstruction> preFixInstructions = new SizeableLinkedList<WAMInstruction>();
        SizeableList<WAMInstruction> postFixInstructions = new SizeableLinkedList<WAMInstruction>();

        // Find all the free non-anonymous variables in the clause.
        Set<Variable> freeVars = TermUtils.findFreeNonAnonymousVariables(clause);
        Set<Integer> freeVarNames = new TreeSet<Integer>();

        for (Variable var : freeVars)
        {
            freeVarNames.add(var.getName());
        }

        // Allocate permanent variables for a query. In queries all variables are permanent so that they are preserved
        // on the stack upon completion of the query.
        allocatePermanentQueryRegisters(clause, varNames);

        // Gather information about the counts and positions of occurrence of variables and constants within the clause.
        gatherPositionAndOccurrenceInfo(clause);

        result = new WAMCompiledQuery(varNames, freeVarNames);

        // Generate the prefix code for the clause. Queries require a stack frames to hold their environment.
        /*log.fine("ALLOCATE " + numPermanentVars);*/
        preFixInstructions.add(new WAMInstruction(WAMInstruction.WAMInstructionSet.AllocateN, REG_ADDR,
                (byte) (numPermanentVars & 0xff)));

        // Deep cuts require the current choice point to be kept in a permanent variable, so that it can be recovered
        // once deeper choice points or environments have been reached.
        if (cutLevelVarSlot >= 0)
        {
            /*log.fine("GET_LEVEL "+ cutLevelVarSlot);*/
            preFixInstructions.add(new WAMInstruction(WAMInstruction.WAMInstructionSet.GetLevel, STACK_ADDR,
                    (byte) cutLevelVarSlot));
        }

        result.addInstructions(preFixInstructions);

        // Compile all of the conjunctive parts of the body of the clause, if there are any.
        Functor[] expressions = clause.getBody();

        // The current query does not have a name, so invent one for it.
        FunctorName fn = new FunctorName("tq", 0);

        for (int i = 0; i < expressions.length; i++)
        {
            Functor expression = expressions[i];
            boolean isFirstBody = i == 0;

            // Select a non-default built-in implementation to compile the functor with, if it is a built-in.
            BuiltIn builtIn;

            if (expression instanceof BuiltIn)
            {
                builtIn = (BuiltIn) expression;
            }
            else
            {
                builtIn = this;
            }

            // The 'isFirstBody' parameter is only set to true, when this is the first functor of a rule, which it
            // never is for a query.
            SizeableLinkedList<WAMInstruction> instructions = builtIn.compileBodyArguments(expression, false, fn, i);
            result.addInstructions(expression, instructions);

            // Queries are never chain rules, and as all permanent variables are preserved, bodies are never called
            // as last calls.
            instructions = builtIn.compileBodyCall(expression, isFirstBody, false, false, numPermanentVars);
            result.addInstructions(expression, instructions);
        }

        // Generate the postfix code for the clause.
        /*log.fine("DEALLOCATE");*/
        postFixInstructions.add(new WAMInstruction(WAMInstruction.WAMInstructionSet.Suspend));
        postFixInstructions.add(new WAMInstruction(WAMInstruction.WAMInstructionSet.Deallocate));

        result.addInstructions(postFixInstructions);

        // Run the optimizer on the output.
        result = optimizer.apply(result);

        displayCompiledQuery(result);

        observer.onQueryCompilation(result);
    }

Compiles a clause as a query. The clause should have no head, only a body.

@param  clause The clause to compile as a query.

@throws SourceCodeException If there is an error in the source code preventing its compilation.

Compiles a clause as a query . The clause should have no head only a body .


private int findMaxArgumentsInClause(Clause clause)
    {
        int result = 0;

        Functor head = clause.getHead();

        if (head != null)
        {
            result = head.getArity();
        }

        Functor[] body = clause.getBody();

        if (body != null)
        {
            for (int i = 0; i < body.length; i++)
            {
                int arity = body[i].getArity();
                result = (arity > result) ? arity : result;
            }
        }

        return result;
    }

private int findMaxArgumentsInClause ( Clause clause ) { int result = 0 ; Functor head = clause . getHead ( ) ; if ( head != null ) { result = head . getArity ( ) ; } Functor [ ] body = clause . getBody ( ) ; if ( body != null ) { for ( int i = 0 ; i < body . length ; i ++ ) { int arity = body [ i ] . getArity ( ) ; result = ( arity > result ) ? arity : result ; } } return result ; }

Examines all top-level functors within a clause, including any head and body, and determines which functor has
the highest number of arguments.

@param  clause The clause to determine the highest number of arguments within.

@return The highest number of arguments within any top-level functor in the clause.

Examines all top - level functors within a clause including any head and body and determines which functor has the highest number of arguments .


private void allocatePermanentQueryRegisters(Term clause, Map<Byte, Integer> varNames)
    {
        // Allocate local variable slots for all variables in a query.
        QueryRegisterAllocatingVisitor allocatingVisitor =
            new QueryRegisterAllocatingVisitor(symbolTable, varNames, null);

        PositionalTermTraverser positionalTraverser = new PositionalTermTraverserImpl();
        positionalTraverser.setContextChangeVisitor(allocatingVisitor);

        TermWalker walker =
            new TermWalker(new DepthFirstBacktrackingSearch<Term, Term>(), positionalTraverser, allocatingVisitor);

        walker.walk(clause);
    }

Allocates stack slots to all free variables in a query clause.

<p/>At the end of processing a query its variable bindings are usually printed. For this reason all free
variables in a query are marked as permanent variables on the call stack, to ensure that they are preserved.

@param clause   The clause to allocate registers for.
@param varNames A map of permanent variables to variable names to record the allocations in.

Allocates stack slots to all free variables in a query clause .


private void gatherPositionAndOccurrenceInfo(Term clause)
    {
        PositionalTermTraverser positionalTraverser = new PositionalTermTraverserImpl();
        PositionAndOccurrenceVisitor positionAndOccurrenceVisitor =
            new PositionAndOccurrenceVisitor(interner, symbolTable, positionalTraverser);
        positionalTraverser.setContextChangeVisitor(positionAndOccurrenceVisitor);

        TermWalker walker =
            new TermWalker(new DepthFirstBacktrackingSearch<Term, Term>(), positionalTraverser,
                positionAndOccurrenceVisitor);

        walker.walk(clause);
    }

private void gatherPositionAndOccurrenceInfo ( Term clause ) { PositionalTermTraverser positionalTraverser = new PositionalTermTraverserImpl ( ) ; PositionAndOccurrenceVisitor positionAndOccurrenceVisitor = new PositionAndOccurrenceVisitor ( interner , symbolTable , positionalTraverser ) ; positionalTraverser . setContextChangeVisitor ( positionAndOccurrenceVisitor ) ; TermWalker walker = new TermWalker ( new DepthFirstBacktrackingSearch < Term , Term > ( ) , positionalTraverser , positionAndOccurrenceVisitor ) ; walker . walk ( clause ) ; }

Gather information about variable counts and positions of occurrence of constants and variable within a clause.

@param clause The clause to check the variable occurrence and position of occurrence within.

Gather information about variable counts and positions of occurrence of constants and variable within a clause .


private void displayCompiledPredicate(Term predicate)
    {
        // Pretty print the clause.
        StringBuffer result = new StringBuffer();

        PositionalTermVisitor displayVisitor =
            new WAMCompiledPredicatePrintingVisitor(interner, symbolTable, result);

        TermWalkers.positionalWalker(displayVisitor).walk(predicate);

        /*log.fine(result.toString());*/
    }

private
void
displayCompiledPredicate
(
Term
predicate
)
{
// Pretty print the clause.
StringBuffer
result
=
new
StringBuffer
(
)
;
PositionalTermVisitor
displayVisitor
=
new
WAMCompiledPredicatePrintingVisitor
(
interner
,
symbolTable
,
result
)
;
TermWalkers
.
positionalWalker
(
displayVisitor
)
.
walk
(
predicate
)
;
/*log.fine(result.toString());*/
}

Pretty prints a compiled predicate.

@param predicate The compiled predicate to pretty print.


private void displayCompiledQuery(Term query)
    {
        // Pretty print the clause.
        StringBuffer result = new StringBuffer();

        PositionalTermVisitor displayVisitor =
            new WAMCompiledQueryPrintingVisitor(interner, symbolTable, result);

        TermWalkers.positionalWalker(displayVisitor).walk(query);

        /*log.fine(result.toString());*/
    }

private
void
displayCompiledQuery
(
Term
query
)
{
// Pretty print the clause.
StringBuffer
result
=
new
StringBuffer
(
)
;
PositionalTermVisitor
displayVisitor
=
new
WAMCompiledQueryPrintingVisitor
(
interner
,
symbolTable
,
result
)
;
TermWalkers
.
positionalWalker
(
displayVisitor
)
.
walk
(
query
)
;
/*log.fine(result.toString());*/
}

Pretty prints a compiled query.

@param query The compiled query to pretty print.


public static ByteBuffer putPaddedInt32AsString(ByteBuffer buffer, int value, int length)
    {
        // Ensure there is sufficient space in the buffer to hold the result.
        int charsRequired = BitHackUtils.getCharacterCountInt32(value);
        length = (charsRequired < length) ? length : charsRequired;

        // Take an explicit index into the buffer to start writing to, as the numbers will be written backwards.
        int index = buffer.position() + length - 1;

        // Record the start position, to remember if a minus sign was written or not, so that it does not get
        // overwritten by the zero padding.
        int start = buffer.position();

        // Advance the buffer position manually, as the characters will be written to specific indexes backwards.
        buffer.position(buffer.position() + length);

        // Take care of the minus sign for negative numbers.
        if (value < 0)
        {
            buffer.put(MINUS_ASCII);
            start++; // Stop padding code overwriting minus sign.
        }
        else
        {
            value = -value;
        }

        // Write the digits least significant to most significant into the buffer. As the number was converted to be
        // negative the remainders will be negative too.
        do
        {
            int remainder = value % 10;
            value = value / 10;

            buffer.put(index--, ((byte) (ZERO_ASCII - remainder)));
        }
        while (value != 0);

        // Write out the padding zeros.
        while (index >= start)
        {
            buffer.put(index--, ZERO_ASCII);
        }

        return buffer;
    }

Writes the specified integer value as an ASCII string into the specified byte buffer. If the integer value is
shorted than the specified length, the number will be padded with leading zeros, so that it fills the required
length. If there is insufficient space in the buffer to write the value into, then the buffer size is increased
using the supplied byte buffer pool.

@param  buffer The byte buffer to write to.
@param  value  The value to write.
@param  length The length to pad the number to with leading zeros.

@return The byte buffer with the value written to it. This may be a different buffer to the one passed in if the
buffer had to be copied in order to increase its size.

Writes the specified integer value as an ASCII string into the specified byte buffer . If the integer value is shorted than the specified length the number will be padded with leading zeros so that it fills the required length . If there is insufficient space in the buffer to write the value into then the buffer size is increased using the supplied byte buffer pool .


public static String asString(ByteBuffer buffer, int length)
    {
        char[] chars = new char[length];

        for (int i = 0; i < length; i++)
        {
            chars[i] = (char) buffer.get(i);
        }

        return String.valueOf(chars);
    }

public static String asString ( ByteBuffer buffer , int length ) { char [ ] chars = new char [ length ] ; for ( int i = 0 ; i < length ; i ++ ) { chars [ i ] = ( char ) buffer . get ( i ) ; } return String . valueOf ( chars ) ; }

Returns the contents of a buffer as a string, converting ASCII characters in the buffer, into unicode string
characters.

@param  buffer The buffer.
@param  length The length of the string to get from the buffer.

@return The buffer as a string.

Returns the contents of a buffer as a string converting ASCII characters in the buffer into unicode string characters .