idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
7,400
private static final void processCellUnaryRules ( final CnfGrammar grammar , final int start , final int end , final ChartCell cell , final Scorer scorer ) { ScoresSnapshot scoresSnapshot = cell . getScoresSnapshot ( ) ; int [ ] nts = cell . getNts ( ) ; for ( final int parentNt : nts ) { for ( final Rule r : grammar . getUnaryRulesWithChild ( parentNt ) ) { double score = scorer . score ( r , start , end , end ) + scoresSnapshot . getScore ( r . getLeftChild ( ) ) ; cell . updateCell ( r . getParent ( ) , score , end , r ) ; } } }
Process a cell unary rules only .
7,401
public NaryTree getLeafAt ( int idx ) { NaryTree leaf = null ; for ( NaryTree l : this . getLeaves ( ) ) { if ( l . start <= idx && idx < l . end ) { leaf = l ; } } return leaf ; }
Gets the leaf containing the specified token index .
7,402
public static LinkVar [ ] getVarsByDist ( int head , boolean isRight , LinkVar [ ] rootVars , LinkVar [ ] [ ] childVars ) { int dir = isRight ? 1 : - 1 ; int maxDist = isRight ? rootVars . length - head - 1 : head - 1 ; LinkVar [ ] varsByDist = new LinkVar [ maxDist ] ; for ( int cDist = 1 ; cDist <= maxDist ; cDist ++ ) { int c = head + dir * cDist ; if ( head == - 1 ) { varsByDist [ cDist - 1 ] = rootVars [ c ] ; } else { varsByDist [ cDist - 1 ] = childVars [ head ] [ c ] ; } } return varsByDist ; }
Gets the variables for this factor ordered from the head outward .
7,403
public VarTensor getMarginal ( VarSet vars , boolean normalize ) { VarSet margVars = new VarSet ( this . vars ) ; margVars . retainAll ( vars ) ; VarTensor marg = new VarTensor ( s , margVars , s . zero ( ) ) ; if ( margVars . size ( ) == 0 ) { return marg ; } IntIter iter = margVars . getConfigIter ( this . vars ) ; for ( int i = 0 ; i < this . values . length ; i ++ ) { int j = iter . next ( ) ; marg . values [ j ] = s . plus ( marg . values [ j ] , this . values [ i ] ) ; } if ( normalize ) { marg . normalize ( ) ; } return marg ; }
Gets the marginal distribution over a subset of the variables in this factor optionally normalized .
7,404
public void add ( VarTensor f ) { VarTensor newFactor = applyBinOp ( this , f , new AlgebraLambda . Add ( ) ) ; internalSet ( newFactor ) ; }
Adds a factor to this one .
7,405
public void prod ( VarTensor f ) { VarTensor newFactor = applyBinOp ( this , f , new AlgebraLambda . Prod ( ) ) ; internalSet ( newFactor ) ; }
Multiplies a factor to this one .
7,406
private void internalSet ( VarTensor newFactor ) { this . vars = newFactor . vars ; this . dims = newFactor . dims ; this . strides = newFactor . strides ; this . values = newFactor . values ; }
This set method is used to internally update ALL the fields .
7,407
private static VarTensor applyBinOp ( final VarTensor f1 , final VarTensor f2 , final AlgebraLambda . LambdaBinOp op ) { checkSameAlgebra ( f1 , f2 ) ; Algebra s = f1 . s ; if ( f1 . vars . size ( ) == 0 ) { return new VarTensor ( f2 ) ; } else if ( f2 . vars . size ( ) == 0 ) { return f1 ; } else if ( f1 . vars == f2 . vars || f1 . vars . equals ( f2 . vars ) ) { assert ( f1 . values . length == f2 . values . length ) ; for ( int c = 0 ; c < f1 . values . length ; c ++ ) { f1 . values [ c ] = op . call ( s , f1 . values [ c ] , f2 . values [ c ] ) ; } return f1 ; } else if ( f1 . vars . isSuperset ( f2 . vars ) ) { IntIter iter2 = f2 . vars . getConfigIter ( f1 . vars ) ; int n = f1 . vars . calcNumConfigs ( ) ; for ( int c = 0 ; c < n ; c ++ ) { f1 . values [ c ] = op . call ( s , f1 . values [ c ] , f2 . values [ iter2 . next ( ) ] ) ; } assert ( ! iter2 . hasNext ( ) ) ; return f1 ; } else { VarSet union = new VarSet ( f1 . vars , f2 . vars ) ; VarTensor out = new VarTensor ( s , union ) ; IntIter iter1 = f1 . vars . getConfigIter ( union ) ; IntIter iter2 = f2 . vars . getConfigIter ( union ) ; int n = out . vars . calcNumConfigs ( ) ; for ( int c = 0 ; c < n ; c ++ ) { out . values [ c ] = op . call ( s , f1 . values [ iter1 . next ( ) ] , f2 . values [ iter2 . next ( ) ] ) ; } assert ( ! iter1 . hasNext ( ) ) ; assert ( ! iter2 . hasNext ( ) ) ; return out ; } }
Applies the binary operator to factors f1 and f2 .
7,408
private static void elemApplyBinOp ( final VarTensor f1 , final VarTensor f2 , final AlgebraLambda . LambdaBinOp op ) { checkSameAlgebra ( f1 , f2 ) ; Algebra s = f1 . s ; if ( f1 . size ( ) != f2 . size ( ) ) { throw new IllegalArgumentException ( "VarTensors are different sizes" ) ; } for ( int c = 0 ; c < f1 . values . length ; c ++ ) { f1 . values [ c ] = op . call ( s , f1 . values [ c ] , f2 . values [ c ] ) ; } }
Applies the operation to each element of f1 and f2 which are assumed to be of the same size . The result is stored in f1 .
7,409
public double evaluate ( List < VarConfig > goldConfigs , List < VarConfig > predictedConfigs ) { int numCorrect = 0 ; int numTotal = 0 ; assert ( goldConfigs . size ( ) == predictedConfigs . size ( ) ) ; for ( int i = 0 ; i < goldConfigs . size ( ) ; i ++ ) { VarConfig gold = goldConfigs . get ( i ) ; VarConfig pred = predictedConfigs . get ( i ) ; for ( Var v : gold . getVars ( ) ) { if ( v . getType ( ) == VarType . PREDICTED ) { int goldState = gold . getState ( v ) ; int predState = pred . getState ( v ) ; if ( goldState == predState ) { numCorrect ++ ; } numTotal ++ ; } } } return ( double ) numCorrect / numTotal ; }
Computes the accuracy on the PREDICTED variables .
7,410
public void updateFromModel ( FgModel model ) { initialized = true ; int numConfigs = this . getVars ( ) . calcNumConfigs ( ) ; for ( int c = 0 ; c < numConfigs ; c ++ ) { double dot = getDotProd ( c , model ) ; assert ! Double . isNaN ( dot ) && dot != Double . POSITIVE_INFINITY : "Invalid value for factor: " + dot ; this . setValue ( c , dot ) ; } }
If this factor depends on the model this method will updates this factor s internal representation accordingly .
7,411
public static Tensor getVectorFromReals ( Algebra s , double ... values ) { Tensor t0 = getVectorFromValues ( RealAlgebra . getInstance ( ) , values ) ; return t0 . copyAndConvertAlgebra ( s ) ; }
Gets a tensor in the s semiring where the input values are assumed to be in the reals .
7,412
public int getConfigIndexOfSubset ( VarSet vars ) { int configIndex = 0 ; int numStatesProd = 1 ; for ( int v = vars . size ( ) - 1 ; v >= 0 ; v -- ) { Var var = vars . get ( v ) ; int state = config . get ( var ) ; configIndex += state * numStatesProd ; numStatesProd *= var . getNumStates ( ) ; if ( numStatesProd <= 0 ) { throw new IllegalStateException ( "Integer overflow when computing config index -- this can occur if trying to compute the index of a high arity factor: " + numStatesProd ) ; } } return configIndex ; }
Gets the index of this configuration for the given variable set .
7,413
public void put ( VarConfig other ) { this . config . putAll ( other . config ) ; this . vars . addAll ( other . vars ) ; }
Sets all variable assignments in other .
7,414
public void put ( Var var , String stateName ) { int state = var . getState ( stateName ) ; if ( state == - 1 ) { throw new IllegalArgumentException ( "Unknown state name " + stateName + " for var " + var ) ; } put ( var , state ) ; }
Sets the state value to stateName for the given variable adding it if necessary .
7,415
public void put ( Var var , int state ) { if ( state < 0 || state >= var . getNumStates ( ) ) { throw new IllegalArgumentException ( "Invalid state idx " + state + " for var " + var ) ; } config . put ( var , state ) ; vars . add ( var ) ; }
Sets the state value to state for the given variable adding it if necessary .
7,416
public VarConfig getSubset ( VarSet subsetVars ) { if ( ! vars . isSuperset ( subsetVars ) ) { throw new IllegalStateException ( "This config does not contain all the given variables." ) ; } return getIntersection ( subsetVars ) ; }
Gets a new variable configuration that contains only a subset of the variables .
7,417
public VarConfig getIntersection ( Iterable < Var > otherVars ) { VarConfig subset = new VarConfig ( ) ; for ( Var v : otherVars ) { Integer state = config . get ( v ) ; if ( state != null ) { subset . put ( v , state ) ; } } return subset ; }
Gets a new variable configuration that keeps only variables in otherVars .
7,418
public void accum ( FgModel model , int i , Accumulator ac ) { try { accumWithException ( model , i , ac ) ; } catch ( Throwable t ) { log . error ( "Skipping example " + i + " due to throwable: " + t . getMessage ( ) ) ; t . printStackTrace ( ) ; } }
Assumed by caller to be threadsafe .
7,419
private ISFSObject createResponseParams ( ) { return ResponseParamsBuilder . create ( ) . addition ( addition ) . excludedVars ( excludedVars ) . includedVars ( includedVars ) . transformer ( new ParamTransformer ( context ) ) . data ( data ) . build ( ) ; }
Create smartfox object to response to client
7,420
public LFgExample get ( int i ) { LFgExample ex ; synchronized ( cache ) { ex = cache . get ( i ) ; } if ( ex == null ) { ex = exampleFactory . get ( i ) ; synchronized ( cache ) { cache . put ( i , ex ) ; } } return ex ; }
Gets the i th example .
7,421
public void updateStartEnd ( ) { ArrayList < IntBinaryTree > leaves = getLeaves ( ) ; for ( int i = 0 ; i < leaves . size ( ) ; i ++ ) { IntBinaryTree leaf = leaves . get ( i ) ; leaf . start = i ; leaf . end = i + 1 ; } postOrderTraversal ( new UpdateStartEnd ( ) ) ; }
Updates all the start end fields treating the current node as the root .
7,422
public ArrayList < IntBinaryTree > getLeaves ( ) { LeafCollector leafCollector = new LeafCollector ( ) ; postOrderTraversal ( leafCollector ) ; return leafCollector . leaves ; }
Gets the leaves of this tree .
7,423
public SmallSet < E > diff ( SmallSet < E > other ) { SmallSet < E > tmp = new SmallSet < E > ( this . size ( ) - other . size ( ) ) ; Sort . diffSortedLists ( this . list , other . list , tmp . list ) ; return tmp ; }
Gets a new SmallSet containing the difference of this set with the other .
7,424
public V get ( Object key ) { if ( super . containsKey ( key ) ) { return super . get ( key ) ; } else { @ SuppressWarnings ( "unchecked" ) K k = ( K ) key ; V v = makeDefault . apply ( k ) ; put ( k , v ) ; return v ; } }
If the key isn t in the dictionary the makeDefault function will be called to create a new value which will be added
7,425
public static Object deserialize ( byte [ ] bytes , boolean gzipOnSerialize ) { try { InputStream is = new ByteArrayInputStream ( bytes ) ; if ( gzipOnSerialize ) { is = new GZIPInputStream ( is ) ; } ObjectInputStream in = new ObjectInputStream ( is ) ; Object inObj = in . readObject ( ) ; in . close ( ) ; return inObj ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( e ) ; } }
Deserialize and ungzip an object .
7,426
public static byte [ ] serialize ( Serializable obj , boolean gzipOnSerialize ) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; ObjectOutputStream out ; if ( gzipOnSerialize ) { out = new ObjectOutputStream ( new GZIPOutputStream ( baos ) ) ; } else { out = new ObjectOutputStream ( baos ) ; } out . writeObject ( obj ) ; out . flush ( ) ; out . close ( ) ; return baos . toByteArray ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }
Serializes and gzips an object .
7,427
@ SuppressWarnings ( { "unchecked" , "rawtypes" } ) static final < R > Comparator < Cell < R > > comparator ( ) { return ( Comparator < Cell < R > > ) ( Comparator ) COMPARATOR ; }
Compare by row then column .
7,428
private void scheduleOneTime ( TaskScheduler scheduler ) { scheduledFuture = scheduler . schedule ( runnable , ( int ) delayTime , TimeUnit . MILLISECONDS ) ; }
Schedule one short
7,429
public SFSDataWrapper transform ( Object value ) { if ( value == null ) return transformNullValue ( value ) ; return transformNotNullValue ( value ) ; }
Transform the value to SFSDataWrapper object
7,430
protected SFSDataWrapper transformArrayObject ( Object value ) { int length = ArrayUtils . getLength ( value ) ; if ( length == 0 ) return new SFSDataWrapper ( SFSDataType . NULL , null ) ; ISFSArray sfsarray = new SFSArray ( ) ; for ( Object obj : ( Object [ ] ) value ) sfsarray . add ( transform ( obj ) ) ; return new SFSDataWrapper ( SFSDataType . SFS_ARRAY , sfsarray ) ; }
Transform a java pojo object array to sfsarray
7,431
protected SFSDataWrapper transformObject ( Object value ) { ResponseParamsClass struct = null ; if ( context != null ) struct = context . getResponseParamsClass ( value . getClass ( ) ) ; if ( struct == null ) struct = new ResponseParamsClass ( value . getClass ( ) ) ; ISFSObject sfsObject = new ResponseParamSerializer ( ) . object2params ( struct , value ) ; return new SFSDataWrapper ( SFSDataType . SFS_OBJECT , sfsObject ) ; }
Transform a java pojo object to sfsobject
7,432
@ SuppressWarnings ( "unchecked" ) protected SFSDataWrapper transformCollection ( Object value ) { Collection < ? > collection = ( Collection < ? > ) value ; if ( collection . isEmpty ( ) ) return new SFSDataWrapper ( SFSDataType . NULL , value ) ; Iterator < ? > it = collection . iterator ( ) ; Object firstItem = it . next ( ) ; if ( firstItem . getClass ( ) . isArray ( ) ) return transformArrayCollection ( collection ) ; if ( isObject ( firstItem . getClass ( ) ) ) return transformObjectCollection ( ( Collection < ? > ) value ) ; if ( firstItem instanceof Boolean ) return new SFSDataWrapper ( SFSDataType . BOOL_ARRAY , value ) ; if ( firstItem instanceof Byte ) return new SFSDataWrapper ( SFSDataType . BYTE_ARRAY , collectionToPrimitiveByteArray ( ( Collection < Byte > ) value ) ) ; if ( firstItem instanceof Character ) return new SFSDataWrapper ( SFSDataType . BYTE_ARRAY , charCollectionToPrimitiveByteArray ( ( Collection < Character > ) value ) ) ; if ( firstItem instanceof Double ) return new SFSDataWrapper ( SFSDataType . DOUBLE_ARRAY , value ) ; if ( firstItem instanceof Float ) return new SFSDataWrapper ( SFSDataType . FLOAT_ARRAY , value ) ; if ( firstItem instanceof Integer ) return new SFSDataWrapper ( SFSDataType . INT_ARRAY , value ) ; if ( firstItem instanceof Long ) return new SFSDataWrapper ( SFSDataType . LONG_ARRAY , value ) ; if ( firstItem instanceof Short ) return new SFSDataWrapper ( SFSDataType . SHORT_ARRAY , value ) ; if ( firstItem instanceof String ) return new SFSDataWrapper ( SFSDataType . UTF_STRING_ARRAY , value ) ; throw new IllegalArgumentException ( "Can not transform value of " + value . getClass ( ) ) ; }
Transform a collection of value to SFSDataWrapper object
7,433
protected Transformer findTransformer ( Class < ? > clazz ) { Transformer answer = transformers . get ( clazz ) ; if ( answer == null ) throw new IllegalArgumentException ( "Can not transform value of " + clazz ) ; return answer ; }
Find transformer of a type
7,434
protected void initWithWrapperType ( ) { transformers . put ( Boolean . class , new Transformer ( ) { public SFSDataWrapper transform ( Object value ) { return new SFSDataWrapper ( SFSDataType . BOOL , value ) ; } } ) ; transformers . put ( Byte . class , new Transformer ( ) { public SFSDataWrapper transform ( Object value ) { return new SFSDataWrapper ( SFSDataType . BYTE , value ) ; } } ) ; transformers . put ( Character . class , new Transformer ( ) { public SFSDataWrapper transform ( Object value ) { return new SFSDataWrapper ( SFSDataType . BYTE , ( byte ) ( ( Character ) value ) . charValue ( ) ) ; } } ) ; transformers . put ( Double . class , new Transformer ( ) { public SFSDataWrapper transform ( Object value ) { return new SFSDataWrapper ( SFSDataType . DOUBLE , value ) ; } } ) ; transformers . put ( Float . class , new Transformer ( ) { public SFSDataWrapper transform ( Object value ) { return new SFSDataWrapper ( SFSDataType . FLOAT , value ) ; } } ) ; transformers . put ( Integer . class , new Transformer ( ) { public SFSDataWrapper transform ( Object value ) { return new SFSDataWrapper ( SFSDataType . INT , value ) ; } } ) ; transformers . put ( Long . class , new Transformer ( ) { public SFSDataWrapper transform ( Object value ) { return new SFSDataWrapper ( SFSDataType . LONG , value ) ; } } ) ; transformers . put ( Short . class , new Transformer ( ) { public SFSDataWrapper transform ( Object value ) { return new SFSDataWrapper ( SFSDataType . SHORT , value ) ; } } ) ; }
Add transformers of wrapper type to the map
7,435
protected void initWithPrimitiveTypeArray ( ) { transformers . put ( boolean [ ] . class , new Transformer ( ) { public SFSDataWrapper transform ( Object value ) { return new SFSDataWrapper ( SFSDataType . BOOL_ARRAY , primitiveArrayToBoolCollection ( ( boolean [ ] ) value ) ) ; } } ) ; transformers . put ( byte [ ] . class , new Transformer ( ) { public SFSDataWrapper transform ( Object value ) { return new SFSDataWrapper ( SFSDataType . BYTE_ARRAY , value ) ; } } ) ; transformers . put ( char [ ] . class , new Transformer ( ) { public SFSDataWrapper transform ( Object value ) { return new SFSDataWrapper ( SFSDataType . BYTE_ARRAY , charArrayToByteArray ( ( char [ ] ) value ) ) ; } } ) ; transformers . put ( double [ ] . class , new Transformer ( ) { public SFSDataWrapper transform ( Object value ) { return new SFSDataWrapper ( SFSDataType . DOUBLE_ARRAY , primitiveArrayToDoubleCollection ( ( double [ ] ) value ) ) ; } } ) ; transformers . put ( float [ ] . class , new Transformer ( ) { public SFSDataWrapper transform ( Object value ) { return new SFSDataWrapper ( SFSDataType . FLOAT_ARRAY , primitiveArrayToFloatCollection ( ( float [ ] ) value ) ) ; } } ) ; transformers . put ( int [ ] . class , new Transformer ( ) { public SFSDataWrapper transform ( Object value ) { return new SFSDataWrapper ( SFSDataType . INT_ARRAY , primitiveArrayToIntCollection ( ( int [ ] ) value ) ) ; } } ) ; transformers . put ( long [ ] . class , new Transformer ( ) { public SFSDataWrapper transform ( Object value ) { return new SFSDataWrapper ( SFSDataType . LONG_ARRAY , primitiveArrayToLongCollection ( ( long [ ] ) value ) ) ; } } ) ; transformers . put ( short [ ] . class , new Transformer ( ) { public SFSDataWrapper transform ( Object value ) { return new SFSDataWrapper ( SFSDataType . SHORT_ARRAY , primitiveArrayToShortCollection ( ( short [ ] ) value ) ) ; } } ) ; }
Add transformers of array of primitive values to the map
7,436
protected void initWithWrapperTypArray ( ) { transformers . put ( Boolean [ ] . class , new Transformer ( ) { public SFSDataWrapper transform ( Object value ) { return new SFSDataWrapper ( SFSDataType . BOOL_ARRAY , wrapperArrayToCollection ( ( Boolean [ ] ) value ) ) ; } } ) ; transformers . put ( Byte [ ] . class , new Transformer ( ) { public SFSDataWrapper transform ( Object value ) { return new SFSDataWrapper ( SFSDataType . BYTE_ARRAY , toPrimitiveByteArray ( ( Byte [ ] ) value ) ) ; } } ) ; transformers . put ( Character [ ] . class , new Transformer ( ) { public SFSDataWrapper transform ( Object value ) { return new SFSDataWrapper ( SFSDataType . BYTE_ARRAY , charWrapperArrayToPrimitiveByteArray ( ( Character [ ] ) value ) ) ; } } ) ; transformers . put ( Double [ ] . class , new Transformer ( ) { public SFSDataWrapper transform ( Object value ) { return new SFSDataWrapper ( SFSDataType . DOUBLE_ARRAY , wrapperArrayToCollection ( ( Double [ ] ) value ) ) ; } } ) ; transformers . put ( Float [ ] . class , new Transformer ( ) { public SFSDataWrapper transform ( Object value ) { return new SFSDataWrapper ( SFSDataType . FLOAT_ARRAY , wrapperArrayToCollection ( ( Float [ ] ) value ) ) ; } } ) ; transformers . put ( Integer [ ] . class , new Transformer ( ) { public SFSDataWrapper transform ( Object value ) { return new SFSDataWrapper ( SFSDataType . INT_ARRAY , wrapperArrayToCollection ( ( Integer [ ] ) value ) ) ; } } ) ; transformers . put ( Long [ ] . class , new Transformer ( ) { public SFSDataWrapper transform ( Object value ) { return new SFSDataWrapper ( SFSDataType . LONG_ARRAY , wrapperArrayToCollection ( ( Long [ ] ) value ) ) ; } } ) ; transformers . put ( Short [ ] . class , new Transformer ( ) { public SFSDataWrapper transform ( Object value ) { return new SFSDataWrapper ( SFSDataType . SHORT_ARRAY , wrapperArrayToCollection ( ( Short [ ] ) value ) ) ; } } ) ; }
Add transformers of array of wrapper values to the map
7,437
protected void initWithStringType ( ) { transformers . put ( String . class , new Transformer ( ) { public SFSDataWrapper transform ( Object value ) { return new SFSDataWrapper ( SFSDataType . UTF_STRING , value ) ; } } ) ; transformers . put ( String [ ] . class , new Transformer ( ) { public SFSDataWrapper transform ( Object value ) { return new SFSDataWrapper ( SFSDataType . UTF_STRING_ARRAY , stringArrayToCollection ( ( String [ ] ) value ) ) ; } } ) ; }
Add transformer of string and transformer of array of strings to the map
7,438
private Room getSfsRoom ( ) { if ( StringUtils . isEmpty ( roomName ) ) return extension . getParentZone ( ) . getRoomById ( roomId ) ; return CommandUtil . getSfsRoom ( roomName , extension ) ; }
Get smartfox room reference by name
7,439
private ISFSObject getMessage ( ) { if ( messageObject != null ) { MessageParamsClass clazz = context . getMessageParamsClass ( messageObject . getClass ( ) ) ; if ( clazz != null ) return new ResponseParamSerializer ( ) . object2params ( clazz . getUnwrapper ( ) , messageObject ) ; } if ( jsonMessage != null ) return SFSObject . newFromJsonData ( jsonMessage ) ; if ( messageString == null ) return new SFSObject ( ) ; ISFSObject answer = new SFSObject ( ) ; answer . putUtfString ( APIKey . MESSAGE , messageString ) ; return answer ; }
Create smartfox parameter object from a POJO object or json string or string
7,440
public static < T > Iterator < T > cycle ( Iterator < T > itr , int times ) { final List < T > items = ( times != 0 ) ? Lists . newLinkedList ( iterable ( itr ) ) : Collections . emptyList ( ) ; return new Iterator < T > ( ) { private Iterator < T > currentItr = Collections . emptyIterator ( ) ; private int ncalls = 0 ; private Iterator < T > getItr ( ) { if ( ! currentItr . hasNext ( ) && ncalls < times ) { currentItr = items . iterator ( ) ; ncalls ++ ; } return currentItr ; } public boolean hasNext ( ) { return getItr ( ) . hasNext ( ) ; } public T next ( ) { return getItr ( ) . next ( ) ; } } ; }
Returns an iterator cycles over the elements in items repeat times ; if repeat < 0 then this cycles indefinitely if repeat == 0 then the iterator is an empty iterator
7,441
public static ArrayList < Integer > getSiblingsOf ( int [ ] parents , int idx ) { int parent = parents [ idx ] ; ArrayList < Integer > siblings = new ArrayList < Integer > ( ) ; for ( int i = 0 ; i < parents . length ; i ++ ) { if ( parents [ i ] == parent ) { siblings . add ( i ) ; } } return siblings ; }
Gets the siblings of the specified word .
7,442
public static boolean containsCycle ( int [ ] parents ) { for ( int i = 0 ; i < parents . length ; i ++ ) { int numAncestors = 0 ; int parent = parents [ i ] ; while ( parent != ParentsArray . WALL_POSITION ) { numAncestors += 1 ; if ( numAncestors > parents . length - 1 ) { return true ; } parent = parents [ parent ] ; } } return false ; }
Checks if a dependency tree represented as a parents array contains a cycle .
7,443
public static boolean isProjective ( int [ ] parents ) { for ( int i = 0 ; i < parents . length ; i ++ ) { int pari = ( parents [ i ] == ParentsArray . WALL_POSITION ) ? parents . length : parents [ i ] ; int minI = i < pari ? i : pari ; int maxI = i > pari ? i : pari ; for ( int j = 0 ; j < parents . length ; j ++ ) { if ( j == i ) { continue ; } int parj = ( parents [ j ] == ParentsArray . WALL_POSITION ) ? parents . length : parents [ j ] ; if ( minI < j && j < maxI ) { if ( ! ( minI <= parj && parj <= maxI ) ) { return false ; } } else { if ( ! ( parj <= minI || parj >= maxI ) ) { return false ; } } } } return true ; }
Checks that a dependency tree represented as a parents array is projective .
7,444
public static int countChildrenOf ( int [ ] parents , int parent ) { int count = 0 ; for ( int i = 0 ; i < parents . length ; i ++ ) { if ( parents [ i ] == parent ) { count ++ ; } } return count ; }
Counts of the number of children in a dependency tree for the given parent index .
7,445
public static IntArrayList getChildrenOf ( int [ ] parents , int parent ) { IntArrayList children = new IntArrayList ( ) ; for ( int i = 0 ; i < parents . length ; i ++ ) { if ( parents [ i ] == parent ) { children . add ( i ) ; } } return children ; }
Gets the children of the specified parent .
7,446
public static boolean isAncestor ( int idx1 , int idx2 , int [ ] parents ) { int anc = parents [ idx2 ] ; while ( anc != - 1 ) { if ( anc == idx1 ) { return true ; } anc = parents [ anc ] ; } return false ; }
Checks whether idx1 is the ancestor of idx2 . If idx1 is the parent of idx2 this will return true but if idx1 == idx2 it will return false .
7,447
public static List < Pair < Integer , Dir > > getDependencyPath ( int start , int end , int [ ] parents ) { int n = parents . length ; if ( start < - 1 || start >= n || end < - 1 || end >= n ) { throw new IllegalArgumentException ( String . format ( "Invalid start/end: %d/%d" , start , end ) ) ; } IntHashSet endAncSet = new IntHashSet ( ) ; IntArrayList endAncList = new IntArrayList ( ) ; int curPos = end ; while ( curPos != ParentsArray . WALL_POSITION && curPos != - 2 && ! endAncSet . contains ( curPos ) ) { endAncSet . add ( curPos ) ; endAncList . add ( curPos ) ; curPos = parents [ curPos ] ; } if ( curPos != - 1 ) { return null ; } endAncSet . add ( curPos ) ; endAncList . add ( curPos ) ; List < Pair < Integer , Dir > > path = new ArrayList < Pair < Integer , Dir > > ( ) ; IntHashSet startAncSet = new IntHashSet ( ) ; curPos = start ; while ( ! endAncSet . contains ( curPos ) && curPos != - 2 && ! startAncSet . contains ( curPos ) ) { path . add ( new Pair < Integer , Dir > ( curPos , Dir . UP ) ) ; startAncSet . add ( curPos ) ; curPos = parents [ curPos ] ; } if ( ! endAncSet . contains ( curPos ) ) { return null ; } int lca = curPos ; int lcaIndex = endAncList . lookupIndex ( lca ) ; for ( int i = lcaIndex ; i > 0 ; i -- ) { path . add ( new Pair < Integer , Dir > ( endAncList . get ( i ) , Dir . DOWN ) ) ; } path . add ( new Pair < Integer , Dir > ( end , Dir . NONE ) ) ; return path ; }
Gets the shortest dependency path between two tokens .
7,448
public static < T > List < T > toposort ( T root , Deps < T > deps ) { List < T > order = new ArrayList < T > ( ) ; HashSet < T > done = new HashSet < T > ( ) ; Stack < T > todo = new Stack < T > ( ) ; HashSet < T > ancestors = new HashSet < T > ( ) ; todo . push ( root ) ; while ( ! todo . isEmpty ( ) ) { T x = todo . peek ( ) ; boolean ready = true ; for ( T y : deps . getDeps ( x ) ) { if ( ! done . contains ( y ) ) { ready = false ; todo . push ( y ) ; } } if ( ready ) { todo . pop ( ) ; ancestors . remove ( x ) ; if ( done . add ( x ) ) { order . add ( x ) ; } } else { if ( ancestors . contains ( x ) ) { throw new IllegalStateException ( "Graph is not a DAG. Cycle involves node: " + x ) ; } ancestors . add ( x ) ; } } return order ; }
Gets a topological sort for the graph .
7,449
public static < T > Deps < T > getCutoffDeps ( final Set < T > inputSet , final Deps < T > deps ) { Deps < T > cutoffDeps = new Deps < T > ( ) { public Collection < T > getDeps ( T x ) { HashSet < T > pruned = new HashSet < T > ( deps . getDeps ( x ) ) ; pruned . removeAll ( inputSet ) ; return pruned ; } } ; return cutoffDeps ; }
Gets a new Deps graph where each node in the input set is removed from the graph .
7,450
public static < T > void checkAreDescendentsOf ( Set < T > inputSet , T root , Deps < T > deps ) { HashSet < T > visited = new HashSet < T > ( ) ; dfs ( root , visited , deps ) ; if ( ! visited . containsAll ( inputSet ) ) { throw new IllegalStateException ( "Input set contains modules which are not descendents of the output module: " + inputSet ) ; } }
Checks that the given inputSet consists of only descendents of the root .
7,451
public static < T > void checkIsFullCut ( Set < T > inputSet , T root , Deps < T > deps ) { HashSet < T > visited = new HashSet < T > ( ) ; visited . addAll ( inputSet ) ; HashSet < T > leaves = dfs ( root , visited , deps ) ; if ( leaves . size ( ) != 0 ) { throw new IllegalStateException ( "Input set is not a valid leaf set for the given output module. Extra leaves: " + leaves ) ; } }
Checks that the given inputSet defines a full cut through the graph rooted at the given root .
7,452
public static < T > HashSet < T > getLeaves ( T root , Deps < T > deps ) { return dfs ( root , new HashSet < T > ( ) , deps ) ; }
Gets the leaves in DFS order .
7,453
public SparseGraph reversed ( ) { SparseGraph reverse = new SparseGraph ( ) ; for ( Entry < Integer , Set < Integer > > entryFrom : edges . entrySet ( ) ) for ( Integer to : entryFrom . getValue ( ) ) reverse . addEdge ( to , entryFrom . getKey ( ) ) ; return reverse ; }
Build and return a sparse graph by reversing all edges in this graph .
7,454
protected void addServerEventHandlers ( ) { Map < Object , Class < ? > > handlers = getServerEventHandlers ( ) ; Set < Entry < Object , Class < ? > > > entries = handlers . entrySet ( ) ; for ( Entry < Object , Class < ? > > entry : entries ) { SFSEventType type = SFSEventType . valueOf ( entry . getKey ( ) . toString ( ) ) ; ServerEventHandler handler = createServerEventHandler ( type , entry . getValue ( ) ) ; addEventHandler ( type , handler ) ; } }
Add server event handlers
7,455
private ServerEventHandler createServerEventHandler ( SFSEventType type , Class < ? > clazz ) { try { return ( ServerEventHandler ) ReflectClassUtil . newInstance ( clazz , BaseAppContext . class , context ) ; } catch ( ExtensionException e ) { getLogger ( ) . error ( "Error when create server event handlers" , e ) ; throw new RuntimeException ( "Can not create event handler of class " + clazz , e ) ; } }
Create server event handler by type and handler class
7,456
public void addSysControllerFilters ( ) { for ( SystemRequest rq : SystemRequest . values ( ) ) { ISystemFilterChain filterChain = new SysControllerFilterChain ( ) ; filterChain . addFilter ( "EzyFoxFilterChain#" + rq , new BaseSysControllerFilter ( appContext ( ) , rq ) ) ; getParentZone ( ) . setFilterChain ( rq , filterChain ) ; } }
Add System Controller Filters
7,457
public double toReal ( double x ) { double unsignedReal = FastMath . exp ( natlog ( x ) ) ; return ( sign ( x ) == POSITIVE ) ? unsignedReal : - unsignedReal ; }
Converts a compacted number to its real value .
7,458
public double fromReal ( double x ) { long sign = POSITIVE ; if ( x < 0 ) { sign = NEGATIVE ; x = - x ; } return compact ( sign , FastMath . log ( x ) ) ; }
Converts a real value to its compacted representation .
7,459
public static final double compact ( long sign , double natlog ) { return Double . longBitsToDouble ( sign | ( FLOAT_MASK & Double . doubleToRawLongBits ( natlog ) ) ) ; }
Gets the compacted version from the sign and natural log .
7,460
public int getNumObsFeats ( ) { int count = 0 ; for ( FactorTemplate ft : fts ) { count += ft . getAlphabet ( ) . size ( ) ; } return count ; }
Gets the number of observation function features .
7,461
@ SuppressWarnings ( "unchecked" ) public ApiBuddy execute ( ) { User sfsOwner = api . getUserByName ( owner ) ; ApiUser targetUser = getUser ( target ) ; ApiUser ownerUser = ( ApiUser ) sfsOwner . getProperty ( APIKey . USER ) ; ISFSBuddyResponseApi responseAPI = SmartFoxServer . getInstance ( ) . getAPIManager ( ) . getBuddyApi ( ) . getResponseAPI ( ) ; ISFSEventManager eventManager = SmartFoxServer . getInstance ( ) . getEventManager ( ) ; BuddyList buddyList = sfsOwner . getZone ( ) . getBuddyListManager ( ) . getBuddyList ( owner ) ; BuddyListManager buddyListManager = sfsOwner . getZone ( ) . getBuddyListManager ( ) ; checkBuddyManagerIsActive ( buddyListManager , sfsOwner ) ; sfsOwner . updateLastRequestTime ( ) ; ApiBuddyImpl buddy = new ApiBuddyImpl ( target , temp ) ; buddy . setOwner ( ownerUser ) ; buddy . setParentBuddyList ( buddyList ) ; if ( targetUser != null ) buddy . setUser ( targetUser ) ; try { buddyList . addBuddy ( buddy ) ; if ( fireClientEvent ) responseAPI . notifyAddBuddy ( buddy , sfsOwner ) ; if ( fireServerEvent ) { Map < ISFSEventParam , Object > evtParams = new HashMap < > ( ) ; evtParams . put ( SFSEventParam . ZONE , sfsOwner . getZone ( ) ) ; evtParams . put ( SFSEventParam . USER , sfsOwner ) ; evtParams . put ( SFSBuddyEventParam . BUDDY , buddy ) ; eventManager . dispatchEvent ( new SFSEvent ( SFSEventType . BUDDY_ADD , evtParams ) ) ; } } catch ( SFSBuddyListException e ) { if ( fireClientEvent ) { api . getResponseAPI ( ) . notifyRequestError ( e , sfsOwner , SystemRequest . AddBuddy ) ; } return null ; } return buddy ; }
Execute to add a buddy to list
7,462
private void checkBuddyManagerIsActive ( BuddyListManager buddyListManager , User sfsOwner ) { if ( ! buddyListManager . isActive ( ) ) { throw new IllegalStateException ( String . format ( "BuddyList operation failure. BuddyListManager is not active. Zone: %s, Sender: %s" , new Object [ ] { sfsOwner . getZone ( ) , sfsOwner } ) ) ; } }
Check whether buddy manager is active
7,463
public ApiUser getUser ( String name ) { User sfsUser = CommandUtil . getSfsUser ( name , api ) ; if ( sfsUser == null ) return null ; return ( ApiUser ) sfsUser . getProperty ( APIKey . USER ) ; }
Get user agent reference
7,464
protected void assignDataToHandler ( ServerHandlerClass handler , Object instance ) { if ( getParentExtension ( ) . getConfigProperties ( ) != null ) { new ConfigPropertyDeserializer ( ) . deserialize ( handler . getPropertiesClassWrapper ( ) , instance , getParentExtension ( ) . getConfigProperties ( ) ) ; } }
Map configuration properties to handler object
7,465
public void handleClientRequest ( User user , ISFSObject params ) { try { debugLogRequestInfo ( user , params ) ; ApiUser apiUser = getUserAgent ( user ) ; for ( RequestResponseClass clazz : listeners ) { Object userAgent = checkUserAgent ( clazz , apiUser ) ; notifyListener ( clazz , params , user , userAgent ) ; } } catch ( Exception e ) { processHandlerException ( e , user ) ; } }
Handle request from client
7,466
private void notifyListener ( RequestResponseClass clazz , ISFSObject params , User user , Object userAgent ) throws Exception { Object listener = clazz . newInstance ( ) ; setDataToListener ( clazz , listener , params ) ; invokeExecuteMethod ( clazz . getExecuteMethod ( ) , listener , userAgent ) ; responseClient ( clazz , listener , user ) ; }
Notify all listeners
7,467
protected void invokeExecuteMethod ( Method method , Object listener , Object userAgent ) { ReflectMethodUtil . invokeExecuteMethod ( method , listener , context , userAgent ) ; }
Invoke the execute method
7,468
private Object checkUserAgent ( RequestResponseClass clazz , ApiUser userAgent ) { if ( clazz . getUserClass ( ) . isAssignableFrom ( userAgent . getClass ( ) ) ) return userAgent ; return UserAgentUtil . getGameUser ( userAgent , clazz . getUserClass ( ) ) ; }
For each listener we may use a class of user agent so we need check it
7,469
private void responseClient ( RequestResponseClass clazz , Object listener , User user ) { if ( ! clazz . isResponseToClient ( ) ) return ; String command = clazz . getResponseCommand ( ) ; ISFSObject params = ( ISFSObject ) new ParamTransformer ( context ) . transform ( listener ) . getObject ( ) ; send ( command , params , user ) ; }
Response information to client
7,470
private void responseErrorToClient ( Exception ex , User user ) { BadRequestException e = getBadRequestException ( ex ) ; if ( ! e . isSendToClient ( ) ) return ; ISFSObject params = new SFSObject ( ) ; params . putUtfString ( APIKey . MESSAGE , e . getReason ( ) ) ; params . putInt ( APIKey . CODE , e . getCode ( ) ) ; send ( APIKey . ERROR , params , user ) ; }
Response error to client
7,471
private BadRequestException getBadRequestException ( Exception ex ) { return ( BadRequestException ) ExceptionUtils . getThrowables ( ex ) [ ExceptionUtils . indexOfThrowable ( ex , BadRequestException . class ) ] ; }
Get BadRequestException from the exception
7,472
protected Object getValue ( SetterMethodCover method , Variable variable ) { if ( method . isTwoDimensionsArray ( ) ) return assignValuesToTwoDimensionsArray ( method , variable . getSFSArrayValue ( ) ) ; if ( method . isArray ( ) ) return assignValuesToArray ( method , variable ) ; if ( method . isColection ( ) ) return assignValuesToCollection ( method , variable ) ; if ( method . isObject ( ) ) return assignValuesToObject ( method , variable . getSFSObjectValue ( ) ) ; if ( method . isByte ( ) ) return variable . getIntValue ( ) . byteValue ( ) ; if ( method . isChar ( ) ) return ( char ) variable . getIntValue ( ) . byteValue ( ) ; if ( method . isFloat ( ) ) return variable . getDoubleValue ( ) . floatValue ( ) ; if ( method . isLong ( ) ) return variable . getDoubleValue ( ) . longValue ( ) ; if ( method . isShort ( ) ) return variable . getIntValue ( ) . shortValue ( ) ; return variable . getValue ( ) ; }
Get value from the variable
7,473
protected ISFSObject parseMethods ( ClassUnwrapper unwrapper , Object object ) { return object2params ( unwrapper , object , new SFSObject ( ) ) ; }
Invoke getter method and add returned value to SFSObject
7,474
protected Object parseTwoDimensionsArray ( GetterMethodCover method , Object array ) { ISFSArray answer = new SFSArray ( ) ; int size = Array . getLength ( array ) ; for ( int i = 0 ; i < size ; i ++ ) { SFSDataType dtype = getSFSArrayDataType ( method ) ; Object value = parseArrayOfTwoDimensionsArray ( method , Array . get ( array , i ) ) ; answer . add ( new SFSDataWrapper ( dtype , value ) ) ; } return answer ; }
Serialize two - dimensions array to ISFSArray
7,475
protected Object parseArray ( GetterMethodCover method , Object array ) { if ( method . isObjectArray ( ) ) { return parseObjectArray ( method , ( Object [ ] ) array ) ; } else if ( method . isPrimitiveBooleanArray ( ) ) { return primitiveArrayToBoolCollection ( ( boolean [ ] ) array ) ; } else if ( method . isPrimitiveCharArray ( ) ) { return charArrayToByteArray ( ( char [ ] ) array ) ; } else if ( method . isPrimitiveDoubleArray ( ) ) { return primitiveArrayToDoubleCollection ( ( double [ ] ) array ) ; } else if ( method . isPrimitiveFloatArray ( ) ) { return primitiveArrayToFloatCollection ( ( float [ ] ) array ) ; } else if ( method . isPrimitiveIntArray ( ) ) { return primitiveArrayToIntCollection ( ( int [ ] ) array ) ; } else if ( method . isPrimitiveLongArray ( ) ) { return primitiveArrayToLongCollection ( ( long [ ] ) array ) ; } else if ( method . isPrimitiveShortArray ( ) ) { return primitiveArrayToShortCollection ( ( short [ ] ) array ) ; } else if ( method . isStringArray ( ) ) { return stringArrayToCollection ( ( String [ ] ) array ) ; } else if ( method . isWrapperBooleanArray ( ) ) { return wrapperArrayToCollection ( ( Boolean [ ] ) array ) ; } else if ( method . isWrapperByteArray ( ) ) { return toPrimitiveByteArray ( ( Byte [ ] ) array ) ; } else if ( method . isWrapperCharArray ( ) ) { return charWrapperArrayToPrimitiveByteArray ( ( Character [ ] ) array ) ; } else if ( method . isWrapperDoubleArray ( ) ) { return wrapperArrayToCollection ( ( Double [ ] ) array ) ; } else if ( method . isWrapperFloatArray ( ) ) { return wrapperArrayToCollection ( ( Float [ ] ) array ) ; } else if ( method . isWrapperIntArray ( ) ) { return wrapperArrayToCollection ( ( Integer [ ] ) array ) ; } else if ( method . isWrapperLongArray ( ) ) { return wrapperArrayToCollection ( ( Long [ ] ) array ) ; } else if ( method . isWrapperShortArray ( ) ) { return wrapperArrayToCollection ( ( Short [ ] ) array ) ; } return array ; }
Convert array of values to collection of values
7,476
@ SuppressWarnings ( { "rawtypes" , "unchecked" } ) protected Object parseCollection ( GetterMethodCover method , Collection collection ) { if ( method . isArrayObjectCollection ( ) ) { return parseArrayObjectCollection ( method , collection ) ; } else if ( method . isObjectCollection ( ) ) { return parseObjectCollection ( method , collection ) ; } else if ( method . isByteCollection ( ) ) { return collectionToPrimitiveByteArray ( collection ) ; } else if ( method . isCharCollection ( ) ) { return charCollectionToPrimitiveByteArray ( collection ) ; } else if ( method . isArrayCollection ( ) ) { return parseArrayCollection ( method , collection ) ; } return collection ; }
Parse collection of values and get the value mapped to smartfox value
7,477
@ SuppressWarnings ( { "rawtypes" } ) protected ISFSArray parseObjectCollection ( GetterMethodCover method , Collection collection ) { ISFSArray result = new SFSArray ( ) ; for ( Object obj : collection ) { result . addSFSObject ( parseObject ( method , obj ) ) ; } return result ; }
Serialize collection of objects to a SFSArray
7,478
@ SuppressWarnings ( { "rawtypes" } ) protected ISFSArray parseArrayObjectCollection ( GetterMethodCover method , Collection collection ) { ISFSArray result = new SFSArray ( ) ; for ( Object obj : collection ) { result . addSFSArray ( parseObjectArray ( method , ( Object [ ] ) obj ) ) ; } return result ; }
Serialize collection of java array object to a SFSArray
7,479
@ SuppressWarnings ( "rawtypes" ) protected ISFSArray parseArrayCollection ( GetterMethodCover method , Collection collection ) { ISFSArray result = new SFSArray ( ) ; SFSDataType dataType = ParamTypeParser . getParamType ( method . getGenericType ( ) ) ; Class < ? > type = method . getGenericType ( ) . getComponentType ( ) ; for ( Object obj : collection ) { Object value = obj ; if ( isPrimitiveChar ( type ) ) { value = charArrayToByteArray ( ( char [ ] ) value ) ; } else if ( isWrapperByte ( type ) ) { value = toPrimitiveByteArray ( ( Byte [ ] ) value ) ; } else if ( isWrapperChar ( type ) ) { value = charWrapperArrayToPrimitiveByteArray ( ( Character [ ] ) value ) ; } else { value = arrayToList ( value ) ; } result . add ( new SFSDataWrapper ( dataType , value ) ) ; } return result ; }
Serialize collection of array to a SFSArray
7,480
private SFSDataType getSFSDataType ( MethodCover method ) { if ( method . isBoolean ( ) ) return SFSDataType . BOOL ; if ( method . isByte ( ) ) return SFSDataType . BYTE ; if ( method . isChar ( ) ) return SFSDataType . BYTE ; if ( method . isDouble ( ) ) return SFSDataType . DOUBLE ; if ( method . isFloat ( ) ) return SFSDataType . FLOAT ; if ( method . isInt ( ) ) return SFSDataType . INT ; if ( method . isLong ( ) ) return SFSDataType . LONG ; if ( method . isShort ( ) ) return SFSDataType . SHORT ; if ( method . isString ( ) ) return SFSDataType . UTF_STRING ; if ( method . isObject ( ) ) return SFSDataType . SFS_OBJECT ; if ( method . isBooleanArray ( ) ) return SFSDataType . BOOL_ARRAY ; if ( method . isByteArray ( ) ) return SFSDataType . BYTE_ARRAY ; if ( method . isCharArray ( ) ) return SFSDataType . BYTE_ARRAY ; if ( method . isDoubleArray ( ) ) return SFSDataType . DOUBLE_ARRAY ; if ( method . isFloatArray ( ) ) return SFSDataType . FLOAT_ARRAY ; if ( method . isIntArray ( ) ) return SFSDataType . INT_ARRAY ; if ( method . isLongArray ( ) ) return SFSDataType . LONG_ARRAY ; if ( method . isShortArray ( ) ) return SFSDataType . SHORT_ARRAY ; if ( method . isStringArray ( ) ) return SFSDataType . UTF_STRING_ARRAY ; if ( method . isObjectArray ( ) ) return SFSDataType . SFS_ARRAY ; if ( method . isBooleanCollection ( ) ) return SFSDataType . BOOL_ARRAY ; if ( method . isByteCollection ( ) ) return SFSDataType . BYTE_ARRAY ; if ( method . isCharCollection ( ) ) return SFSDataType . BYTE_ARRAY ; if ( method . isDoubleCollection ( ) ) return SFSDataType . DOUBLE_ARRAY ; if ( method . isFloatCollection ( ) ) return SFSDataType . FLOAT_ARRAY ; if ( method . isIntCollection ( ) ) return SFSDataType . INT_ARRAY ; if ( method . isLongCollection ( ) ) return SFSDataType . LONG_ARRAY ; if ( method . isShortCollection ( ) ) return SFSDataType . SHORT_ARRAY ; if ( method . isStringCollection ( ) ) return SFSDataType . UTF_STRING_ARRAY ; if ( method . isObjectCollection ( ) ) return SFSDataType . SFS_ARRAY ; if ( method . isArrayObjectCollection ( ) ) return SFSDataType . SFS_ARRAY ; return SFSDataType . SFS_ARRAY ; }
Get SFSDataType mapped to returned value type of getter method
7,481
protected void initContext ( ) { context = createContext ( ) ; SmartFoxContext sfsContext = ( SmartFoxContext ) context ; sfsContext . setApi ( getApi ( ) ) ; sfsContext . setExtension ( this ) ; }
Initialize application context
7,482
protected void addClientRequestHandlers ( ) { Set < String > commands = context . getClientRequestCommands ( ) ; for ( String command : commands ) addClientRequestHandler ( command ) ; }
Add client request handlers
7,483
protected ApiUser createUserAgent ( User sfsUser ) { ApiUser answer = UserAgentFactory . newUserAgent ( sfsUser . getName ( ) , context . getUserAgentClass ( ) , context . getGameUserAgentClasses ( ) ) ; sfsUser . setProperty ( APIKey . USER , answer ) ; answer . setId ( sfsUser . getId ( ) ) ; answer . setIp ( sfsUser . getIpAddress ( ) ) ; answer . setSession ( new ApiSessionImpl ( sfsUser . getSession ( ) ) ) ; answer . setCommand ( context . command ( UserInfo . class ) . user ( sfsUser . getId ( ) ) ) ; return answer ; }
Create user agent object
7,484
public static Module < Factors > getFactorsModule ( FactorGraph fg , Algebra s ) { ForwardOnlyFactorsModule fm = new ForwardOnlyFactorsModule ( null , fg , s ) ; fm . forward ( ) ; return fm ; }
Constructs a factors module and runs the forward computation .
7,485
public FactorGraph getClamped ( VarConfig clampVars ) { FactorGraph clmpFg = new FactorGraph ( ) ; for ( Var v : this . getVars ( ) ) { clmpFg . addVar ( v ) ; } for ( Factor origFactor : this . getFactors ( ) ) { clmpFg . addFactor ( origFactor ) ; } for ( Var v : clampVars . getVars ( ) ) { int c = clampVars . getState ( v ) ; clmpFg . addFactor ( new ClampFactor ( v , c ) ) ; } return clmpFg ; }
Gets a new factor graph identical to this one except that specified variables are clamped to their values . This is accomplished by adding a unary factor on each clamped variable . The original K factors are preserved in order with IDs 1 ... K .
7,486
public void addFactor ( Factor factor ) { int id = factor . getId ( ) ; boolean alreadyAdded = ( 0 <= id && id < factors . size ( ) ) ; if ( alreadyAdded ) { if ( factors . get ( id ) != factor ) { throw new IllegalStateException ( "Factor id already set, but factor not yet added." ) ; } } else { if ( id != - 1 && id != factors . size ( ) ) { throw new IllegalStateException ( "Factor id already set, but incorrect: " + id ) ; } factor . setId ( factors . size ( ) ) ; factors . add ( factor ) ; for ( Var var : factor . getVars ( ) ) { addVar ( var ) ; numUndirEdges ++ ; } if ( bg != null ) { log . warn ( "Discarding BipartiteGraph. This may indicate inefficiency." ) ; } bg = null ; } }
Adds a factor to this factor graph if not already present additionally adding any variables in its VarSet which have not already been added .
7,487
public void addVar ( Var var ) { int id = var . getId ( ) ; boolean alreadyAdded = ( 0 <= id && id < vars . size ( ) ) ; if ( alreadyAdded ) { if ( vars . get ( id ) != var ) { throw new IllegalStateException ( "Var id already set, but factor not yet added." ) ; } } else { if ( id != - 1 && id != vars . size ( ) ) { throw new IllegalStateException ( "Var id already set, but incorrect: " + id ) ; } var . setId ( vars . size ( ) ) ; vars . add ( var ) ; if ( bg != null ) { log . warn ( "Discarding BipartiteGraph. This may indicate inefficiency." ) ; } bg = null ; } }
Adds a variable to this factor graph if not already present .
7,488
public FgModel train ( LogLinearXYData data ) { IntObjectBimap < String > alphabet = data . getFeatAlphabet ( ) ; FgExampleList list = getData ( data ) ; log . info ( "Number of train instances: " + list . size ( ) ) ; log . info ( "Number of model parameters: " + alphabet . size ( ) ) ; FgModel model = new FgModel ( alphabet . size ( ) , new StringIterable ( alphabet . getObjects ( ) ) ) ; CrfTrainer trainer = new CrfTrainer ( prm . crfPrm ) ; trainer . train ( model , list ) ; return model ; }
Trains a log - linear model .
7,489
public Pair < String , VarTensor > decode ( FgModel model , LogLinearExample llex ) { LFgExample ex = getFgExample ( llex ) ; MbrDecoderPrm prm = new MbrDecoderPrm ( ) ; prm . infFactory = getBpPrm ( ) ; MbrDecoder decoder = new MbrDecoder ( prm ) ; decoder . decode ( model , ex ) ; List < VarTensor > marginals = decoder . getVarMarginals ( ) ; VarConfig vc = decoder . getMbrVarConfig ( ) ; String stateName = vc . getStateName ( ex . getFactorGraph ( ) . getVar ( 0 ) ) ; if ( marginals . size ( ) != 1 ) { throw new IllegalStateException ( "Example is not from a LogLinearData factory" ) ; } return new Pair < String , VarTensor > ( stateName , marginals . get ( 0 ) ) ; }
Decodes a single example .
7,490
public FgExampleList getData ( LogLinearXYData data ) { IntObjectBimap < String > alphabet = data . getFeatAlphabet ( ) ; List < LogLinearExample > exList = data . getData ( ) ; if ( this . alphabet == null ) { this . alphabet = alphabet ; this . stateNames = getStateNames ( exList , data . getYAlphabet ( ) ) ; } if ( prm . cacheExamples ) { FgExampleMemoryStore store = new FgExampleMemoryStore ( ) ; for ( final LogLinearExample desc : exList ) { LFgExample ex = getFgExample ( desc ) ; store . add ( ex ) ; } return store ; } else { return new FgExampleList ( ) { public LFgExample get ( int i ) { return getFgExample ( exList . get ( i ) ) ; } public int size ( ) { return exList . size ( ) ; } } ; } }
For testing only . Converts to the graphical model s representation of the data .
7,491
private void swapVals ( int e , int f , int [ ] vals ) { int vals_e = vals [ e ] ; vals [ e ] = vals [ f ] ; vals [ f ] = vals_e ; }
Swap the values of two positions in an array .
7,492
public int dfs ( int root , boolean isRootT1 , boolean [ ] marked1 , boolean [ ] marked2 , BipVisitor < T1 , T2 > visitor ) { IntStack sNode = new IntStack ( ) ; ByteStack sIsT1 = new ByteStack ( ) ; sNode . push ( root ) ; sIsT1 . push ( ( byte ) ( isRootT1 ? 1 : 0 ) ) ; int numMarkedChecks = 0 ; while ( sNode . size ( ) != 0 ) { int node = sNode . pop ( ) ; boolean isT1 = ( sIsT1 . pop ( ) == 1 ) ; if ( isT1 ) { int t1 = node ; if ( ! marked1 [ t1 ] ) { marked1 [ t1 ] = true ; if ( visitor != null ) { visitor . visit ( t1 , true , this ) ; } for ( int nb = numNbsT1 ( t1 ) - 1 ; nb >= 0 ; nb -- ) { int t2 = childT1 ( t1 , nb ) ; if ( ! marked2 [ t2 ] ) { sNode . push ( t2 ) ; sIsT1 . push ( ( byte ) 0 ) ; } numMarkedChecks ++ ; } } numMarkedChecks ++ ; } else { int t2 = node ; if ( ! marked2 [ t2 ] ) { marked2 [ t2 ] = true ; if ( visitor != null ) { visitor . visit ( t2 , false , this ) ; } for ( int nb = numNbsT2 ( t2 ) - 1 ; nb >= 0 ; nb -- ) { int t1 = childT2 ( t2 , nb ) ; if ( ! marked1 [ t1 ] ) { sNode . push ( t1 ) ; sIsT1 . push ( ( byte ) 1 ) ; } numMarkedChecks ++ ; } } numMarkedChecks ++ ; } } return numMarkedChecks ; }
Runs a depth - first - search starting at the root node .
7,493
protected void onCreate ( Bundle savedInstanceState ) { final RoboInjector injector = RoboGuice . getInjector ( this ) ; eventManager = injector . getInstance ( EventManager . class ) ; preferenceListener = injector . getInstance ( PreferenceListener . class ) ; injector . injectMembersWithoutViews ( this ) ; super . onCreate ( savedInstanceState ) ; eventManager . fire ( new OnCreateEvent ( savedInstanceState ) ) ; }
BUG find a better place to put this
7,494
public static double [ ] insideAlgorithm ( final Hypergraph graph , final Hyperpotential w , final Semiring s ) { final int n = graph . getNodes ( ) . size ( ) ; final double [ ] beta = new double [ n ] ; Arrays . fill ( beta , s . zero ( ) ) ; graph . applyTopoSort ( new HyperedgeFn ( ) { public void apply ( Hyperedge e ) { double prod = s . one ( ) ; for ( Hypernode jNode : e . getTailNodes ( ) ) { prod = s . times ( prod , beta [ jNode . getId ( ) ] ) ; } int i = e . getHeadNode ( ) . getId ( ) ; prod = s . times ( w . getScore ( e , s ) , prod ) ; beta [ i ] = s . plus ( beta [ i ] , prod ) ; } } ) ; return beta ; }
Runs the inside algorithm on a hypergraph .
7,495
public static double [ ] outsideAlgorithm ( final Hypergraph graph , final Hyperpotential w , final Semiring s , final double [ ] beta ) { final int n = graph . getNodes ( ) . size ( ) ; final double [ ] alpha = new double [ n ] ; Arrays . fill ( alpha , s . zero ( ) ) ; alpha [ graph . getRoot ( ) . getId ( ) ] = s . one ( ) ; graph . applyRevTopoSort ( new HyperedgeFn ( ) { public void apply ( Hyperedge e ) { int i = e . getHeadNode ( ) . getId ( ) ; for ( Hypernode jNode : e . getTailNodes ( ) ) { int j = jNode . getId ( ) ; double prod = s . one ( ) ; for ( Hypernode kNode : e . getTailNodes ( ) ) { int k = kNode . getId ( ) ; if ( k == j ) { continue ; } prod = s . times ( prod , beta [ k ] ) ; } prod = s . times ( prod , alpha [ i ] ) ; prod = s . times ( prod , w . getScore ( e , s ) ) ; alpha [ j ] = s . plus ( alpha [ j ] , prod ) ; } } } ) ; return alpha ; }
Runs the outside algorithm on a hypergraph .
7,496
public static void insideAlgorithmFirstOrderExpect ( final Hypergraph graph , final HyperpotentialFoe w , final Algebra s , final Scores scores ) { final int n = graph . getNodes ( ) . size ( ) ; final double [ ] beta = new double [ n ] ; final double [ ] betaFoe = new double [ n ] ; Arrays . fill ( beta , s . zero ( ) ) ; Arrays . fill ( betaFoe , s . zero ( ) ) ; graph . applyTopoSort ( new HyperedgeFn ( ) { public void apply ( Hyperedge e ) { double prod = s . one ( ) ; double prodFoe = s . zero ( ) ; for ( Hypernode jNode : e . getTailNodes ( ) ) { int j = jNode . getId ( ) ; double p1 = prod ; double p2 = beta [ j ] ; double r1 = prodFoe ; double r2 = betaFoe [ j ] ; prod = s . times ( p1 , p2 ) ; prodFoe = s . plus ( s . times ( p1 , r2 ) , s . times ( p2 , r1 ) ) ; } double p1 = prod ; double p2 = w . getScore ( e , s ) ; double r1 = prodFoe ; double r2 = w . getScoreFoe ( e , s ) ; prod = s . times ( p1 , p2 ) ; prodFoe = s . plus ( s . times ( p1 , r2 ) , s . times ( p2 , r1 ) ) ; int i = e . getHeadNode ( ) . getId ( ) ; beta [ i ] = s . plus ( beta [ i ] , prod ) ; betaFoe [ i ] = s . plus ( betaFoe [ i ] , prodFoe ) ; assert ! s . isNaN ( beta [ i ] ) ; assert ! s . isNaN ( betaFoe [ i ] ) ; } } ) ; scores . beta = beta ; scores . betaFoe = betaFoe ; }
Runs the inside algorithm on a hypergraph with the first - order expectation semiring .
7,497
private static void outsideAdjoint ( final Hypergraph graph , final Hyperpotential w , final Algebra s , final Scores scores ) { final double [ ] beta = scores . beta ; final double [ ] alphaAdj = scores . alphaAdj ; graph . applyTopoSort ( new HyperedgeFn ( ) { public void apply ( Hyperedge e ) { int i = e . getHeadNode ( ) . getId ( ) ; for ( Hypernode j : e . getTailNodes ( ) ) { double prod = s . times ( alphaAdj [ j . getId ( ) ] , w . getScore ( e , s ) ) ; for ( Hypernode k : e . getTailNodes ( ) ) { if ( k == j ) { continue ; } prod = s . times ( prod , beta [ k . getId ( ) ] ) ; } alphaAdj [ i ] = s . plus ( alphaAdj [ i ] , prod ) ; } } } ) ; scores . alphaAdj = alphaAdj ; }
Computes the adjoints of the outside scores only . Performs only a partial backwards pass through the outside algorithm .
7,498
private static void insideAdjoint ( final Hypergraph graph , final Hyperpotential w , final Algebra s , final Scores scores , final boolean backOutside ) { final double [ ] alpha = scores . alpha ; final double [ ] beta = scores . beta ; final double [ ] alphaAdj = scores . alphaAdj ; final double [ ] betaAdj = scores . betaAdj ; graph . applyRevTopoSort ( new HyperedgeFn ( ) { public void apply ( Hyperedge e ) { int i = e . getHeadNode ( ) . getId ( ) ; for ( Hypernode jNode : e . getTailNodes ( ) ) { int j = jNode . getId ( ) ; double prod = s . times ( betaAdj [ i ] , w . getScore ( e , s ) ) ; for ( Hypernode kNode : e . getTailNodes ( ) ) { int k = kNode . getId ( ) ; if ( j == k ) { continue ; } prod = s . times ( prod , beta [ k ] ) ; } betaAdj [ j ] = s . plus ( betaAdj [ j ] , prod ) ; if ( backOutside ) { for ( Hypernode kNode : e . getTailNodes ( ) ) { int k = kNode . getId ( ) ; if ( k == j ) { continue ; } ; prod = s . times ( alphaAdj [ k ] , w . getScore ( e , s ) ) ; prod = s . times ( prod , alpha [ i ] ) ; for ( Hypernode lNode : e . getTailNodes ( ) ) { int l = lNode . getId ( ) ; if ( l == j || l == k ) { continue ; } prod = s . times ( prod , beta [ l ] ) ; } betaAdj [ j ] = s . plus ( betaAdj [ j ] , prod ) ; } } } } } ) ; scores . betaAdj = betaAdj ; }
Computes the adjoints of the inside scores only . Performs a partial backwards pass through the outside algorithm and a partial backwards pass through the inside algorithm .
7,499
private static void weightAdjoint ( final Hypergraph graph , final Hyperpotential w , final Algebra s , final Scores scores , boolean backOutside ) { final double [ ] weightAdj = new double [ graph . getNumEdges ( ) ] ; HyperedgeDoubleFn lambda = new HyperedgeDoubleFn ( ) { public void apply ( Hyperedge e , double val ) { weightAdj [ e . getId ( ) ] = val ; } } ; weightAdjoint ( graph , w , s , scores , lambda , backOutside ) ; scores . weightAdj = weightAdj ; }
Computes the adjoints of the hyperedge weights .