Input: Given a string potentially containing one or more copies of the replacement pattern $ { name } where name may be any value identifier ( e . g . home_dir1 ) replace each occurrence with the value of the parameter with the enclosed name . [CODESPLIT] public String replaceObjectNameParameters ( String pattern , MBeanLocationParameterSource parameterSource ) { Matcher matcher = replaceParamPattern . matcher ( pattern ) ; StringBuffer result = new StringBuffer ( ) ; while ( matcher . find ( ) ) { String name = matcher . group ( "paramName" ) ; String value = parameterSource . getParameter ( name ) ; if ( value != null ) { matcher . appendReplacement ( result , value ) ; } else { matcher . appendReplacement ( result , Matcher . quoteReplacement ( matcher . group ( ) ) ) ; } } matcher . appendTail ( result ) ; return result . toString ( ) ; }


Input: Return a new fully initialized instance of a { @link MessageQ } class to use for JAAS event messageing . <p > Classes implementing the { @link MessageQ } interface <b > must< / b > be thread safe . [CODESPLIT] public static MessageQ getInstance ( final String className , final CommonProperties properties ) throws FactoryException { Validate . notBlank ( className , "The validated character sequence 'className' is null or empty" ) ; Validate . notNull ( properties , "The validated object 'properties' is null" ) ; final Class < ? extends MessageQ > messageClazz ; try { messageClazz = Class . forName ( className ) . asSubclass ( MessageQ . class ) ; } catch ( ClassNotFoundException e ) { final String error = "Class not found: " + className ; LOG . warn ( error ) ; throw new FactoryException ( error , e ) ; } catch ( ClassCastException e ) { final String error = "The provided registry factory class name ('" + className + "') is not a subclass of '" + MessageQ . class . getCanonicalName ( ) + "'" ; LOG . warn ( error ) ; throw new FactoryException ( error , e ) ; } final MessageQ messageQ ; try { final Constructor < ? extends MessageQ > constructor = messageClazz . getDeclaredConstructor ( ) ; if ( ! constructor . isAccessible ( ) ) { final String error = "Constructor of class '" + messageClazz . getCanonicalName ( ) + "' is not accessible, changing the accessible flag to instantiate the class" ; LOG . info ( error ) ; constructor . setAccessible ( true ) ; } messageQ = constructor . newInstance ( ) ; } catch ( InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException | IllegalArgumentException e ) { final String error = "Cannot instantiate class '" + messageClazz . getCanonicalName ( ) + "'" ; LOG . warn ( error , e ) ; throw new FactoryException ( error , e ) ; } messageQ . init ( properties ) ; return messageQ ; }


Input: Return a singleton fully initialized instance of a { @link MessageQ } class to use for JAAS event messageing . <p > Retrieving a singleton by this method will cause the factory to keep state and store a reference to the singleton for later use . You may reset the factory state using the { @code reset () } method to retrieve a new / different singleton the next time this method is called .. <p > Note that any properties of the singleton ( e . g . configuration ) cannot necessarily be changed easily . You may call the singleton s { @code init () } method but depending on the implementation provided by the respective class this may or may not have the expected effect . <p > If you need tight control over the singleton including its lifecycle and configuration or you require more than one singleton that are different in their internal state ( e . g . with different configurations ) then you should create such objects with the { @code getInstance () } method and maintain their state as singletons in your application s business logic . <p > Classes implementing the { @link MessageQ } interface <b > must< / b > be thread safe . [CODESPLIT] @ SuppressWarnings ( "PMD.NonThreadSafeSingleton" ) public static MessageQ getSingleton ( final String className , final CommonProperties properties ) throws FactoryException { Validate . notBlank ( className , "The validated character sequence 'className' is null or empty" ) ; Validate . notNull ( properties , "The validated object 'properties' is null" ) ; // The double-check idiom is safe and acceptable here (Bloch, 2nd ed. p 284) if ( messageQInstance == null ) { synchronized ( MessageQFactory . class ) { if ( messageQInstance == null ) { messageQInstance = getInstance ( className , properties ) ; } } } return messageQInstance ; }


Input: <p > Synchronize APersistableBaseVersion ( itsVersion changed time ) . < / p > [CODESPLIT] @ Override public final boolean sync ( final Map < String , Object > pAddParam , final Object pEntity ) throws Exception { APersistableBaseVersion entityPb = ( APersistableBaseVersion ) pEntity ; int currDbId = getSrvOrm ( ) . getIdDatabase ( ) ; if ( currDbId == entityPb . getIdDatabaseBirth ( ) ) { throw new ExceptionWithCode ( ExceptionWithCode . SOMETHING_WRONG , "Foreign entity born in this database! {ID, ID BIRTH, DB BIRTH}:" + " {" + entityPb . getItsId ( ) + ", " + entityPb . getIdBirth ( ) + "," + entityPb . getIdDatabaseBirth ( ) ) ; } String tblNm = pEntity . getClass ( ) . getSimpleName ( ) . toUpperCase ( ) ; String whereStr = " where " + tblNm + ".IDBIRTH=" + entityPb . getItsId ( ) + " and " + tblNm + ".IDDATABASEBIRTH=" + entityPb . getIdDatabaseBirth ( ) ; APersistableBaseVersion entityPbDb = getSrvOrm ( ) . retrieveEntityWithConditions ( pAddParam , entityPb . getClass ( ) , whereStr ) ; entityPb . setIdBirth ( entityPb . getItsId ( ) ) ; entityPb . setItsId ( null ) ; boolean isNew = true ; if ( entityPbDb != null ) { entityPb . setItsVersion ( entityPbDb . getItsVersion ( ) ) ; entityPb . setItsId ( entityPbDb . getItsId ( ) ) ; isNew = false ; } return isNew ; }


Input: / * Add your property controls to this panel . Remember to set your own layout manager . Also remember to create a new JPanel and pass it to the super class so controls of the superclass can be included . You have a 3 x 3 grid so add three columns for each control [CODESPLIT] public void addControlsToView ( JPanel panel ) { panel . setLayout ( new BorderLayout ( ) ) ; this . makeNewPanel ( panel , BorderLayout . CENTER ) ; JPanel panelSub = this . makeNewPanel ( panel , BorderLayout . SOUTH ) ; super . addControlsToView ( panelSub ) ; }


Input: Examines a Throwable object and gets it s root cause [CODESPLIT] 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 ; } } }


Input: Appends single <code > byte< / code > to buffer . [CODESPLIT] public FastByteBuffer append ( byte element ) { if ( ( currentBuffer == null ) || ( offset == currentBuffer . length ) ) { needNewBuffer ( size + 1 ) ; } currentBuffer [ offset ] = element ; offset ++ ; size ++ ; return this ; }


