signature:
public class PMMLConsumers { /** * Consumes the PMML in the given file and converts it to a Weka { @ link Classifier } .
 * @ param file The file with the PMML representation of the classifier .
 * @ return A Weka { @ link Classifier } .
 * @ throws PMMLConversionException If if fails to consume the PMML file . */
public static Classifier consume ( File file ) throws PMMLConversionException { } }

implementation: PMML pmml = null ; try { if ( isGzipped ( file ) ) { logger . debug ( "Consuming GZipped PMML file '{}'." , file . getAbsolutePath ( ) ) ; try ( FileInputStream fis = new FileInputStream ( file ) ; GZIPInputStream gzipInputStream = new GZIPInputStream ( fis ) ) { pmml = JAXBUtil . unmarshalPMML ( new StreamSource ( gzipInputStream ) ) ; } } else { logger . debug ( "Consuming PMML file '{}'." , file . getAbsolutePath ( ) ) ; try ( FileInputStream fis = new FileInputStream ( file ) ) { pmml = JAXBUtil . unmarshalPMML ( new StreamSource ( fis ) ) ; } } } catch ( Exception e ) { throw new PMMLConversionException ( "Failed to unmarshal PMML file '" + file + "'. Make sure the file is a valid PMML." , e ) ; } Algorithm algorithm = getAlgorithm ( pmml ) ; logger . debug ( "Consumed PMML file using algorithm {}." , algorithm ) ; return algorithm . getPMMLConsumer ( ) . consume ( pmml ) ;


signature:
public class PMMLConsumers { /** * Checks if the given file is in GZIP format .
 * It checks this by checking the head for the { @ link java . util . zip . GZIPInputStream # GZIP _ MAGIC } number .
 * @ param file The file to check .
 * @ return { @ code true } if the file is in GZIP format , or { @ code false }
 * @ throws IOException */
private static boolean isGzipped ( File file ) throws IOException { } }

implementation: FileInputStream fileInputStream = new FileInputStream ( file ) ; int head = ( fileInputStream . read ( ) & 0xff ) | ( ( fileInputStream . read ( ) << 8 ) & 0xff00 ) ; return GZIPInputStream . GZIP_MAGIC == head ;


signature:
public class PMMLConsumers { /** * Retrieves the { @ link com . feedzai . fos . impl . weka . utils . pmml . PMMLConversionCommons . Algorithm } represented
 * as a PMML extension named { @ link com . feedzai . fos . impl . weka . utils . pmml . PMMLConversionCommons # ALGORITHM _ EXTENSION _ ELEMENT } .
 * @ param pmml The { @ link PMML } .
 * @ return The { @ link com . feedzai . fos . impl . weka . utils . pmml . PMMLConversionCommons . Algorithm } in the PMML .
 * @ throws PMMLConversionException If it fails to retrieve the algorithm from the given PPML . */
private static Algorithm getAlgorithm ( PMML pmml ) throws PMMLConversionException { } }

implementation: for ( Extension extension : pmml . getExtensions ( ) ) { if ( ALGORITHM_EXTENSION_ELEMENT . equals ( extension . getName ( ) ) ) { return Algorithm . valueOf ( extension . getValue ( ) ) ; } } throw new PMMLConversionException ( "Couldn't find '" + ALGORITHM_EXTENSION_ELEMENT + "' extension element in PMML." ) ;


signature:
public class PickConstructor { /** * Pick best constructor for a provider or resource class
 * Picks constructor with most parameters . Will ignore constructors that
 * have parameters with no @ Context annotation
 * @ param clazz
 * @ return */
public static Constructor pickSingletonConstructor ( Class clazz ) { } }

implementation:
Constructor < ? > [ ] constructors = clazz . getConstructors ( ) ; Constructor < ? > constructor = null ; // prefer a no - arg constructor
int numParameters = 0 ; Constructor pick = null ; boolean potentialConflict = false ; // https : / / issues . jboss . org / browse / RESTEASY - 645
for ( Constructor con : constructors ) { if ( Modifier . isPublic ( con . getModifiers ( ) ) == false ) { continue ; } if ( con . getParameterTypes ( ) . length >= numParameters ) { if ( con . getParameterTypes ( ) . length > numParameters ) { potentialConflict = false ; } boolean noContextAnnotation = false ; if ( con . getParameterAnnotations ( ) != null ) { for ( Annotation [ ] ann : con . getParameterAnnotations ( ) ) { if ( FindAnnotation . findAnnotation ( ann , Context . class ) == null ) { noContextAnnotation = true ; } } } if ( noContextAnnotation ) continue ; if ( con . getParameterTypes ( ) . length == numParameters && numParameters != 0 ) { potentialConflict = true ; } numParameters = con . getParameterTypes ( ) . length ; pick = con ; } } if ( potentialConflict ) { // TODO logger . warn ( " Ambiguity constructors are found in " + clazz +
// " . More details please refer to http : / / jsr311 . java . net / nonav / releases / 1.1 / spec / spec . html " ) ;
} return pick ;


signature:
public class PickConstructor { /** * Pick best constructor for a provider or resource class
 * Picks constructor with most parameters . Will ignore constructors that
 * have parameters with no @ Context annotation
 * @ param clazz
 * @ return */
public static Constructor pickPerRequestConstructor ( Class clazz ) { } }

implementation:
Constructor < ? > [ ] constructors = clazz . getConstructors ( ) ; Constructor < ? > [ ] declaredConstructors = clazz . getDeclaredConstructors ( ) ; Constructor < ? > constructor = null ; // prefer a no - arg constructor
int numParameters = 0 ; Constructor pick = null ; boolean potentialConflict = false ; // https : / / issues . jboss . org / browse / RESTEASY - 645
for ( Constructor con : constructors ) { if ( Modifier . isPublic ( con . getModifiers ( ) ) == false ) { continue ; } if ( con . getParameterTypes ( ) . length >= numParameters ) { if ( con . getParameterTypes ( ) . length > numParameters ) { potentialConflict = false ; } boolean noContextAnnotation = false ; if ( con . getParameterAnnotations ( ) != null ) { for ( Annotation [ ] ann : con . getParameterAnnotations ( ) ) { if ( FindAnnotation . findJaxRSAnnotations ( ann ) . length == 0 ) { noContextAnnotation = true ; } } } if ( noContextAnnotation ) continue ; if ( con . getParameterTypes ( ) . length == numParameters && numParameters != 0 ) { potentialConflict = true ; } numParameters = con . getParameterTypes ( ) . length ; pick = con ; } } if ( potentialConflict ) { // todo logger . warn ( " Ambiguity constructors are found in " + clazz +
// " . More details please refer to http : / / jsr311 . java . net / nonav / releases / 1.1 / spec / spec . html " ) ;
} return pick ;


signature:
public class WekaModelConfig { /** * Returns the pool configuration of the scorer .
 * @ return a map from configuration key to configuration value */
@ NotNull public Map < Object , Object > getPoolConfiguration ( ) { } }

implementation: return ConfigurationConverter . getMap ( configuration . subset ( GenericObjectPoolConfig . class . getName ( ) ) ) ;


signature:
public class WekaModelConfig { /** * Sets the ID of the model .
 * @ param id the ID */
public void setId ( UUID id ) { } }

implementation: this . dirty = true ; this . id = id ; this . modelConfig . setProperty ( ID , id . toString ( ) ) ;


signature:
public class WekaModelConfig { /** * Sets the model file of the serialized classifier .
 * @ param model the model file */
public void setModel ( File model ) { } }

implementation: this . dirty = true ; this . model = model ; this . modelConfig . setProperty ( MODEL_FILE , model . getAbsolutePath ( ) ) ;


signature:
public class WekaModelConfig { /** * Sets the { @ link com . feedzai . fos . api . ModelDescriptor } of the model .
 * @ param modelDescriptor The { @ link com . feedzai . fos . api . ModelDescriptor } of the model . */
public void setModelDescriptor ( ModelDescriptor modelDescriptor ) { } }

implementation: this . modelDescriptor = modelDescriptor ; setModel ( new File ( modelDescriptor . getModelFilePath ( ) ) ) ; this . modelConfig . setProperty ( CLASSIFIER_FORMAT , modelDescriptor . getFormat ( ) . toString ( ) ) ;


signature:
public class WekaModelConfig { /** * Updates the underlying < code > ModelConfig < / code > using < code > ModelConfig . update < / code > .
 * @ param modelConfig the model config with the new settings */
public void update ( ModelConfig modelConfig ) throws FOSException { } }

implementation:
checkNotNull ( modelConfig ) ; this . dirty = true ; // The class index should be reset everytime a model config is updated .
// TODO : Refactor the classIndex to be in ModelConfig .
this . modelConfig . getProperties ( ) . remove ( CLASS_INDEX ) ; this . modelConfig . update ( modelConfig ) ; parseModelConfig ( ) ;


signature:
public class WekaScorer { /** * Score the < code > scorable < / code > for each model ID identified by < code > modelIds < / code > .
 * < p > If multiple models are given as parameters , they will be scored in parallel .
 * @ param modelIds the list of models to score
 * @ param scorable the item to score
 * @ return a List of scores with the same order and the received modelIds
 * @ throws FOSException when classification was not possible */
@ Override @ NotNull public List < double [ ] > score ( List < UUID > modelIds , Object [ ] scorable ) throws FOSException { } }

implementation:
checkNotNull ( modelIds , "Models to score cannot be null" ) ; checkNotNull ( scorable , "Instance cannot be null" ) ; List < double [ ] > scores = new ArrayList < > ( modelIds . size ( ) ) ; try { reloadModelsLock . readLock ( ) . lock ( ) ; if ( modelIds . size ( ) == 1 ) { // if only one model , then don ' t parallelize scoring
WekaThreadSafeScorer wekaThreadSafeScorer = getScorer ( modelIds . get ( 0 ) ) ; scores . add ( wekaThreadSafeScorer . score ( scorable ) ) ; } else { Map < UUID , Future < double [ ] > > futureScores = new HashMap < > ( modelIds . size ( ) ) ; // scatter
for ( UUID modelId : modelIds ) { WekaThreadSafeScorer wekaThreadSafeScorer = getScorer ( modelId ) ; futureScores . put ( modelId , executorService . submit ( new AsyncScoringTask ( wekaThreadSafeScorer , scorable ) ) ) ; } // gather
for ( UUID modelId : modelIds ) { scores . add ( getFuture ( futureScores . get ( modelId ) , modelId ) ) ; } } } finally { reloadModelsLock . readLock ( ) . unlock ( ) ; } return scores ;


signature:
public class WekaScorer { /** * Score each < code > scorable < / code > with the given < code > modelId < / code > .
 * < p > If multiple < code > scorables < / code > are given as parameters , they will be scored in parallel .
 * @ param modelId the id of the model
 * @ param scorables an array of instances to score
 * @ return a list of scores with the same order as the scorable array
 * @ throws FOSException when classification was not possible */
@ Override @ NotNull public List < double [ ] > score ( UUID modelId , List < Object [ ] > scorables ) throws FOSException { } }

implementation:
checkNotNull ( scorables , "List of scorables cannot be null" ) ; List < double [ ] > scores = new ArrayList < > ( scorables . size ( ) ) ; try { reloadModelsLock . readLock ( ) . lock ( ) ; if ( scorables . size ( ) == 1 ) { // if only one model , then don ' t parallelize scoring
WekaThreadSafeScorer wekaThreadSafeScorer = getScorer ( modelId ) ; scores . add ( wekaThreadSafeScorer . score ( scorables . get ( 0 ) ) ) ; } else { Map < Object [ ] , Future < double [ ] > > futureScores = new HashMap < > ( scorables . size ( ) ) ; // scatter
for ( Object [ ] scorable : scorables ) { WekaThreadSafeScorer wekaThreadSafeScorer = wekaThreadSafeScorers . get ( modelId ) ; futureScores . put ( scorable , executorService . submit ( new AsyncScoringTask ( wekaThreadSafeScorer , scorable ) ) ) ; } // gather
for ( Object [ ] scorable : scorables ) { scores . add ( getFuture ( futureScores . get ( scorable ) , modelId ) ) ; } } } finally { reloadModelsLock . readLock ( ) . unlock ( ) ; } return scores ;


signature:
public class WekaScorer { /** * Score a single < code > scorable < / code > with the given < code > modelId < / code > .
 * @ param modelId the id of the model
 * @ param scorable the instance to score
 * @ return a list of scores with the same order as the scorable array
 * @ throws FOSException when classification was not possible */
@ Override @ NotNull public double [ ] score ( UUID modelId , Object [ ] scorable ) throws FOSException { } }

implementation: checkNotNull ( scorable , "The scorable cannot be null" ) ; try { reloadModelsLock . readLock ( ) . lock ( ) ; WekaThreadSafeScorer wekaThreadSafeScorer = getScorer ( modelId ) ; return wekaThreadSafeScorer . score ( scorable ) ; } finally { reloadModelsLock . readLock ( ) . unlock ( ) ; }


