Input: Takes an object and serializes it to a byte array . Don t enforce that it extends serializable to allow for lists and maps to be passed in . [CODESPLIT] public static < T > byte [ ] serialize ( T object ) { try { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream ( ) ; ObjectOutputStream objectOutputStream = new ObjectOutputStream ( byteArrayOutputStream ) ; objectOutputStream . writeObject ( object ) ; return byteArrayOutputStream . toByteArray ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }


Input: De - serialize a byte array back to it s original object . [CODESPLIT] public static < K > K deserialize ( byte [ ] bytes ) { try { ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream ( bytes ) ; ObjectInputStream objectInputStream = new ObjectInputStream ( byteArrayInputStream ) ; @ SuppressWarnings ( "unchecked" ) final K k = ( K ) objectInputStream . readObject ( ) ; return k ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( e ) ; } }


Input: Takes a class type and constructs it . If the class does not have an empty constructor this will find the parametrized constructor and use nulls and default values to construct the class . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public static < T > T createInstance ( Class < T > clazz ) { if ( clazz . isInterface ( ) ) { if ( clazz == List . class ) { return ( T ) new ArrayList ( ) ; } else if ( clazz == Map . class ) { return ( T ) new HashMap ( ) ; } throw new UnsupportedOperationException ( "Interface types can not be instantiated." ) ; } ObjectInstantiator instantiator = OBJENESIS . getInstantiatorOf ( clazz ) ; return ( T ) instantiator . newInstance ( ) ; }


Input: Check if the element has the [CODESPLIT] private void checkForTableId ( TableObject tableObject , Element element ) { // Check if user wants to use an id other than _id Id idAnnotation = element . getAnnotation ( Id . class ) ; if ( idAnnotation != null ) { if ( element . asType ( ) . getKind ( ) != TypeKind . LONG && ! ( "java.lang.Long" . equals ( element . asType ( ) . toString ( ) ) ) ) { logger . e ( "@Id must be on a long" ) ; } // Id attribute set and continue String columnName = Strings . isBlank ( idAnnotation . name ( ) ) // ? element . getSimpleName ( ) . toString ( ) // : idAnnotation . name ( ) ; final TableColumn idColumn = new TableColumn ( columnName , element . getSimpleName ( ) . toString ( ) , element . asType ( ) . toString ( ) , SqliteType . INTEGER ) ; tableObject . setIdColumn ( idColumn ) ; } }


Input: Check if the element has a [CODESPLIT] private void checkForFields ( TableObject tableObject , Element columnElement ) { Column columnAnnotation = columnElement . getAnnotation ( Column . class ) ; if ( columnAnnotation == null ) return ; // Convert the element from a field to a type final Element typeElement = typeUtils . asElement ( columnElement . asType ( ) ) ; final String type = typeElement == null ? columnElement . asType ( ) . toString ( ) : elementUtils . getBinaryName ( ( TypeElement ) typeElement ) . toString ( ) ; TableColumn tableColumn = new TableColumn ( columnElement , type , columnAnnotation . name ( ) ) ; if ( tableColumn . isBlob ( ) && ! tableColumn . isByteArray ( ) ) { String columnType = columnElement . asType ( ) . toString ( ) ; logger . d ( "Column Element Type: " + columnType ) ; if ( ! checkForSuperType ( columnElement , Serializable . class ) && ! columnType . equals ( "java.lang.Byte[]" ) && ! columnType . startsWith ( "java.util.Map" ) && ! columnType . startsWith ( "java.util.List" ) ) { logger . e ( String . format ( "%s in %s is not Serializable and will not be able to be converted to a byte array" , columnElement . toString ( ) , tableObject . getTableName ( ) ) ) ; } } else if ( tableColumn . isOneToMany ( ) ) { // List<T> should only have one generic type. Get that type and make sure // it has @Table annotation TypeMirror typeMirror = ( ( DeclaredType ) columnElement . asType ( ) ) . getTypeArguments ( ) . get ( 0 ) ; if ( typeUtils . asElement ( typeMirror ) . getAnnotation ( Table . class ) == null ) { logger . e ( "One to many relationship in class %s where %s is not annotated with @Table" , tableObject . getTableName ( ) , tableColumn . getColumnName ( ) ) ; } oneToManyCache . put ( typeMirror . toString ( ) , tableObject ) ; TypeElement childColumnElement = elementUtils . getTypeElement ( typeMirror . toString ( ) ) ; tableColumn . setType ( getClassName ( childColumnElement , getPackageName ( childColumnElement ) ) ) ; } else if ( tableColumn . getSqlType ( ) == SqliteType . UNKNOWN ) { @ SuppressWarnings ( "ConstantConditions" ) Table annotation = typeElement . getAnnotation ( Table . class ) ; if ( annotation == null ) { logger . e ( String . format ( "%s in %s needs to be marked as a blob or should be " + "annotated with @Table" , columnElement . toString ( ) , tableObject . getTableName ( ) ) ) ; } tableColumn . setOneToOne ( true ) ; } tableObject . addColumn ( tableColumn ) ; }


Input: Checks for a supertype returns true if element has a supertype [CODESPLIT] private boolean checkForSuperType ( Element element , Class type ) { List < ? extends TypeMirror > superTypes = typeUtils . directSupertypes ( element . asType ( ) ) ; for ( TypeMirror superType : superTypes ) { if ( superType . toString ( ) . equals ( type . getName ( ) ) ) { return true ; } } return false ; }


Input: Get table schema [CODESPLIT] private String getSchema ( ) { StringBuilder sb = new StringBuilder ( ) ; Iterator < TableColumn > iterator = columns . iterator ( ) ; while ( iterator . hasNext ( ) ) { TableColumn column = iterator . next ( ) ; if ( column . isOneToMany ( ) ) { if ( ! iterator . hasNext ( ) ) { // remove the extra ", " after one to many int length = sb . length ( ) ; sb . replace ( length - 2 , length , "" ) ; } continue ; } sb . append ( column ) ; if ( iterator . hasNext ( ) ) { sb . append ( ", " ) ; } } // writes out id_missing for logging, the actual idMissing check happens // by the annotation processor. String idCol = idColumn == null ? "id_missing" : idColumn . getColumnName ( ) ; return String . format ( CREATE_TABLE_DEFAULT , getTableName ( ) , idCol , sb . toString ( ) ) ; }


Input: Create the java functions required for the internal class [CODESPLIT] void brewJava ( Writer writer ) throws IOException { logger . d ( "brewJava" ) ; JavaWriter javaWriter = new JavaWriter ( writer ) ; javaWriter . setCompressingTypes ( false ) ; javaWriter . emitSingleLineComment ( "Generated code from Shillelagh. Do not modify!" ) // . emitPackage ( classPackage ) // /* Knows nothing of android types, must use strings. */ // . emitImports ( "android.content.ContentValues" , "android.database.Cursor" , // "android.database.DatabaseUtils" , "android.database.sqlite.SQLiteDatabase" ) // . emitImports ( ShillelaghUtil . class , ByteArrayInputStream . class , ByteArrayOutputStream . class , IOException . class , ObjectInputStream . class , ObjectOutputStream . class , LinkedList . class , Date . class , List . class ) // . beginType ( className , "class" , EnumSet . of ( PUBLIC , FINAL ) ) ; if ( this . isChildTable ) { emitParentInsert ( javaWriter ) ; emitSelectAll ( javaWriter ) ; } emitInsert ( javaWriter ) ; emitOneToOneInsert ( javaWriter ) ; emitGetId ( javaWriter ) ; emitCreateTable ( javaWriter ) ; emitDropTable ( javaWriter ) ; emitUpdate ( javaWriter ) ; emitUpdateColumnId ( javaWriter ) ; emitDeleteWithId ( javaWriter ) ; emitDeleteWithObject ( javaWriter ) ; emitMapCursorToObject ( javaWriter ) ; emitSingleMap ( javaWriter ) ; emitSelectById ( javaWriter ) ; javaWriter . endType ( ) ; }


Input: Create a way to get an id for foreign keys [CODESPLIT] private void emitGetId ( JavaWriter javaWriter ) throws IOException { logger . d ( "emitGetId" ) ; javaWriter . beginMethod ( "long" , GET_ID_FUNCTION , EnumSet . of ( PUBLIC , STATIC ) , getTargetClass ( ) , "value" ) . emitStatement ( "return value.%s" , idColumn . getMemberName ( ) ) . endMethod ( ) ; }


Input: Creates the function for creating the table [CODESPLIT] private void emitCreateTable ( JavaWriter javaWriter ) throws IOException { logger . d ( "emitCreateTable" ) ; javaWriter . beginMethod ( "void" , $$ CREATE_TABLE_FUNCTION , EnumSet . of ( PUBLIC , STATIC ) , "SQLiteDatabase" , "db" ) . emitStatement ( "db.execSQL(\"%s\")" , getSchema ( ) ) . endMethod ( ) ; }


Input: Creates the function dropping the table [CODESPLIT] private void emitDropTable ( JavaWriter javaWriter ) throws IOException { logger . d ( "emitDropTable" ) ; javaWriter . beginMethod ( "void" , $$ DROP_TABLE_FUNCTION , EnumSet . of ( PUBLIC , STATIC ) , "SQLiteDatabase" , "db" ) . emitStatement ( "db.execSQL(\"DROP TABLE IF EXISTS %s\")" , getTableName ( ) ) . endMethod ( ) ; }


Input: Creates the function for inserting a new value into the database [CODESPLIT] private void emitInsert ( JavaWriter javaWriter ) throws IOException { logger . d ( "emitInsert" ) ; String tableName = getTableName ( ) ; javaWriter . beginMethod ( "void" , $$ INSERT_OBJECT_FUNCTION , EnumSet . of ( PUBLIC , STATIC ) , getTargetClass ( ) , "element" , "SQLiteDatabase" , "db" ) . emitStatement ( "ContentValues values = new ContentValues()" ) ; List < TableColumn > childColumns = Lists . newLinkedList ( ) ; for ( TableColumn column : columns ) { String columnName = column . getColumnName ( ) ; String memberName = column . getMemberName ( ) ; if ( column . isBlob ( ) && ! column . isByteArray ( ) ) { javaWriter . emitStatement ( "values.put(\"%s\", %s(element.%s))" , columnName , SERIALIZE_FUNCTION , memberName ) ; } else if ( column . isOneToOne ( ) ) { javaWriter . emitStatement ( "%s%s.%s(element.%s, db)" , column . getType ( ) , $$ SUFFIX , INSERT_ONE_TO_ONE , column . getColumnName ( ) ) . emitStatement ( "values.put(\"%s\", %s%s.%s(element.%s))" , columnName , column . getType ( ) , $$ SUFFIX , GET_ID_FUNCTION , memberName ) ; } else if ( column . isDate ( ) ) { javaWriter . emitStatement ( "values.put(\"%s\", element.%s.getTime())" , columnName , memberName ) ; } else if ( column . isOneToMany ( ) ) { childColumns . add ( column ) ; } else if ( ! column . isOneToManyChild ( ) ) { javaWriter . emitStatement ( "values.put(\"%s\", element.%s)" , columnName , memberName ) ; } } javaWriter . emitStatement ( "db.insert(\"%s\", null, values)" , tableName ) ; if ( ! childColumns . isEmpty ( ) ) { javaWriter . emitStatement ( "long id = DatabaseUtils.longForQuery(db, " + "\"SELECT ROWID FROM %s ORDER BY ROWID DESC LIMIT 1\", null)" , tableName ) ; } for ( TableColumn childColumn : childColumns ) { javaWriter . emitStatement ( "%s%s.%s(id, element.%s, db)" , childColumn . getType ( ) , $$ SUFFIX , PARENT_INSERT_FUNCTION , childColumn . getMemberName ( ) ) ; } javaWriter . endMethod ( ) ; }


Input: Creates the function for updating an object [CODESPLIT] private void emitUpdate ( JavaWriter javaWriter ) throws IOException { logger . d ( "emitUpdate" ) ; javaWriter . beginMethod ( "void" , $$ UPDATE_OBJECT_FUNCTION , EnumSet . of ( PUBLIC , STATIC ) , getTargetClass ( ) , "element" , "SQLiteDatabase" , "db" ) . emitStatement ( "ContentValues values = new ContentValues()" ) ; for ( TableColumn column : columns ) { String columnName = column . getColumnName ( ) ; String memberName = column . getMemberName ( ) ; if ( column . getSqlType ( ) == SqliteType . BLOB && ! column . isByteArray ( ) ) { javaWriter . emitStatement ( "values.put(\"%s\", %s(element.%s))" , columnName , SERIALIZE_FUNCTION , memberName ) ; } else if ( column . isOneToOne ( ) ) { javaWriter . emitStatement ( "values.put(\"%s\", %s%s.%s(element.%s))" , columnName , column . getType ( ) , $$ SUFFIX , GET_ID_FUNCTION , memberName ) ; } else if ( column . isDate ( ) ) { javaWriter . emitStatement ( "values.put(\"%s\", element.%s.getTime())" , columnName , memberName ) ; } else if ( column . isOneToMany ( ) ) { javaWriter . beginControlFlow ( "for (%s child : element.%s)" , column . getType ( ) . replace ( "$" , "." ) , column . getColumnName ( ) ) . emitStatement ( "%s%s.%s(child, db)" , column . getType ( ) , $$ SUFFIX , $$ UPDATE_OBJECT_FUNCTION ) . endControlFlow ( ) ; } else if ( column . isOneToManyChild ( ) ) { // TODO: actually no way of actually updating this value directly add a wrapper? } else { javaWriter . emitStatement ( "values.put(\"%s\", element.%s)" , columnName , memberName ) ; } } javaWriter . emitStatement ( "db.update(\"%s\", values, \"%s = \" + element.%s, null)" , getTableName ( ) , idColumn . getColumnName ( ) , idColumn . getMemberName ( ) ) ; javaWriter . endMethod ( ) ; }


Input: Updates the id of the object to the last insert [CODESPLIT] private void emitUpdateColumnId ( JavaWriter javaWriter ) throws IOException { logger . d ( "emitUpdateColumnId" ) ; // Updates the column id for the last inserted row javaWriter . beginMethod ( "void" , $$ UPDATE_ID_FUNCTION , EnumSet . of ( PUBLIC , STATIC ) , getTargetClass ( ) , "element" , "SQLiteDatabase" , "db" ) . emitStatement ( "long id = DatabaseUtils.longForQuery(db, \"%s\", null)" , String . format ( GET_ID_OF_LAST_INSERTED_ROW_SQL , getTableName ( ) ) ) . emitStatement ( "element.%s = id" , idColumn . getMemberName ( ) ) . endMethod ( ) ; }


Input: Creates the function for deleting an object by id [CODESPLIT] private void emitDeleteWithId ( JavaWriter javaWriter ) throws IOException { logger . d ( "emitDeleteWithId" ) ; javaWriter . beginMethod ( "void" , $$ DELETE_OBJECT_FUNCTION , EnumSet . of ( PUBLIC , STATIC ) , "Long" , "id" , "SQLiteDatabase" , "db" ) . emitStatement ( "db.delete(\"%s\", \"%s = \" + id, null)" , getTableName ( ) , idColumn . getColumnName ( ) ) . endMethod ( ) ; }


Input: Creates the function for deleting an object from the table [CODESPLIT] private void emitDeleteWithObject ( JavaWriter javaWriter ) throws IOException { logger . d ( "emitDeleteWithObject" ) ; javaWriter . beginMethod ( "void" , $$ DELETE_OBJECT_FUNCTION , EnumSet . of ( PUBLIC , STATIC ) , getTargetClass ( ) , "element" , "SQLiteDatabase" , "db" ) . emitStatement ( "%s(element.%s, db)" , $$ DELETE_OBJECT_FUNCTION , idColumn . getMemberName ( ) ) . endMethod ( ) ; }


Input: Creates the function for mapping a cursor to the object after executing a sql statement [CODESPLIT] private void emitMapCursorToObject ( JavaWriter javaWriter ) throws IOException { logger . d ( "emitMapCursorToObject" ) ; final String targetClass = getTargetClass ( ) ; javaWriter . beginMethod ( "List<" + targetClass + ">" , $$ MAP_OBJECT_FUNCTION , EnumSet . of ( PUBLIC , STATIC ) , "Cursor" , "cursor" , "SQLiteDatabase" , "db" ) . emitStatement ( "List<%s> tableObjects = new LinkedList<%s>()" , targetClass , targetClass ) . beginControlFlow ( "if (cursor.moveToFirst())" ) . beginControlFlow ( "while (!cursor.isAfterLast())" ) . emitStatement ( "%s tableObject = %s(cursor, db)" , targetClass , $$ MAP_SINGLE_FUNCTION ) . emitStatement ( "tableObjects.add(tableObject)" ) . emitStatement ( "cursor.moveToNext()" ) . endControlFlow ( ) . endControlFlow ( ) . emitStatement ( "return tableObjects" ) . endMethod ( ) ; }


Input: Creates function for getting an object by value [CODESPLIT] private void emitSelectById ( JavaWriter javaWriter ) throws IOException { logger . d ( "emitSelectById" ) ; javaWriter . beginMethod ( getTargetClass ( ) , $$ GET_OBJECT_BY_ID , EnumSet . of ( PUBLIC , STATIC ) , "long" , "id" , "SQLiteDatabase" , "db" ) . emitStatement ( "Cursor cursor = db.rawQuery(\"SELECT * FROM %s WHERE %s  = id\", null)" , getTableName ( ) , idColumn . getColumnName ( ) ) . emitStatement ( "%s value = %s(cursor, db).get(0)" , getTargetClass ( ) , $$ MAP_OBJECT_FUNCTION ) . emitStatement ( "cursor.close()" ) . emitStatement ( "return value" ) . endMethod ( ) ; }


Input: Executes a query and returns the results wrapped in an observable [CODESPLIT] public final Observable < T > toObservable ( ) { if ( ! HAS_RX_JAVA ) { throw new RuntimeException ( "RxJava not available! Add RxJava to your build to use this feature" ) ; } return shillelagh . getObservable ( tableObject , new CursorLoader ( ) { @ Override public Cursor getCursor ( ) { return shillelagh . rawQuery ( query . toString ( ) ) ; } } ) ; }


Input: Check to ensure that the column name provided is valid [CODESPLIT] final void checkColumnName ( String columnName ) { try { tableObject . getDeclaredField ( columnName ) ; } catch ( NoSuchFieldException e ) { throw new RuntimeException ( String . format ( "%s isEqualTo not a field found in %s" , columnName , tableObject ) ) ; } }


Input: Checks if a string there if not returns the default string [CODESPLIT] static String valueOrDefault ( String string , String defaultString ) { return isBlank ( string ) ? defaultString : string ; }


Input: Capitalizes the first letter of the string passed in [CODESPLIT] static String capitalize ( String string ) { if ( isBlank ( string ) ) { return "" ; } char first = string . charAt ( 0 ) ; if ( Character . isUpperCase ( first ) ) { return string ; } else { return Character . toUpperCase ( first ) + string . substring ( 1 ) ; } }


Input: Checks if a TypeMirror is mapped to Sqlite Type [CODESPLIT] boolean isTypeOf ( TypeMirror typeMirror ) { if ( realKinds . contains ( typeMirror . getKind ( ) ) ) { return true ; } if ( realObjects . contains ( typeMirror . toString ( ) ) ) { return true ; } return false ; }


Input: Order the results in descending order [CODESPLIT] public Builder < T > descending ( ) { this . query . append ( " DESC" ) ; return new Builder < T > ( shillelagh , tableObject , query ) ; }


Input: Read temperature from the sensors . [CODESPLIT] public float readTemperature ( ) throws IOException { byte [ ] encoded = Files . readAllBytes ( new File ( deviceFile , "w1_slave" ) . toPath ( ) ) ; String tmp = new String ( encoded ) ; int tmpIndex = tmp . indexOf ( "t=" ) ; if ( tmpIndex < 0 ) { throw new IOException ( "Could not read temperature!" ) ; } return Integer . parseInt ( tmp . substring ( tmpIndex + 2 ) . trim ( ) ) / 1000f ; }


Input: Maps a type to the corresponding Cursor get function . For mapping objects between the database and java . If a type is not found getBlob is returned [CODESPLIT] public static String get ( String type ) { final String returnValue = SUPPORTED_CURSOR_METHODS . get ( type ) ; return returnValue != null ? returnValue : SUPPORTED_CURSOR_METHODS . get ( BLOB ) ; }


Input: Print out debug logs will only print if { [CODESPLIT] void d ( String message , Object ... args ) { if ( DEBUG ) { messenger . printMessage ( NOTE , formatString ( message , args ) ) ; } }


Input: Print out notes [CODESPLIT] void n ( String message , Object ... args ) { messenger . printMessage ( NOTE , formatString ( message , args ) ) ; }


Input: Print out errors this will stop the build from succeeding [CODESPLIT] void e ( String message , Object ... args ) { messenger . printMessage ( ERROR , formatString ( message , args ) ) ; }


Input: Returns all icon fonts from bundle . [CODESPLIT] public static List < IconFont > getIconFonts ( ) { List < IconFont > list = new ArrayList <> ( ) ; list . add ( GoogleMaterialDesignIcons . getIconFont ( ) ) ; list . add ( Elusive . getIconFont ( ) ) ; list . add ( Entypo . getIconFont ( ) ) ; list . add ( FontAwesome . getIconFont ( ) ) ; list . add ( Iconic . getIconFont ( ) ) ; list . add ( Typicons . getIconFont ( ) ) ; return list ; }


Input: Returns all icons from bundle . [CODESPLIT] public static List < IconCode > getIcons ( ) { List < IconCode > list = new ArrayList <> ( ) ; for ( IconCode icon : GoogleMaterialDesignIcons . values ( ) ) { list . add ( icon ) ; } for ( IconCode icon : Elusive . values ( ) ) { list . add ( icon ) ; } for ( IconCode icon : Entypo . values ( ) ) { list . add ( icon ) ; } for ( IconCode icon : FontAwesome . values ( ) ) { list . add ( icon ) ; } for ( IconCode icon : Iconic . values ( ) ) { list . add ( icon ) ; } for ( IconCode icon : Typicons . values ( ) ) { list . add ( icon ) ; } return list ; }


Input: Return the next data point in the approximation of the solution . [CODESPLIT] @ Override public DataPoint nextPoint ( final float h ) { m_fY += h * m_aEquation . at ( m_fX , m_fY ) ; m_fX += h ; return new DataPoint ( m_fX , m_fY ) ; }


Input: Add new data point : Augment the divided difference table by appending a new entry at the bottom of each column . [CODESPLIT] public void addDataPoint ( final DataPoint dataPoint ) { if ( m_nDataPoints >= m_aData . length ) return ; m_aData [ m_nDataPoints ] = dataPoint ; m_aDivDiff [ m_nDataPoints ] [ 0 ] = dataPoint . getY ( ) ; ++ m_nDataPoints ; for ( int order = 1 ; order < m_nDataPoints ; ++ order ) { final int bottom = m_nDataPoints - order - 1 ; final float numerator = m_aDivDiff [ bottom + 1 ] [ order - 1 ] - m_aDivDiff [ bottom ] [ order - 1 ] ; final float denominator = m_aData [ bottom + order ] . getX ( ) - m_aData [ bottom ] . getX ( ) ; m_aDivDiff [ bottom ] [ order ] = numerator / denominator ; } }


Input: Return the value of the polynomial interpolation function at x . ( Implementation of Evaluatable . ) [CODESPLIT] public float at ( final float x ) { if ( m_nDataPoints < 2 ) return Float . NaN ; float y = m_aDivDiff [ 0 ] [ 0 ] ; float xFactor = 1 ; // Compute the value of the function. for ( int order = 1 ; order < m_nDataPoints ; ++ order ) { xFactor = xFactor * ( x - m_aData [ order - 1 ] . getX ( ) ) ; y = y + xFactor * m_aDivDiff [ 0 ] [ order ] ; } return y ; }


Input:
Create the Sld Editor layout and attach handlers to the actions . [CODESPLIT] public VLayout createSldEditorLayout ( ) { final VLayout vLayout = new VLayout ( ) ; toolStrip = new ToolStrip ( ) ; toolStrip . setWidth100 ( ) ; codeMirrorPanel = new CodeMirrorPanel ( ) ; WidgetCanvas canvas = new WidgetCanvas ( codeMirrorPanel ) ; canvas . setWidth100 ( ) ; canvas . setHeight100 ( ) ; vLayout . addMember ( toolStrip ) ; vLayout . addMember ( canvas ) ; ToolStripButton saveButton = new ToolStripButton ( ) ; saveButton . setIcon ( "[ISOMORPHIC]/" + "icons/silk/disk.png" ) ; saveButton . setTitle ( msg . saveButtonTitle ( ) ) ; saveButton . setTooltip ( msg . saveButtonTooltip ( ) ) ; saveButton . addClickHandler ( new ClickHandler ( ) { @ Override public void onClick ( ClickEvent clickEvent ) { presenter . onSaveButton ( ) ; } } ) ; ToolStripButton cancelButton = new ToolStripButton ( ) ; cancelButton . setIcon ( "[ISOMORPHIC]/" + "icons/silk/cancel.png" ) ; cancelButton . setTitle ( msg . cancelButtonTitle ( ) ) ; cancelButton . addClickHandler ( new ClickHandler ( ) { @ Override public void onClick ( ClickEvent clickEvent ) { presenter . onCancelButton ( ) ; } } ) ; ToolStripButton validateButton = new ToolStripButton ( ) ; validateButton . setIcon ( "[ISOMORPHIC]/" + "icons/silk/tick.png" ) ; validateButton . setTitle ( msg . validateButtonTitle ( ) ) ; validateButton . setTooltip ( msg . validateButtonTooltip ( ) ) ; validateButton . addClickHandler ( new ClickHandler ( ) { @ Override public void onClick ( ClickEvent clickEvent ) { presenter . onValidateButton ( ) ; } } ) ; ToolStripButton formatBtn = new ToolStripButton ( ) ; formatBtn . setIcon ( "[ISOMORPHIC]/" + "icons/silk/text_align_left.png" ) ; formatBtn . setTitle ( msg . formatButtonTitle ( ) ) ; formatBtn . setTooltip ( msg . formatButtonTooltip ( ) ) ; formatBtn . addClickHandler ( new ClickHandler ( ) { public void onClick ( ClickEvent event ) { presenter . onFormatButton ( ) ; } } ) ; selectTemplate = new SelectItem ( ) ; selectTemplate . setTitle ( msg . templateSelectTitle ( ) ) ; selectTemplate . setTooltip ( msg . templateSelectTooltip ( ) ) ; selectTemplate . setWidth ( 200 ) ; selectTemplate . addChangeHandler ( new ChangeHandler ( ) { @ Override public void onChange ( ChangeEvent changeEvent ) { presenter . onTemplateSelect ( ( String ) changeEvent . getValue ( ) ) ; } } ) ; toolStrip . addFormItem ( selectTemplate ) ; toolStrip . addButton ( saveButton ) ; toolStrip . addButton ( validateButton ) ; toolStrip . addButton ( formatBtn ) ; /*
		 * toolStrip.addSeparator(); toolStrip.addButton(saveButton);
		 */ toolStrip . addFill ( ) ; toolStrip . addButton ( cancelButton ) ; return vLayout ; }


Input:
Create background content decoration for the widget tab . [CODESPLIT] private HTMLFlow getBackgroundDecoration ( ) { // Show some background content in the tab. HTMLFlow htmlFlow = new HTMLFlow ( ) ; htmlFlow . setWidth100 ( ) ; htmlFlow . setHeight100 ( ) ; String contents = "
GEOMAJAS
" + "
SLD-Editor
" + "
EXPERT-mode
" ; htmlFlow . setContents ( contents ) ; return htmlFlow ; }


Input: Compute and return x^power . [CODESPLIT] public static double raise ( final double px , final int pexponent ) { double x = px ; int exponent = pexponent ; if ( exponent < 0 ) return 1 / raise ( x , - exponent ) ; double power = 1 ; // Loop to compute x^exponent. while ( exponent > 0 ) { // Is the rightmost exponent bit a 1? if ( ( exponent & 1 ) == 1 ) power *= x ; // Square x and shift the exponent 1 bit to the right. x *= x ; exponent >>= 1 ; } return power ; }


Input: Copy the values of this matrix . [CODESPLIT] public float [ ] copyValues1D ( ) { final float v [ ] = new float [ m_nRows ] ; for ( int r = 0 ; r < m_nRows ; ++ r ) { v [ r ] = m_aValues [ r ] [ 0 ] ; } return v ; }


Input: Set this column vector from an array of values . [CODESPLIT] protected void set ( final float values [ ] ) { this . m_nRows = values . length ; this . m_nCols = 1 ; this . m_aValues = new float [ m_nRows ] [ 1 ] ; for ( int r = 0 ; r < m_nRows ; ++ r ) { this . m_aValues [ r ] [ 0 ] = values [ r ] ; } }


Input: Compute the Euclidean norm . [CODESPLIT] public float norm ( ) { double t = 0 ; for ( int r = 0 ; r < m_nRows ; ++ r ) { final float v = m_aValues [ r ] [ 0 ] ; t += v * v ; } return ( float ) Math . sqrt ( t ) ; }


Input: Print the vector values . [CODESPLIT] public void print ( ) { for ( int r = 0 ; r < m_nRows ; ++ r ) { System . out . print ( "  " + m_aValues [ r ] [ 0 ] ) ; } System . out . println ( ) ; }


Input: Compute x^exponent to a given scale . Uses the same algorithm as class numbercruncher . mathutils . IntPower . [CODESPLIT] public static BigDecimal intPower ( @ Nonnull final BigDecimal px , final long pexponent , final int scale ) { BigDecimal x = px ; long exponent = pexponent ; // If the exponent is negative, compute 1/(x^-exponent). if ( exponent < 0 ) { return BigDecimal . ONE . divide ( intPower ( x , - exponent , scale ) , scale , RoundingMode . HALF_EVEN ) ; } BigDecimal power = BigDecimal . ONE ; // Loop to compute value^exponent. while ( exponent > 0 ) { // Is the rightmost bit a 1? if ( ( exponent & 1 ) == 1 ) { power = power . multiply ( x ) . setScale ( scale , RoundingMode . HALF_EVEN ) ; } // Square x and shift exponent 1 bit to the right. x = x . multiply ( x ) . setScale ( scale , RoundingMode . HALF_EVEN ) ; exponent >>= 1 ; Thread . yield ( ) ; } return power ; }


Input: Compute the integral root of x to a given scale x &ge ; 0 . Use Newton s algorithm . [CODESPLIT] public static BigDecimal intRoot ( @ Nonnull final BigDecimal px , final long index , final int scale ) { BigDecimal x = px ; // Check that x >= 0. if ( x . signum ( ) < 0 ) { throw new IllegalArgumentException ( "x < 0: " + x ) ; } final int sp1 = scale + 1 ; final BigDecimal n = x ; final BigDecimal i = BigDecimal . valueOf ( index ) ; final BigDecimal im1 = BigDecimal . valueOf ( index - 1 ) ; final BigDecimal tolerance = BigDecimal . valueOf ( 5 ) . movePointLeft ( sp1 ) ; BigDecimal xPrev ; // The initial approximation is x/index. x = x . divide ( i , scale , RoundingMode . HALF_EVEN ) ; // Loop until the approximations converge // (two successive approximations are equal after rounding). do { // x^(index-1) final BigDecimal xToIm1 = intPower ( x , index - 1 , sp1 ) ; // x^index final BigDecimal xToI = x . multiply ( xToIm1 ) . setScale ( sp1 , RoundingMode . HALF_EVEN ) ; // n + (index-1)*(x^index) final BigDecimal numerator = n . add ( im1 . multiply ( xToI ) ) . setScale ( sp1 , RoundingMode . HALF_EVEN ) ; // (index*(x^(index-1)) final BigDecimal denominator = i . multiply ( xToIm1 ) . setScale ( sp1 , RoundingMode . HALF_EVEN ) ; // x = (n + (index-1)*(x^index)) / (index*(x^(index-1))) xPrev = x ; x = numerator . divide ( denominator , sp1 , RoundingMode . DOWN ) ; Thread . yield ( ) ; } while ( x . subtract ( xPrev ) . abs ( ) . compareTo ( tolerance ) > 0 ) ; return x ; }


Input: Compute e^x to a given scale . Break x into its whole and fraction parts and compute ( e^ ( 1 + fraction / whole )) ^whole using Taylor s formula . [CODESPLIT] public static BigDecimal exp ( final BigDecimal x , final int scale ) { // e^0 = 1 if ( x . signum ( ) == 0 ) { return BigDecimal . ONE ; } // If x is negative, return 1/(e^-x). if ( x . signum ( ) == - 1 ) { return BigDecimal . ONE . divide ( exp ( x . negate ( ) , scale ) , scale , RoundingMode . HALF_EVEN ) ; } // Compute the whole part of x. BigDecimal xWhole = x . setScale ( 0 , RoundingMode . DOWN ) ; // If there isn't a whole part, compute and return e^x. if ( xWhole . signum ( ) == 0 ) return _expTaylor ( x , scale ) ; // Compute the fraction part of x. final BigDecimal xFraction = x . subtract ( xWhole ) ; // z = 1 + fraction/whole final BigDecimal z = BigDecimal . ONE . add ( xFraction . divide ( xWhole , scale , RoundingMode . HALF_EVEN ) ) ; // t = e^z final BigDecimal t = _expTaylor ( z , scale ) ; final BigDecimal maxLong = BigDecimal . valueOf ( Long . MAX_VALUE ) ; BigDecimal result = BigDecimal . ONE ; // Compute and return t^whole using intPower(). // If whole > Long.MAX_VALUE, then first compute products // of e^Long.MAX_VALUE. while ( xWhole . compareTo ( maxLong ) >= 0 ) { result = result . multiply ( intPower ( t , Long . MAX_VALUE , scale ) ) . setScale ( scale , RoundingMode . HALF_EVEN ) ; xWhole = xWhole . subtract ( maxLong ) ; Thread . yield ( ) ; } return result . multiply ( intPower ( t , xWhole . longValue ( ) , scale ) ) . setScale ( scale , RoundingMode . HALF_EVEN ) ; }


Input: Compute e^x to a given scale by the Taylor series . [CODESPLIT] private static BigDecimal _expTaylor ( final BigDecimal x , final int scale ) { BigDecimal factorial = BigDecimal . ONE ; BigDecimal xPower = x ; BigDecimal sumPrev ; // 1 + x BigDecimal sum = x . add ( BigDecimal . ONE ) ; // Loop until the sums converge // (two successive sums are equal after rounding). int i = 2 ; do { // x^i xPower = xPower . multiply ( x ) . setScale ( scale , RoundingMode . HALF_EVEN ) ; // i! factorial = factorial . multiply ( BigDecimal . valueOf ( i ) ) ; // x^i/i! final BigDecimal term = xPower . divide ( factorial , scale , RoundingMode . HALF_EVEN ) ; // sum = sum + x^i/i! sumPrev = sum ; sum = sum . add ( term ) ; ++ i ; Thread . yield ( ) ; } while ( sum . compareTo ( sumPrev ) != 0 ) ; return sum ; }


Input: Compute the natural logarithm of x to a given scale x &gt ; 0 . [CODESPLIT] public static BigDecimal ln ( @ Nonnull final BigDecimal x , final int scale ) { // Check that x > 0. if ( x . signum ( ) <= 0 ) { throw new IllegalArgumentException ( "x <= 0: " + x ) ; } // The number of digits to the left of the decimal point. final int magnitude = x . toString ( ) . length ( ) - x . scale ( ) - 1 ; if ( magnitude < 3 ) { return _lnNewton ( x , scale ) ; } // Compute magnitude*ln(x^(1/magnitude)). // x^(1/magnitude) final BigDecimal root = intRoot ( x , magnitude , scale ) ; // ln(x^(1/magnitude)) final BigDecimal lnRoot = _lnNewton ( root , scale ) ; // magnitude*ln(x^(1/magnitude)) return BigDecimal . valueOf ( magnitude ) . multiply ( lnRoot ) . setScale ( scale , RoundingMode . HALF_EVEN ) ; }


Input: Compute the natural logarithm of x to a given scale x > 0 . Use Newton s algorithm . [CODESPLIT] private static BigDecimal _lnNewton ( @ Nonnull final BigDecimal px , final int scale ) { BigDecimal x = px ; final int sp1 = scale + 1 ; final BigDecimal n = x ; BigDecimal term ; // Convergence tolerance = 5*(10^-(scale+1)) final BigDecimal tolerance = BigDecimal . valueOf ( 5 ) . movePointLeft ( sp1 ) ; // Loop until the approximations converge // (two successive approximations are within the tolerance). do { // e^x final BigDecimal eToX = exp ( x , sp1 ) ; // (e^x - n)/e^x term = eToX . subtract ( n ) . divide ( eToX , sp1 , RoundingMode . DOWN ) ; // x - (e^x - n)/e^x x = x . subtract ( term ) ; Thread . yield ( ) ; } while ( term . compareTo ( tolerance ) > 0 ) ; return x . setScale ( scale , RoundingMode . HALF_EVEN ) ; }


Input: Compute the arctangent of x to a given scale |x| &lt ; 1 [CODESPLIT] public static BigDecimal arctan ( @ Nonnull final BigDecimal x , final int scale ) { // Check that |x| < 1. if ( x . abs ( ) . compareTo ( BigDecimal . ONE ) >= 0 ) { throw new IllegalArgumentException ( "|x| >= 1: " + x ) ; } // If x is negative, return -arctan(-x). if ( x . signum ( ) == - 1 ) { return arctan ( x . negate ( ) , scale ) . negate ( ) ; } return _arctanTaylor ( x , scale ) ; }


Input: Compute the arctangent of x to a given scale by the Taylor series |x| < 1 [CODESPLIT] private static BigDecimal _arctanTaylor ( final BigDecimal x , final int scale ) { final int sp1 = scale + 1 ; int i = 3 ; boolean addFlag = false ; BigDecimal power = x ; BigDecimal sum = x ; BigDecimal term ; // Convergence tolerance = 5*(10^-(scale+1)) final BigDecimal tolerance = BigDecimal . valueOf ( 5 ) . movePointLeft ( sp1 ) ; // Loop until the approximations converge // (two successive approximations are within the tolerance). do { // x^i power = power . multiply ( x ) . multiply ( x ) . setScale ( sp1 , RoundingMode . HALF_EVEN ) ; // (x^i)/i term = power . divide ( BigDecimal . valueOf ( i ) , sp1 , RoundingMode . HALF_EVEN ) ; // sum = sum +- (x^i)/i sum = addFlag ? sum . add ( term ) : sum . subtract ( term ) ; i += 2 ; addFlag = ! addFlag ; Thread . yield ( ) ; } while ( term . compareTo ( tolerance ) > 0 ) ; return sum ; }


Input: Compute the square root of x to a given scale x &ge ; 0 . Use Newton s algorithm . [CODESPLIT] public static BigDecimal sqrt ( @ Nonnull final BigDecimal x , final int scale ) { // Check that x >= 0. if ( x . signum ( ) < 0 ) { throw new IllegalArgumentException ( "x < 0: " + x ) ; } // n = x*(10^(2*scale)) final BigInteger n = x . movePointRight ( scale << 1 ) . toBigInteger ( ) ; // The first approximation is the upper half of n. final int bits = ( n . bitLength ( ) + 1 ) >> 1 ; BigInteger ix = n . shiftRight ( bits ) ; BigInteger ixPrev ; // Loop until the approximations converge // (two successive approximations are equal after rounding). do { ixPrev = ix ; // x = (x + n/x)/2 ix = ix . add ( n . divide ( ix ) ) . shiftRight ( 1 ) ; Thread . yield ( ) ; } while ( ix . compareTo ( ixPrev ) != 0 ) ; return new BigDecimal ( ix , scale ) ; }


Input: Print the string containing the digits of pi . [CODESPLIT] protected void printPi ( final String piString ) { System . out . print ( "\npi = " + piString . substring ( 0 , 2 ) ) ; int index = 2 ; int line = 0 ; int group = 0 ; final int length = piString . length ( ) ; // Loop for each group of 5 digits while ( index + 5 < length ) { System . out . print ( piString . substring ( index , index + 5 ) + " " ) ; index += 5 ; // End of line after 10 groups. if ( ++ group == 10 ) { System . out . println ( ) ; // Print a blank line after 10 lines. if ( ++ line == 10 ) { System . out . println ( ) ; line = 0 ; } System . out . print ( "       " ) ; group = 0 ; } } // Print the last partial line. if ( index < length ) { System . out . println ( piString . substring ( index ) ) ; } }


Input: Return a timestamp string that contains the elapsed time period . [CODESPLIT] protected String timestamp ( final long time ) { // Current time followed by elapsed time as (hh:mm:ss). final LocalDateTime aLDT = PDTFactory . getCurrentLocalDateTime ( ) ; final LocalDateTime aOld = PDTFactory . createLocalDateTime ( time ) ; return aLDT . toLocalTime ( ) . toString ( ) + " (" + Duration . between ( aOld , aLDT ) . toString ( ) + ")" ; }


Input: Set the minimum and maximum random values . [CODESPLIT] public void setLimits ( final float rMin , final float rMax ) { this . m_fMin = rMin ; this . m_fMax = rMax ; this . m_fWidth = ( rMax - rMin ) / m_n ; }


Input: Determine a random value s interval and count it . [CODESPLIT] public void put ( final float r ) { // Ignore the value if it's out of range. if ( ( r < m_fMin ) || ( r > m_fMax ) ) return ; // Determine its interval and count it. final int i = ( int ) ( ( r - m_fMin ) / m_fWidth ) ; ++ m_aCounters [ i ] ; }


Input: Print the counter values as a horizontal bar chart . Scale the chart so that the longest bar is MAX_BAR_SIZE . [CODESPLIT] public void print ( ) { // Get the longest bar's length. int maxCount = 0 ; for ( int i = 0 ; i < m_n ; ++ i ) { maxCount = Math . max ( maxCount , m_aCounters [ i ] ) ; } // Compute the scaling factor. final float factor = ( ( float ) MAX_BAR_SIZE ) / maxCount ; // Loop to print each bar. for ( int i = 0 ; i < m_n ; ++ i ) { final int b = m_aCounters [ i ] ; // Interval number. m_aAlignRight . print ( i , 2 ) ; m_aAlignRight . print ( b , 7 ) ; System . out . print ( ": " ) ; // Bar. final int length = Math . round ( factor * b ) ; for ( int j = 0 ; j < length ; ++ j ) System . out . print ( "*" ) ; System . out . println ( ) ; } }


Input: Add another complex number to this one . [CODESPLIT] public Complex add ( final Complex z ) { return new Complex ( m_fReal + z . real ( ) , m_fImaginary + z . imaginary ( ) ) ; }


Input: Subtract another complex number from this one . [CODESPLIT] public Complex subtract ( final Complex z ) { return new Complex ( m_fReal - z . real ( ) , m_fImaginary - z . imaginary ( ) ) ; }


Input: Multiply this complex number by another one . [CODESPLIT] public Complex multiply ( final Complex z ) { return new Complex ( m_fReal * z . real ( ) - m_fImaginary * z . imaginary ( ) , m_fReal * z . imaginary ( ) + m_fImaginary * z . real ( ) ) ; }


Input: Divide this complex number by another one . [CODESPLIT] public Complex divide ( final Complex z ) { final float denom = z . real ( ) * z . real ( ) + z . imaginary ( ) * z . imaginary ( ) ; final float qr = ( m_fReal * z . real ( ) + m_fImaginary * z . imaginary ( ) ) / denom ; final float qi = ( m_fImaginary * z . real ( ) - m_fReal * z . imaginary ( ) ) / denom ; return new Complex ( qr , qi ) ; }


Input: Copy the values of this matrix . [CODESPLIT] @ Nonnull @ ReturnsMutableCopy public float [ ] copyValues1D ( ) { final float v [ ] = new float [ m_nCols ] ; for ( int c = 0 ; c < m_nCols ; ++ c ) v [ ] = m_aValues [ 0 ] [ ] ; return v ; }


Input: Set this row vector from a matrix . Only the first row is used . [CODESPLIT] private void _set ( final Matrix m ) { m_nRows = 1 ; m_nCols = m . m_nCols ; m_aValues = m . m_aValues ; }


Input: Compute the Euclidean norm . [CODESPLIT] public float norm ( ) { double t = 0 ; for ( int c = 0 ; c < m_nCols ; ++ c ) { final float v = m_aValues [ 0 ] [ c ] ; t += v * v ; } return ( float ) Math . sqrt ( t ) ; }


Input: Print the vector values . [CODESPLIT] public void print ( ) { for ( int c = 0 ; c < m_nCols ; ++ c ) { System . out . print ( "  " + m_aValues [ 0 ] [ c ] ) ; } System . out . println ( ) ; }


Input: Get the value of element [ r c ] in the matrix . [CODESPLIT] public float at ( final int r , final int c ) throws MatrixException { if ( ( r < 0 ) || ( r >= m_nRows ) || ( c < 0 ) || ( c >= m_nCols ) ) { throw new MatrixException ( MatrixException . INVALID_INDEX ) ; } return m_aValues [ r ] [ c ] ; }


Input: Get a row of this matrix . [CODESPLIT] public RowVector getRow ( final int r ) throws MatrixException { if ( ( r < 0 ) || ( r >= m_nRows ) ) { throw new MatrixException ( MatrixException . INVALID_INDEX ) ; } final RowVector rv = new RowVector ( m_nCols ) ; for ( int c = 0 ; c < m_nCols ; ++ c ) { rv . m_aValues [ 0 ] [ c ] = m_aValues [ r ] [ c ] ; } return rv ; }


Input: Get a column of this matrix . [CODESPLIT] public ColumnVector getColumn ( final int c ) throws MatrixException { if ( ( c < 0 ) || ( c >= m_nCols ) ) { throw new MatrixException ( MatrixException . INVALID_INDEX ) ; } final ColumnVector cv = new ColumnVector ( m_nRows ) ; for ( int r = 0 ; r < m_nRows ; ++ r ) { cv . m_aValues [ r ] [ 0 ] = m_aValues [ r ] [ c ] ; } return cv ; }


Input: Copy the values of this matrix . [CODESPLIT] public float [ ] [ ] copyValues2D ( ) { final float v [ ] [ ] = new float [ m_nRows ] [ m_nCols ] ; for ( int r = 0 ; r < m_nRows ; ++ r ) { for ( int c = 0 ; c < m_nCols ; ++ c ) { v [ r ] [ c ] = m_aValues [ r ] [ c ] ; } } return v ; }


Input: Set the value of element [ r c ] . [CODESPLIT] public void set ( final int r , final int c , final float value ) throws MatrixException { if ( ( r < 0 ) || ( r >= m_nRows ) || ( c < 0 ) || ( c >= m_nCols ) ) { throw new MatrixException ( MatrixException . INVALID_INDEX ) ; } m_aValues [ r ] [ c ] = value ; }


Input: Set this matrix from a 2 - d array of values . If the rows do not have the same length then the matrix column count is the length of the shortest row . [CODESPLIT] protected void set ( final float values [ ] [ ] ) { m_nRows = values . length ; m_nCols = values [ 0 ] . length ; m_aValues = values ; for ( int r = 1 ; r < m_nRows ; ++ r ) { m_nCols = Math . min ( m_nCols , values [ r ] . length ) ; } }


Input: Set a row of this matrix from a row vector . [CODESPLIT] public void setRow ( final RowVector rv , final int r ) throws MatrixException { if ( ( r < 0 ) || ( r >= m_nRows ) ) { throw new MatrixException ( MatrixException . INVALID_INDEX ) ; } if ( m_nCols != rv . m_nCols ) { throw new MatrixException ( MatrixException . INVALID_DIMENSIONS ) ; } for ( int c = 0 ; c < m_nCols ; ++ c ) { m_aValues [ r ] [ c ] = rv . m_aValues [ 0 ] [ c ] ; } }


Input: Set a column of this matrix from a column vector . [CODESPLIT] public void setColumn ( final ColumnVector cv , final int c ) throws MatrixException { if ( ( c < 0 ) || ( c >= m_nCols ) ) { throw new MatrixException ( MatrixException . INVALID_INDEX ) ; } if ( m_nRows != cv . m_nRows ) { throw new MatrixException ( MatrixException . INVALID_DIMENSIONS ) ; } for ( int r = 0 ; r < m_nRows ; ++ r ) { m_aValues [ r ] [ c ] = cv . m_aValues [ r ] [ 0 ] ; } }


Input: Return the transpose of this matrix . [CODESPLIT] public Matrix transpose ( ) { final float tv [ ] [ ] = new float [ m_nCols ] [ m_nRows ] ; // transposed values // Set the values of the transpose. for ( int r = 0 ; r < m_nRows ; ++ r ) { for ( int c = 0 ; c < m_nCols ; ++ c ) { tv [ c ] [ r ] = m_aValues [ r ] [ c ] ; } } return new Matrix ( tv ) ; }


Input: Add another matrix to this matrix . [CODESPLIT] public Matrix add ( final Matrix m ) throws MatrixException { // Validate m's size. if ( ( m_nRows != m . m_nRows ) && ( m_nCols != m . m_nCols ) ) { throw new MatrixException ( MatrixException . INVALID_DIMENSIONS ) ; } final float sv [ ] [ ] = new float [ m_nRows ] [ m_nCols ] ; // sum values // Compute values of the sum. for ( int r = 0 ; r < m_nRows ; ++ r ) { for ( int c = 0 ; c < m_nCols ; ++ c ) { sv [ r ] [ c ] = m_aValues [ r ] [ c ] + m . m_aValues [ r ] [ c ] ; } } return new Matrix ( sv ) ; }


Input: Subtract another matrix from this matrix . [CODESPLIT] public Matrix subtract ( final Matrix m ) throws MatrixException { // Validate m's size. if ( ( m_nRows != m . m_nRows ) && ( m_nCols != m . m_nCols ) ) { throw new MatrixException ( MatrixException . INVALID_DIMENSIONS ) ; } final float dv [ ] [ ] = new float [ m_nRows ] [ m_nCols ] ; // difference values // Compute values of the difference. for ( int r = 0 ; r < m_nRows ; ++ r ) { for ( int c = 0 ; c < m_nCols ; ++ c ) { dv [ r ] [ c ] = m_aValues [ r ] [ c ] - m . m_aValues [ r ] [ c ] ; } } return new Matrix ( dv ) ; }


Input: Multiply this matrix by a constant . [CODESPLIT] public Matrix multiply ( final float k ) { final float pv [ ] [ ] = new float [ m_nRows ] [ m_nCols ] ; // product values // Compute values of the product. for ( int r = 0 ; r < m_nRows ; ++ r ) { for ( int c = 0 ; c < m_nCols ; ++ c ) { pv [ r ] [ c ] = k * m_aValues [ r ] [ c ] ; } } return new Matrix ( pv ) ; }


Input: Multiply this matrix by another matrix . [CODESPLIT] public Matrix multiply ( final Matrix m ) throws MatrixException { // Validate m's dimensions. if ( m_nCols != m . m_nRows ) { throw new MatrixException ( MatrixException . INVALID_DIMENSIONS ) ; } final float pv [ ] [ ] = new float [ m_nRows ] [ m . m_nCols ] ; // product values // Compute values of the product. for ( int r = 0 ; r < m_nRows ; ++ r ) { for ( int c = 0 ; c < m . m_nCols ; ++ c ) { float dot = 0 ; for ( int k = 0 ; k < m_nCols ; ++ k ) { dot += m_aValues [ r ] [ k ] * m . m_aValues [ k ] [ c ] ; } pv [ r ] [ c ] = dot ; } } return new Matrix ( pv ) ; }


Input: Multiply this matrix by a column vector : this * cv [CODESPLIT] public ColumnVector multiply ( final ColumnVector cv ) throws MatrixException { // Validate cv's size. if ( m_nRows != cv . m_nRows ) { throw new MatrixException ( MatrixException . INVALID_DIMENSIONS ) ; } final float pv [ ] = new float [ m_nRows ] ; // product values // Compute the values of the product. for ( int r = 0 ; r < m_nRows ; ++ r ) { float dot = 0 ; for ( int c = 0 ; c < m_nCols ; ++ c ) { dot += m_aValues [ r ] [ c ] * cv . m_aValues [ c ] [ 0 ] ; } pv [ r ] = dot ; } return new ColumnVector ( pv ) ; }


Input: Multiply a row vector by this matrix : rv * this [CODESPLIT] public RowVector multiply ( final RowVector rv ) throws MatrixException { // Validate rv's size. if ( m_nCols != rv . m_nCols ) { throw new MatrixException ( MatrixException . INVALID_DIMENSIONS ) ; } final float pv [ ] = new float [ m_nRows ] ; // product values // Compute the values of the product. for ( int c = 0 ; c < m_nCols ; ++ c ) { float dot = 0 ; for ( int r = 0 ; r < m_nRows ; ++ r ) { dot += rv . m_aValues [ 0 ] [ r ] * m_aValues [ r ] [ c ] ; } pv [ c ] = dot ; } return new RowVector ( pv ) ; }


Input: Print the matrix values . [CODESPLIT] public void print ( final int width , @ Nonnull final PrintStream aPS ) { final SystemOutAlignRight ar = new SystemOutAlignRight ( aPS ) ; for ( int r = 0 ; r < m_nRows ; ++ r ) { ar . print ( "Row " , 0 ) ; ar . print ( r + 1 , 2 ) ; ar . print ( ":" , 0 ) ; for ( int c = 0 ; c < m_nCols ; ++ c ) { ar . print ( m_aValues [ r ] [ c ] , width ) ; } ar . println ( ) ; } }


Input: Compute the next position of x [ n + 1 ] . [CODESPLIT] @ Override protected void computeNextPosition ( ) { m_fFn = m_fFnp1 ; m_fFpn = m_aFunction . derivativeAt ( m_fXn ) ; // Compute the value of x[n+1]. m_fPrevXnp1 = m_fXnp1 ; m_fXnp1 = m_fXn - m_fFn / m_fFpn ; m_fFnp1 = m_aFunction . at ( m_fXnp1 ) ; }


Input: Check the position of x [ n + 1 ] . [CODESPLIT] @ Override protected void checkPosition ( ) throws AbstractRootFinder . PositionUnchangedException { if ( EqualsHelper . equals ( m_fXnp1 , m_fPrevXnp1 ) ) { throw new AbstractRootFinder . PositionUnchangedException ( ) ; } }


Input: Attach an ImageResource to the button . [CODESPLIT] public void setResource ( ImageResource imageResource ) { Image img = new Image ( imageResource ) ; DOM . insertChild ( getElement ( ) , img . getElement ( ) , 0 ) ; }


Input: Add a new data point : Update the sums . [CODESPLIT] public void addDataPoint ( final DataPoint dataPoint ) { m_dSumX += dataPoint . getX ( ) ; m_dSumY += dataPoint . getY ( ) ; m_dSumXX += dataPoint . getX ( ) * dataPoint . getX ( ) ; m_dSumXY += dataPoint . getX ( ) * dataPoint . getY ( ) ; ++ m_nDataPoints ; m_bCoefsValid = false ; }


Input: Validate the coefficients . [CODESPLIT] private void _validateCoefficients ( ) { if ( m_bCoefsValid ) return ; if ( m_nDataPoints >= 2 ) { final float xBar = ( float ) m_dSumX / m_nDataPoints ; final float yBar = ( float ) m_dSumY / m_nDataPoints ; m_fA1 = ( float ) ( ( m_nDataPoints * m_dSumXY - m_dSumX * m_dSumY ) / ( m_nDataPoints * m_dSumXX - m_dSumX * m_dSumX ) ) ; m_fA0 = yBar - m_fA1 * xBar ; } else { m_fA0 = m_fA1 = Float . NaN ; } m_bCoefsValid = true ; }


Input: Compute the next position of xn . [CODESPLIT] @ Override protected void computeNextPosition ( ) { m_fPrevXn = m_fXn ; m_fXn = m_fGn ; m_fGn = m_aFunction . at ( m_fXn ) ; }


Input: Does not clear templateNames . [CODESPLIT] public void clear ( ) { rawSld = new RawSld ( ) ; dirty = false ; valid = false ; template = null ; sldDescriptor = null ; }


Input: Convert StyledLayerDescriptorInfo to raw xml . [CODESPLIT] public RawSld toXml ( StyledLayerDescriptorInfo sldi ) throws SldException { try { if ( sldi . getVersion ( ) == null ) { sldi . setVersion ( "1.0.0" ) ; } return parseSldI ( sldi ) ; } catch ( JiBXException e ) { throw new SldException ( "Validation error" , e ) ; } }


Input: Convert raw xml to StyledLayerDescriptorInfo . [CODESPLIT] public StyledLayerDescriptorInfo toSldI ( RawSld sld ) throws SldException { try { return parseXml ( sld . getName ( ) , sld . getXml ( ) ) ; } catch ( JiBXException e ) { throw new SldException ( "Validation error" , e ) ; } }


Input: Test by marshalling . [CODESPLIT] public void validate ( StyledLayerDescriptorInfo sld ) throws SldException { try { parseSldI ( sld ) ; } catch ( JiBXException e ) { throw new SldException ( "Validation error" , e ) ; } }


Input: Test by unmarshalling . [CODESPLIT] public boolean validate ( RawSld sld ) throws SldException { try { parseXml ( "" , sld . getXml ( ) ) ; return true ; } catch ( JiBXException e ) { return false ; } }


Input: --------------------------------------------------------------- [CODESPLIT] private StyledLayerDescriptorInfo parseXml ( String name , String raw ) throws JiBXException { IBindingFactory bfact = BindingDirectory . getFactory ( StyledLayerDescriptorInfo . class ) ; IUnmarshallingContext uctx = bfact . createUnmarshallingContext ( ) ; Object object = uctx . unmarshalDocument ( new StringReader ( raw ) ) ; StyledLayerDescriptorInfo sld = ( StyledLayerDescriptorInfo ) object ; if ( sld . getName ( ) == null ) { sld . setName ( name ) ; } if ( sld . getTitle ( ) == null ) { sld . setTitle ( getTitle ( sld , name ) ) ; } if ( sld . getVersion ( ) == null ) { sld . setVersion ( "1.0.0" ) ; } return sld ; }


Input: Return the next data point in the approximation of the solution . [CODESPLIT] @ Override public DataPoint nextPoint ( final float h ) { final float predictor = m_fY + Math . abs ( h ) * m_aEquation . at ( m_fX ) ; final float avgSlope = ( m_aEquation . at ( m_fX , m_fY ) + m_aEquation . at ( m_fX + h , predictor ) ) / 2 ; m_fY += h * avgSlope ; // corrector m_fX += h ; return new DataPoint ( m_fX , m_fY ) ; }


Input: Integrate the function from a to b using the trapezoidal algorithm and return an approximation to the area . ( Integrator implementation . ) [CODESPLIT] public float integrate ( final float a , final float b , final int intervals ) { if ( b <= a ) return 0 ; final float h = ( b - a ) / intervals ; // interval width float totalArea = 0 ; // Compute the area using the current number of intervals. for ( int i = 0 ; i < intervals ; ++ i ) { final float x1 = a + i * h ; totalArea += _areaOf ( x1 , h ) ; } return totalArea ; }


Input: Compute the area of the ith trapezoidal region . [CODESPLIT] private float _areaOf ( final float x1 , final float h ) { final float x2 = x1 + h ; // right bound of the region final float y1 = m_aIntegrand . at ( x1 ) ; // value at left bound final float y2 = m_aIntegrand . at ( x2 ) ; // value at right bound final float area = h * ( y1 + y2 ) / 2 ; // area of the region return area ; }


Input: Set this square matrix from another matrix . Note that this matrix will reference the values of the argument matrix . If the values are not square only the upper left square is used . [CODESPLIT] private void _set ( final Matrix m ) { this . m_nRows = this . m_nCols = Math . min ( m . m_nRows , m . m_nCols ) ; this . m_aValues = m . m_aValues ; }


Input: Set this square matrix from a 2 - d array of values . If the values are not square only the upper left square is used . [CODESPLIT] @ Override protected void set ( final float values [ ] [ ] ) { super . set ( values ) ; m_nRows = m_nCols = Math . min ( m_nRows , m_nCols ) ; }


Input: Fires a { @link SldCloseEvent } that will save the current SLD and close it . If not successful the current SLD remains open . [CODESPLIT] public static void fireSave ( HasHandlers source ) { SldCloseEvent eventInstance = new SldCloseEvent ( true ) ; source . fireEvent ( eventInstance ) ; }


Input: Fires a { @link SldCloseEvent } that will close the current SLD regardless of changes . [CODESPLIT] public static void fire ( HasHandlers source ) { SldCloseEvent eventInstance = new SldCloseEvent ( false ) ; source . fireEvent ( eventInstance ) ; }


Input: Compute the inverse of this matrix . [CODESPLIT] public InvertibleMatrix inverse ( ) throws MatrixException { final InvertibleMatrix inverse = new InvertibleMatrix ( m_nRows ) ; final IdentityMatrix identity = new IdentityMatrix ( m_nRows ) ; // Compute each column of the inverse matrix // using columns of the identity matrix. for ( int c = 0 ; c < m_nCols ; ++ c ) { final ColumnVector col = solve ( identity . getColumn ( c ) , true ) ; inverse . setColumn ( col , c ) ; } return inverse ; }


Input: Compute the determinant . [CODESPLIT] public float determinant ( ) throws MatrixException { decompose ( ) ; // Each row exchange during forward elimination flips the sign // of the determinant, so check for an odd number of exchanges. float determinant = ( ( m_nExchangeCount & 1 ) == 0 ) ? 1 : - 1 ; // Form the product of the diagonal elements of matrix U. for ( int i = 0 ; i < m_nRows ; ++ i ) { final int pi = m_aPermutation [ i ] ; // permuted index determinant *= m_aLU . at ( pi , i ) ; } return determinant ; }


Input: Compute the Euclidean norm of this matrix . [CODESPLIT] public float norm ( ) { float sum = 0 ; for ( int r = 0 ; r < m_nRows ; ++ r ) { for ( int c = 0 ; c < m_nCols ; ++ c ) { final float v = m_aValues [ r ] [ c ] ; sum += v * v ; } } return ( float ) Math . sqrt ( sum ) ; }


Input: Set the value of element [ r c ] in the matrix . [CODESPLIT] @ Override public void set ( final int r , final int c , final float value ) throws MatrixException { super . set ( r , c , value ) ; reset ( ) ; }


Input: Set a row of this matrix from a row vector . [CODESPLIT] @ Override public void setRow ( final RowVector rv , final int r ) throws MatrixException { super . setRow ( rv , r ) ; reset ( ) ; }


Input: Set a column of this matrix from a column vector . [CODESPLIT] @ Override public void setColumn ( final ColumnVector cv , final int c ) throws MatrixException { super . setColumn ( cv , c ) ; reset ( ) ; }


Input: Solve Ax = b for x using the Gaussian elimination algorithm . [CODESPLIT] public ColumnVector solve ( final ColumnVector b , final boolean improve ) throws MatrixException { // Validate b's size. if ( b . m_nRows != m_nRows ) { throw new MatrixException ( MatrixException . INVALID_DIMENSIONS ) ; } decompose ( ) ; // Solve Ly = b for y by forward substitution. // Solve Ux = y for x by back substitution. final ColumnVector y = _forwardSubstitution ( b ) ; final ColumnVector x = _backSubstitution ( y ) ; // Improve and return x. if ( improve ) _improve ( b , x ) ; return x ; }


Input: Print the decomposed matrix LU . [CODESPLIT] public void printDecomposed ( final int width , @ Nonnull final PrintStream aPS ) throws MatrixException { decompose ( ) ; final SystemOutAlignRight ar = new SystemOutAlignRight ( aPS ) ; for ( int r = 0 ; r < m_nRows ; ++ r ) { final int pr = m_aPermutation [ r ] ; // permuted row index ar . print ( "Row " , 0 ) ; ar . print ( r + 1 , 2 ) ; ar . print ( ":" , 0 ) ; for ( int c = 0 ; c < m_nCols ; ++ c ) { ar . print ( m_aLU . m_aValues [ pr ] [ c ] , width ) ; } ar . println ( ) ; } }


Input: Compute the upper triangular matrix U and lower triangular matrix L such that A = L * U . Store L and U together in matrix LU . Compute the permutation vector permutation of the row indices . [CODESPLIT] protected void decompose ( ) throws MatrixException { // Return if the decomposition is valid. if ( m_aLU != null ) return ; // Create a new LU matrix and permutation vector. // LU is initially just a copy of the values of this system. m_aLU = new SquareMatrix ( this . copyValues2D ( ) ) ; m_aPermutation = new int [ m_nRows ] ; final float scales [ ] = new float [ m_nRows ] ; // Loop to initialize the permutation vector and scales. for ( int r = 0 ; r < m_nRows ; ++ r ) { m_aPermutation [ r ] = r ; // initially no row exchanges // Find the largest row element. float largestRowElmt = 0 ; for ( int c = 0 ; c < m_nRows ; ++ c ) { final float elmt = Math . abs ( m_aLU . at ( r , c ) ) ; if ( largestRowElmt < elmt ) largestRowElmt = elmt ; } // Set the scaling factor for row equilibration. if ( largestRowElmt != 0 ) { scales [ r ] = 1 / largestRowElmt ; } else { throw new MatrixException ( MatrixException . ZERO_ROW ) ; } } // Do forward elimination with scaled partial row pivoting. _forwardElimination ( scales ) ; // Check bottom right element of the permuted matrix. if ( m_aLU . at ( m_aPermutation [ m_nRows - 1 ] , m_nRows - 1 ) == 0 ) { throw new MatrixException ( MatrixException . SINGULAR ) ; } }


Input: Do forward elimination with scaled partial row pivoting . [CODESPLIT] private void _forwardElimination ( final float scales [ ] ) throws MatrixException { // Loop once per pivot row 0..nRows-1. for ( int rPivot = 0 ; rPivot < m_nRows - 1 ; ++ rPivot ) { float largestScaledElmt = 0 ; int rLargest = 0 ; // Starting from the pivot row rPivot, look down // column rPivot to find the largest scaled element. for ( int r = rPivot ; r < m_nRows ; ++ r ) { // Use the permuted row index. final int pr = m_aPermutation [ r ] ; final float absElmt = Math . abs ( m_aLU . at ( pr , rPivot ) ) ; final float scaledElmt = absElmt * scales [ pr ] ; if ( largestScaledElmt < scaledElmt ) { // The largest scaled element and // its row index. largestScaledElmt = scaledElmt ; rLargest = r ; } } // Is the matrix singular? if ( largestScaledElmt == 0 ) { throw new MatrixException ( MatrixException . SINGULAR ) ; } // Exchange rows if necessary to choose the best // pivot element by making its row the pivot row. if ( rLargest != rPivot ) { final int temp = m_aPermutation [ rPivot ] ; m_aPermutation [ rPivot ] = m_aPermutation [ rLargest ] ; m_aPermutation [ rLargest ] = temp ; ++ m_nExchangeCount ; } // Use the permuted pivot row index. final int prPivot = m_aPermutation [ rPivot ] ; final float pivotElmt = m_aLU . at ( prPivot , rPivot ) ; // Do the elimination below the pivot row. for ( int r = rPivot + 1 ; r < m_nRows ; ++ r ) { // Use the permuted row index. final int pr = m_aPermutation [ r ] ; final float multiple = m_aLU . at ( pr , rPivot ) / pivotElmt ; // Set the multiple into matrix L. m_aLU . set ( pr , rPivot , multiple ) ; // Eliminate an unknown from matrix U. if ( multiple != 0 ) { for ( int c = rPivot + 1 ; c < m_nCols ; ++ c ) { float elmt = m_aLU . at ( pr , c ) ; // Subtract the multiple of the pivot row. elmt -= multiple * m_aLU . at ( prPivot , c ) ; m_aLU . set ( pr , c , elmt ) ; } } } } }


Input: Solve Ly = b for y by forward substitution . [CODESPLIT] private ColumnVector _forwardSubstitution ( final ColumnVector b ) throws MatrixException { final ColumnVector y = new ColumnVector ( m_nRows ) ; // Do forward substitution. for ( int r = 0 ; r < m_nRows ; ++ r ) { final int pr = m_aPermutation [ r ] ; // permuted row index float dot = 0 ; for ( int c = 0 ; c < r ; ++ c ) { dot += m_aLU . at ( pr , c ) * y . at ( c ) ; } y . set ( r , b . at ( pr ) - dot ) ; } return y ; }


Input: Solve Ux = y for x by back substitution . [CODESPLIT] private ColumnVector _backSubstitution ( final ColumnVector y ) throws MatrixException { final ColumnVector x = new ColumnVector ( m_nRows ) ; // Do back substitution. for ( int r = m_nRows - 1 ; r >= 0 ; -- r ) { final int pr = m_aPermutation [ r ] ; // permuted row index float dot = 0 ; for ( int c = r + 1 ; c < m_nRows ; ++ c ) { dot += m_aLU . at ( pr , c ) * x . at ( c ) ; } x . set ( r , ( y . at ( r ) - dot ) / m_aLU . at ( pr , r ) ) ; } return x ; }


Input: Iteratively improve the solution x to machine accuracy . [CODESPLIT] private void _improve ( final ColumnVector b , final ColumnVector x ) throws MatrixException { // Find the largest x element. float largestX = 0 ; for ( int r = 0 ; r < m_nRows ; ++ r ) { final float absX = Math . abs ( x . m_aValues [ r ] [ 0 ] ) ; if ( largestX < absX ) largestX = absX ; } // Is x already as good as possible? if ( largestX == 0 ) return ; final ColumnVector residuals = new ColumnVector ( m_nRows ) ; // Iterate to improve x. for ( int iter = 0 ; iter < MAX_ITER ; ++ iter ) { // Compute residuals = b - Ax. // Must use double precision! for ( int r = 0 ; r < m_nRows ; ++ r ) { double dot = 0 ; for ( int c = 0 ; c < m_nRows ; ++ c ) { final double elmt = at ( r , c ) ; dot += elmt * x . at ( c ) ; // dbl.prec. * } final double value = b . at ( r ) - dot ; // dbl.prec. - residuals . set ( r , ( float ) value ) ; } // Solve Az = residuals for z. final ColumnVector z = solve ( residuals , false ) ; // Set x = x + z. // Find largest the largest difference. float largestDiff = 0 ; for ( int r = 0 ; r < m_nRows ; ++ r ) { final float oldX = x . at ( r ) ; x . set ( r , oldX + z . at ( r ) ) ; final float diff = Math . abs ( x . at ( r ) - oldX ) ; if ( largestDiff < diff ) largestDiff = diff ; } // Is any further improvement possible? if ( largestDiff < largestX * TOLERANCE ) return ; } // Failed to converge because A is nearly singular. throw new MatrixException ( MatrixException . NO_CONVERGENCE ) ; }


Input: Convert a square matrix into an identity matrix . [CODESPLIT] public static void convert ( final SquareMatrix sm ) { for ( int r = 0 ; r < sm . m_nRows ; ++ r ) { for ( int c = 0 ; c < sm . m_nCols ; ++ c ) { sm . m_aValues [ r ] [ c ] = ( r == c ) ? 1 : 0 ; } } }


Input: Compute the next randomn value using the von Neumann algorithm . Requires sequences of uniformly - distributed random values in [ 0 1 ) . [CODESPLIT] public float nextVonNeumann ( ) { int n ; int k = 0 ; float u1 ; // Loop to try sequences of uniformly-distributed // random values. for ( ; ; ) { n = 1 ; u1 = GENERATOR . nextFloat ( ) ; float u = u1 ; float uPrev = Float . NaN ; // Loop to generate a sequence of ramdom values // as long as they are decreasing. for ( ; ; ) { uPrev = u ; u = GENERATOR . nextFloat ( ) ; // No longer decreasing? if ( u > uPrev ) { // n is even. if ( ( n & 1 ) == 0 ) { return u1 + k ; // return a random value } // n is odd. ++ k ; break ; // try another sequence } ++ n ; } } }


Input: Return the next data point in the approximation of the solution . [CODESPLIT] @ Override public DataPoint nextPoint ( final float h ) { final float k1 = m_aEquation . at ( m_fX , m_fY ) ; final float k2 = m_aEquation . at ( m_fX + h / 2 , m_fY + k1 * h / 2 ) ; final float k3 = m_aEquation . at ( m_fX + h / 2 , m_fY + k2 * h / 2 ) ; final float k4 = m_aEquation . at ( m_fX + h , m_fY + k3 * h ) ; m_fY += ( k1 + 2 * ( k2 + k3 ) + k4 ) * h / 6 ; m_fX += h ; return new DataPoint ( m_fX , m_fY ) ; }


Input: Do the regula falsi iteration procedure . [CODESPLIT] @ Override protected void doIterationProcedure ( final int n ) { if ( n == 1 ) return ; // already initialized if ( m_fFalse < 0 ) { m_fXNeg = m_fXFalse ; // the root is in the xPos side m_fNeg = m_fFalse ; } else { m_fXPos = m_fXFalse ; // the root is in the xNeg side m_fPos = m_fFalse ; } }


Input: Compute the next position of x - false . [CODESPLIT] @ Override protected void computeNextPosition ( ) { m_fPrevXFalse = m_fXFalse ; m_fXFalse = m_fXPos - m_fPos * ( m_fXNeg - m_fXPos ) / ( m_fNeg - m_fPos ) ; m_fFalse = m_aFunction . at ( m_fXFalse ) ; }


Input: Check the position of x - false . [CODESPLIT] @ Override protected void checkPosition ( ) throws AbstractRootFinder . PositionUnchangedException { if ( EqualsHelper . equals ( m_fXFalse , m_fPrevXFalse ) ) { throw new AbstractRootFinder . PositionUnchangedException ( ) ; } }


Input: Compute the next position of xFalse . [CODESPLIT] @ Override protected void computeNextPosition ( ) { m_fPrevXFalse = m_fXFalse ; m_fPrevFFalse = m_fFalse ; m_fXFalse = m_fXPos - m_fPos * ( m_fXNeg - m_fXPos ) / ( m_fNeg - m_fPos ) ; m_fFalse = m_aFunction . at ( m_fXFalse ) ; m_bDecreasePos = m_bDecreaseNeg = false ; // If there was no sign change in f(xFalse), // or if this is the first iteration step, // then decrease the slope of the secant. if ( Float . isNaN ( m_fPrevFFalse ) || ( m_fPrevFFalse * m_fFalse > 0 ) ) { if ( m_fFalse < 0 ) m_bDecreasePos = true ; else m_bDecreaseNeg = true ; } }


Input: Check the interval . [CODESPLIT] public void checkInterval ( final float x1 , final float x2 ) throws InvalidIntervalException { final float y1 = m_aFunction . at ( x1 ) ; final float y2 = m_aFunction . at ( x2 ) ; // The interval is invalid if y1 and y2 have the same signs. if ( y1 * y2 > 0 ) throw new InvalidIntervalException ( ) ; }


Input: Add the value of an addend to the running sum . [CODESPLIT] public void add ( final float addend ) { // Correct the addend value and add it to the running sum. m_fCorrectedAddend = addend + m_fCorrection ; final float tempSum = m_fSum + m_fCorrectedAddend ; // Compute the next correction and set the running sum. // The parentheses are necessary to compute the high-order // bits of the addend. m_fCorrection = m_fCorrectedAddend - ( tempSum - m_fSum ) ; m_fSum = tempSum ; }


Input: Multiply two integer values a and b modulo m . [CODESPLIT] public static int multiply ( final int pa , final int pb , final int m ) { int a = pa ; int b = pb ; int product = 0 ; // Loop to compute product = (a*b)%m. while ( a > 0 ) { // Does the rightmost bit of a == 1? if ( ( a & 1 ) == 1 ) { product += b ; product %= m ; } // Double b modulo m, and // shift a 1 bit to the right. b <<= 1 ; b %= m ; a >>= 1 ; } return product ; }


Input: Raise a to the b power modulo m . [CODESPLIT] public static int raise ( final int pbase , final int pexponent , final int m ) { int base = pbase ; int exponent = pexponent ; int power = 1 ; // Loop to compute power = (base^exponent)%m. while ( exponent > 0 ) { // Does the rightmost bit of the exponent == 1? if ( ( exponent & 1 ) == 1 ) { power = multiply ( power , base , m ) ; } // Square the base modulo m and // shift the exponent 1 bit to the right. base = multiply ( base , base , m ) ; exponent >>= 1 ; } return power ; }


Input: Do the secant iteration procedure . [CODESPLIT] @ Override protected void doIterationProcedure ( final int n ) { if ( n == 1 ) return ; // already initialized // Use the latest two points. m_fXnm1 = m_fXn ; // x[n-1] = x[n] m_fXn = m_fXnp1 ; // x[n] = x[n+1] m_fFnm1 = m_fFn ; // f(x[n-1]) = f(x[n]) m_fFn = m_fFnp1 ; // f(x[n]) = f(x[n+1]) }


Input: Compute the next position of x [ n + 1 ] . [CODESPLIT] @ Override protected void computeNextPosition ( ) { m_fPrevXnp1 = m_fXnp1 ; m_fXnp1 = m_fXn - m_fFn * ( m_fXnm1 - m_fXn ) / ( m_fFnm1 - m_fFn ) ; m_fFnp1 = m_aFunction . at ( m_fXnp1 ) ; }


Input: Create an instance of the SldManager . [CODESPLIT] public SldManager getSldManager ( ) { if ( sldManager == null ) { sldManager = new SldManagerImpl ( getEventBus ( ) , getSldEditorServiceFactory ( ) . createSldGwtServiceAsync ( ) ) ; } return sldManager ; }


Input: Convert a long value into a character array of 0 and 1 that represents the value in base 2 . [CODESPLIT] private static char [ ] _toCharBitArray ( final long pvalue , final int size ) { long value = pvalue ; final char bits [ ] = new char [ size ] ; // Convert each bit from right to left. for ( int i = size - 1 ; i >= 0 ; -- i ) { bits [ i ] = ( value & 1 ) == 0 ? ' ' : ' ' ; value >>>= 1 ; } return bits ; }


Input: Decompose a floating - point value into its parts . [CODESPLIT] private void _decompose ( final char [ ] bits , final int bias , final int reserved , final int signIndex , final int signSize , final int exponentIndex , final int exponentSize , final int fractionIndex , final int fractionSize ) { this . m_nBias = bias ; // Extract the individual parts as strings of '0' and '1'. m_sSignBit = new String ( bits , signIndex , signSize ) ; m_sExponentBits = new String ( bits , exponentIndex , exponentSize ) ; m_sFractionBits = new String ( bits , fractionIndex , fractionSize ) ; try { m_nBiased = Integer . parseInt ( m_sExponentBits , 2 ) ; m_nFraction = Long . parseLong ( m_sFractionBits , 2 ) ; } catch ( final NumberFormatException ex ) { } m_bIsZero = ( m_nBiased == 0 ) && ( m_nFraction == 0 ) ; m_bIsDenormalized = ( m_nBiased == 0 ) && ( m_nFraction != 0 ) ; m_bIsReserved = ( m_nBiased == reserved ) ; m_sImpliedBit = m_bIsDenormalized || m_bIsZero || m_bIsReserved ? "0" : "1" ; }


Input: Print the decomposed parts of the value . [CODESPLIT] public void print ( @ Nonnull final PrintStream aPW ) { aPW . println ( "------------------------------" ) ; // Print the value. if ( isDouble ( ) ) aPW . println ( "double value = " + doubleValue ( ) ) ; else aPW . println ( "float value = " + floatValue ( ) ) ; // Print the sign. aPW . print ( "sign=" + signBit ( ) ) ; // Print the bit representation of the exponent and its // biased and unbiased values. Indicate whether the value // is denormalized, or whether the exponent is reserved. aPW . print ( ", exponent=" + exponentBits ( ) + " (biased=" + biasedExponent ( ) ) ; if ( isZero ( ) ) aPW . println ( ", zero)" ) ; else if ( isExponentReserved ( ) ) aPW . println ( ", reserved)" ) ; else if ( isDenormalized ( ) ) aPW . println ( ", denormalized, use " + unbiasedExponent ( ) + ")" ) ; else aPW . println ( ", normalized, unbiased=" + unbiasedExponent ( ) + ")" ) ; // Print the significand. aPW . println ( "significand=" + significandBits ( ) ) ; }


Input: Validate the value of the float biased exponent value . [CODESPLIT] public static void validateFloatBiasedExponent ( final int biased ) throws IEEE754Exception { if ( ( biased < 0 ) || ( biased > IEEE754Constants . FLOAT_EXPONENT_RESERVED ) ) { throw new IEEE754Exception ( "The biased exponent value should be " + "0 through " + IEEE754Constants . FLOAT_EXPONENT_RESERVED + "." ) ; } }


Input: Validate the value of the float unbiased exponent value . [CODESPLIT] public static void validateFloatUnbiasedExponent ( final int unbiased ) throws IEEE754Exception { if ( ( unbiased < - IEEE754Constants . FLOAT_EXPONENT_BIAS + 1 ) || ( unbiased > IEEE754Constants . FLOAT_EXPONENT_BIAS ) ) { throw new IEEE754Exception ( "The unbiased exponent value should be " + - ( IEEE754Constants . FLOAT_EXPONENT_BIAS - 1 ) + " through " + IEEE754Constants . FLOAT_EXPONENT_BIAS + "." ) ; } }


Input: Validate the value of the double biased exponent value . [CODESPLIT] public static void validateDoubleBiasedExponent ( final int biased ) throws IEEE754Exception { if ( ( biased < 0 ) || ( biased > IEEE754Constants . DOUBLE_EXPONENT_RESERVED ) ) { throw new IEEE754Exception ( "The biased exponent value should be " + "0 through " + IEEE754Constants . DOUBLE_EXPONENT_RESERVED + "." ) ; } }


Input: Validate the value of the double unbiased exponent value . [CODESPLIT] public static void validateDoubleUnbiasedExponent ( final int unbiased ) throws IEEE754Exception { if ( ( unbiased < - IEEE754Constants . DOUBLE_EXPONENT_BIAS + 1 ) || ( unbiased > IEEE754Constants . DOUBLE_EXPONENT_BIAS ) ) { throw new IEEE754Exception ( "The unbiased exponent value should be " + - ( IEEE754Constants . DOUBLE_EXPONENT_BIAS - 1 ) + " through " + IEEE754Constants . DOUBLE_EXPONENT_BIAS + "." ) ; } }


Input: SldEditorServiceFactory constructor . [CODESPLIT] public SldGwtServiceAsync createSldGwtServiceAsync ( ) { this . service = GWT . create ( SldGwtService . class ) ; ServiceDefTarget endpoint = ( ServiceDefTarget ) service ; endpoint . setServiceEntryPoint ( GWT . getHostPageBaseURL ( ) + "d/sldTemplates" ) ; return service ; }


Input: Compute the next random value using the Central Limit Theorem which states that the averages of sets of uniformly - distributed random values are normally distributed . [CODESPLIT] public float nextCentral ( ) { // Average 12 uniformly-distributed random values. float sum = 0.0f ; for ( int j = 0 ; j < 12 ; ++ j ) sum += GENERATOR . nextFloat ( ) ; // Subtract 6 to center about 0. return m_fStddev * ( sum - 6 ) + m_fMean ; }


Input: Compute the next randomn value using the polar algorithm . Requires two uniformly - distributed random values in [ - 1 + 1 ) . Actually computes two random values and saves the second one for the next invokation . [CODESPLIT] public float nextPolar ( ) { // If there's a saved value, return it. if ( m_bHaveNextPolar ) { m_bHaveNextPolar = false ; return m_fNextPolar ; } // point coordinates and their radius float u1 , u2 , r ; do { // u1 and u2 will be uniformly-distributed // random values in [-1, +1). u1 = 2 * GENERATOR . nextFloat ( ) - 1 ; u2 = 2 * GENERATOR . nextFloat ( ) - 1 ; // Want radius r inside the unit circle. r = u1 * u1 + u2 * u2 ; } while ( r >= 1 ) ; // Factor incorporates the standard deviation. final float factor = ( float ) ( m_fStddev * Math . sqrt ( - 2 * Math . log ( r ) / r ) ) ; // v1 and v2 are normally-distributed random values. final float v1 = factor * u1 + m_fMean ; final float v2 = factor * u2 + m_fMean ; // Save v1 for next time. m_fNextPolar = v1 ; m_bHaveNextPolar = true ; return v2 ; }


Input: Compute the next random value using the ratio algorithm . Requires two uniformly - distributed random values in [ 0 1 ) . [CODESPLIT] public float nextRatio ( ) { float u , v , x , xx ; do { // u and v are two uniformly-distributed random values // in [0, 1), and u != 0. while ( ( u = GENERATOR . nextFloat ( ) ) == 0 ) { // try again if 0 } v = GENERATOR . nextFloat ( ) ; // y coord of point (u, y) final float y = C1 * ( v - 0.5f ) ; // ratio of point's coords x = y / u ; xx = x * x ; } while ( ( xx > 5f - C2 * u ) && // quick acceptance ( ( xx >= C3 / u + 1.4f ) || // quick rejection ( xx > ( float ) ( - 4 * Math . log ( u ) ) ) ) // final test ) ; return m_fStddev * x + m_fMean ; }


Input: Compute the Sieve of Eratosthenes . [CODESPLIT] public static boolean [ ] primeSieve ( final int n ) { final int halfN = ( n + 1 ) >> 1 ; final boolean sieve [ ] = new boolean [ n + 1 ] ; // Initialize every integer from 2 onwards to prime. for ( int i = 2 ; i <= n ; ++ i ) sieve [ i ] = true ; int prime = 2 ; // first prime number // Loop to create the sieve. while ( prime < halfN ) { // Mark as composites multiples of the prime. for ( int composite = prime << 1 ; composite <= n ; composite += prime ) sieve [ composite ] = false ; // Skip over composites to the next prime. while ( ( ++ prime < halfN ) && ( ! sieve [ prime ] ) ) { } } return sieve ; }


Input: Compute the prime factors of an integer value . [CODESPLIT] public static int [ ] factorsOf ( final int pn ) { int n = pn ; final boolean isPrime [ ] = primeSieve ( n ) ; // primes <= n final ICommonsList < Integer > v = new CommonsArrayList <> ( ) ; // Loop to try prime divisors. for ( int factor = 2 ; n > 1 ; ++ factor ) { if ( isPrime [ factor ] && ( n % factor == 0 ) ) { // Prime divisor found. v . add ( Integer . valueOf ( factor ) ) ; // Factor out multiples of the divisor. do { n /= factor ; } while ( n % factor == 0 ) ; } } // Create an array of the distinct prime factors. final int factors [ ] = new int [ v . size ( ) ] ; for ( int i = 0 ; i < v . size ( ) ; ++ i ) { factors [ i ] = v . get ( i ) . intValue ( ) ; } return factors ; }


Input: Do the bisection iteration procedure . [CODESPLIT] @ Override protected void doIterationProcedure ( final int n ) { if ( n == 1 ) return ; // already initialized if ( m_fMid < 0 ) { m_fXNeg = m_fXMid ; // the root is in the xPos half m_fNeg = m_fMid ; } else { m_fXPos = m_fXMid ; // the root is in the xNeg half m_fPos = m_fMid ; } }


Input: Compute the next position of xMid . [CODESPLIT] @ Override protected void computeNextPosition ( ) { m_fPrevXMid = m_fXMid ; m_fXMid = ( m_fXNeg + m_fXPos ) / 2 ; m_fMid = m_aFunction . at ( m_fXMid ) ; }


Input: Check the position of xMid . [CODESPLIT] @ Override protected void checkPosition ( ) throws AbstractRootFinder . PositionUnchangedException { if ( EqualsHelper . equals ( m_fXMid , m_fPrevXMid ) ) { throw new AbstractRootFinder . PositionUnchangedException ( ) ; } }


Input: Sets the JavaFX application instance to be provided by the CDI BeanManager . [CODESPLIT] public static void setJavaFxApplication ( final CdiApplication javaFxApplication ) { final CountDownLatch latch = new CountDownLatch ( 1 ) ; Platform . runLater ( ( ) -> { JAVA_FX_APPLICATION . set ( javaFxApplication ) ; latch . countDown ( ) ; } ) ; if ( ! Platform . isFxApplicationThread ( ) ) { try { latch . await ( ) ; } catch ( InterruptedException e ) { throw new IllegalStateException ( e ) ; } } }


Input: Settings from a custom calabash . xml [CODESPLIT] public void setConfiguration ( File configFile ) { if ( configFile == null ) nextConfig = null ; else try { XProcConfiguration config = new XProcConfiguration ( "he" , false ) ; nextConfig = config . getProcessor ( ) . newDocumentBuilder ( ) . build ( new SAXSource ( new InputSource ( new FileReader ( configFile ) ) ) ) ; } catch ( FileNotFoundException e ) { throw new IllegalArgumentException ( "Config file does not exist" , e ) ; } catch ( SaxonApiException e ) { throw new RuntimeException ( e ) ; } }


Input: Settings to be always applied [CODESPLIT] public void setDefaultConfiguration ( Reader defaultConfig ) { XProcConfiguration config = new XProcConfiguration ( "he" , false ) ; try { nextDefaultConfig = config . getProcessor ( ) . newDocumentBuilder ( ) . build ( new SAXSource ( new InputSource ( defaultConfig ) ) ) ; } catch ( SaxonApiException e ) { throw new RuntimeException ( e ) ; } }


Input: Retrieves a { [CODESPLIT] private StringConverter < ? > getStringConverter ( final Class < ? > valueClass ) { Class < ? extends StringConverter < ? > > aClass = StringConverterRetriever . retrieveConverterFor ( valueClass ) ; if ( aClass == null ) { throw new IllegalArgumentException ( String . format ( "Can't find StringConverter for class '%s'." , valueClass . getName ( ) ) ) ; } try { return aClass . newInstance ( ) ; } catch ( final InstantiationException | IllegalAccessException e ) { throw new IllegalStateException ( e ) ; } }


Input: Create a CDI - aware FXMLLoader . If an annotation of type @FXMLLoaderParams can be found use it s parameters to configure the FXMLLoader instance that shall be used to perform the loading of the FXML file . [CODESPLIT] @ Produces @ FXMLLoaderParams FXMLLoader createCdiFXMLLoader ( final InjectionPoint injectionPoint ) { final CdiFXMLLoader fxmlLoader = new CdiFXMLLoader ( ) ; final Annotated annotated = injectionPoint . getAnnotated ( ) ; final Class < ? > declaringClass = injectionPoint . getMember ( ) . getDeclaringClass ( ) ; if ( annotated . isAnnotationPresent ( FXMLLoaderParams . class ) ) { final FXMLLoaderParams annotation = annotated . getAnnotation ( FXMLLoaderParams . class ) ; initializeFXMLLoader ( fxmlLoader , declaringClass , annotation . location ( ) , annotation . resources ( ) , annotation . charset ( ) ) ; } return fxmlLoader ; }


Input: Initializes the given FXMLLoader instance using the provided parameters . [CODESPLIT] static void initializeFXMLLoader ( final FXMLLoader fxmlLoader , final Class < ? > targetClass , final String location , final String resources , final String charset ) { checkAndSetLocation ( fxmlLoader , targetClass , location ) ; if ( charset != null && ! charset . equals ( CHARSET_UNSPECIFIED ) ) { fxmlLoader . setCharset ( Charset . forName ( charset ) ) ; } if ( resources != null && ! resources . equals ( RESOURCES_UNSPECIFIED ) ) { fxmlLoader . setResources ( ResourceBundle . getBundle ( resources ) ) ; } }


Input: Checks the location that has been specified ( if any ) and uses the default class loader to create an URL that points to a FXML file on the classpath . [CODESPLIT] private static void checkAndSetLocation ( FXMLLoader fxmlLoader , Class < ? > targetClass , String location ) { if ( location != null && ! location . equals ( LOCATION_UNSPECIFIED ) ) { final URL locationUrl = targetClass . getResource ( location ) ; if ( locationUrl == null ) { throw new IllegalArgumentException ( String . format ( "Couldn't find FXML file: \"%s\"." , location ) ) ; } fxmlLoader . setLocation ( locationUrl ) ; } }


Input: TODO Refactor HATEOAS link building . Time for ResourceAssembler or moving this stuff up the service . Although moving it up will create a circular dep . [CODESPLIT] @ RequestMapping ( value = "" , method = { RequestMethod . GET , RequestMethod . HEAD } ) public Resources < EventDefinitionResource > getEventDefinitions ( ) throws EventDefinitionNotFoundException , ProviderNotFoundException , AttributeDefinitionNotFoundException { if ( LOG . isTraceEnabled ( ) ) { LOG . entry ( ) ; } final Resources < EventDefinitionResource > resources = getEventDefinitions ( eventDefinitionService . getEventDefinitions ( ) ) ; if ( LOG . isTraceEnabled ( ) ) { LOG . exit ( resources ) ; } return resources ; }


Input: Your business application s API key . This key identifies your application for purposes of quota management . [CODESPLIT] public ReverseGeocodeRequestBuilder key ( String client , String signature ) { parameters . put ( "client" , client ) ; parameters . put ( "signature" , signature ) ; return this ; }


Input: The location latitude and longitude . [CODESPLIT] public ReverseGeocodeRequestBuilder latlng ( Double lat , Double lng ) { parameters . put ( "latlng" , lat + "," + lng ) ; return this ; }


Input:
One or more address types separated by a pipe ( | ) . [CODESPLIT] public ReverseGeocodeRequestBuilder resultType ( Type [ ] types ) { if ( types == null || types . length == 0 ) return this ; StringBuffer resultType = new StringBuffer ( ) ; for ( int i = 0 ; i < types . length - 1 ; i ++ ) resultType . append ( types [ i ] + "|" ) ; resultType . append ( types [ types . length - 1 ] ) ; parameters . put ( "result_type" , resultType . toString ( ) ) ; return this ; } /**
	 * One or more location types, separated by a pipe (|).
	 *
	 * Specifying a type will restrict the results to this type. If multiple
	 * types are specified, the API will return all addresses that match any
	 * of the types.
	 *
	 * Note: This parameter is available only for requests that include an API
	 * key or a client ID.
	 *
	 * The following values are supported:
	 *
	 *   "ROOFTOP" restricts the results to addresses for which we have
	 *   location information accurate down to street address precision.
	 *
	 *   "RANGE_INTERPOLATED" restricts the results to those that reflect
	 *   an approximation (usually on a road) interpolated between two precise
	 *   points (such as intersections). An interpolated range generally
	 *   indicates that rooftop geocodes are unavailable for a street address.
	 *
	 *   "GEOMETRIC_CENTER" restricts the results to geometric centers of a
	 *   location such as a polyline (for example, a street) or polygon (region).
	 *
	 *   "APPROXIMATE" restricts the results to those that are characterized
	 *   as approximate.
	 *
	 * @param types
	 * @return ReverseGeocodeRequestBuilder
	 */ public ReverseGeocodeRequestBuilder locationType ( LocationType [ ] types ) { if ( types == null || types . length == 0 ) return this ; StringBuffer resultType = new StringBuffer ( ) ; for ( int i = 0 ; i < types . length - 1 ; i ++ ) resultType . append ( types [ i ] + "|" ) ; resultType . append ( types [ types . length - 1 ] ) ; parameters . put ( "location_type" , resultType . toString ( ) ) ; return this ; } /**
	 * Build the request object.
	 *
	 * @return AddressRequest
	 */ public ReverseGeocodeRequest build ( ) { return new ReverseGeocodeRequest ( parameters ) ; } }


Input: Safely get the information from our convention [CODESPLIT] public static InetSocketAddress getHostPortPair ( Service svc ) { try { return new InetSocketAddress ( svc . getMetadata ( ) . get ( "service.host" ) , Integer . parseInt ( svc . getMetadata ( ) . get ( "service.port" ) ) ) ; } catch ( Exception e ) { logger . error ( "Exception extracting metadata from service instance {}" , svc , e ) ; return null ; } }


Input: Find an attribute definition that applies to a particular attribute filter . [CODESPLIT] protected AttributeDefinition getApplicableAttributeDefinition ( final UUID attributeDefinitionUuid , final List < AttributeDefinition > attributeDefinitions ) { if ( LOG . isTraceEnabled ( ) ) { LOG . entry ( attributeDefinitionUuid , attributeDefinitions ) ; } AttributeDefinition attributeDefinition = null ; for ( AttributeDefinition anAttributeDefinition : attributeDefinitions ) { if ( anAttributeDefinition . getUUID ( ) . equals ( attributeDefinitionUuid ) ) { attributeDefinition = anAttributeDefinition ; break ; } } if ( LOG . isTraceEnabled ( ) ) { LOG . exit ( attributeDefinition ) ; } return attributeDefinition ; }


Input: Evaluate single attribute filter [CODESPLIT] protected boolean evaluate ( final UUID attributeDefinitionUuid , final AttributeFilterExpression attributeFilter , final Map < UUID , String > eventAttributes , final List < AttributeDefinition > attributeDefinitions ) throws ParseException { if ( LOG . isTraceEnabled ( ) ) { LOG . entry ( attributeDefinitionUuid , attributeFilter , eventAttributes , attributeDefinitions ) ; } // Find a matching attribute final String attributeValue = eventAttributes . get ( attributeDefinitionUuid ) ; if ( attributeValue == null ) { // No attribute value to match attribute filter. if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( "An attributeValue was not specified for this attribute definition." ) ; LOG . exit ( false ) ; } return false ; } // Find the Attribute definition that matches our filter. final AttributeDefinition attributeDefinition = getApplicableAttributeDefinition ( attributeDefinitionUuid , attributeDefinitions ) ; if ( attributeDefinition == null ) { // Really shouldn't have any filters defined for attributes that don't exist. if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( "The attributeDefinition did not exist." ) ; LOG . exit ( false ) ; } return false ; } final Unit unit = attributeDefinition . getUnits ( ) ; try { boolean result = unit . evaluate ( attributeFilter . getOperator ( ) , attributeValue , attributeFilter . getOperand ( ) ) ; if ( LOG . isTraceEnabled ( ) ) { LOG . exit ( result ) ; } return result ; } catch ( ParseException e ) { if ( LOG . isTraceEnabled ( ) ) { LOG . throwing ( e ) ; } throw e ; } }


Input: TODO I d like to push a lot of this down into NickNack - core . [CODESPLIT] protected Action processVariables ( Action origAction , Event cause ) { final ActionResource newAction = new ActionResource ( ) ; final Map < UUID , String > newParameters = new HashMap <> ( ) ; newAction . setAppliesToActionDefinition ( origAction . getAppliesToActionDefinition ( ) ) ; for ( UUID key : origAction . getAttributes ( ) . keySet ( ) ) { newParameters . put ( key , processVariables ( origAction . getAttributes ( ) . get ( key ) , cause ) ) ; } newAction . setParameters ( newParameters ) ; return newAction ; }


Input: helpers [CODESPLIT] private boolean isPertinent ( Event e ) { return ( e . getPayload ( ) instanceof ServicePayload ) && ( ( ServicePayload ) e . getPayload ( ) ) . getService ( ) . getTags ( ) . contains ( discovery . getType ( ) ) ; }


Input: todo : switch to iterator . [CODESPLIT] private void pollAndProcessEvents ( ) { MethodOptions options = new MethodOptions ( 100 , null ) ; List < Event > events = null ; int count = 0 ; do { if ( shouldStopPolling ) break ; count += 1 ; try { // get events from server, filter the ones we are interested in. events = Lists . newArrayList ( discovery . getClient ( ) . getEventsClient ( ) . list ( options ) ) ; String lastEventId = processEvents ( events ) ; options = options . withMarker ( lastEventId ) ; } catch ( Exception ex ) { // todo: just log it. events = null ; } } while ( events != null && events . size ( ) > 0 ) ; // if it only happened once, assume there are not many events happening. if ( count == 1 ) { // todo: trace message. // todo: this should become configurable. try { Thread . sleep ( 1000 ) ; } catch ( Exception ex ) { } } }


Input: 1 .. 55 chars . anything goes . [CODESPLIT] public static String sanitizeTag ( String s ) { // if > 55 chars, assume max entropy is at the end (like a class name). if ( s . length ( ) > MAX_TAG_LENGTH ) { s = s . substring ( s . length ( ) - MAX_TAG_LENGTH ) ; } return s ; }


Input: TODO Refactor HATEOAS link building . Time for ResourceAssembler or moving this stuff up the service . Although moving it up will create a circular dep . [CODESPLIT] @ RequestMapping ( value = "" , method = { RequestMethod . GET , RequestMethod . HEAD } ) public Resources < StatesResource > getAllStates ( ) throws StateDefinitionNotFoundException , ProviderNotFoundException , AttributeDefinitionNotFoundException { if ( LOG . isTraceEnabled ( ) ) { LOG . entry ( ) ; } final Resources < StatesResource > resources = getAllStates ( statesService . getAllStates ( ) , null ) ; if ( LOG . isTraceEnabled ( ) ) { LOG . exit ( resources ) ; } return resources ; }


Input: Your business application s API key . This key identifies your application for purposes of quota management . [CODESPLIT] public GeocodeRequestBuilder key ( String client , String signature ) { parameters . put ( "client" , client ) ; parameters . put ( "signature" , signature ) ; return this ; }


Input: The address that you want to geocode . [CODESPLIT] public GeocodeRequestBuilder address ( String address ) { parameters . put ( "address" , address != null ? address . replace ( ' ' , ' ' ) : address ) ; return this ; }


Input: In a geocoding response the Google Geocoding API can return address results restricted to a specific area . [CODESPLIT] public GeocodeRequestBuilder componenets ( Map < String , String > components ) { StringBuffer filters = new StringBuffer ( ) ; for ( Iterator < Map . Entry < String , String > > iterator = components . entrySet ( ) . iterator ( ) ; iterator . hasNext ( ) ; ) { Map . Entry < String , String > entry = iterator . next ( ) ; filters . append ( entry . getKey ( ) + ":" + entry . getValue ( ) != null ? entry . getValue ( ) . replace ( ' ' , ' ' ) : entry . getValue ( ) ) ; if ( iterator . hasNext ( ) ) filters . append ( "|" ) ; } parameters . put ( "components" , filters . toString ( ) ) ; return this ; }


Input: ServiceInstance<T > instances required by the Curator interfaces . [CODESPLIT] public static ServiceInstance < BarCuratorService > convert ( BarCuratorService bar ) throws Exception { ServiceInstanceBuilder < BarCuratorService > builder = ServiceInstance . builder ( ) ; // these values are for the most part nonsensical. return builder . payload ( bar ) . uriSpec ( new UriSpec ( "http://" ) ) . sslPort ( 2400 ) . serviceType ( ServiceType . STATIC ) . port ( 2300 ) . address ( "127.0.0.1" ) . id ( String . format ( "bar-%s-%d-%s" , bar . a , bar . b , bar . c ) ) . name ( bar . name ) . build ( ) ; }


Input: ServiceInstance<T > instances required by the Curator interfaces . [CODESPLIT] public static ServiceInstance < BarCuratorService > convert ( Service svc ) throws Exception { BarCuratorService bar = new BarCuratorService ( svc . getMetadata ( ) . get ( "name" ) , svc . getMetadata ( ) . get ( "a" ) , Integer . parseInt ( svc . getMetadata ( ) . get ( "b" ) ) , Float . parseFloat ( svc . getMetadata ( ) . get ( "c" ) ) ) ; return convert ( bar ) ; }


Input: return all distinct names registered by this discovery type . [CODESPLIT] public Collection < String > queryForNames ( ) throws Exception { Set < String > names = new HashSet < String > ( ) ; // todo: it would be better to do: // services = client.getServicesClient().list(options, typeTag); // but there are some validation problems (the tag is allowed to be written, but not queried on). Iterator < Service > services = client . getServicesClient ( ) . list ( new MethodOptions ( 100 , null ) ) ; while ( services . hasNext ( ) ) { Service service = services . next ( ) ; // this conditional can be removed when the above operation works. if ( ! service . getTags ( ) . contains ( typeTag ) ) { continue ; } String name = service . getMetadata ( ) . get ( ServiceTracker . NAME ) ; if ( ! names . contains ( name ) ) { names . add ( name ) ; } } return names ; }


Input: return all instances registered to this particular name for this discovery type [CODESPLIT] public Collection < ServiceInstance < T > > queryForInstances ( String name ) throws Exception { List < ServiceInstance < T >> serviceInstances = new ArrayList < ServiceInstance < T > > ( ) ; Iterator < Service > services = client . getServicesClient ( ) . list ( new MethodOptions ( 100 , null ) ) ; while ( services . hasNext ( ) ) { Service service = services . next ( ) ; if ( service . getTags ( ) . contains ( typeTag ) && service . getMetadata ( ) . get ( ServiceTracker . NAME ) . equals ( name ) ) { // does the job of the serializer in the curator code (theirs is just a json marshaller anyway). serviceInstances . add ( convert ( service ) ) ; } } return serviceInstances ; }


Input: TODO Refactor HATEOAS link building . Time for ResourceAssembler or moving this stuff up the service . Although moving it up will create a circular dep . [CODESPLIT] @ RequestMapping ( value = "" , method = { RequestMethod . GET , RequestMethod . HEAD } ) public Resources < StateDefinitionResource > getStateDefinitions ( ) throws StateDefinitionNotFoundException , ProviderNotFoundException , AttributeDefinitionNotFoundException { if ( LOG . isTraceEnabled ( ) ) { LOG . entry ( ) ; } final Resources < StateDefinitionResource > resources = getStateDefinitions ( stateDefinitionService . getStateDefinitions ( ) ) ; if ( LOG . isTraceEnabled ( ) ) { LOG . exit ( resources ) ; } return resources ; }


Input: taken from spark ( https : // github . com / perwendel / spark ) [CODESPLIT] public static Map < String , String > getParams ( List < String > request , List < String > matched ) { Map < String , String > params = new HashMap <> ( ) ; for ( int i = 0 ; ( i < request . size ( ) ) && ( i < matched . size ( ) ) ; i ++ ) { String matchedPart = matched . get ( i ) ; if ( SparkUtils . isParam ( matchedPart ) ) { params . put ( matchedPart . toLowerCase ( ) , request . get ( i ) ) ; } } return Collections . unmodifiableMap ( params ) ; }


Input: taken from spark ( https : // github . com / perwendel / spark ) [CODESPLIT] public static List < String > getSplat ( List < String > request , List < String > matched ) { int nbrOfRequestParts = request . size ( ) ; int nbrOfMatchedParts = matched . size ( ) ; boolean sameLength = ( nbrOfRequestParts == nbrOfMatchedParts ) ; List < String > splat = new ArrayList <> ( ) ; for ( int i = 0 ; ( i < nbrOfRequestParts ) && ( i < nbrOfMatchedParts ) ; i ++ ) { String matchedPart = matched . get ( i ) ; if ( SparkUtils . isSplat ( matchedPart ) ) { StringBuilder splatParam = new StringBuilder ( request . get ( i ) ) ; if ( ! sameLength && ( i == ( nbrOfMatchedParts - 1 ) ) ) { for ( int j = i + 1 ; j < nbrOfRequestParts ; j ++ ) { splatParam . append ( "/" ) ; splatParam . append ( request . get ( j ) ) ; } } splat . add ( splatParam . toString ( ) ) ; } } return Collections . unmodifiableList ( splat ) ; }


Input: Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Fluid Item... if ( this . getFluidItem ( ) != null ) { returnVal . put ( JSONMapping . FLUID_ITEM , this . getFluidItem ( ) . toJsonObject ( ) ) ; } //Flow Step Rule... if ( this . getFlowStepRule ( ) != null ) { returnVal . put ( JSONMapping . FLOW_STEP_RULE , this . getFlowStepRule ( ) . toJsonObject ( ) ) ; } return returnVal ; }


Input: Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Key... if ( this . getKey ( ) != null ) { returnVal . put ( JSONMapping . KEY , this . getKey ( ) ) ; } //Value... if ( this . getValue ( ) != null ) { returnVal . put ( JSONMapping . VALUE , this . getValue ( ) ) ; } return returnVal ; }


Input: Create a new Form Container / Electronic Forms . [CODESPLIT] public List < Collaboration > createCollaboration ( List < Collaboration > collaborationsParam ) { CollaborationListing collaborationListing = new CollaborationListing ( ) ; collaborationListing . setListing ( collaborationsParam ) ; if ( this . serviceTicket != null ) { collaborationListing . setServiceTicket ( this . serviceTicket ) ; } return new CollaborationListing ( this . putJson ( collaborationListing , WS . Path . Collaboration . Version1 . collaborationCreate ( ) ) ) . getListing ( ) ; }


Input: Retrieve all Collaboration items TO where logged in user . [CODESPLIT] public List < Collaboration > getAllToByLoggedIn ( ) { CollaborationListing collaborationListing = new CollaborationListing ( ) ; if ( this . serviceTicket != null ) { collaborationListing . setServiceTicket ( this . serviceTicket ) ; } return new CollaborationListing ( this . postJson ( collaborationListing , WS . Path . Collaboration . Version1 . getAllToByLoggedIn ( ) ) ) . getListing ( ) ; }


Input: Retrieve all Collaboration items TO where { @code Form } is { @code formParam } . [CODESPLIT] public List < Collaboration > getAllToByForm ( Form formParam ) { if ( formParam != null && this . serviceTicket != null ) { formParam . setServiceTicket ( this . serviceTicket ) ; } return new CollaborationListing ( this . postJson ( formParam , WS . Path . Collaboration . Version1 . getAllToByForm ( ) ) ) . getListing ( ) ; }


Input: Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Form Container... if ( this . getFormContainer ( ) != null ) { returnVal . put ( JSONMapping . FORM_CONTAINER , this . getFormContainer ( ) . toJsonObject ( ) ) ; } //Parent Form Container... if ( this . getParentFormContainer ( ) != null ) { returnVal . put ( JSONMapping . PARENT_FORM_CONTAINER , this . getParentFormContainer ( ) . toJsonObject ( ) ) ; } //Parent Form Field... if ( this . getParentFormField ( ) != null ) { returnVal . put ( JSONMapping . PARENT_FORM_FIELD , this . getParentFormField ( ) . toJsonObject ( ) ) ; } return returnVal ; }


Input: Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Can Create... if ( this . isCanCreateAndModify ( ) != null ) { returnVal . put ( JSONMapping . CAN_CREATE_AND_MODIFY , this . isCanCreateAndModify ( ) . booleanValue ( ) ) ; } //Can View... if ( this . isCanView ( ) != null ) { returnVal . put ( JSONMapping . CAN_VIEW , this . isCanView ( ) . booleanValue ( ) ) ; } //Form Definition... if ( this . getFormFieldToFormDefinition ( ) != null ) { returnVal . put ( JSONMapping . FORM_FIELD_TO_FORM_DEFINITION , this . getFormFieldToFormDefinition ( ) . toJsonObject ( ) ) ; } return returnVal ; }