Input: Appends another fast buffer to this one . [CODESPLIT] public FastByteBuffer append ( FastByteBuffer buff ) { if ( buff . size == 0 ) { return this ; } for ( int i = 0 ; i < buff . currentBufferIndex ; i ++ ) { append ( buff . buffers [ i ] ) ; } append ( buff . currentBuffer , 0 , buff . offset ) ; return this ; }


Input:
/ * Final wrapup - pad to 64 - byte boundary with the bit pattern 1 0 * ( 64 - bit count of bits processed MSB - first ) [CODESPLIT] public void md5final ( byte [ ] digest ) { /* "final" is a poor method name in Java. :v) */ int count ; int p ; // in original code, this is a pointer; in this java code // it's an index into the array this->in. /* Compute number of bytes mod 64 */ count = ( int ) ( ( bits >>> 3 ) & 0x3F ) ; /* Set the first char of padding to 0x80.  This is safe since there is
	       always at least one byte free */ p = count ; in [ p ++ ] = ( byte ) 0x80 ; /* Bytes of padding needed to make 64 bytes */ count = 64 - 1 - count ; /* Pad out to 56 mod 64 */ if ( count < 8 ) { /* Two lots of padding:  Pad the first block to 64 bytes */ zeroByteArray ( in , p , count ) ; transform ( ) ; /* Now fill the next block with 56 bytes */ zeroByteArray ( in , 0 , 56 ) ; } else { /* Pad block to 56 bytes */ zeroByteArray ( in , p , count - 8 ) ; } /* Append length in bits and transform */ // Could use a PUT_64BIT... func here. This is a fairly // direct translation from the C code, where bits was an array // of two 32-bit ints. int lowbits = ( int ) bits ; int highbits = ( int ) ( bits >>> 32 ) ; PUT_32BIT_LSB_FIRST ( in , 56 , lowbits ) ; PUT_32BIT_LSB_FIRST ( in , 60 , highbits ) ; transform ( ) ; PUT_32BIT_LSB_FIRST ( digest , 0 , buf [ 0 ] ) ; PUT_32BIT_LSB_FIRST ( digest , 4 , buf [ 1 ] ) ; PUT_32BIT_LSB_FIRST ( digest , 8 , buf [ 2 ] ) ; PUT_32BIT_LSB_FIRST ( digest , 12 , buf [ 3 ] ) ; /* zero sensitive data */ /* notice this misses any sneaking out on the stack. The C
		 * version uses registers in some spots, perhaps because
		 * they care about this.
		 */ zeroByteArray ( in ) ; zeroIntArray ( buf ) ; bits = 0 ; zeroIntArray ( inint ) ; }


Input: / * private void debugStatus ( String m ) { System . out . println ( m + : ) ; System . out . println ( in : + dumpBytes ( in )) ; System . out . println ( bits : + bits ) ; System . out . println ( buf : + Integer . toHexString ( buf [ 0 ] ) + + Integer . toHexString ( buf [ 1 ] ) + + Integer . toHexString ( buf [ 2 ] ) + + Integer . toHexString ( buf [ 3 ] )) ; } [CODESPLIT] public static String dumpBytes ( byte [ ] bytes ) { int i ; StringBuffer sb = new StringBuffer ( ) ; for ( i = 0 ; i < bytes . length ; i ++ ) { if ( i % 32 == 0 && i != 0 ) { sb . append ( "\n" ) ; } String s = Integer . toHexString ( bytes [ i ] ) ; if ( s . length ( ) < 2 ) { s = "0" + s ; } if ( s . length ( ) > 2 ) { s = s . substring ( s . length ( ) - 2 ) ; } sb . append ( s ) ; } return sb . toString ( ) ; }


Input: multipart / form - data [CODESPLIT] private static MultipartRequest asMultipartRequest ( HttpServletRequest request ) throws Exception { String encoding = request . getCharacterEncoding ( ) ; MultipartRequest req = new MultipartRequest ( request ) ; ServletFileUpload upload = new ServletFileUpload ( ) ; upload . setHeaderEncoding ( encoding ) ; FileItemIterator it = upload . getItemIterator ( request ) ; while ( it . hasNext ( ) ) { FileItemStream item = it . next ( ) ; String fieldName = item . getFieldName ( ) ; InputStream stream = item . openStream ( ) ; try { if ( item . isFormField ( ) ) { req . setParameter ( fieldName , Streams . asString ( stream , encoding ) ) ; } else { String originalFilename = item . getName ( ) ; File diskFile = getTempFile ( originalFilename ) ; OutputStream fos = new FileOutputStream ( diskFile ) ; try { IoUtils . copy ( stream , fos ) ; } finally { IoUtils . closeQuietly ( fos ) ; } FilePart filePart = new FilePart ( fieldName , originalFilename , diskFile ) ; req . addFile ( filePart ) ; } } finally { IoUtils . closeQuietly ( stream ) ; } } return req ; }


Input: application / octet - stream [CODESPLIT] private static MultipartRequest asHtml5Request ( HttpServletRequest request ) throws Exception { String originalFilename = request . getHeader ( "content-disposition" ) ; if ( originalFilename == null ) { throw new ServletException ( "The request is not a html5 file upload request." ) ; } originalFilename = new String ( originalFilename . getBytes ( "iso8859-1" ) , request . getCharacterEncoding ( ) ) ; originalFilename = StringUtils . substringAfter ( originalFilename , "; filename=" ) ; originalFilename = StringUtils . remove ( originalFilename , "\"" ) ; originalFilename = URLDecoder . decode ( originalFilename , "utf-8" ) ; File diskFile = getTempFile ( originalFilename ) ; InputStream fis = request . getInputStream ( ) ; OutputStream fos = new FileOutputStream ( diskFile ) ; try { IoUtils . copy ( fis , fos ) ; } finally { IoUtils . closeQuietly ( fis ) ; IoUtils . closeQuietly ( fos ) ; } MultipartRequest req = new MultipartRequest ( request ) ; FilePart filePart = new FilePart ( "file" , originalFilename , diskFile ) ; req . addFile ( filePart ) ; return req ; }


Input: 添加用户自定义的对象 [CODESPLIT] public void addBean ( Object beanObject ) { Validate . notNull ( beanObject ) ; addBean ( beanObject . getClass ( ) . getName ( ) , beanObject ) ; }


Input: 添加用户自定义的对象 [CODESPLIT] public void addBean ( Class < ? > beanClass , Object beanObject ) { Validate . notNull ( beanClass ) ; addBean ( beanClass . getName ( ) , beanObject ) ; }


Input: 添加用户自定义的对象 [CODESPLIT] public void addBean ( String name , Object beanObject ) { Validate . notNull ( beanObject ) ; addBean ( name , new ValueObject ( beanObject ) ) ; }