signature:
public class WekaScorer { /** * Adds the given model to the managed models .
 * < p > If the provided model id already exists , then the older model is removed and the new one is instantiated .
 * @ param wekaModelConfig the configuration of the new model
 * @ throws FOSException when the new model could not be instantiated */
public void addOrUpdate ( WekaModelConfig wekaModelConfig ) throws FOSException { } }

implementation: checkNotNull ( wekaModelConfig , "Model config cannot be null" ) ; WekaThreadSafeScorer newWekaThreadSafeScorer = new WekaThreadSafeScorerPool ( wekaModelConfig , wekaManagerConfig ) ; WekaThreadSafeScorer oldWekaThreadSafeScorer = quickSwitch ( wekaModelConfig . getId ( ) , newWekaThreadSafeScorer ) ; WekaUtils . closeSilently ( oldWekaThreadSafeScorer ) ;


signature:
public class WekaScorer { /** * Removes the given model from the managed models .
 * < p > If the model does not exist no exception will be thrown .
 * @ param modelId the id of the model to remove . */
public void removeModel ( UUID modelId ) { } }

implementation: WekaThreadSafeScorer newWekaThreadSafeScorer = null ; WekaThreadSafeScorer oldWekaThreadSafeScorer = quickSwitch ( modelId , newWekaThreadSafeScorer ) ; WekaUtils . closeSilently ( oldWekaThreadSafeScorer ) ;


signature:
public class WekaScorer { /** * Switches the { @ link com . feedzai . fos . impl . weka . WekaScorer } used for the model with the given UUID .
 * @ param modelId The UUID of the model whose scorer to switch .
 * @ param newWekaThreadSafeScorer The score to switch to .
 * @ return The previous scorer associated to the given UUID . */
private WekaThreadSafeScorer quickSwitch ( UUID modelId , WekaThreadSafeScorer newWekaThreadSafeScorer ) { } }

implementation:
try { // quick switch - do not do anything inside for performance reasons ! !
reloadModelsLock . writeLock ( ) . lock ( ) ; return wekaThreadSafeScorers . put ( modelId , newWekaThreadSafeScorer ) ; } finally { reloadModelsLock . writeLock ( ) . unlock ( ) ; }


signature:
public class RandomForestPMMLConsumer { /** * Builds a new { @ link weka . classifiers . trees . RandomTree Weka RandomTree } from the given { @ link org . dmg . pmml . TreeModel PMML TreeModel } .
 * @ param root The { @ link weka . classifiers . trees . RandomTree Weka RandomTree } which is to be built .
 * @ param instances The { @ link weka . core . Instances } with the tree ' s attributes .
 * @ param treeModel The { @ link org . dmg . pmml . TreeModel PMML TreeModel } which is to be converted to a { @ link weka . classifiers . trees . RandomTree Weka RandomTree } .
 * @ return The same { @ code root } instance . */
private static RandomTree buildRandomTree ( RandomTree root , Instances instances , TreeModel treeModel ) { } }

implementation: Instances treeInstances = new Instances ( instances ) ; treeInstances . setClassIndex ( getClassIndex ( instances , treeModel ) ) ; root . m_Info = treeInstances ; root . m_Tree = buildRandomTreeNode ( root , treeModel . getNode ( ) ) ; return root ;


signature:
public class RandomForestPMMLConsumer { /** * Builds a { @ link weka . classifiers . trees . RandomTree . Tree Weka RandomTree } node
 * represented by the given { @ link org . dmg . pmml . Node PMML node } .
 * @ param tree The { @ link weka . classifiers . trees . RandomTree Weka RandomTree } which the returned tree node is part of .
 * @ param pmmlNode The { @ link org . dmg . pmml . PMML PMML node } to be converted to a { @ link weka . classifiers . trees . RandomTree . Tree Weka RandomTree } node .
 * @ return A new { @ link weka . classifiers . trees . RandomTree . Tree Weka RandomTree } node . */
private static RandomTree . Tree buildRandomTreeNode ( RandomTree tree , Node pmmlNode ) { } }

implementation:
RandomTree . Tree treeNode = tree . new Tree ( ) ; // Set the class distribution .
treeNode . m_ClassDistribution = getClassDistribution ( pmmlNode ) ; Instances instances = tree . m_Info ; boolean isLeaf = pmmlNode . getNodes ( ) . size ( ) == 0 ; if ( ! isLeaf ) { List < Node > children = pmmlNode . getNodes ( ) ; String attributeName = ( ( SimplePredicate ) children . get ( 0 ) . getPredicate ( ) ) . getField ( ) . getValue ( ) ; Attribute attribute = instances . attribute ( attributeName ) ; treeNode . m_Attribute = attribute . index ( ) ; if ( attribute . isNumeric ( ) ) { /* If the node is numeric , get its two child nodes and covert them into a new RandomTree . Tree node .
 For example , consider the following PPML Node :
 < Node id = " 2 " >
 < SimplePredicate field = " petal _ length " operator = " lessThan " value = " 5.05 " / >
 < Node id = " 3 " score = " Iris - setosa " >
 < SimplePredicate field = " petal _ length " operator = " lessThan " value = " 2.95 " / >
 < / Node >
 < Node id = " 4 " score = " Iris - versicolor " >
 < SimplePredicate field = " petal _ length " operator = " greaterOrEqual " value = " 2.95 " / >
 < / Node >
 < / Node >
 We ' ll grab the two child nodes and their value will be the split point of the current RandomTree . Tree node . */
assert children . size ( ) == 2 : "Numeric attributes must have exactly 2 children" ; Node left = children . get ( 0 ) ; Node right = children . get ( 1 ) ; Predicate leftPredicate = left . getPredicate ( ) ; Predicate rightPredicate = right . getPredicate ( ) ; assert leftPredicate instanceof SimplePredicate && leftPredicate . getClass ( ) . equals ( rightPredicate . getClass ( ) ) : "Numeric attribute's nodes must have the same simple predicate." ; double splitPoint = Double . valueOf ( ( ( SimplePredicate ) leftPredicate ) . getValue ( ) ) ; treeNode . m_SplitPoint = splitPoint ; treeNode . m_Successors = new RandomTree . Tree [ ] { buildRandomTreeNode ( tree , left ) , buildRandomTreeNode ( tree , right ) } ; treeNode . m_Prop = new double [ ] { getNodeTrainingProportion ( left ) , getNodeTrainingProportion ( right ) } ; } else if ( attribute . isNominal ( ) ) { treeNode . m_Successors = new RandomTree . Tree [ children . size ( ) ] ; treeNode . m_Prop = new double [ treeNode . m_Successors . length ] ; for ( int i = 0 ; i < children . size ( ) ; i ++ ) { Node child = children . get ( i ) ; SimplePredicate predicate = ( SimplePredicate ) child . getPredicate ( ) ; int valueIndex = attribute . indexOfValue ( predicate . getValue ( ) ) ; treeNode . m_Successors [ valueIndex ] = buildRandomTreeNode ( tree , child ) ; treeNode . m_Prop [ valueIndex ] = getNodeTrainingProportion ( child ) ; } } else { throw new RuntimeException ( "Attribute type not supported: " + attribute ) ; } } return treeNode ;


signature:
public class ClusterConfiguration { /** * The actual service queue for the clustered event bus .
 * All events are sent to this queue first .
 * @ param eventBusCluster actual event manager impl no proxy
 * @ return the service queue */
@ Bean public ServiceQueue clusteredEventManagerServiceQueue ( final @ Qualifier ( "eventBusCluster" ) EventBusCluster eventBusCluster ) { } }

implementation: if ( eventBusCluster == null ) { return null ; } return eventBusCluster . eventServiceQueue ( ) ;


signature:
public class ClusterConfiguration { /** * Wraps factory method call so we can provide another implementation of interface if needed .
 * @ param eventConnectorHub the cluster of event connectors
 * @ return the event manager */
@ Bean public EventManager clusteredEventManagerImpl ( final EventConnectorHub eventConnectorHub ) { } }

implementation: return EventManagerBuilder . eventManagerBuilder ( ) . setEventConnector ( eventConnectorHub ) . setName ( "CLUSTERED_EVENT_MANAGER" ) . build ( ) ;


signature:
public class WekaUtils { /** * Converts the given instance fields into a fast vector with < code > Attributes < / code > .
 * @ param classIndex classifier index
 * @ param instanceFields the list of instance fields that will generate the < code > Attributes < / code >
 * @ return a vector with one < code > Attribute < / code > for each instanceFields ( in the same order ) . */
@ NotNull public static FastVector instanceFields2Attributes ( int classIndex , List < ? extends Attribute > instanceFields ) throws FOSException { } }

implementation: checkNotNull ( instanceFields , "Instance fields cannot be null" ) ; FastVector result = new FastVector ( instanceFields . size ( ) ) ; classIndex = classIndex == - 1 ? instanceFields . size ( ) - 1 : classIndex ; int idx = 0 ; for ( Attribute instanceField : instanceFields ) { weka . core . Attribute attribute ; Class < ? > type = instanceField . getClass ( ) ; if ( type == CategoricalAttribute . class ) { CategoricalAttribute categorical = ( CategoricalAttribute ) instanceField ; List < String > instances = categorical . getCategoricalInstances ( ) ; FastVector categoricalInstances = new FastVector ( instances . size ( ) ) ; for ( String categoricalInstance : instances ) { categoricalInstances . addElement ( categoricalInstance ) ; } attribute = new weka . core . Attribute ( instanceField . getName ( ) , categoricalInstances , idx ) ; } else if ( type == NumericAttribute . class ) { attribute = new weka . core . Attribute ( instanceField . getName ( ) , idx ) ; } else { throw new FOSException ( "Unknown instance class" ) ; } result . addElement ( attribute ) ; idx ++ ; } return result ;


signature:
public class WekaUtils { /** * Converts from the received Object [ ] to a weka < code > Instance < / code > .
 * @ param data the Object [ ] to convert ( the scorable )
 * @ param setters the setters that will copy the data to the instance
 * @ param attributes the list of attributes to copy over
 * @ return an < code > Instance < / code > with all data elements copied over from the Object [ ]
 * @ throws WekaClassifierException when the setters and the data do not have the same size ( more data than setters , or more setters than data ) */
public static Instance objectArray2Instance ( Object [ ] data , InstanceSetter [ ] setters , FastVector attributes ) throws FOSException { } }

implementation: checkNotNull ( data , "Instance cannot be null" ) ; checkNotNull ( attributes , "Attributes cannot be null" ) ; checkNotNull ( setters , "Setters cannot be null" ) ; Instance instance = new Instance ( attributes . size ( ) ) ; if ( data . length == setters . length ) { for ( int idx = 0 ; idx < data . length ; idx ++ ) { if ( data [ idx ] != null ) { setters [ idx ] . set ( instance , ( weka . core . Attribute ) attributes . elementAt ( idx ) , data [ idx ] . toString ( ) ) ; } else { instance . setMissing ( idx ) ; } } } else { throw new Data2ConfigurationMismatch ( String . format ( "Data is not the same size as configured attributes (expected data size '%s' but was '%s')" , setters . length , data . length ) ) ; } return instance ;


signature:
public class WekaUtils { /** * Converts from < code > InstanceFields < / code > to < code > InstanceSetters < / code > ( required for scorable manipulation ) .
 * @ param instanceFields The instance fields for which to create the converters
 * @ param type The type of instance to handle .
 * @ return an array of < code > InstanceSetter < / code > with one < code > InstanceSetter < / code > for each < code > InstanceField < / code > . */
@ NotNull public static InstanceSetter [ ] instanceFields2ValueSetters ( final List < ? extends Attribute > instanceFields , final InstanceType type ) throws FOSException { } }

implementation: InstanceSetter [ ] instanceSetters = new InstanceSetter [ instanceFields . size ( ) ] ; for ( int idx = 0 ; idx < instanceFields . size ( ) ; idx ++ ) { final Attribute att = instanceFields . get ( idx ) ; instanceSetters [ idx ] = new InstanceSetter ( ) { @ Override public void set ( Instance instance , weka . core . Attribute attribute , Object value ) throws FOSException { instance . setValue ( attribute , att . parseOrMissing ( value ) ) ; } } ; } return instanceSetters ;


signature:
public class DefaultDbUnitManagerImpl { /** * Executes DbUnit < code > operation < / code > on dataset
 * < code > dataSetSource < / code > .
 * @ param operation
 * the DBUnit operation
 * @ param dataSetSource
 * the dataset to be used by this operation */
protected void execute ( DatabaseOperation operation , DataSetSource dataSetSource ) { } }

implementation: IDatabaseConnection dbconn = null ; try { dbconn = connectionCreator . create ( ) ; operation . execute ( dbconn , findDataSet ( dataSetSource ) ) ; } catch ( Exception e ) { throw new IllegalStateException ( "It's not possible to execute DbUnit operation: " + e . getMessage ( ) , e ) ; } finally { connectionCreator . close ( dbconn ) ; }


signature:
public class Encode { /** * Encode ' % ' if it is not an encoding sequence
 * @ param string
 * @ return */
public static String encodeNonCodes ( String string ) { } }

implementation:
Matcher matcher = nonCodes . matcher ( string ) ; StringBuffer buf = new StringBuffer ( ) ; // FYI : we do not use the no - arg matcher . find ( )
// coupled with matcher . appendReplacement ( )
// because the matched text may contain
// a second % and we must make sure we
// encode it ( if necessary ) .
int idx = 0 ; while ( matcher . find ( idx ) ) { int start = matcher . start ( ) ; buf . append ( string . substring ( idx , start ) ) ; buf . append ( "%25" ) ; idx = start + 1 ; } buf . append ( string . substring ( idx ) ) ; return buf . toString ( ) ;


signature:
public class Encode { /** * Keep encoded values " % . . . " and template parameters intact i . e . " { x } "
 * @ param segment
 * @ param encoding
 * @ return */
public static String encodeValue ( String segment , String [ ] encoding ) { } }

implementation: ArrayList < String > params = new ArrayList < String > ( ) ; boolean foundParam = false ; StringBuffer newSegment = new StringBuffer ( ) ; if ( savePathParams ( segment , newSegment , params ) ) { foundParam = true ; segment = newSegment . toString ( ) ; } String result = encodeFromArray ( segment , encoding , false ) ; result = encodeNonCodes ( result ) ; segment = result ; if ( foundParam ) { segment = pathParamReplacement ( segment , params ) ; } return segment ;


signature:
public class Encode { /** * Keep any valid encodings from string i . e . keep " % 2D " but don ' t keep " % p "
 * @ param segment
 * @ return */
public static String encodePathSaveEncodings ( String segment ) { } }

implementation: String result = encodeFromArray ( segment , pathEncoding , false ) ; result = encodeNonCodes ( result ) ; return result ;


signature:
public class Encode { /** * Keep any valid encodings from string i . e . keep " % 2D " but don ' t keep " % p "
 * @ param segment
 * @ return */
public static String encodePathSegmentSaveEncodings ( String segment ) { } }

implementation: String result = encodeFromArray ( segment , pathSegmentEncoding , false ) ; result = encodeNonCodes ( result ) ; return result ;


signature:
public class Encode { /** * Keep any valid encodings from string i . e . keep " % 2D " but don ' t keep " % p "
 * @ param segment
 * @ return */
public static String encodeQueryParamSaveEncodings ( String segment ) { } }

implementation: String result = encodeFromArray ( segment , queryNameValueEncoding , false ) ; result = encodeNonCodes ( result ) ; return result ;


signature:
public class Encode { /** * decode an encoded map
 * @ param map
 * @ return */
public static MultivaluedMap < String , String > decode ( MultivaluedMap < String , String > map ) { } }