Input: 添加用户自定义的对象 [CODESPLIT] public void addBean ( String name , IocObject object ) { Validate . notNull ( name ) ; Validate . notNull ( object ) ; log . debug ( "addBean: {}" , name ) ; if ( pool . put ( name , object ) != null ) { log . warn ( "Duplicated Bean: {}" , name ) ; } }


Input: 注册 [CODESPLIT] public void addBean ( Class < ? > beanClass , Configuration properties , boolean singleton ) { Validate . notNull ( beanClass ) ; addBean ( beanClass . getName ( ) , beanClass , properties , singleton ) ; }


Input: 注册 [CODESPLIT] public void addBean ( String name , Class < ? > beanClass , Configuration properties , boolean singleton ) { Validate . notNull ( name ) ; Validate . notNull ( beanClass ) ; Validate . isFalse ( beanClass . isInterface ( ) , "Must not be interface: %s" , beanClass . getName ( ) ) ; Validate . isFalse ( Modifier . isAbstract ( beanClass . getModifiers ( ) ) , "Must not be abstract class: %s" , beanClass . getName ( ) ) ; log . debug ( "addBean: {}" , name , beanClass . getName ( ) ) ; IocObject iocObject = doGetIocObject ( beanClass , properties , singleton ) ; if ( pool . put ( name , iocObject ) != null ) { log . warn ( "Duplicated Bean: {}" , name ) ; } }


Input: 获取一个 Bean [CODESPLIT] @ Override @ SuppressWarnings ( "unchecked" ) public < T > T getBean ( Class < T > beanClass ) { Validate . notNull ( beanClass ) ; return ( T ) getBean ( beanClass . getName ( ) ) ; }


Input: 获取一个 Bean [CODESPLIT] @ Override public Object getBean ( String name ) { IocObject iocObject = pool . get ( name ) ; if ( iocObject == null ) { return null ; } return iocObject . getObject ( ) ; }


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] public < T > T unwrap ( Class < T > type ) { checkArgument ( Element . class . equals ( type ) , "Cannot unwrap to: %s" , type ) ; return type . cast ( element ) ; }


Input: Launches the debugger as a stand - alone Swing application . [CODESPLIT] 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 ( ) ; } }


Input: Should be notified every time byte - code is added to the machine . [CODESPLIT] 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 ) ; }


Input: Copies code from the specified code buffer into the internal one resizing the internal code buffer if necessary to make enough room . [CODESPLIT] 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 ) ; }


Input: Renders disassembled instructions into the code table starting at the specified row and instruction address . [CODESPLIT] 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 ( ) ; } }


Input: { [CODESPLIT] public void visit ( Functor functor ) { // functor is ground if all of its arguments are ground. boolean ground = true ; if ( functor . getArguments ( ) != null ) { for ( Term argument : functor . getArguments ( ) ) { SymbolKey symbolKey = argument . getSymbolKey ( ) ; TermDomain annotation = ( TermDomain ) symbolTable . get ( symbolKey , TERM_DOMAIN ) ; if ( ( annotation == null ) || ! annotation . ground ) { ground = false ; break ; } } } /*log.fine((ground ? "ground " : "non-ground ") + functor.toString(interner, true, false));*/ symbolTable . put ( functor . getSymbolKey ( ) , TERM_DOMAIN , new TermDomain ( ground ) ) ; }


Input:
{ [CODESPLIT] public void visit ( Variable variable ) { SymbolKey symbolKey = variable . getSymbolKey ( ) ; // Check if the variable has already been annotated. TermDomain annotation = ( TermDomain ) symbolTable . get ( symbolKey , TERM_DOMAIN ) ; if ( annotation == null ) { // variable is ground if it appears in a call to a predicate that always grounds that argument. /*log.fine("non-ground " + variable.toString(interner, true, false));*/ symbolTable . put ( symbolKey , TERM_DOMAIN , new TermDomain ( false ) ) ; } else { /*log.fine("already seen " + variable.toString(interner, true, false));*/ } // Check if the variable domain has already been annotated for a previous occurrence of the variable. VarDomain varDomain = ( VarDomain ) symbolTable . get ( symbolKey , VARIABLE_DOMAIN ) ; if ( varDomain == null ) { varDomain = new VarDomain ( traverser . isInHead ( ) ) ; symbolTable . put ( symbolKey , VARIABLE_DOMAIN , varDomain ) ; } else { varDomain . isTemporary = traverser . isInHead ( ) && varDomain . isTemporary ( ) ; } /*log.fine(variable.toString(interner, true, false) +
            (varDomain.isTemporary() ? " may be temporary." : " is not temporary."));*/ }


Input: { [CODESPLIT] public void visit ( LiteralType literal ) { // literal is ground. /*log.fine("ground " + literal.toString(interner, true, false));*/ symbolTable . put ( literal . getSymbolKey ( ) , TERM_DOMAIN , new TermDomain ( true ) ) ; }


Input: Gets the actual value of a term which is a numeric type equal in value to the arithmetic operator applied to its arguments . This method checks that both arguments produce values which are fully instantiated and numeric when their { @link Term#getValue () } methods are invoked . [CODESPLIT] public Term getValue ( ) { Term firstArgValue = arguments [ 0 ] . getValue ( ) ; Term secondArgValue = arguments [ 1 ] . getValue ( ) ; // Check that the arguments to operate on are both numeric values. if ( firstArgValue . isNumber ( ) && secondArgValue . isNumber ( ) ) { return evaluate ( ( NumericType ) firstArgValue , ( NumericType ) secondArgValue ) ; } else { return this ; } }


Input: 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 . [CODESPLIT] 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 ) ; }


Input:
{ [CODESPLIT] public boolean proofStep ( ResolutionState state ) { Functor goalTerm = state . getGoalStack ( ) . poll ( ) . getFunctor ( ) ; Term leftArg = goalTerm . getArgument ( 0 ) ; Term rightArg = goalTerm . getArgument ( 1 ) ; // This is used to record variables bound during the unification, so that they may be undone if the resolution // state is backtracked over. List < Variable > boundVariables = new LinkedList < Variable > ( ) ; // Unify the current query goal with the possibly matching clause, creating variable bindings. boolean matched = state . getUnifier ( ) . unifyInternal ( leftArg , rightArg , boundVariables , boundVariables ) ; if ( matched ) { if ( TRACE ) { /*trace.fine(state.getTraceIndenter().generateTraceIndent() + "Unify " +
                    leftArg.toString(state.getInterner(), true, true) + " against " +
                    rightArg.toString(state.getInterner(), true, true) + ", ok.");*/ } for ( Variable binding : boundVariables ) { state . getVariableBindings ( ) . offer ( binding ) ; } } return matched ; }


Input: Return a QueryParameter which contains reference to the original elements except for those from the exception list . [CODESPLIT] 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 ; }


Input: 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 . [CODESPLIT] 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 ) ; }


Input: 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 . [CODESPLIT] 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 ; } }


Input: Gets the next element from the sequence if one is available . The difference between this method and { @link #nextInSequence } is that this method consumes any cached solution so subsequent calls advance onto subsequent solutions . [CODESPLIT] public E next ( ) { // Consume the next element in the sequence, if one is available. E result = nextInternal ( ) ; if ( exhausted ) { throw new NoSuchElementException ( ) ; } nextSolution = null ; return result ; }


Input: 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 . [CODESPLIT] 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 ; }


Input: Adds a conjunctive body functor or head functor to this clause along with the instructions that implement it . [CODESPLIT] 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 ) ; }


Input: Adds some instructions to the parent predicate and also adds this as a clause on the parent if it has not already been added . [CODESPLIT] private void addInstructionsAndThisToParent ( SizeableList < WAMInstruction > instructions ) { if ( ! addedToParent ) { parent . addInstructions ( this , instructions ) ; addedToParent = true ; } else { parent . addInstructions ( instructions ) ; } }


Input: Evaluates the arithmetic operator on its two numeric arguments . [CODESPLIT] protected NumericType evaluate ( NumericType firstNumber , NumericType secondNumber ) { // If either of the arguments is a real number, then use real number arithmetic, otherwise use integer arithmetic. if ( firstNumber . isInteger ( ) && secondNumber . isInteger ( ) ) { return new IntLiteral ( firstNumber . intValue ( ) - secondNumber . intValue ( ) ) ; } else { return new DoubleLiteral ( firstNumber . doubleValue ( ) - secondNumber . doubleValue ( ) ) ; } }


Input: Called when a property in the WorkPanelState is changed . This method calls initPanels to rebuild the user interface to reflect the current application state . [CODESPLIT] 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 ) ; } } }


Input: 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 . [CODESPLIT] 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 ) ; }


Input: The { [CODESPLIT] public Result process ( Result parent , InputStream input ) throws IOException { ValueStack < Node > stack = new DefaultValueStack < Node > ( ) ; // Make the scope of each parent result accessible for variable and mixin resolution during parsing ScopeNode parentScope = null ; if ( parent != null ) { parentScope = parent . getScope ( ) ; stack . push ( parentScope ) ; } // Parse the input ParseRunner < Node > parseRunner = new ReportingParseRunner < Node > ( Parboiled . createParser ( Parser . class , _translationEnabled ) . Document ( ) ) . withValueStack ( stack ) ; ParsingResult < Node > result = parseRunner . run ( IOUtils . toString ( input , "UTF-8" ) ) ; if ( result . hasErrors ( ) ) { throw new LessTranslationException ( "An error occurred while parsing a LESS input file:\n" + ErrorUtils . printParseErrors ( result ) ) ; } // Retrieve the processed result ScopeNode scope = ( ScopeNode ) stack . pop ( ) ; // Link the new scope to the last parent for later variable resolution if ( parentScope != null ) { scope . setParentScope ( parentScope ) ; } return new Result ( scope ) ; }


Input: { [CODESPLIT] public void addLayoutComponent ( String name , Component comp ) { componentMap . put ( name , comp ) ; reverseMap . put ( comp , name ) ; }


Input: { [CODESPLIT] public void removeLayoutComponent ( Component comp ) { String name = reverseMap . remove ( comp ) ; if ( name != null ) { componentMap . remove ( name ) ; } }


Input: { [CODESPLIT] public Dimension preferredLayoutSize ( Container parent ) { Insets insets = parent . getInsets ( ) ; return new Dimension ( insets . left + insets . right , insets . top + insets . bottom ) ; }


Input: { [CODESPLIT] public void layoutContainer ( Container parent ) { // Get the available area to layout within. Insets insets = parent . getInsets ( ) ; int maxWidth = parent . getWidth ( ) - ( insets . left + insets . right ) ; int maxHeight = parent . getHeight ( ) - ( insets . top + insets . bottom ) ; // Check which optional components are present. updatePresentComponentFlags ( ) ; int centerHeight = maxHeight - ( ( hasConsole ? consoleHeight : 0 ) + ( hasStatusBar ? DEFAULT_STATUS_BAR_HEIGHT : 0 ) ) ; int statusBarTop = centerHeight ; int consoleTop = statusBarTop + DEFAULT_STATUS_BAR_HEIGHT ; int centerLeft = ( hasLeftPane ? leftPaneWidth : 0 ) + ( hasLeftBar ? DEFAULT_VBAR_WIDTH : 0 ) ; int centerRight = maxWidth - ( hasRightPane ? rightPaneWidth : 0 ) - ( hasRightBar ? DEFAULT_VBAR_WIDTH : 0 ) ; int centerWidth = centerRight - centerLeft ; int leftBarRight = centerLeft ; int leftBarLeft = leftBarRight - DEFAULT_VBAR_WIDTH ; int leftPaneRight = leftBarLeft ; int rightBarLeft = centerRight ; int rightPaneLeft = rightBarLeft + DEFAULT_VBAR_WIDTH ; for ( Component component : parent . getComponents ( ) ) { String type = reverseMap . get ( component ) ; int left = 0 ; int top = 0 ; int width = maxWidth ; int height = maxHeight ; if ( CENTER . equals ( type ) ) { left = centerLeft ; width = centerWidth ; height = centerHeight ; } else if ( STATUS_BAR . equals ( type ) ) { top = statusBarTop ; height = DEFAULT_STATUS_BAR_HEIGHT ; } else if ( CONSOLE . equals ( type ) ) { top = consoleTop ; height = consoleHeight ; } else if ( LEFT_PANE . equals ( type ) ) { width = leftPaneRight ; height = centerHeight ; } else if ( LEFT_VERTICAL_BAR . equals ( type ) ) { left = leftBarLeft ; width = DEFAULT_VBAR_WIDTH ; height = centerHeight ; } else if ( RIGHT_VERTICAL_BAR . equals ( type ) ) { left = rightBarLeft ; width = DEFAULT_VBAR_WIDTH ; height = centerHeight ; } else if ( RIGHT_PANE . equals ( type ) ) { left = rightPaneLeft ; width = rightPaneWidth ; height = centerHeight ; } component . setBounds ( left , top , width , height ) ; } }


Input: Keeps the set of flags indicating which window components are present up - to - date . [CODESPLIT] 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 ) ; }


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] public MicrodataDocument get ( String url ) { newUrl ( url ) ; driver . get ( url ) ; return new SeleniumMicrodataDocument ( driver ) ; }


Input: Creates a new decimal type with the specified name if it does not already exist . [CODESPLIT] 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 ; } } }


Input: { [CODESPLIT] public void acceptVisitor ( TypeVisitor visitor ) { if ( visitor instanceof BigDecimalTypeVisitor ) { ( ( BigDecimalTypeVisitor ) visitor ) . visit ( this ) ; } else { super . acceptVisitor ( visitor ) ; } }


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void submitSubmitsRequest ( ) throws InterruptedException { server ( ) . enqueue ( new MockResponse ( ) . setBody ( String . format ( "" + "<form name='f' method='%s' action='/x'>" + "<input type='submit'/>" + "</form>" + "" , getMethod ( ) ) ) ) ; server ( ) . enqueue ( new MockResponse ( ) ) ; newBrowser ( ) . get ( url ( server ( ) ) ) . getForm ( "f" ) . submit ( ) ; server ( ) . takeRequest ( ) ; assertThat ( "request" , takeRequest ( server ( ) ) , is ( method ( "/x" ) ) ) ; }


Input: Determine whether a term is a free variable . [CODESPLIT] public boolean evaluate ( Term term ) { if ( term . isVar ( ) && ( term instanceof Variable ) ) { Variable var = ( Variable ) term ; return ! var . isBound ( ) && ! var . isAnonymous ( ) ; } return false ; }


Input: { @inheritDoc } [CODESPLIT] public < T extends WAMOptimizeableListing > T apply ( WAMOptimizeableListing listing ) { SizeableList < WAMInstruction > optListing = optimize ( listing . getInstructions ( ) ) ; listing . setOptimizedInstructions ( optListing ) ; return ( T ) listing ; }


Input: Performs an optimization pass for specialized instructions . [CODESPLIT] 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 ; }


Input: Compares two collections using lexicographic ordering based on a comparator of their elements . [CODESPLIT] 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 ; }