implementation: MultivaluedMapImpl < String , String > decoded = new MultivaluedMapImpl < String , String > ( ) ; for ( Map . Entry < String , List < String > > entry : map . entrySet ( ) ) { List < String > values = entry . getValue ( ) ; for ( String value : values ) { try { decoded . add ( URLDecoder . decode ( entry . getKey ( ) , UTF_8 ) , URLDecoder . decode ( value , UTF_8 ) ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } } } return decoded ;


signature:
public class FastRandomForestPMMLProducer { /** * Builds a new { @ link org . dmg . pmml . Node PMML Node } from the given { @ link weka . classifiers . trees . RandomTree . Tree Weka Tree Node } .
 * @ param node The Id to give to the generted { @ link org . dmg . pmml . Node PMML Node } .
 * @ param nodeId The Id to give to the generted { @ link org . dmg . pmml . Node PMML Node } .
 * @ param parentPMMLNode The parent { @ link org . dmg . pmml . Node PMML Node } .
 * @ return The incremented Id given to recursively created { @ link org . dmg . pmml . Node PMML Nodes } . */
private static int buildTreeNode ( FastRandomTree node , int nodeId , Node parentPMMLNode ) { } }

implementation:
Instances instance = node . m_MotherForest . m_Info ; addScoreDistribution ( parentPMMLNode , node . m_ClassProbs , instance ) ; if ( node . m_Attribute == - 1 ) { // Leaf : Add the node ' s score .
parentPMMLNode . withScore ( leafScoreFromDistribution ( node . m_ClassProbs , instance ) ) ; return nodeId ; } Attribute attribute = instance . attribute ( node . m_Attribute ) ; if ( attribute . isNominal ( ) ) { return buildNominalNode ( attribute , node , nodeId , parentPMMLNode ) ; } else if ( attribute . isNumeric ( ) ) { return buildNumericNode ( attribute , node , nodeId , parentPMMLNode ) ; } else { throw new RuntimeException ( "Unsupported attribute type for: " + attribute ) ; }


signature:
public class ResourceClassProcessor { /** * Main method , creates API model from metadata
 * @ param resourceClasses
 * @ return */
public ServiceGroup createServiceGroup ( Set < ResourceClass > resourceClasses , ServiceGroup . ServiceGroupBuilder serviceGroupBuilder ) { } }

implementation: for ( ResourceClass resourceClass : resourceClasses ) { Logger . info ( "{0} processing started" , resourceClass . getClazz ( ) . getCanonicalName ( ) ) ; Service service = createResource ( resourceClass ) ; serviceGroupBuilder . service ( service ) ; Logger . info ( "{0} processing finished" , resourceClass . getClazz ( ) . getCanonicalName ( ) ) ; } return serviceGroupBuilder . build ( ) ;


signature:
public class JmsSendService { /** * curl - X PUT - H " Content - Type : application / json " - d ' { " name " : " deploy app " , " done " : true } ' http : / / localhost : 8080 / jms / todo /
 * @ param todo todo object
 * @ return true or throws an exception */
@ PUT ( value = "/todo/" , code = 202 ) public boolean send ( final Todo todo ) { } }

implementation: if ( ! sendQueue . isPresent ( ) ) { initSendQueue ( ) ; } try { sendQueue . ifPresent ( todoSendQueue -> todoSendQueue . send ( todo ) ) ; } catch ( JmsException ex ) { queue = Optional . empty ( ) ; sendQueue = Optional . empty ( ) ; initSendQueue ( ) ; sendQueue . ifPresent ( todoSendQueue -> todoSendQueue . send ( todo ) ) ; } return true ;


signature:
public class WekaManager { /** * Save dirty configurations to disk .
 * < p / > If saving configuration was not possible , a log is produced but no exception is thrown . */
private synchronized void saveConfiguration ( ) { } }

implementation:
for ( WekaModelConfig wekaModelConfig : modelConfigs . values ( ) ) { if ( wekaModelConfig . isDirty ( ) && wekaModelConfig . getModelConfig ( ) . isStoreModel ( ) ) { try { String modelConfigJson = mapper . writeValueAsString ( wekaModelConfig . getModelConfig ( ) ) ; // create a new file because this model has never been written
if ( wekaModelConfig . getHeader ( ) == null ) { File file = File . createTempFile ( wekaModelConfig . getId ( ) . toString ( ) , "." + WekaManagerConfig . HEADER_EXTENSION , wekaManagerConfig . getHeaderLocation ( ) ) ; wekaModelConfig . setHeader ( file ) ; } FileUtils . write ( ( wekaModelConfig ) . getHeader ( ) , modelConfigJson ) ; wekaModelConfig . setDirty ( false /* contents have been updated so the model is no longer dirty */
) ; } catch ( IOException e ) { logger . error ( "Could not store configuration for model '{}' (will continue to save others)" , wekaModelConfig . getId ( ) , e ) ; } } }


signature:
public class WekaManager { /** * Will save the configuration to file .
 * @ throws FOSException when there are IO problems writing the configuration to file */
@ Override public synchronized void close ( ) throws FOSException { } }

implementation: acceptThreadRunning = false ; if ( scorerHandler != null ) { scorerHandler . close ( ) ; } IOUtils . closeQuietly ( serverSocket ) ; saveConfiguration ( ) ;


signature:
public class WekaManager { /** * Returns a new { @ link com . feedzai . fos . api . ModelDescriptor } for the given { @ code model } and { @ code file } .
 * @ param model The { @ link Model } with the classifier .
 * @ param modelFile The file where the model will be saved .
 * @ return A new { @ link com . feedzai . fos . api . ModelDescriptor }
 * @ throws FOSException If the given { @ code model } is of an unknown instance . */
private ModelDescriptor getModelDescriptor ( Model model , File modelFile ) throws FOSException { } }

implementation: if ( model instanceof ModelBinary ) { return new ModelDescriptor ( ModelDescriptor . Format . BINARY , modelFile . getAbsolutePath ( ) ) ; } else if ( model instanceof ModelPMML ) { return new ModelDescriptor ( ModelDescriptor . Format . PMML , modelFile . getAbsolutePath ( ) ) ; } else { throw new FOSException ( "Unsupported Model type '" + model . getClass ( ) . getSimpleName ( ) + "'." ) ; }


signature:
public class WekaManager { /** * Trains the given { @ code classifier } using the given { @ link com . feedzai . fos . impl . weka . config . WekaModelConfig modelConfig }
 * and { @ link weka . core . Instances wekaInstances } .
 * @ param classIndex The index of the class .
 * @ param classifier The classifier to be trained .
 * @ param wekaInstances The training instances .
 * @ throws FOSException If it fails to train the classifier . */
private void trainClassifier ( int classIndex , Classifier classifier , Instances wekaInstances ) throws FOSException { } }

implementation: wekaInstances . setClassIndex ( classIndex == - 1 ? wekaInstances . numAttributes ( ) - 1 : classIndex ) ; try { classifier . buildClassifier ( wekaInstances ) ; } catch ( Exception e ) { throw new FOSException ( e . getMessage ( ) , e ) ; }


signature:
public class ClassifierFactory { /** * Make on object of the factory type .
 * Reads the { @ link Classifier } from file .
 * @ return a new classifier instance
 * @ throws WekaClassifierException when the object could not be read from file . */
@ Override @ NotNull public Classifier makeObject ( ) throws WekaClassifierException { } }

implementation: logger . debug ( "Creating classifier" ) ; File file = new File ( modelDescriptor . getModelFilePath ( ) ) ; checkArgument ( file . exists ( ) , "Source file '" + file . getAbsolutePath ( ) + "' must exist" ) ; long time = System . currentTimeMillis ( ) ; switch ( modelDescriptor . getFormat ( ) ) { case BINARY : try ( FileInputStream fileInputStream = new FileInputStream ( file ) ; BufferedInputStream bufferedInputStream = new BufferedInputStream ( fileInputStream , 1024 * 1024 ) ; ObjectInputStream objectInputStream = new ObjectInputStream ( bufferedInputStream ) ) { Classifier classifier = ( Classifier ) objectInputStream . readObject ( ) ; logger . debug ( "Loaded binary model {} in {} ms." , file . getPath ( ) , ( System . currentTimeMillis ( ) - time ) ) ; return classifier ; } catch ( IOException | ClassNotFoundException e ) { throw new WekaClassifierException ( e ) ; } case PMML : try { Classifier classifier = PMMLConsumers . consume ( file ) ; logger . debug ( "Loaded PMML model {} in {} ms." , file . getPath ( ) , ( System . currentTimeMillis ( ) - time ) ) ; return classifier ; } catch ( FOSException e ) { throw new WekaClassifierException ( "Failed to consume PMML file " + file . getAbsolutePath ( ) + "." , e ) ; } default : throw new WekaClassifierException ( "Unknown model type " + modelDescriptor . getFormat ( ) ) ; }


signature:
public class EventRemoteReplicatorService { /** * This message receives an event from a remote call . */
@ Override public void forwardEvent ( final EventTransferObject < Object > event ) { } }

implementation:
eventConnector . forwardEvent ( new EventTransferObject < Object > ( ) { @ Override public String channel ( ) { return event . channel ( ) ; } @ Override public long id ( ) { return event . id ( ) ; } @ Override public Object body ( ) { return event . body ( ) ; } @ Override public boolean isSingleton ( ) { return true ; } @ Override public MultiMap < String , String > params ( ) { return event . params ( ) ; } @ Override public MultiMap < String , String > headers ( ) { return event . headers ( ) ; } /* Save a map lookup or building a header map . */
@ Override public boolean wasReplicated ( ) { return true ; } @ SuppressWarnings ( "EqualsWhichDoesntCheckParameterClass" ) @ Override public boolean equals ( Object obj ) { // noinspection EqualsBetweenInconvertibleTypes
return event . equals ( obj ) ; } @ Override public int hashCode ( ) { return event . hashCode ( ) ; } } ) ;


signature:
public class FindAnnotation { /** * Returns an array of annotations the specified method of a resource class .
 * @ param method
 * @ return */
public static Annotation [ ] getResourcesAnnotations ( Method method ) { } }

implementation: Map < Class < ? > , Annotation > annotations = new HashMap < Class < ? > , Annotation > ( ) ; for ( Annotation annotation : method . getDeclaringClass ( ) . getAnnotations ( ) ) { annotations . put ( annotation . getClass ( ) , annotation ) ; } for ( Annotation annotation : method . getAnnotations ( ) ) { annotations . put ( annotation . getClass ( ) , annotation ) ; } return annotations . values ( ) . toArray ( new Annotation [ annotations . size ( ) ] ) ;


signature:
public class FindAnnotation { /** * Look for an annotation in a list of annotations . If not there , see if it
 * is on the type provided
 * @ param type
 * @ param annotations
 * @ param annnotation
 * @ return */
public static < T extends Annotation > T findAnnotation ( Class < ? > type , Annotation [ ] annotations , Class < T > annotation ) { } }

implementation: T config = FindAnnotation . findAnnotation ( annotations , annotation ) ; if ( config == null ) { config = type . getAnnotation ( annotation ) ; } return config ;


signature:
public class Main { /** * public static void mainArrayBlockingQueue ( String . . . args ) throws Exception { */
public static void mainArrayBlockingQueue ( String ... args ) throws Exception { } }

implementation: final int runs = 20 ; final int tradeCount = 5_000_000 ; final int batchSize = 125 ; int currentBatchSize = batchSize ; run ( runs , tradeCount , 1 ) ; run ( runs , tradeCount , batchSize ) ; for ( int index = 0 ; index < 10 ; index ++ ) { run ( runs , tradeCount , currentBatchSize ) ; currentBatchSize *= 2 ; }


signature:
public class Main { /** * public static void main ( String . . . args ) throws Exception { */
public static void mainTransferQueue ( String ... args ) throws Exception { } }

implementation: final int runs = 20 ; final int tradeCount = 5_000_000 ; final int batchSize = 50_000 ; final int checkEvery = 1000 ; int currentCheckEvery = checkEvery ; run ( runs , tradeCount , batchSize , 10 ) ; for ( int index = 0 ; index < 10 ; index ++ ) { run ( runs , tradeCount , batchSize , currentCheckEvery ) ; currentCheckEvery *= 2 ; }


signature:
public class ResourceBuilder { /** * Picks a constructor from an annotated resource class based on spec rules
 * @ param annotatedResourceClass
 * @ return */
public static ResourceConstructor constructor ( Class < ? > annotatedResourceClass ) { } }

implementation: Constructor constructor = PickConstructor . pickPerRequestConstructor ( annotatedResourceClass ) ; if ( constructor == null ) { throw new RuntimeException ( "Could not find constructor for class: " + annotatedResourceClass . getName ( ) ) ; } ResourceConstructorBuilder builder = rootResource ( annotatedResourceClass ) . constructor ( constructor ) ; if ( constructor . getParameterTypes ( ) != null ) { for ( int i = 0 ; i < constructor . getParameterTypes ( ) . length ; i ++ ) builder . param ( i ) . fromAnnotations ( ) ; } return builder . buildConstructor ( ) . buildClass ( ) . getConstructor ( ) ;


signature:
public class ResourceBuilder { /** * Build metadata from annotations on classes and methods
 * @ return */
public static ResourceClass rootResourceFromAnnotations ( Class < ? > clazz ) { } }

implementation: ResourceClass resourceClass = fromAnnotations ( false , clazz ) ; return resourceClass ;


signature:
public class ResourceBuilder { /** * Whether the given class is a proxy created by Weld or not . This is the
 * case if the given class implements the interface
 * { @ code org . jboss . weld . bean . proxy . ProxyObject } .
 * @ param clazz
 * the class of interest
 * @ return { @ code true } if the given class is a Weld proxy , { @ code false }
 * otherwise */
private static boolean isWeldProxy ( Class < ? > clazz ) { } }

implementation: for ( Class < ? > implementedInterface : clazz . getInterfaces ( ) ) { if ( implementedInterface . getName ( ) . equals ( WELD_PROXY_INTERFACE_NAME ) ) { return true ; } } return false ;


signature:
public class JmsConsumerService { /** * curl - X PUT http : / / localhost : 9090 / jms / todo /
 * @ return true or throws an exception */
@ PUT ( value = "/todo/" , code = 202 ) public Todo get ( ) { } }

implementation: if ( ! consumeQueue . isPresent ( ) ) { initConsumeQueue ( ) ; } Todo todo ; try { todo = consumeQueue . get ( ) . poll ( ) ; } catch ( JmsException ex ) { queue = Optional . empty ( ) ; consumeQueue = Optional . empty ( ) ; initConsumeQueue ( ) ; todo = consumeQueue . get ( ) . poll ( ) ; } return todo ;


signature:
public class RandomForestUtils { /** * Sets the classifiers in a bagging .
 * @ param bagging The bag for which to set the classifiers .
 * @ throws Exception If it fails to set the classifiers . */
public static void setupBaggingClassifiers ( IteratedSingleClassifierEnhancer bagging ) throws Exception { } }

implementation: bagging . m_Classifiers = Classifier . makeCopies ( bagging . m_Classifier , bagging . m_NumIterations ) ;


signature:
public class Parser { /** * selectors _ group
 * : selector [ COMMA S * selector ] * */
protected List < Selector > groups ( ) throws ParserException { } }

implementation: List < Selector > groups = new ArrayList < Selector > ( ) ; int groupNumber = 0 ; while ( ! end ( ) ) { ignoreWhitespaces ( ) ; parserListener . beginGroup ( groupNumber , pos ) ; Selector selector = selector ( ) ; groups . add ( selector ) ; parserListener . endGroup ( selector ) ; groupNumber ++ ; ignoreWhitespaces ( ) ; if ( ! end ( ) && current != ',' ) { throw new ParserException ( "There is something left in the selector at position " + pos ) ; } next ( ) ; } return groups ;


signature:
public class Parser { /** * selector
 * : simple _ selector _ sequence [ combinator simple _ selector _ sequence ] *
 * combinator
 * : PLUS S * | GREATER S * | TILDE S * | S + */
protected Selector selector ( ) throws ParserException { } }

implementation:
int initialPosition = pos ; StringBuilder sb = new StringBuilder ( ) ; List < SimpleSelectorSequence > simpleSelectors = new ArrayList < SimpleSelectorSequence > ( ) ; List < Combinator > combinators = new ArrayList < Combinator > ( ) ; int lastChar = pos ; while ( ! end ( ) ) { // finds combinator , but not in the first iteration
Combinator combinator = null ; if ( ! simpleSelectors . isEmpty ( ) ) { // stores if it has spaces until the next token
boolean hasWhitespace = false ; if ( ! end ( ) && Character . isWhitespace ( current ) ) { hasWhitespace = true ; ignoreWhitespaces ( ) ; } if ( ! end ( ) ) { // implements " combinator " rule
if ( current == '+' ) combinator = Combinator . ADJASCENT_SIBLING ; else if ( current == '>' ) combinator = Combinator . CHILD ; else if ( current == '~' ) combinator = Combinator . GENERAL_SIBLING ; // if hasn ' t any but spaces
else if ( hasWhitespace ) combinator = Combinator . DESCENDANT ; // is it the end ?
if ( combinator == null || current == ',' ) { break ; } // don ' t advance because spaces were just advanced
if ( combinator != Combinator . DESCENDANT ) { sb . append ( current ) ; next ( ) ; } else { sb . append ( ' ' ) ; } ignoreWhitespaces ( ) ; if ( end ( ) ) { throw new ParserException ( "Unexpected end of selector at position " + pos ) ; } } else { break ; } combinators . add ( combinator ) ; } // get next sequence
SimpleSelectorSequence simpleSelectorSequence = simpleSelectorSequence ( ) ; sb . append ( simpleSelectorSequence ) ; // sends combinator here ( the first case it ' s null )
simpleSelectors . add ( simpleSelectorSequence ) ; parserListener . selectorSequence ( simpleSelectorSequence , combinator ) ; lastChar = pos ; } return new Selector ( simpleSelectors , combinators , new Context ( content , sb . toString ( ) , initialPosition , lastChar ) ) ;


signature:
public class Parser { /** * simple _ selector _ sequence
 * : [ type _ selector | universal ]
 * [ HASH | class | attrib | pseudo | negation ] *
 * | [ HASH | class | attrib | pseudo | negation ] +
 * type _ selector
 * : [ namespace _ prefix ] ? element _ name
 * namespace _ prefix * * not implemented
 * : [ IDENT | ' * ' ] ? ' | '
 * element _ name
 * : IDENT
 * universal
 * : [ namespace _ prefix ] ? ' * '
 * class
 * : ' . ' IDENT */
protected SimpleSelectorSequence simpleSelectorSequence ( ) throws ParserException { } }

implementation:
List < SimpleSelector > simpleSelectorList = new ArrayList < SimpleSelector > ( ) ; StringBuilder sb = new StringBuilder ( ) ; boolean hasSimpleSelector = false ; int initialPos = pos ; if ( current == '*' ) { // universal selector
sb . append ( current ) ; hasSimpleSelector = true ; TypeSelector ts = new TypeSelector ( "*" , new Context ( content , "*" , initialPos , pos + 1 ) ) ; parserListener . typeSelector ( ts ) ; simpleSelectorList . add ( ts ) ; next ( ) ; } else if ( Character . isLetter ( current ) ) { // type selector
String type = identifier ( ) ; sb . append ( type ) ; hasSimpleSelector = true ; TypeSelector ts = new TypeSelector ( type , new Context ( content , type , initialPos , pos ) ) ; parserListener . typeSelector ( ts ) ; simpleSelectorList . add ( ts ) ; } int selectorCount = 0 ; boolean hasPseudoElement = false ; while ( ! end ( ) ) { int initialLoopPos = pos ; if ( current == '.' ) { // class selector
sb . append ( current ) ; next ( ) ; String className = ! end ( ) ? identifier ( ) : null ; if ( className == null || className . isEmpty ( ) ) { throw new ParserException ( "Expected className at position " + pos ) ; } sb . append ( className ) ; ClassSelector cs = new ClassSelector ( className , new Context ( content , "." + className , initialLoopPos , pos ) ) ; simpleSelectorList . add ( cs ) ; parserListener . classSelector ( cs ) ; } else if ( current == '#' ) { // hash selector
sb . append ( current ) ; next ( ) ; String id = ! end ( ) ? identifier ( ) : null ; if ( id == null || id . isEmpty ( ) ) { throw new ParserException ( "Expected id at position " + pos ) ; } HashSelector hs = new HashSelector ( id , new Context ( content , "#" + id , initialLoopPos , pos ) ) ; simpleSelectorList . add ( hs ) ; parserListener . idSelector ( hs ) ; sb . append ( id ) ; } else if ( current == '[' ) { // attribute selectors
sb . append ( current ) ; next ( ) ; AttributeSelector as = attribute ( ) ; simpleSelectorList . add ( as ) ; parserListener . attributeSelector ( as ) ; sb . append ( as ) ; sb . append ( ']' ) ; } else if ( current == ':' ) { // pseudo - element , pseudo - class or negation
sb . append ( current ) ; next ( ) ; if ( end ( ) ) { throw new ParserException ( "Expected pseudo-element or pseudo-class at " + pos ) ; } boolean doubleColon = false ; if ( current == ':' ) { doubleColon = true ; sb . append ( current ) ; next ( ) ; } String ident = ! end ( ) ? identifier ( ) : null ; if ( ident == null || ident . isEmpty ( ) ) { throw new ParserException ( "Expected identifier at position " + pos ) ; } boolean special = isPseudoSpecialCase ( ident ) ; if ( special || doubleColon ) { // pseudo - element ( double colon or special cases )
// allow just one
if ( hasPseudoElement ) { throw new ParserException ( "Only one pseudo-element is allowed for each simple selector and a second one was found at position " + pos ) ; } PseudoSelector ps = pseudo ( ident , PseudoType . PSEUDO_ELEMENT , doubleColon ) ; simpleSelectorList . add ( ps ) ; parserListener . pseudoSelector ( ps ) ; sb . append ( ps ) ; hasPseudoElement = true ; } else if ( "not" . equalsIgnoreCase ( ident ) ) { // negation
NegationSelector n = negation ( selectorCount ) ; simpleSelectorList . add ( n ) ; sb . append ( ident ) ; sb . append ( '(' ) ; sb . append ( n ) ; sb . append ( ')' ) ; } else { // pseudo - class
PseudoSelector ps = pseudo ( ident , PseudoType . PSEUDO_CLASS , false ) ; simpleSelectorList . add ( ps ) ; parserListener . pseudoSelector ( ps ) ; sb . append ( ps ) ; } } else { break ; } selectorCount ++ ; } if ( ! hasSimpleSelector && selectorCount == 0 ) { throw new ParserException ( "No real selector found at position " + pos ) ; } return new SimpleSelectorSequence ( simpleSelectorList , new Context ( content , sb . toString ( ) , initialPos , pos ) ) ;


signature:
public class Parser { /** * attrib
 * : ' [ ' S * [ namespace _ prefix ] ? IDENT S *
 * [ [ PREFIXMATCH |
 * SUFFIXMATCH |
 * SUBSTRINGMATCH |
 * INCLUDES |
 * DASHMATCH ] S * [ IDENT | STRING ] S * */
protected AttributeSelector attribute ( ) throws ParserException { } }

implementation:
int initialPos = pos ; StringBuilder sb = new StringBuilder ( ) ; ignoreWhitespaces ( ) ; String name = ! end ( ) ? identifier ( ) : null ; if ( name == null || name . isEmpty ( ) ) { throw new ParserException ( "Expected attribute name at position " + pos ) ; } sb . append ( name ) ; ignoreWhitespaces ( ) ; if ( end ( ) ) { throw new ParserException ( "Unexpected end of selector selector at position " + pos ) ; } AttributeOperator operator = null ; if ( current == '=' ) { operator = AttributeOperator . EQUALS ; next ( ) ; } else if ( current != ']' ) { if ( current == '~' ) operator = AttributeOperator . INCLUDES ; else if ( current == '|' ) operator = AttributeOperator . DASH_MATCH ; else if ( current == '^' ) operator = AttributeOperator . PREFIX_MATCH ; else if ( current == '$' ) operator = AttributeOperator . SUFFIX_MATCH ; else if ( current == '*' ) operator = AttributeOperator . SUBSTRING_MATCH ; else throw new ParserException ( "Invalid operator ('" + current + "') at position " + pos ) ; next ( ) ; if ( end ( ) || current != '=' ) { throw new ParserException ( "Expected '=' sign at position " + pos ) ; } next ( ) ; } ignoreWhitespaces ( ) ; if ( end ( ) ) { throw new ParserException ( "Unexpected end of attribute selector at position " + pos ) ; } // value
StringValue value = null ; if ( operator != null ) { sb . append ( operator . getSign ( ) ) ; if ( current == '\'' || current == '"' ) { char quote = current ; value = string ( ) ; sb . append ( quote ) ; sb . append ( value . getContext ( ) . toString ( ) ) ; sb . append ( quote ) ; } else { int identPos = pos ; String ident = identifier ( ) ; value = new StringValue ( new Context ( content , ident , identPos , pos ) , ident ) ; sb . append ( value ) ; } } ignoreWhitespaces ( ) ; // end of attribute
if ( end ( ) || current != ']' ) { throw new ParserException ( "Token ']' expected at position " + pos ) ; } int endPos = pos ; next ( ) ; return new AttributeSelector ( name , operator , value , new Context ( content , sb . toString ( ) , initialPos , endPos ) ) ;


signature:
public class Parser { /** * string { string1 } | { string2}
 * string1 \ " ( [ ^ \ n \ r \ f \ \ " ] | \ \ { nl } | { nonascii } | { escape } ) * \ "
 * string2 \ ' ( [ ^ \ n \ r \ f \ \ ' ] | \ \ { nl } | { nonascii } | { escape } ) * \ '
 * nonascii [ ^ \ 0 - \ 177]
 * escape { unicode } | \ \ [ ^ \ n \ r \ f0-9a - f ]
 * unicode \ \ [ 0-9a - f ] { 1,6 } ( \ r \ n | [ \ n \ r \ t \ f ] ) ?
 * nl \ n | \ r \ n | \ r | \ f */
protected StringValue string ( ) throws ParserException { } }

implementation:
Character openQuote = current ; int initialPosition = pos ; boolean escape = false ; next ( ) ; StringBuilder value = new StringBuilder ( ) ; StringBuilder string = new StringBuilder ( ) ; while ( ! end ( ) ) { if ( escape ) { // TODO implement UNICODE
if ( current == openQuote || current == '\\' ) { value . append ( current ) ; string . append ( current ) ; escape = false ; } else { throw new ParserException ( "Invalid escape character at position " + pos ) ; } } else { if ( current == openQuote ) break ; string . append ( current ) ; if ( current == '\\' ) { escape = true ; } else { value . append ( current ) ; } } next ( ) ; } if ( current != openQuote ) { throw new ParserException ( "String not closed!" ) ; } next ( ) ; return new StringValue ( new Context ( content , string . toString ( ) , initialPosition , pos ) , value . toString ( ) ) ;


signature:
public class Parser { /** * num [ 0-9 ] + | [ 0-9 ] * \ . [ 0-9 ] + */
protected String number ( ) throws ParserException { } }

implementation: StringBuilder sb = new StringBuilder ( ) ; sb . append ( current ) ; next ( ) ; boolean hasDot = false ; while ( ! end ( ) && ( Character . isDigit ( current ) || current == '.' ) ) { if ( current == '.' ) { if ( hasDot ) { throw new ParserException ( "Unexpected '.' at position " + pos ) ; } hasDot = true ; } sb . append ( current ) ; next ( ) ; } return sb . toString ( ) ;


signature:
public class Parser { /** * negation
 * : NOT S * negation _ arg S * ' ) '
 * negation _ arg
 * : type _ selector | universal | HASH | class | attrib | pseudo
 * TODO include " not " or not ? It would be necessary to use parameters */
protected NegationSelector negation ( int number ) throws ParserException { } }

implementation:
StringBuilder sb = new StringBuilder ( ) ; ignoreWhitespaces ( ) ; if ( end ( ) || current != '(' ) { throw new ParserException ( "Expected '(' at position " + pos ) ; } // sb . append ( current ) ;
int parenthesisPos = pos ; next ( ) ; ignoreWhitespaces ( ) ; if ( end ( ) ) { throw new ParserException ( "Selector expected at position " + pos ) ; } int initialPos = pos ; SimpleSelector simpleSelector = null ; if ( current == '*' ) { // universal selector
sb . append ( current ) ; TypeSelector ts = new TypeSelector ( "*" , new Context ( content , "*" , initialPos , pos + 1 ) ) ; parserListener . negationTypeSelector ( ts ) ; simpleSelector = ts ; next ( ) ; } else if ( Character . isLetter ( current ) ) { // type selector
String type = identifier ( ) ; sb . append ( type ) ; TypeSelector ts = new TypeSelector ( type , new Context ( content , type , initialPos , pos ) ) ; parserListener . negationTypeSelector ( ts ) ; simpleSelector = ts ; } else if ( current == '.' ) { // class selector
sb . append ( current ) ; next ( ) ; String className = ! end ( ) ? identifier ( ) : null ; if ( className == null || className . isEmpty ( ) ) { throw new ParserException ( "Expected className at position " + pos ) ; } ClassSelector cs = new ClassSelector ( className , new Context ( content , "." + className , initialPos , pos ) ) ; simpleSelector = cs ; parserListener . negationClassSelector ( cs ) ; sb . append ( className ) ; } else if ( current == '#' ) { // hash selector
sb . append ( current ) ; next ( ) ; String id = ! end ( ) ? identifier ( ) : null ; if ( id == null || id . isEmpty ( ) ) { throw new ParserException ( "Expected id at position " + pos ) ; } HashSelector hs = new HashSelector ( id , new Context ( content , "#" + id , initialPos , pos ) ) ; simpleSelector = hs ; parserListener . negationIdSelector ( hs ) ; sb . append ( id ) ; } else if ( current == '[' ) { // attribute selectors
sb . append ( current ) ; next ( ) ; AttributeSelector as = attribute ( ) ; simpleSelector = as ; parserListener . negationAttributeSelector ( as ) ; sb . append ( as . getContext ( ) ) ; sb . append ( ']' ) ; } else if ( current == ':' ) { // pseudo - class only
sb . append ( current ) ; next ( ) ; if ( end ( ) ) { throw new ParserException ( "Expected pseudo-element or pseudo-class at " + pos ) ; } boolean doubleColon = false ; if ( current == ':' ) { doubleColon = true ; sb . append ( current ) ; next ( ) ; } String ident = ! end ( ) ? identifier ( ) : null ; if ( ident == null || ident . isEmpty ( ) ) { throw new ParserException ( "Expected identifier at position " + pos ) ; } if ( "not" . equalsIgnoreCase ( ident ) || isPseudoSpecialCase ( ident ) || doubleColon ) { throw new ParserException ( "Expected pseudo-class (starting with ':', except ':not', ':first-line', ':first-letter', ':before' and ':after') at position " + pos ) ; } PseudoSelector ps = pseudo ( ident , PseudoType . PSEUDO_CLASS , doubleColon ) ; simpleSelector = ps ; parserListener . negationPseudoSelector ( ps ) ; sb . append ( ps . getContext ( ) ) ; } else { throw new ParserException ( "Selector expected at position " + pos ) ; } ignoreWhitespaces ( ) ; if ( end ( ) || current != ')' ) { throw new ParserException ( "Expected ')' at position " + pos ) ; } // sb . append ( current ) ;
next ( ) ; return new NegationSelector ( simpleSelector , new Context ( content , sb . toString ( ) , parenthesisPos , pos ) ) ;


signature:
public class Parser { /** * pseudo
 * / / ' : : ' starts a pseudo - element , ' : ' a pseudo - class
 * / / Exceptions : : first - line , : first - letter , : before and : after .
 * / / Note that pseudo - elements are restricted to one per selector and
 * / / occur only in the last simple _ selector _ sequence .
 * : ' : ' ' : ' ? [ IDENT | functional _ pseudo ]
 * functional _ pseudo
 * : FUNCTION S * expression ' ) ' */
protected PseudoSelector pseudo ( String ident , PseudoType type , boolean doubleColon ) throws ParserException { } }

implementation:
int initialPos = pos ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( ident ) ; PseudoExpression expression = null ; if ( ! end ( ) && current == '(' ) { sb . append ( current ) ; next ( ) ; ignoreWhitespaces ( ) ; if ( end ( ) ) { throw new ParserException ( "Expected expression at position " + pos ) ; } // expression
expression = expression ( ) ; sb . append ( expression . getContext ( ) ) ; // close parenthesis
ignoreWhitespaces ( ) ; if ( end ( ) || current != ')' ) { throw new ParserException ( "Expected ')' at position " + pos ) ; } sb . append ( current ) ; next ( ) ; } return new PseudoSelector ( ident , type , doubleColon , expression , new Context ( content , sb . toString ( ) , initialPos , pos ) ) ;


signature:
public class Parser { /** * expression
 * / / In CSS3 , the expressions are identifiers , strings ,
 * / / or of the form " an + b "
 * : [ [ PLUS | ' - ' | DIMENSION | NUMBER | STRING | IDENT ] S * ] +
 * { num } { ident } return DIMENSION ;
 * { num } return NUMBER ; */
protected PseudoExpression expression ( ) throws ParserException { } }

implementation:
List < Item > items = new ArrayList < Item > ( ) ; StringBuilder sb = new StringBuilder ( ) ; int initialPos = pos ; if ( current == '\'' || current == '"' ) { // string
Character quote = current ; StringValue s = string ( ) ; sb . append ( quote ) ; sb . append ( s . getContext ( ) . toString ( ) ) ; sb . append ( quote ) ; items . add ( new Item ( Type . STRING , s . getActualValue ( ) ) ) ; return new PseudoExpression ( items , null , s . getActualValue ( ) , new Context ( content , sb . toString ( ) , initialPos , pos ) ) ; } else { while ( ! end ( ) ) { if ( current == '+' ) { items . add ( new Item ( Type . SIGNAL , "+" ) ) ; sb . append ( current ) ; next ( ) ; } else if ( current == '-' ) { items . add ( new Item ( Type . SIGNAL , "-" ) ) ; sb . append ( current ) ; next ( ) ; } else if ( Character . isLetter ( current ) ) { // identifier
String ident = simpleIdentifier ( ) ; sb . append ( ident ) ; items . add ( new Item ( Type . IDENTIFIER , ident ) ) ; } else if ( Character . isDigit ( current ) ) { // number or dimension
String number = number ( ) ; sb . append ( number ) ; items . add ( new Item ( Type . NUMBER , number ) ) ; } else { break ; } ignoreWhitespaces ( ) ; } } return new PseudoExpression ( items , PseudoExpressionEvaluator . evaluate ( items ) , sb . toString ( ) , new Context ( content , sb . toString ( ) , initialPos , pos ) ) ;


signature:
public class Parser { /** * ident [ - ] ? { nmstart } { nmchar } *
 * name { nmchar } +
 * nmstart [ _ a - z ] | { nonascii } | { escape }
 * nonascii [ ^ \ 0 - \ 177]
 * unicode \ \ [ 0-9a - f ] { 1,6 } ( \ r \ n | [ \ n \ r \ t \ f ] ) ?
 * escape { unicode } | \ \ [ ^ \ n \ r \ f0-9a - f ]
 * nmchar [ _ a - z0-9 - ] | { nonascii } | { escape }
 * num [ 0-9 ] + | [ 0-9 ] * \ . [ 0-9 ] + */
protected String identifier ( ) throws ParserException { } }

implementation:
// TODO implement unicode , escape , [ - ] , nonascii
StringBuilder sb = new StringBuilder ( ) ; // validates first character
if ( ! end ( ) && ! Character . isLetter ( current ) && current != '_' ) { return "" ; } while ( ! end ( ) && ( Character . isLetterOrDigit ( current ) || current == '-' || current == '_' ) ) { sb . append ( current ) ; next ( ) ; } return sb . toString ( ) ;


signature:
public class Parser { /** * pseudo ( Special cases )
 * / / ' : : ' starts a pseudo - element , ' : ' a pseudo - class
 * / / Exceptions : : first - line , : first - letter , : before and : after . */
protected boolean isPseudoSpecialCase ( String identifier ) { } }

implementation: return "first-line" . equalsIgnoreCase ( identifier ) || "first-letter" . equalsIgnoreCase ( identifier ) || "before" . equalsIgnoreCase ( identifier ) || "after" . equalsIgnoreCase ( identifier ) ;


signature:
public class Cloner { /** * Gets a fresh clone of the object .
 * @ return a fresh clone
 * @ throws IOException when there were problems serializing the object
 * @ throws ClassNotFoundException when the serialized objects ' s class was not found */
@ NotNull public T get ( ) throws IOException , ClassNotFoundException { } }

implementation:
/* cannot be pre - instantiated to enable thread concurrency */
ByteArrayInputStream byteArrayInputStream = null ; ObjectInputStream objectInputStream = null ; try { byteArrayInputStream = new ByteArrayInputStream ( this . serializedObject ) ; objectInputStream = new ObjectInputStream ( byteArrayInputStream ) ; return ( T ) objectInputStream . readObject ( ) ; } finally { IOUtils . closeQuietly ( byteArrayInputStream ) ; IOUtils . closeQuietly ( objectInputStream ) ; }


signature:
public class Cloner { /** * Returns a copy of the serialized object .
 * @ return a copy ( this object is immutable ) */
@ NotNull public byte [ ] getSerialized ( ) { } }

implementation: byte [ ] result = new byte [ serializedObject . length ] ; System . arraycopy ( serializedObject , 0 , result , 0 , serializedObject . length ) ; return result ;


signature:
public class Cloner { /** * Writes the serialized object to file .
 * @ param file the file to write to ( will be overwritten )
 * @ throws IOException when the file could not be written */
public void write ( File file ) throws IOException { } }

implementation: checkNotNull ( file , "Output file cannot be null" ) ; FileUtils . writeByteArrayToFile ( file , serializedObject ) ;


signature:
public class RandomForestPMMLProducer { /** * Builds a { @ link org . dmg . pmml . Segment PMML Segment } that contains the { @ link org . dmg . pmml . TreeModel PMML TreeModel }
 * representing the given { @ link weka . classifiers . trees . RandomTree Weka RandomTree } .
 * @ param miningSchema The { @ link org . dmg . pmml . MiningSchema PMML MiningSchema } that lists fields as used in the model .
 * @ param segmentId The Id to given to the { @ link org . dmg . pmml . Segment PMML Segment element } .
 * @ param randomTree The { @ link weka . classifiers . trees . RandomTree Weka RandomTree } to be converted to a { @ link org . dmg . pmml . TreeModel PMML TreeModel } .
 * @ return The created { @ link org . dmg . pmml . Segment PMML Segment } . */
private static Segment buildSegment ( MiningSchema miningSchema , int segmentId , RandomTree randomTree ) { } }

implementation: int rootNodeId = 1 ; Node rootNode = new Node ( ) . withId ( String . valueOf ( rootNodeId ) ) . withPredicate ( new True ( ) ) ; TreeModel treeModel = new TreeModel ( miningSchema , rootNode , MiningFunctionType . CLASSIFICATION ) . withAlgorithmName ( ALGORITHM_NAME ) . withModelName ( MODEL_NAME ) . withSplitCharacteristic ( TreeModel . SplitCharacteristic . MULTI_SPLIT ) ; buildTreeNode ( randomTree , randomTree . m_Tree , rootNodeId , rootNode ) ; Segment segment = new Segment ( ) ; segment . withId ( String . valueOf ( segmentId ) ) ; segment . withModel ( treeModel ) ; return segment ;


signature:
public class RandomForestPMMLProducer { /** * Builds a new { @ link org . dmg . pmml . Node PMML Node } from the given { @ link RandomTree . Tree Weka Tree Node } .
 * @ param tree The { @ link weka . classifiers . trees . RandomTree Weka RandomTree } being converted to a { @ link org . dmg . pmml . PMML TreeModel } .
 * @ param node The Id to give to the generted { @ link org . dmg . pmml . Node PMML Node } .
 * @ param nodeId The Id to give to the generted { @ link org . dmg . pmml . Node PMML Node } .
 * @ param parentPMMLNode The parent { @ link org . dmg . pmml . Node PMML Node } .
 * @ return The incremented Id given to recursively created { @ link org . dmg . pmml . Node PMML Nodes } . */
private static int buildTreeNode ( RandomTree tree , RandomTree . Tree node , int nodeId , Node parentPMMLNode ) { } }

implementation:
addScoreDistribution ( parentPMMLNode , node . m_ClassDistribution , tree . m_Info ) ; if ( node . m_Attribute == - 1 ) { // Leaf : Add the node ' s score .
parentPMMLNode . withScore ( leafScoreFromDistribution ( node . m_ClassDistribution , tree . m_Info ) ) ; return nodeId ; } Attribute attribute = tree . m_Info . attribute ( node . m_Attribute ) ; if ( attribute . isNominal ( ) ) { return buildNominalNode ( tree , attribute , node , nodeId , parentPMMLNode ) ; } else if ( attribute . isNumeric ( ) ) { return buildNumericNode ( tree , attribute , node , nodeId , parentPMMLNode ) ; } else { throw new RuntimeException ( "Unsupported attribute type for: " + attribute ) ; }


signature:
public class RandomForestPMMLProducer { /** * Builds the { @ link org . dmg . pmml . Node PMML Node } for a nominal attribute .
 * In PMML these nodes are represented with multiple children , one for each of the attribute ' s values .
 * For example , consider a nominal attribute , named " nominalAttribute " , with values " cold " , " hot " and " warm " . In PMML this translates to :
 * < pre >
 * { @ code
 * < Node id = " 2 " score = " 1 " >
 * < SimplePredicate field = " nominalAttribute " operator = " equal " value = " cold " / >
 * < / Node >
 * < Node id = " 3 " score = " 0 " >
 * < SimplePredicate field = " nominalAttribute " operator = " equal " value = " hot " / >
 * < / Node >
 * < Node id = " 4 " score = " 1.5 " >
 * < SimplePredicate field = " nominalAttribute " operator = " equal " value = " warm " / >
 * < / Node >
 * < / pre >
 * @ param tree The { @ link weka . classifiers . trees . RandomTree Weka RandomTree } being converted to a { @ link org . dmg . pmml . PMML TreeModel } .
 * @ param attribute The { @ link weka . core . Attribute } to which the node to build refers to .
 * @ param node The { @ link weka . classifiers . trees . RandomTree . Tree Weka RandomTree node } we are converting to PMML .
 * @ param nodeId The Id to give to the generted { @ link org . dmg . pmml . Node PMML Node } .
 * @ param parentPMMLNode The parent { @ link org . dmg . pmml . Node PMML Node } .
 * @ return The incremented Id given to recursively created { @ link org . dmg . pmml . Node PMML Nodes } . */
private static int buildNominalNode ( RandomTree tree , Attribute attribute , RandomTree . Tree node , int nodeId , Node parentPMMLNode ) { } }

implementation:
List < Object > values = new ArrayList < > ( ) ; Enumeration enumeration = attribute . enumerateValues ( ) ; while ( enumeration . hasMoreElements ( ) ) { values . add ( enumeration . nextElement ( ) ) ; } assert values . size ( ) == node . m_Successors . length : "Number of successors expected to be the same as the number of attribute values" ; List < Node > children = new ArrayList < > ( ) ; for ( int i = 0 ; i < values . size ( ) ; i ++ ) { Object value = values . get ( i ) ; SimplePredicate predicate = new SimplePredicate ( new FieldName ( attribute . name ( ) ) , SimplePredicate . Operator . EQUAL ) . withValue ( String . valueOf ( value ) ) ; Node child = new Node ( ) . withId ( String . valueOf ( ++ nodeId ) ) . withPredicate ( predicate ) ; nodeId = buildTreeNode ( tree , node . m_Successors [ i ] , nodeId , child ) ; // Training proportion extension .
child . withExtensions ( new Extension ( ) . withName ( TRAINING_PROPORTION_ELEMENT ) . withValue ( String . valueOf ( node . m_Prop [ i ] ) ) ) ; children . add ( child ) ; } parentPMMLNode . withNodes ( children ) ; return nodeId ;


signature:
public class RandomForestPMMLProducer { /** * Builds the { @ link org . dmg . pmml . Node PMML Node } for a numeric attribute .
 * In PMML these nodes are represented having two children , each with a predicate that checks the node ' s split point .
 * For example , consider a numeric attribute , named " numericAttribute " , with a split point of 2.5 and two leaf nodes . In PMML this translates to :
 * < pre >
 * { @ code
 * < Node id = " 2 " score = " 1 " >
 * < SimplePredicate field = " numericAttribute " operator = " lessThan " value = " 2.5 " / >
 * < / Node >
 * < Node id = " 3 " score = " 0 " >
 * < SimplePredicate field = " numericAttribute " operator = " greaterOrEqual " value = " 2.5 " / >
 * < / Node >
 * < / pre >
 * @ param tree The { @ link weka . classifiers . trees . RandomTree Weka RandomTree } being converted to a { @ link org . dmg . pmml . PMML TreeModel } .
 * @ param attribute The { @ link weka . core . Attribute } to which the node to build refers to .
 * @ param node The { @ link weka . classifiers . trees . RandomTree . Tree Weka RandomTree node } we are converting to PMML .
 * @ param nodeId The Id to give to the generted { @ link org . dmg . pmml . Node PMML Node } .
 * @ param parentPMMLNode The parent { @ link org . dmg . pmml . Node PMML Node } .
 * @ return The incremented Id given to recursively created { @ link org . dmg . pmml . Node PMML Nodes } . */
private static int buildNumericNode ( RandomTree tree , Attribute attribute , RandomTree . Tree node , int nodeId , Node parentPMMLNode ) { } }

implementation:
SimplePredicate predicateLo = new SimplePredicate ( new FieldName ( attribute . name ( ) ) , SimplePredicate . Operator . LESS_THAN ) . withValue ( String . valueOf ( node . m_SplitPoint ) ) ; SimplePredicate predicateHi = new SimplePredicate ( new FieldName ( attribute . name ( ) ) , SimplePredicate . Operator . GREATER_OR_EQUAL ) . withValue ( String . valueOf ( node . m_SplitPoint ) ) ; Node nodeLo = new Node ( ) . withId ( String . valueOf ( ++ nodeId ) ) ; nodeLo . withPredicate ( predicateLo ) ; nodeId = buildTreeNode ( tree , node . m_Successors [ 0 ] , nodeId , nodeLo ) ; Node nodeHi = new Node ( ) . withId ( String . valueOf ( ++ nodeId ) ) ; nodeHi . withPredicate ( predicateHi ) ; nodeId = buildTreeNode ( tree , node . m_Successors [ 1 ] , nodeId , nodeHi ) ; // Training proportion extension .
nodeLo . withExtensions ( new Extension ( ) . withName ( TRAINING_PROPORTION_ELEMENT ) . withValue ( String . valueOf ( node . m_Prop [ 0 ] ) ) ) ; nodeHi . withExtensions ( new Extension ( ) . withName ( TRAINING_PROPORTION_ELEMENT ) . withValue ( String . valueOf ( node . m_Prop [ 1 ] ) ) ) ; parentPMMLNode . withNodes ( nodeLo , nodeHi ) ; return nodeId ;


signature:
public class RandomNumberExample { /** * This is the main class of the example client . I ' m using a { @ link CommandLineRunner CommandLineRunner } here to
 * keep the example simple , but this could be any spring bean that needs a QBit proxy injected .
 * @ param randomNumberServiceAsync this is the async service that is injected by Spring
 * @ return the runner instance . */
@ Bean public CommandLineRunner runner ( final RandomNumberServiceAsync randomNumberServiceAsync ) { } }

implementation: return args -> { for ( int i = 0 ; i < 100 ; i ++ ) { randomNumberServiceAsync . getRandom ( CallbackBuilder . newCallbackBuilder ( ) . withCallback ( n -> logger . info ( "Here's a random number: " + n ) ) . withErrorHandler ( e -> logger . error ( "blew up: " + e . getMessage ( ) ) ) . < Integer > build ( ) , 0 , 100 ) ; } } ;


signature:
public class PMMLConversionCommons { /** * Creates a new { @ link org . dmg . pmml . Header } element .
 * @ param description The description to have in the header .
 * @ return A new { @ link org . dmg . pmml . Header } element . */
public static Header buildPMMLHeader ( String description ) { } }

implementation: return new Header ( ) . withCopyright ( "www.dmg.org" ) . withDescription ( description ) . withApplication ( new Application ( "Feedzai FOS-Weka" ) . withVersion ( "1.0.4" ) ) ;


signature:
public class PMMLConversionCommons { /** * Adds a { @ link org . dmg . pmml . ScoreDistribution PMML ScoreDistribution element } to the given { @ link org . dmg . pmml . Node PMML Node }
 * with the confidence from the given { @ code classDistribution } .
 * @ param pmmlNode The { @ link org . dmg . pmml . Node PMML Node } to which add a { @ link org . dmg . pmml . ScoreDistribution PMML ScoreDistribution element } .
 * @ param classDistribution The class distribution to calculate a score for .
 * @ param instances The header { @ link weka . core . Instances } . */
public static void addScoreDistribution ( Node pmmlNode , double [ ] classDistribution , Instances instances ) { } }

implementation: if ( classDistribution != null ) { double sum = 0.0 ; for ( int i = 0 ; i < classDistribution . length ; i ++ ) { sum += classDistribution [ i ] ; } for ( int i = 0 ; i < classDistribution . length ; i ++ ) { String value = instances . classAttribute ( ) . value ( i ) ; double probability ; if ( sum != 0.0 ) { probability = classDistribution [ i ] / sum ; } else { probability = 1.0 / classDistribution . length ; } ScoreDistribution scoreDistribution = new ScoreDistribution ( value , 0 ) ; scoreDistribution . withConfidence ( classDistribution [ i ] ) ; scoreDistribution . withProbability ( probability ) ; pmmlNode . withScoreDistributions ( scoreDistribution ) ; } }


signature:
public class PMMLConversionCommons { /** * Retrieves a String representing the score of the given class distribution .
 * @ param classDistribution The class distribution to calculate a score for .
 * @ param instances The header { @ link weka . core . Instances } .
 * @ return A String representing the score of the given class distribution . */
public static String leafScoreFromDistribution ( double [ ] classDistribution , Instances instances ) { } }

implementation: double sum = 0 , maxCount = 0 ; int maxIndex = 0 ; if ( classDistribution != null ) { sum = Utils . sum ( classDistribution ) ; maxIndex = Utils . maxIndex ( classDistribution ) ; maxCount = classDistribution [ maxIndex ] ; } return instances . classAttribute ( ) . value ( maxIndex ) ;


signature:
public class PMMLConversionCommons { /** * Retrieves the class distribution for the given node .
 * We represent this in PMML as the confidence of a list of { @ link org . dmg . pmml . ScoreDistribution } elements .
 * @ param node The { @ link org . dmg . pmml . Node PMML node } for which to retrieve the class distribution .
 * @ return A array with the class distribution for the given node . */
public static double [ ] getClassDistribution ( Node node ) { } }

implementation: List < ScoreDistribution > scoreDistributions = node . getScoreDistributions ( ) ; double [ ] classDistribution = null ; if ( ! scoreDistributions . isEmpty ( ) ) { classDistribution = new double [ scoreDistributions . size ( ) ] ; for ( int i = 0 ; i < scoreDistributions . size ( ) ; i ++ ) { classDistribution [ i ] = scoreDistributions . get ( i ) . getConfidence ( ) ; } } return classDistribution ;


signature:
public class PMMLConversionCommons { /** * Retrieves the training proportion of the given node .
 * We represent this value in PMML as an { @ link org . dmg . pmml . Extension } element of the node .
 * @ param node The { @ link org . dmg . pmml . Node PMML node } for which to retrieve the training proportion .
 * @ return The training proportion of the given node . */
public static double getNodeTrainingProportion ( Node node ) { } }

implementation: for ( Extension extension : node . getExtensions ( ) ) { if ( TRAINING_PROPORTION_ELEMENT . equals ( extension . getName ( ) ) ) { return Double . valueOf ( extension . getValue ( ) ) ; } } return 0 ;


signature:
public class PMMLConversionCommons { /** * Retrieves the index of the class attribute . This is the attribute to be predicted .
 * @ param instances The { @ link weka . core . Instances } .
 * @ param treeModel The { @ link org . dmg . pmml . TreeModel PMML TreeModel element } .
 * @ return An int representing the index of the class attribute . */
public static int getClassIndex ( Instances instances , TreeModel treeModel ) { } }

implementation: MiningSchema miningModel = treeModel . getMiningSchema ( ) ; String className = null ; for ( MiningField miningField : miningModel . getMiningFields ( ) ) { if ( miningField . getUsageType ( ) == FieldUsageType . PREDICTED ) { className = miningField . getName ( ) . getValue ( ) ; break ; } } return instances . attribute ( className ) . index ( ) ;


signature:
public class PMMLConversionCommons { /** * Retrieves the index of the class attribute . This is the attribute to be predicted .
 * @ param instances The { @ link weka . core . Instances } .
 * @ param miningSchema The { @ link org . dmg . pmml . MiningSchema PMML MiningSchema element } .
 * @ return An int representing the index of the class attribute . */
public static int getClassIndex ( Instances instances , MiningSchema miningSchema ) { } }

implementation: String className = null ; for ( MiningField miningField : miningSchema . getMiningFields ( ) ) { if ( miningField . getUsageType ( ) == FieldUsageType . PREDICTED ) { className = miningField . getName ( ) . getValue ( ) ; break ; } } return instances . attribute ( className ) . index ( ) ;


signature:
public class PMMLConversionCommons { /** * Creates a new { @ link weka . core . Instances } instance from the attributes in a { @ link org . dmg . pmml . DataDictionary PMML DataDictionary } .
 * @ param dataDict The { @ link org . dmg . pmml . DataDictionary PMML DataDictionary } from which to build instances .
 * @ return A new { @ link weka . core . Instances } instance . */
public static Instances buildInstances ( DataDictionary dataDict ) { } }

implementation: List < weka . core . Attribute > attributes = buildAttributes ( dataDict ) ; FastVector fastVector = new FastVector ( attributes . size ( ) ) ; for ( weka . core . Attribute attribute : attributes ) { fastVector . addElement ( attribute ) ; } return new Instances ( "instances" , fastVector , attributes . size ( ) ) ;


signature:
public class PMMLConversionCommons { /** * Creates and returns { @ link weka . core . Attribute attributes } from a { @ link org . dmg . pmml . DataDictionary PMML DataDictionary } .
 * @ param dataDict The { @ link org . dmg . pmml . DataDictionary PMML DataDictionary } from which to build the attributes .
 * @ return A new immutable list of { @ link weka . core . Attribute attributes } . */
public static List < weka . core . Attribute > buildAttributes ( DataDictionary dataDict ) { } }

implementation: ImmutableList . Builder < weka . core . Attribute > attribuesBuilder = ImmutableList . builder ( ) ; for ( DataField dataField : dataDict . getDataFields ( ) ) { attribuesBuilder . add ( buildAttribute ( dataField ) ) ; } return attribuesBuilder . build ( ) ;


signature:
public class PMMLConversionCommons { /** * Creates a new { @ link weka . core . Attribute } from a { @ link org . dmg . pmml . DataField PMML DataField } .
 * @ param dataField The { @ link org . dmg . pmml . DataField PMML DataField } representing the attribute .
 * @ return A new { @ link weka . core . Attribute } . */
public static weka . core . Attribute buildAttribute ( DataField dataField ) { } }

implementation: switch ( dataField . getOptype ( ) ) { case CONTINUOUS : return new weka . core . Attribute ( dataField . getName ( ) . getValue ( ) ) ; case CATEGORICAL : List < Value > values = dataField . getValues ( ) ; FastVector nominalValues = new FastVector ( ) ; for ( Value value : values ) { nominalValues . addElement ( value . getValue ( ) ) ; } return new weka . core . Attribute ( dataField . getName ( ) . getValue ( ) , nominalValues ) ; default : throw new RuntimeException ( "PMML DataField OPTYPE " + dataField . getOptype ( ) + " not supported." ) ; }


signature:
public class PMMLConversionCommons { /** * Retrieves the { @ link org . dmg . pmml . MiningModel PMML MiningModel } element in a { @ link org . dmg . pmml . PMML } .
 * @ param pmml The { @ link org . dmg . pmml . PMML } from which to retrieve the { @ link org . dmg . pmml . MiningModel PMML MiningModel } .
 * @ return A { @ link org . dmg . pmml . MiningModel PMML MiningModel } . */
public static MiningModel getMiningModel ( PMML pmml ) { } }

implementation: for ( Model model : pmml . getModels ( ) ) { if ( model instanceof MiningModel ) { return ( MiningModel ) model ; } } throw new RuntimeException ( "PMML MiningModel not found." ) ;


signature:
public class JmsServiceBuilder { /** * If null , will build based on host , port and provider url pattern .
 * @ return providerURL
 * @ see JmsServiceBuilder # providerURL */
public String getProviderURL ( ) { } }

implementation: if ( providerURL == null ) { providerURL = getProviderURLPattern ( ) . replace ( "#host#" , getHost ( ) ) . replace ( "#port#" , Integer . toString ( getPort ( ) ) ) ; } return providerURL ;


signature:
public class JmsServiceBuilder { /** * Gets the initial JNDI context , if not set uses the jndi settings and ` initialContextFactory ` to create
 * a JNDI initial context .
 * @ return JNDI initial context .
 * @ see JmsServiceBuilder # context
 * @ see JmsServiceBuilder # initialContextFactory
 * @ see JmsServiceBuilder # jndiSettings */
public Context getContext ( ) { } }

implementation: if ( context == null ) { try { context = new InitialContext ( createProperties ( ) ) ; } catch ( NamingException e ) { throw new IllegalStateException ( "Unable to create context" , e ) ; } } return context ;


signature:
public class JmsServiceBuilder { /** * If the user name is set , use the user name and password to create the JMS connection .
 * @ return connection supplier
 * @ see JmsServiceBuilder # connectionSupplier */
public Supplier < Connection > getConnectionSupplier ( ) { } }

implementation: final boolean startConnection = isStartConnection ( ) ; if ( connectionSupplier == null ) { if ( getUserName ( ) == null ) { connectionSupplier = ( ) -> { try { final Connection connection = getConnectionFactory ( ) . createConnection ( ) ; if ( startConnection ) { connection . start ( ) ; } return connection ; } catch ( JMSException e ) { throw new JmsNotConnectedException ( "Unable to create context" , e ) ; } } ; } else { final String userName = getUserName ( ) ; final String password = getPassword ( ) ; connectionSupplier = ( ) -> { try { final Connection connection = getConnectionFactory ( ) . createConnection ( userName , password ) ; if ( startConnection ) { connection . start ( ) ; } return connection ; } catch ( JMSException e ) { throw new JmsNotConnectedException ( "Unable to create context for user " + userName , e ) ; } } ; } } return connectionSupplier ;


signature:
public class JmsServiceBuilder { /** * Used to construct properties for JMS JNDI context .
 * Populates with
 * properties . put ( Context . INITIAL _ CONTEXT _ FACTORY , getInitialContextFactory ( ) ) ;
 * properties . put ( Context . PROVIDER _ URL , getProviderURL ( ) ) ;
 * Then adds all of the setting in jndi settings .
 * @ return this */
private Hashtable < Object , Object > createProperties ( ) { } }

implementation: Hashtable < Object , Object > properties = new Hashtable < > ( ) ; properties . put ( Context . INITIAL_CONTEXT_FACTORY , getInitialContextFactory ( ) ) ; properties . put ( Context . PROVIDER_URL , getProviderURL ( ) ) ; if ( getJndiSettings ( ) != null ) { getJndiSettings ( ) . entrySet ( ) . forEach ( entry -> properties . put ( entry . getKey ( ) , entry . getValue ( ) ) ) ; } return properties ;


signature:
public class JmsServiceBuilder { /** * Build JMS Service
 * @ return new JMS Service */
public JmsService build ( ) { } }

implementation: return new JmsService ( getConnectionSupplier ( ) , getDestinationSupplier ( ) , isTransacted ( ) , getAcknowledgeMode ( ) , isStartConnection ( ) , getDefaultDestination ( ) , getDefaultTimeout ( ) ) ;


signature:
public class FastRandomForestPMMLConsumer { /** * Builds a new { @ link weka . classifiers . trees . RandomTree Weka RandomTree } from the given { @ link org . dmg . pmml . TreeModel PMML TreeModel } .
 * @ param motherForest The { @ link FastRandomForest } which is the mother of the tree to build . .
 * @ param treeModel The { @ link org . dmg . pmml . TreeModel PMML TreeModel } which is to be converted to a { @ link weka . classifiers . trees . RandomTree Weka RandomTree } .
 * @ return The same { @ code root } instance . */
private static FastRandomTree buildRandomTree ( FastRandomForest motherForest , TreeModel treeModel ) { } }

implementation: return buildRandomTreeNode ( motherForest , treeModel . getNode ( ) ) ;


signature:
public class JacksonToJrapidocProcessor { /** * From Jackson type creates a JRAPIDoc type , type is stored in cache
 * @ param jacksonType
 * @ return */
public Type getType ( SimpleType jacksonType ) { } }

implementation: try { String signature = JacksonSignature . createSignature ( jacksonType ) ; CustomType type = new CustomType ( jacksonType . getRawClass ( ) . getName ( ) , signature , jacksonType . getRawClass ( ) ) ; if ( cache . containsKey ( signature ) ) { return cache . get ( signature ) ; } cache . put ( signature , type ) ; ObjectWriter objectWriter = objectMapper . writerFor ( jacksonType ) ; Field prefetchField = objectWriter . getClass ( ) . getDeclaredField ( "_prefetch" ) ; prefetchField . setAccessible ( true ) ; ObjectWriter . Prefetch prefetch = ( ObjectWriter . Prefetch ) prefetchField . get ( objectWriter ) ; doIntrospection ( prefetch . valueSerializer , type ) ; return type ; } catch ( NoSuchFieldException e ) { e . printStackTrace ( ) ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } return null ;


signature:
public class JacksonToJrapidocProcessor { /** * Same as { @ link # getType ( com . fasterxml . jackson . databind . type . SimpleType ) }
 * @ param jacksonType
 * @ return */
public Type getType ( CollectionLikeType jacksonType ) { } }

implementation:
// try {
String signature = JacksonSignature . createSignature ( jacksonType ) ; JavaType contentType = jacksonType . getContentType ( ) ; String contentSignature = JacksonSignature . createSignature ( contentType ) ; Class < ? > containerClass = jacksonType . getRawClass ( ) ; CollectionTypeJrapidoc type = new CollectionTypeJrapidoc ( containerClass . getName ( ) , signature , contentType . getRawClass ( ) . getName ( ) , contentSignature ) ; if ( cache . containsKey ( signature ) ) { return cache . get ( signature ) ; } cache . put ( signature , type ) ; getType ( jacksonType . getContentType ( ) ) ; return type ;


signature:
public class JacksonToJrapidocProcessor { /** * Same as { @ link # getType ( com . fasterxml . jackson . databind . type . SimpleType ) }
 * @ param jacksonType
 * @ return */
public Type getType ( MapLikeType jacksonType ) { } }

implementation: String signature = JacksonSignature . createSignature ( jacksonType ) ; JavaType keyType = jacksonType . getKeyType ( ) ; JavaType valueType = jacksonType . getContentType ( ) ; Class < ? > containerClass = jacksonType . getRawClass ( ) ; String keySignature = JacksonSignature . createSignature ( keyType ) ; String valSignature = JacksonSignature . createSignature ( valueType ) ; MapTypeJrapidoc type = new MapTypeJrapidoc ( containerClass . getName ( ) , signature , keyType . getRawClass ( ) . getName ( ) , keySignature , valueType . getRawClass ( ) . getName ( ) , valSignature ) ; if ( cache . containsKey ( signature ) ) { return cache . get ( signature ) ; } cache . put ( signature , type ) ; getType ( keyType ) ; getType ( valueType ) ; return type ;


signature:
public class JacksonToJrapidocProcessor { /** * Do redirection from general Jackson type to the concrete one
 * @ param type
 * jackson type
 * @ return JRAPIDoc type */
public Type getType ( JavaType type ) { } }

implementation: if ( type instanceof SimpleType ) { return getType ( ( SimpleType ) type ) ; } else if ( type instanceof CollectionType ) { return getType ( ( CollectionLikeType ) type ) ; } else if ( type instanceof ArrayType ) { return getType ( ( ArrayType ) type ) ; } else if ( type instanceof MapLikeType ) { return getType ( ( MapLikeType ) type ) ; } throw new RuntimeException ( "Unimplemented Jackson type: " + type ) ;


signature:
public class JacksonToJrapidocProcessor { /** * Do redirection from general Jackson serializer to the concrete one
 * @ param serializer
 * @ param type */
private void doIntrospection ( JsonSerializer serializer , Type type ) { } }

implementation: if ( serializer == null ) { return ; } if ( EnumSerializer . class . isAssignableFrom ( serializer . getClass ( ) ) ) { introspectSerializer ( ( EnumSerializer ) serializer , ( CustomType ) type ) ; } else if ( BeanSerializerBase . class . isAssignableFrom ( serializer . getClass ( ) ) ) { introspectSerializer ( ( BeanSerializerBase ) serializer , ( CustomType ) type ) ; } else if ( StdScalarSerializer . class . isAssignableFrom ( serializer . getClass ( ) ) ) { introspectSerializer ( ( StdScalarSerializer ) serializer , ( CustomType ) type ) ; } else if ( AsArraySerializerBase . class . isAssignableFrom ( serializer . getClass ( ) ) ) { introspectSerializer ( ( AsArraySerializerBase ) serializer , ( CollectionTypeJrapidoc ) type ) ; } else if ( MapSerializer . class . isAssignableFrom ( serializer . getClass ( ) ) ) { introspectSerializer ( ( MapSerializer ) serializer , ( MapTypeJrapidoc ) type ) ; }


signature:
public class JacksonToJrapidocProcessor { /** * Introspect serializer for java beans
 * @ param beanSerializer
 * @ param type */
private void introspectSerializer ( BeanSerializerBase beanSerializer , CustomType type ) { } }

implementation: try { Field propsField = beanSerializer . getClass ( ) . getSuperclass ( ) . getDeclaredField ( "_props" ) ; propsField . setAccessible ( true ) ; BeanPropertyWriter [ ] props = ( BeanPropertyWriter [ ] ) propsField . get ( beanSerializer ) ; for ( BeanPropertyWriter prop : props ) { JavaType propType = prop . getType ( ) ; getType ( propType ) ; String signature = JacksonSignature . createSignature ( propType ) ; type . addBeanProperty ( new BeanProperty ( prop . getName ( ) , signature , prop . getPropertyType ( ) , prop . getMetadata ( ) . getDescription ( ) , prop . getMetadata ( ) . isRequired ( ) ) ) ; } } catch ( NoSuchFieldException e ) { e . printStackTrace ( ) ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; }


signature:
public class JacksonToJrapidocProcessor { /** * Introspect serializer for enumerations
 * @ param enumSerializer
 * @ param type */
private void introspectSerializer ( EnumSerializer enumSerializer , CustomType type ) { } }

implementation: for ( SerializableString value : enumSerializer . getEnumValues ( ) . values ( ) ) { type . addEnumeration ( value . getValue ( ) ) ; }


signature:
public class JacksonToJrapidocProcessor { /** * Introspect serializer for map
 * @ param mapSerializer
 * @ param type */
private void introspectSerializer ( MapSerializer mapSerializer , MapTypeJrapidoc type ) { } }

implementation: try { Field keyTypeField = mapSerializer . getClass ( ) . getDeclaredField ( "_keyType" ) ; keyTypeField . setAccessible ( true ) ; JavaType keyType = ( JavaType ) keyTypeField . get ( mapSerializer ) ; JavaType valueType = mapSerializer . getContentType ( ) ; getType ( keyType ) ; getType ( valueType ) ; } catch ( NoSuchFieldException e ) { e . printStackTrace ( ) ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; }


signature:
public class SmppServerResourceAdaptor { /** * Protected */
protected void startNewSmppServerTransactionActivity ( SmppTransactionImpl txImpl ) throws ActivityAlreadyExistsException , NullPointerException , IllegalStateException , SLEEException , StartActivityException { } }

implementation: sleeEndpoint . startActivity ( txImpl . getActivityHandle ( ) , txImpl , ActivityFlags . REQUEST_ENDED_CALLBACK ) ; DelayedActivityEndTask activityEndTask = new DelayedActivityEndTask ( tracer , this , txImpl , raContext . getTimer ( ) ) ; activityEndTasks . put ( txImpl , activityEndTask ) ; SmppManagement smppManagemet = SmppManagement . getInstance ( ) ; int delay = smppManagemet . getSmppServerManagement ( ) . getSmppActivityTimeout ( ) ; activityEndTask . schedule ( delay , TimeUnit . SECONDS ) ;


signature:
public class SmppServerResourceAdaptor { /** * Private methods */
protected void fireEvent ( String eventName , ActivityHandle handle , Object event ) { } }

implementation: FireableEventType eventID = eventIdCache . getEventId ( this . eventLookup , eventName ) ; if ( eventID == null ) { tracer . severe ( "Event id for " + eventID + " is unknown, cant fire!!!" ) ; } else { try { sleeEndpoint . fireEvent ( handle , eventID , event , address , null ) ; } catch ( UnrecognizedActivityHandleException e ) { this . tracer . severe ( "Error while firing event" , e ) ; } catch ( IllegalEventException e ) { this . tracer . severe ( "Error while firing event" , e ) ; } catch ( ActivityIsEndingException e ) { this . tracer . severe ( "Error while firing event" , e ) ; } catch ( NullPointerException e ) { this . tracer . severe ( "Error while firing event" , e ) ; } catch ( SLEEException e ) { this . tracer . severe ( "Error while firing event" , e ) ; } catch ( FireEventException e ) { this . tracer . severe ( "Error while firing event" , e ) ; } }


signature:
public class TradeOrderProc { /** * Get customer , customer account , and broker information */
private void frame1 ( ) { } }

implementation:
// SELECT acct _ name = ca _ name , broker _ id = ca _ b _ id ,
// cust _ id = ca _ c _ id , tax _ status = ca _ tax _ st FROM
// customer _ account WHERE ca _ id = acct _ id
String sql = "SELECT ca_name, ca_b_id, ca_c_id, ca_tax_st FROM customer_account" + " WHERE ca_id = " + paramHelper . getAcctId ( ) ; Scan s = executeQuery ( sql ) ; acctName = ( String ) s . getVal ( "ca_name" ) . asJavaVal ( ) ; brokerId = ( Long ) s . getVal ( "ca_b_id" ) . asJavaVal ( ) ; custId = ( Long ) s . getVal ( "ca_c_id" ) . asJavaVal ( ) ; taxStatus = ( Integer ) s . getVal ( "ca_tax_st" ) . asJavaVal ( ) ; // TODO : Add this
// num _ found = row _ count
// SELECT cust _ f _ name = c _ f _ name , cust _ l _ name = c _ l _ name ,
// cust _ tier = c _ tier , tax _ id = c _ tax _ id FROM
// customer WHERE c _ id = cust _ id
sql = "SELECT c_f_name, c_l_name, c_tier, c_tax_id FROM customer" + " WHERE c_id = " + custId ; s = executeQuery ( sql ) ; custFName = ( String ) s . getVal ( "c_f_name" ) . asJavaVal ( ) ; custLName = ( String ) s . getVal ( "c_l_name" ) . asJavaVal ( ) ; custTier = ( Integer ) s . getVal ( "c_tier" ) . asJavaVal ( ) ; taxId = ( String ) s . getVal ( "c_tax_id" ) . asJavaVal ( ) ; // SELECT broker _ name = b _ name FROM broker WHERE b _ id = broker _ id
sql = "SELECT b_name FROM broker WHERE b_id = " + brokerId ; s = executeQuery ( sql ) ; brokerName = ( String ) s . getVal ( "b_name" ) . asJavaVal ( ) ;


signature:
public class TradeOrderProc { /** * Estimate overall effects of the trade */
private void frame3 ( ) { } }

implementation:
// = = = = = Simplified Version = = = = =
// SELECT co _ id = s _ co _ id , exch _ id = s _ ex _ id , s _ name = s _ name
// FROM security WHERE s _ symb = symbol
String sql = "SELECT s_co_id, s_ex_id, s_name FROM security WHERE " + "s_symb = " + paramHelper . getSymbol ( ) ; Scan s = executeQuery ( sql ) ; coId = ( Long ) s . getVal ( "s_co_id" ) . asJavaVal ( ) ; exchId = ( String ) s . getVal ( "s_ex_id" ) . asJavaVal ( ) ; sName = ( String ) s . getVal ( "s_name" ) . asJavaVal ( ) ; // SELECT market _ price = lt _ price FROM last _ trade
// WHERE lt _ s _ symb = symbol
sql = "SELECT lt_price FROM last_trade WHERE " + "lt_s_symb = " + paramHelper . getSymbol ( ) ; s = executeQuery ( sql ) ; marketPrice = ( Double ) s . getVal ( "lt_price" ) . asJavaVal ( ) ; // SELECT type _ is _ market = tt _ is _ mrkt , type _ is _ sell = tt _ is _ sell
// FROM trade _ type WHERE tt _ id = trade _ type _ id
sql = "SELECT tt_is_mrkt, tt_is_sell FROM trade_type WHERE " + "tt_id = " + paramHelper . getTradeTypeId ( ) ; s = executeQuery ( sql ) ; typeIsMarket = ( Integer ) s . getVal ( "tt_is_mrkt" ) . asJavaVal ( ) ; typeIsSell = ( Integer ) s . getVal ( "tt_is_sell" ) . asJavaVal ( ) ; if ( typeIsMarket == 1 ) { statusId = "A" ; } else { statusId = "B" ; } // TODO : Implement this version
// = = = = = Full Version = = = = =
// Get information on the security
if ( true ) { // SELECT co _ id = co _ id FROM company WHERE co _ name = co _ name
// SELECT exch _ id = s _ ex _ id , s _ name = s _ name , symbol = s _ symb
// FROM security WHERE s _ co _ id = co _ id AND s _ issue = issue
} else { // SELECT co _ id = s _ co _ id , exch _ id = s _ ex _ id , s _ name = s _ name
// FROM security WHERE s _ symb = symbol
// SELECT co _ name = co _ name FROM company WHERE co _ id = co _ id
} // Get current pricing information for the security
// SELECT market _ price = lt _ price FROM last _ trade
// WHERE lt _ s _ symb = symbol
// Set trade characteristics based on the type of trade
// SELECT type _ is _ market = tt _ is _ mrkt , type _ is _ sell = tt _ is _ sell
// FROM trade _ type WHERE tt _ id = trade _ type _ id
// If this is a limit - order , then the requested _ price was passed in to the frame ,
// but if this a market - order , then the requested _ price needs to be set to the
// current market price .
// if ( type _ is _ market ) then {
// requested _ price = market _ price
// TODO : Estimation