Input:
---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getNameReturnsName ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "
" + "
" + "
" + "" ) ) ; String actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getItem ( "http://i" ) . getProperty ( "x" ) . getName ( ) ; assertThat ( "item property name" , actual , is ( "x" ) ) ; }


Input:
---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getValueWhenMetaReturnsContent ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "
" + "<meta itemprop='p' content='x'/>" + "
" + "" ) ) ; String actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getItem ( "http://i" ) . getProperty ( "p" ) . getValue ( ) ; assertThat ( "item property value" , actual , is ( "x" ) ) ; }


Input:
TODO : fix for Selenium [CODESPLIT] @ Ignore @ Test public void getValueWhenObjectReturnsAbsoluteUrl ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "
" + "<object itemprop='p' data='x'/>" + "
" + "" ) ) ; String actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getItem ( "http://i" ) . getProperty ( "p" ) . getValue ( ) ; assertThat ( "item property value" , actual , equalToIgnoringCase ( url ( server ( ) , "/x" ) ) ) ; }


Input:
---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getBooleanValueWhenTrueReturnsTrue ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "
" + "
true
" + "
" + "" ) ) ; boolean actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getItem ( "http://i" ) . getProperty ( "p" ) . getBooleanValue ( ) ; assertThat ( "item property value" , actual , is ( true ) ) ; }


Input:
---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getLongValueReturnsLong ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "
" + "
1
" + "
" + "" ) ) ; long actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getItem ( "http://i" ) . getProperty ( "p" ) . getLongValue ( ) ; assertThat ( "item property value" , actual , is ( 1L ) ) ; }


Input:
---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getFloatValueReturnsFloat ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "
" + "
1
" + "
" + "" ) ) ; float actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getItem ( "http://i" ) . getProperty ( "p" ) . getFloatValue ( ) ; assertThat ( "item property value" , actual , is ( 1f ) ) ; }


Input:
---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getDoubleValueReturnsDouble ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "
" + "
1
" + "
" + "" ) ) ; double actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getItem ( "http://i" ) . getProperty ( "p" ) . getDoubleValue ( ) ; assertThat ( "item property value" , actual , is ( 1d ) ) ; }


Input:
---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void unwrapWithUnknownTypeThrowsException ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "
" + "
" + "
" + "" ) ) ; MicrodataProperty property = newBrowser ( ) . get ( url ( server ( ) ) ) . getItem ( "http://i" ) . getProperty ( "x" ) ; thrown ( ) . expect ( IllegalArgumentException . class ) ; thrown ( ) . expectMessage ( "Cannot unwrap to: class java.lang.Void" ) ; property . unwrap ( Void . class ) ; }


Input: Processes the http request that is directed to this servlet . [CODESPLIT] 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 ( ) ; }


Input: Renders the paging control . [CODESPLIT] 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 ; }


Input: Renders a button control as a hyperlink for the page control . [CODESPLIT] 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 ) ; } }


Input: { [CODESPLIT] public int internFunctorName ( String name , int numArgs ) { FunctorName functorName = new FunctorName ( name , numArgs ) ; return getFunctorInterner ( ) . createIdAttribute ( functorName ) . ordinal ( ) ; }


Input: { [CODESPLIT] public boolean proofStep ( ResolutionState state ) { Functor goalTerm = state . getGoalStack ( ) . poll ( ) . getFunctor ( ) ; Term argument = goalTerm . getArgument ( 0 ) . getValue ( ) ; // Check that the argument is not a free variable. if ( argument . isVar ( ) ) { throw new IllegalStateException ( "instantiation_error, 'call' expects a fully instantiated term to unify against." ) ; } // Check that the argument is callable. if ( ! argument . isFunctor ( ) && ! argument . isAtom ( ) ) { throw new IllegalStateException ( "type_error, callable expected as argument to 'call'." ) ; } // Set up the argument to call as a new goal. state . getGoalStack ( ) . offer ( state . getBuiltInTransform ( ) . apply ( ( Functor ) argument ) ) ; return true ; }


Input: Resets the learning method . This should clear all the examples properties to learn from and for and the input machine to train . [CODESPLIT] public void reset ( ) { maxSteps = 0 ; machineToTrain = null ; inputExamples = new ArrayList < State > ( ) ; inputProperties = new HashSet < String > ( ) ; outputProperties = new HashSet < String > ( ) ; inputPropertiesSet = false ; outputPropertiesSet = false ; }


Input: This should be called at the start of the learn method to initialize the input and output property sets . [CODESPLIT] 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 ) ; } } }


Input: Returns the value to which this map maps the specified key . [CODESPLIT] 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 ( ) ) ; }


Input: Returns the index to which this map maps the specified key . [CODESPLIT] 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 ; }


Input: Associates the specified value with the specified key in this map . [CODESPLIT] public V put ( K key , V value ) { // Remove any existing matching key from the data V removedObject = remove ( key ) ; // Insert the data into the array data . add ( value ) ; // Insert a key into the map that points to the end of the array keyToIndex . put ( key , data . size ( ) - 1 ) ; // Create an entry in the key set to track the insertion order of the keys (automatically goes at the end of // a linked hash set) keySet . add ( key ) ; // Return the replaced value if there was one return removedObject ; }


Input: Inserts the element at the specified index . This only works if this index already exists . [CODESPLIT] 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 ) ; }


Input: Removes the mapping for the specified key from this map if present . [CODESPLIT] 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 ; }


Input: Removes the specified index from the data structure . This only works if the index already exists . [CODESPLIT] 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 ( ) ; }


Input: 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 . [CODESPLIT] public boolean hasProperty ( String property ) { // Check if a getter method exists for the property. Method getterMethod = getters . get ( property ) ; return getterMethod != null ; }


Input: Sets the value of a property of the bean by name . [CODESPLIT] 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 ) ; } }


Input: Returns a single named property of the bean . [CODESPLIT] 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 ; }


Input: Checks if a wrapper type is assignable from a primtive type . [CODESPLIT] 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 ; }


Input: Initialized this property introspector on a specified object building the caches of getter and setter methods . [CODESPLIT] 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 ; }


Input: { [CODESPLIT] public void propertyChange ( PropertyChangeEvent evt ) { String hex = String . format ( "%08X" , evt . getNewValue ( ) ) ; labeledTable . put ( evt . getPropertyName ( ) , hex ) ; }


Input: { [CODESPLIT] public boolean proofStep ( ResolutionState state ) { Functor goalTerm = state . getGoalStack ( ) . poll ( ) . getFunctor ( ) ; Term argument = goalTerm . getArgument ( 0 ) . getValue ( ) ; // Check that the argument is not a free variable. return argument . isNumber ( ) && ( ( NumericType ) argument . getValue ( ) ) . isReal ( ) ; }


Input: 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 . [CODESPLIT] 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 ( ) ] ; }


Input: 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 . [CODESPLIT] 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 ; } }


Input: Unifies two terms and produces a list of bound variables that form the unification when it it possible . [CODESPLIT] 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 ; }


Input:
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 . [CODESPLIT] 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 ; } }


Input:
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 . [CODESPLIT] 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;
        }*/ }


Input: { [CODESPLIT] public void endScope ( ) throws SourceCodeException { // Loop over all predicates in the current scope, found in the symbol table, and consume and compile them. for ( SymbolKey predicateKey = predicatesInScope . poll ( ) ; predicateKey != null ; predicateKey = predicatesInScope . poll ( ) ) { List < Clause > clauseList = ( List < Clause > ) scopeTable . get ( predicateKey , SymbolTableKeys . SYMKEY_PREDICATES ) ; // Used to keep track of where within the predicate the current clause is. int size = clauseList . size ( ) ; int current = 0 ; boolean multipleClauses = size > 1 ; // Used to build up the compiled predicate in. WAMCompiledPredicate result = null ; for ( Iterator < Clause > iterator = clauseList . iterator ( ) ; iterator . hasNext ( ) ; iterator . remove ( ) ) { Clause clause = iterator . next ( ) ; if ( result == null ) { result = new WAMCompiledPredicate ( clause . getHead ( ) . getName ( ) ) ; } // Compile the single clause, adding it to the parent compiled predicate. compileClause ( clause , result , current == 0 , current >= ( size - 1 ) , multipleClauses , current ) ; current ++ ; } // Run the optimizer on the output. result = optimizer . apply ( result ) ; displayCompiledPredicate ( result ) ; observer . onCompilation ( result ) ; // Move up the low water mark on the predicates table. symbolTable . setLowMark ( predicateKey , SymbolTableKeys . SYMKEY_PREDICATES ) ; } // Clear up the symbol table, and bump the compilation scope up by one. symbolTable . clearUpToLowMark ( SymbolTableKeys . SYMKEY_PREDICATES ) ; scopeTable = null ; scope ++ ; }


Input: { @inheritDoc } [CODESPLIT] public void compile ( Sentence < Clause > sentence ) throws SourceCodeException { /*log.fine("public WAMCompiledClause compile(Sentence<Term> sentence = " + sentence + "): called");*/ // Extract the clause to compile from the parsed sentence. Clause clause = sentence . getT ( ) ; // Classify the sentence to compile by the different sentence types in the language. if ( clause . isQuery ( ) ) { compileQuery ( clause ) ; } else { // Initialise a nested symbol table for the current compilation scope, if it has not already been. if ( scopeTable == null ) { scopeTable = symbolTable . enterScope ( scope ) ; } // Check in the symbol table, if a compiled predicate with name matching the program clause exists, and if // not create it. SymbolKey predicateKey = scopeTable . getSymbolKey ( clause . getHead ( ) . getName ( ) ) ; Collection < Clause > clauseList = ( List < Clause > ) scopeTable . get ( predicateKey , SymbolTableKeys . SYMKEY_PREDICATES ) ; if ( clauseList == null ) { clauseList = new LinkedList < Clause > ( ) ; scopeTable . put ( predicateKey , SymbolTableKeys . SYMKEY_PREDICATES , clauseList ) ; predicatesInScope . offer ( predicateKey ) ; } // Add the clause to compile to its parent predicate for compilation at the end of the current scope. clauseList . add ( clause ) ; } }


Input: Compiles a program clause and adds its instructions to a compiled predicate . [CODESPLIT] private void compileClause ( Clause clause , WAMCompiledPredicate compiledPredicate , boolean isFirst , boolean isLast , boolean multipleClauses , int clauseNumber ) throws SourceCodeException { // Used to build up the compiled clause in. WAMCompiledClause result = new WAMCompiledClause ( compiledPredicate ) ; // Check if the clause to compile is a fact (no body). boolean isFact = clause . getBody ( ) == null ; // Check if the clause to compile is a chain rule, (one called body). boolean isChainRule = ( clause . getBody ( ) != null ) && ( clause . getBody ( ) . length == 1 ) ; // 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 ) ; Collection < Integer > freeVarNames = new TreeSet < Integer > ( ) ; for ( Variable var : freeVars ) { freeVarNames . add ( var . getName ( ) ) ; } // Allocate permanent variables for a program clause. Program clauses only use permanent variables when really // needed to preserve variables across calls. allocatePermanentProgramRegisters ( clause ) ; // Gather information about the counts and positions of occurrence of variables and constants within the clause. gatherPositionAndOccurrenceInfo ( clause ) ; // Labels the entry point to each choice point. FunctorName fn = interner . getFunctorFunctorName ( clause . getHead ( ) ) ; WAMLabel entryLabel = new WAMLabel ( fn , clauseNumber ) ; // Label for the entry point to the next choice point, to backtrack to. WAMLabel retryLabel = new WAMLabel ( fn , clauseNumber + 1 ) ; // Create choice point instructions for the clause, depending on its position within the containing predicate. // The choice point instructions are only created when a predicate is built from multiple clauses, as otherwise // there are no choices to be made. if ( isFirst && ! isLast && multipleClauses ) { // try me else. preFixInstructions . add ( new WAMInstruction ( entryLabel , WAMInstruction . WAMInstructionSet . TryMeElse , retryLabel ) ) ; } else if ( ! isFirst && ! isLast && multipleClauses ) { // retry me else. preFixInstructions . add ( new WAMInstruction ( entryLabel , WAMInstruction . WAMInstructionSet . RetryMeElse , retryLabel ) ) ; } else if ( isLast && multipleClauses ) { // trust me. preFixInstructions . add ( new WAMInstruction ( entryLabel , WAMInstruction . WAMInstructionSet . TrustMe ) ) ; } // Generate the prefix code for the clause. // Rules may chain multiple, so require stack frames to preserve registers across calls. // Facts are always leafs so can use the global continuation point register to return from calls. // Chain rules only make one call, so also do not need a stack frame. if ( ! ( isFact || isChainRule ) ) { // Allocate a stack frame at the start of the clause. /*log.fine("ALLOCATE " + numPermanentVars);*/ preFixInstructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . Allocate ) ) ; } // 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 , ( byte ) cutLevelVarSlot ) ) ; } result . addInstructions ( preFixInstructions ) ; // Compile the clause head. Functor expression = clause . getHead ( ) ; SizeableLinkedList < WAMInstruction > instructions = compileHead ( expression ) ; result . addInstructions ( expression , instructions ) ; // Compile all of the conjunctive parts of the body of the clause, if there are any. if ( ! isFact ) { Functor [ ] expressions = clause . getBody ( ) ; for ( int i = 0 ; i < expressions . length ; i ++ ) { expression = expressions [ i ] ; boolean isLastBody = i == ( expressions . length - 1 ) ; boolean isFirstBody = i == 0 ; Integer permVarsRemaining = ( Integer ) symbolTable . get ( expression . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_PERM_VARS_REMAINING ) ; // 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. instructions = builtIn . compileBodyArguments ( expression , i == 0 , fn , i ) ; result . addInstructions ( expression , instructions ) ; // Call the body. The number of permanent variables remaining is specified for environment trimming. instructions = builtIn . compileBodyCall ( expression , isFirstBody , isLastBody , isChainRule , permVarsRemaining ) ; result . addInstructions ( expression , instructions ) ; } } // Generate the postfix code for the clause. Rules may chain, so require stack frames. // Facts are always leafs so can use the global continuation point register to return from calls. if ( isFact ) { /*log.fine("PROCEED");*/ postFixInstructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . Proceed ) ) ; } result . addInstructions ( postFixInstructions ) ; }


Input: Compiles a clause as a query . The clause should have no head only a body . [CODESPLIT] 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 ) ; }


Input: Examines all top - level functors within a clause including any head and body and determines which functor has the highest number of arguments . [CODESPLIT] 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 ; }


Input:
Compiles the head of a clause into an instruction listing in WAM . [CODESPLIT] private SizeableLinkedList < WAMInstruction > compileHead ( Functor expression ) { // Used to build up the results in. SizeableLinkedList < WAMInstruction > instructions = new SizeableLinkedList < WAMInstruction > ( ) ; // Allocate argument registers on the body, to all functors as outermost arguments. // Allocate temporary registers on the body, to all terms not already allocated. allocateArgumentRegisters ( expression ) ; allocateTemporaryRegisters ( expression ) ; // Program instructions are generated in the same order as the registers are assigned, the postfix // ordering used for queries is not needed. SearchMethod outInSearch = new BreadthFirstSearch < Term , Term > ( ) ; outInSearch . reset ( ) ; outInSearch . addStartState ( expression ) ; Iterator < Term > treeWalker = Searches . allSolutions ( outInSearch ) ; // Skip the outermost functor. treeWalker . next ( ) ; // Allocate argument registers on the body, to all functors as outermost arguments. // Allocate temporary registers on the body, to all terms not already allocated. // Keep track of processing of the arguments to the outermost functor as get_val and get_var instructions // need to be output for variables encountered in the arguments only. int numOutermostArgs = expression . getArity ( ) ; for ( int j = 0 ; treeWalker . hasNext ( ) ; j ++ ) { Term nextTerm = treeWalker . next ( ) ; /*log.fine("nextTerm = " + nextTerm);*/ // For each functor encountered: get_struc. if ( nextTerm . isFunctor ( ) ) { Functor nextFunctor = ( Functor ) nextTerm ; int allocation = ( Integer ) symbolTable . get ( nextFunctor . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION ) ; byte addrMode = ( byte ) ( ( allocation & 0xff00 ) >> 8 ) ; byte address = ( byte ) ( allocation & 0xff ) ; // Ouput a get_struc instruction, except on the outermost functor. /*log.fine("GET_STRUC " + interner.getFunctorName(nextFunctor) + "/" + nextFunctor.getArity() +
                    ((addrMode == REG_ADDR) ? ", X" : ", Y") + address);*/ WAMInstruction instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . GetStruc , addrMode , address , interner . getFunctorFunctorName ( nextFunctor ) , nextFunctor ) ; instructions . add ( instruction ) ; // For each argument of the functor. int numArgs = nextFunctor . getArity ( ) ; for ( int i = 0 ; i < numArgs ; i ++ ) { Term nextArg = nextFunctor . getArgument ( i ) ; allocation = ( Integer ) symbolTable . get ( nextArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION ) ; addrMode = ( byte ) ( ( allocation & 0xff00 ) >> 8 ) ; address = ( byte ) ( allocation & 0xff ) ; /*log.fine("nextArg = " + nextArg);*/ // If it is register not seen before: unify_var. // If it is register seen before: unify_val. if ( ! seenRegisters . contains ( allocation ) ) { /*log.fine("UNIFY_VAR " + ((addrMode == REG_ADDR) ? "X" : "Y") + address);*/ seenRegisters . add ( allocation ) ; instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . UnifyVar , addrMode , address , nextArg ) ; // Record the way in which this variable was introduced into the clause. symbolTable . put ( nextArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VARIABLE_INTRO , VarIntroduction . Unify ) ; } else { // Check if the variable is 'local' and use a local instruction on the first occurrence. VarIntroduction introduction = ( VarIntroduction ) symbolTable . get ( nextArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VARIABLE_INTRO ) ; if ( isLocalVariable ( introduction , addrMode ) ) { /*log.fine("UNIFY_LOCAL_VAL " + ((addrMode == REG_ADDR) ? "X" : "Y") +
                                address);*/ instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . UnifyLocalVal , addrMode , address , nextArg ) ; symbolTable . put ( nextArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VARIABLE_INTRO , null ) ; } else { /*log.fine("UNIFY_VAL " + ((addrMode == REG_ADDR) ? "X" : "Y") + address);*/ instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . UnifyVal , addrMode , address , nextArg ) ; } } instructions . add ( instruction ) ; } } else if ( j < numOutermostArgs ) { Term nextVar = ( Variable ) nextTerm ; int allocation = ( Integer ) symbolTable . get ( nextVar . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION ) ; byte addrMode = ( byte ) ( ( allocation & 0xff00 ) >> 8 ) ; byte address = ( byte ) ( allocation & 0xff ) ; WAMInstruction instruction ; // If it is register not seen before: get_var. // If it is register seen before: get_val. if ( ! seenRegisters . contains ( allocation ) ) { /*log.fine("GET_VAR " + ((addrMode == REG_ADDR) ? "X" : "Y") + address + ", A" + j);*/ seenRegisters . add ( allocation ) ; instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . GetVar , addrMode , address , ( byte ) ( j & 0xff ) ) ; // Record the way in which this variable was introduced into the clause. symbolTable . put ( nextVar . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VARIABLE_INTRO , VarIntroduction . Get ) ; } else { /*log.fine("GET_VAL " + ((addrMode == REG_ADDR) ? "X" : "Y") + address + ", A" + j);*/ instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . GetVal , addrMode , address , ( byte ) ( j & 0xff ) ) ; } instructions . add ( instruction ) ; } } return instructions ; }


Input: Allocates stack slots where needed to the variables in a program clause . The algorithm here is fairly complex . [CODESPLIT] private void allocatePermanentProgramRegisters ( Clause clause ) { // A bag to hold variable occurrence counts in. Map < Variable , Integer > variableCountBag = new HashMap < Variable , Integer > ( ) ; // A mapping from variables to the body number in which they appear last. Map < Variable , Integer > lastBodyMap = new HashMap < Variable , Integer > ( ) ; // Holds the variable that are in the head and first clause body argument. Collection < Variable > firstGroupVariables = new HashSet < Variable > ( ) ; // Get the occurrence counts of variables in all clauses after the initial head and first body grouping. // In the same pass, pick out which body variables last occur in. if ( ( clause . getBody ( ) != null ) ) { for ( int i = clause . getBody ( ) . length - 1 ; i >= 1 ; i -- ) { Set < Variable > groupVariables = TermUtils . findFreeVariables ( clause . getBody ( ) [ i ] ) ; // Add all their counts to the bag and update their last occurrence positions. for ( Variable variable : groupVariables ) { Integer count = variableCountBag . get ( variable ) ; variableCountBag . put ( variable , ( count == null ) ? 1 : ( count + 1 ) ) ; if ( ! lastBodyMap . containsKey ( variable ) ) { lastBodyMap . put ( variable , i ) ; } // If the cut level variable is seen, automatically add it to the first group variables, // so that it will be counted as a permanent variable, and assigned a stack slot. This // will only occur for deep cuts, that is where the cut comes after the first group. if ( variable instanceof Cut . CutLevelVariable ) { firstGroupVariables . add ( variable ) ; } } } } // Get the set of variables in the head and first clause body argument. if ( clause . getHead ( ) != null ) { Set < Variable > headVariables = TermUtils . findFreeVariables ( clause . getHead ( ) ) ; firstGroupVariables . addAll ( headVariables ) ; } if ( ( clause . getBody ( ) != null ) && ( clause . getBody ( ) . length > 0 ) ) { Set < Variable > firstArgVariables = TermUtils . findFreeVariables ( clause . getBody ( ) [ 0 ] ) ; firstGroupVariables . addAll ( firstArgVariables ) ; } // Add their counts to the bag, and set their last positions of occurrence as required. for ( Variable variable : firstGroupVariables ) { Integer count = variableCountBag . get ( variable ) ; variableCountBag . put ( variable , ( count == null ) ? 1 : ( count + 1 ) ) ; if ( ! lastBodyMap . containsKey ( variable ) ) { lastBodyMap . put ( variable , 0 ) ; } } // Sort the variables by reverse position of last occurrence. List < Map . Entry < Variable , Integer > > lastBodyList = new ArrayList < Map . Entry < Variable , Integer > > ( lastBodyMap . entrySet ( ) ) ; Collections . sort ( lastBodyList , new Comparator < Map . Entry < Variable , Integer > > ( ) { public int compare ( Map . Entry < Variable , Integer > o1 , Map . Entry < Variable , Integer > o2 ) { return o2 . getValue ( ) . compareTo ( o1 . getValue ( ) ) ; } } ) ; // Holds counts of permanent variable last appearances against the body in which they last occur. int [ ] permVarsRemainingCount = new int [ ( clause . getBody ( ) != null ) ? clause . getBody ( ) . length : 0 ] ; // Search the count bag for all variable occurrences greater than one, and assign them to stack slots. // The variables are examined by reverse position of last occurrence, to ensure that later variables // are assigned to lower permanent allocation slots for environment trimming purposes. for ( Map . Entry < Variable , Integer > entry : lastBodyList ) { Variable variable = entry . getKey ( ) ; Integer count = variableCountBag . get ( variable ) ; int body = entry . getValue ( ) ; if ( ( count != null ) && ( count > 1 ) ) { /*log.fine("Variable " + variable + " is permanent, count = " + count);*/ int allocation = ( numPermanentVars ++ & ( 0xff ) ) | ( WAMInstruction . STACK_ADDR << 8 ) ; symbolTable . put ( variable . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION , allocation ) ; // Check if the variable is the cut level variable, and cache its stack slot in 'cutLevelVarSlot', so that // the clause compiler knows which variable to use for the get_level instruction. if ( variable instanceof Cut . CutLevelVariable ) { //cutLevelVarSlot = allocation; cutLevelVarSlot = numPermanentVars - 1 ; /*log.fine("cutLevelVarSlot = " + cutLevelVarSlot);*/ } permVarsRemainingCount [ body ] ++ ; } } // Roll up the permanent variable remaining counts from the counts of last position of occurrence and // store the count of permanent variables remaining against the body. int permVarsRemaining = 0 ; for ( int i = permVarsRemainingCount . length - 1 ; i >= 0 ; i -- ) { symbolTable . put ( clause . getBody ( ) [ i ] . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_PERM_VARS_REMAINING , permVarsRemaining ) ; permVarsRemaining += permVarsRemainingCount [ i ] ; } }


Input: Allocates stack slots to all free variables in a query clause . [CODESPLIT] 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 ) ; }


Input: Gather information about variable counts and positions of occurrence of constants and variable within a clause . [CODESPLIT] 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 ) ; }


Input: Pretty prints a compiled predicate . [CODESPLIT] 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());*/ }


Input: Pretty prints a compiled query . [CODESPLIT] 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());*/ }


Input: 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 . [CODESPLIT] 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 ; }


Input: Returns the contents of a buffer as a string converting ASCII characters in the buffer into unicode string characters . [CODESPLIT] 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 ) ; }