idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
37,100 | static < T , S extends Iterable < T > > String printTreeForGraphViz ( SuffixTree < T , S > tree , boolean printSuffixLinks ) { LinkedList < Node < T , S > > stack = new LinkedList < > ( ) ; stack . add ( tree . getRoot ( ) ) ; Map < Node < T , S > , Integer > nodeMap = new HashMap < > ( ) ; nodeMap . put ( tree . getRoot ( ) , 0 ) ; int nodeId = 1 ; StringBuilder sb = new StringBuilder ( "\ndigraph suffixTree{\n node [shape=circle, label=\"\", fixedsize=true, width=0.1, height=0.1]\n" ) ; while ( stack . size ( ) > 0 ) { LinkedList < Node < T , S > > childNodes = new LinkedList < > ( ) ; for ( Node < T , S > node : stack ) { for ( Edge < T , S > edge : node ) { int id = nodeId ++ ; if ( edge . isTerminating ( ) ) { childNodes . push ( edge . getTerminal ( ) ) ; nodeMap . put ( edge . getTerminal ( ) , id ) ; } sb . append ( nodeMap . get ( node ) ) . append ( " -> " ) . append ( id ) . append ( " [label=\"" ) ; for ( T item : edge ) { sb . append ( item . toString ( ) ) ; } sb . append ( "\"];\n" ) ; } } stack = childNodes ; } if ( printSuffixLinks ) { sb . append ( "edge [color=red]\n" ) ; for ( Map . Entry < Node < T , S > , Integer > entry : nodeMap . entrySet ( ) ) { Node n1 = entry . getKey ( ) ; int id1 = entry . getValue ( ) ; if ( n1 . hasSuffixLink ( ) ) { Node n2 = n1 . getSuffixLink ( ) ; Integer id2 = nodeMap . get ( n2 ) ; sb . append ( id1 ) . append ( " -> " ) . append ( id2 ) . append ( " ;\n" ) ; } } } sb . append ( "}" ) ; return ( sb . toString ( ) ) ; } | Generates a . dot format string for visualizing a suffix tree . |
37,101 | public int [ ] buildSuffixArray ( CharSequence sequence ) { this . input = new int [ sequence . length ( ) + SuffixArrays . MAX_EXTRA_TRAILING_SPACE ] ; for ( int i = sequence . length ( ) - 1 ; i >= 0 ; i -- ) { input [ i ] = sequence . charAt ( i ) ; } final int start = 0 ; final int length = sequence . length ( ) ; final ISymbolMapper mapper = new DensePositiveMapper ( input , start , length ) ; mapper . map ( input , start , length ) ; return delegate . buildSuffixArray ( input , start , length ) ; } | Construct a suffix array for a given character sequence . |
37,102 | void setPosition ( Node < T , S > node , Edge < T , S > edge , int length ) { activeNode = node ; activeEdge = edge ; activeLength = length ; } | Sets the active point to a new node edge length tripple . |
37,103 | public void updateAfterInsert ( Suffix < T , S > suffix ) { if ( activeNode == root && suffix . isEmpty ( ) ) { activeNode = root ; activeEdge = null ; activeLength = 0 ; } else if ( activeNode == root ) { Object item = suffix . getStart ( ) ; activeEdge = root . getEdgeStarting ( item ) ; decrementLength ( ) ; fixActiveEdgeAfterSuffixLink ( suffix ) ; if ( activeLength == 0 ) activeEdge = null ; } else if ( activeNode . hasSuffixLink ( ) ) { activeNode = activeNode . getSuffixLink ( ) ; findTrueActiveEdge ( ) ; fixActiveEdgeAfterSuffixLink ( suffix ) ; if ( activeLength == 0 ) activeEdge = null ; } else { activeNode = root ; findTrueActiveEdge ( ) ; fixActiveEdgeAfterSuffixLink ( suffix ) ; if ( activeLength == 0 ) activeEdge = null ; } } | Resets the active point after an insert . |
37,104 | private void fixActiveEdgeAfterSuffixLink ( Suffix < T , S > suffix ) { while ( activeEdge != null && activeLength > activeEdge . getLength ( ) ) { activeLength = activeLength - activeEdge . getLength ( ) ; activeNode = activeEdge . getTerminal ( ) ; Object item = suffix . getItemXFromEnd ( activeLength + 1 ) ; activeEdge = activeNode . getEdgeStarting ( item ) ; } resetActivePointToTerminal ( ) ; } | Deal with the case when we follow a suffix link but the active length is greater than the new active edge length . In this situation we must walk down the tree updating the entire active point . |
37,105 | private void findTrueActiveEdge ( ) { if ( activeEdge != null ) { Object item = activeEdge . getStartItem ( ) ; activeEdge = activeNode . getEdgeStarting ( item ) ; } } | Finds the edge instance who s start item matches the current active edge start item but comes from the current active node . |
37,106 | private boolean resetActivePointToTerminal ( ) { if ( activeEdge != null && activeEdge . getLength ( ) == activeLength && activeEdge . isTerminating ( ) ) { activeNode = activeEdge . getTerminal ( ) ; activeEdge = null ; activeLength = 0 ; return true ; } return false ; } | Resizes the active length in the case where we are sitting on a terminal . |
37,107 | public int [ ] buildSuffixArray ( T [ ] tokens ) { final int length = tokens . length ; input = new int [ length + SuffixArrays . MAX_EXTRA_TRAILING_SPACE ] ; tokIDs = new TreeMap < > ( comparator ) ; for ( int i = 0 ; i < length ; i ++ ) { tokIDs . putIfAbsent ( tokens [ i ] , i ) ; input [ i ] = tokIDs . get ( tokens [ i ] ) ; } return delegate . buildSuffixArray ( input , 0 , length ) ; } | Construct a suffix array for a given generic token array . |
37,108 | public void add ( S sequence ) { int start = currentEnd ; this . sequence . add ( sequence ) ; suffix = new Suffix < > ( currentEnd , currentEnd , this . sequence ) ; activePoint . setPosition ( root , null , 0 ) ; extendTree ( start , this . sequence . getLength ( ) ) ; } | Add a sequence to the suffix tree . It is immediately processed and added to the tree . |
37,109 | void insert ( Suffix < I , S > suffix ) { if ( activePoint . isNode ( ) ) { Node < I , S > node = activePoint . getNode ( ) ; node . insert ( suffix , activePoint ) ; } else if ( activePoint . isEdge ( ) ) { Edge < I , S > edge = activePoint . getEdge ( ) ; edge . insert ( suffix , activePoint ) ; } } | Inserts the given suffix into this tree . |
37,110 | void setSuffixLink ( Node < I , S > node ) { if ( isNotFirstInsert ( ) ) { lastNodeInserted . setSuffixLink ( node ) ; } lastNodeInserted = node ; } | Sets the suffix link of the last inserted node to point to the supplied node . This method checks the state of the step and only applies the suffix link if there is a previous node inserted during this step . This method also set the last node inserted to the supplied node after applying any suffix linking . |
37,111 | public static MatchTable create ( VariantGraph graph , Iterable < Token > witness ) { Comparator < Token > comparator = new EqualityTokenComparator ( ) ; return MatchTableImpl . create ( graph , witness , comparator ) ; } | assumes default token comparator |
37,112 | public Set < Island > getIslands ( ) { Map < Coordinate , Island > coordinateMapper = new HashMap < > ( ) ; List < Coordinate > allMatches = allMatches ( ) ; for ( Coordinate c : allMatches ) { addToIslands ( coordinateMapper , c ) ; } Set < Coordinate > smallestIslandsCoordinates = new HashSet < > ( allMatches ) ; smallestIslandsCoordinates . removeAll ( coordinateMapper . keySet ( ) ) ; for ( Coordinate coordinate : smallestIslandsCoordinates ) { Island island = new Island ( ) ; island . add ( coordinate ) ; coordinateMapper . put ( coordinate , island ) ; } return new HashSet < > ( coordinateMapper . values ( ) ) ; } | we don t need to check the lower right neighbor . |
37,113 | private void fillTableWithMatches ( VariantGraphRanking ranking , VariantGraph graph , Iterable < Token > witness , Comparator < Token > comparator ) { Matches matches = Matches . between ( graph . vertices ( ) , witness , comparator ) ; Set < Token > unique = matches . uniqueInWitness ; Set < Token > ambiguous = matches . ambiguousInWitness ; int rowIndex = 0 ; for ( Token t : witness ) { if ( unique . contains ( t ) || ambiguous . contains ( t ) ) { List < VariantGraph . Vertex > matchingVertices = matches . allMatches . getOrDefault ( t , Collections . emptyList ( ) ) ; for ( VariantGraph . Vertex vgv : matchingVertices ) { set ( rowIndex , ranking . apply ( vgv ) - 1 , t , vgv ) ; } } rowIndex ++ ; } } | move parameters into fields? |
37,114 | public void remove ( int id ) { String symbol = invert ( ) . keyForId ( id ) ; idToSymbol . remove ( id ) ; symbolToId . remove ( symbol ) ; } | Remove the mapping for the given id . Note that the newly assigned next ids are monotonically increasing so removing one id does not free it up to be assigned in future symbol table adds ; there will just be holes in the symbol mappings |
37,115 | public void trimIds ( ) { if ( idToSymbol . containsKey ( nextId - 1 ) ) { return ; } int max = - 1 ; for ( IntObjectCursor < String > cursor : idToSymbol ) { max = Math . max ( max , cursor . key ) ; } nextId = max + 1 ; } | If there are ids to reclaim at the end then this will do this . Certainly be careful if you are doing operations where it is expected that the id mappings will be consistent across multiple FSTs such as in compose where you want the output of A to be equal to the input of B |
37,116 | public static PrecomputedComposeFst precomputeInner ( Fst fst2 , Semiring semiring ) { fst2 . throwIfInvalid ( ) ; MutableFst mutableFst = MutableFst . copyFrom ( fst2 ) ; WriteableSymbolTable table = mutableFst . getInputSymbols ( ) ; int e1index = getOrAddEps ( table , true ) ; int e2index = getOrAddEps ( table , false ) ; String eps1 = table . invert ( ) . keyForId ( e1index ) ; String eps2 = table . invert ( ) . keyForId ( e2index ) ; augment ( AugmentLabels . INPUT , mutableFst , semiring , eps1 , eps2 ) ; ArcSort . sortByInput ( mutableFst ) ; MutableFst filter = makeFilter ( table , semiring , eps1 , eps2 ) ; ArcSort . sortByInput ( filter ) ; return new PrecomputedComposeFst ( eps1 , eps2 , new ImmutableFst ( mutableFst ) , semiring , new ImmutableFst ( filter ) ) ; } | Pre - processes a FST that is going to be used on the right hand side of a compose operator many times |
37,117 | private static MutableFst makeFilter ( WriteableSymbolTable table , Semiring semiring , String eps1 , String eps2 ) { MutableFst filter = new MutableFst ( semiring , table , table ) ; MutableState s0 = filter . newStartState ( ) ; s0 . setFinalWeight ( semiring . one ( ) ) ; MutableState s1 = filter . newState ( ) ; s1 . setFinalWeight ( semiring . one ( ) ) ; MutableState s2 = filter . newState ( ) ; s2 . setFinalWeight ( semiring . one ( ) ) ; filter . addArc ( s0 , eps2 , eps1 , s0 , semiring . one ( ) ) ; filter . addArc ( s0 , eps1 , eps1 , s1 , semiring . one ( ) ) ; filter . addArc ( s0 , eps2 , eps2 , s2 , semiring . one ( ) ) ; filter . addArc ( s1 , eps1 , eps1 , s1 , semiring . one ( ) ) ; filter . addArc ( s2 , eps2 , eps2 , s2 , semiring . one ( ) ) ; for ( ObjectIntCursor < String > cursor : table ) { int i = cursor . value ; String key = cursor . key ; if ( key . equals ( Fst . EPS ) || key . equals ( eps1 ) || key . equals ( eps2 ) ) { continue ; } filter . addArc ( s0 , i , i , s0 , semiring . one ( ) ) ; filter . addArc ( s1 , i , i , s0 , semiring . one ( ) ) ; filter . addArc ( s2 , i , i , s0 , semiring . one ( ) ) ; } return filter ; } | Get a filter to use for avoiding multiple epsilon paths in the resulting Fst |
37,118 | private static void augment ( AugmentLabels label , MutableFst fst , Semiring semiring , String eps1 , String eps2 ) { int e1inputIndex = fst . getInputSymbols ( ) . getOrAdd ( eps1 ) ; int e2inputIndex = fst . getInputSymbols ( ) . getOrAdd ( eps2 ) ; int e1outputIndex = fst . getOutputSymbols ( ) . getOrAdd ( eps1 ) ; int e2outputIndex = fst . getOutputSymbols ( ) . getOrAdd ( eps2 ) ; int iEps = fst . getInputSymbols ( ) . get ( Fst . EPS ) ; int oEps = fst . getOutputSymbols ( ) . get ( Fst . EPS ) ; int numStates = fst . getStateCount ( ) ; for ( int i = 0 ; i < numStates ; i ++ ) { MutableState s = fst . getState ( i ) ; for ( MutableArc arc : s . getArcs ( ) ) { if ( ( label == AugmentLabels . OUTPUT ) && ( arc . getOlabel ( ) == oEps ) ) { arc . setOlabel ( e2outputIndex ) ; } else if ( ( label == AugmentLabels . INPUT ) && ( arc . getIlabel ( ) == iEps ) ) { arc . setIlabel ( e1inputIndex ) ; } } if ( label == AugmentLabels . INPUT ) { fst . addArc ( s , e2inputIndex , oEps , s , semiring . one ( ) ) ; } else if ( label == AugmentLabels . OUTPUT ) { fst . addArc ( s , iEps , e1outputIndex , s , semiring . one ( ) ) ; } } } | Augments the labels of an Fst in order to use it for composition avoiding multiple epsilon paths in the resulting Fst |
37,119 | public static void apply ( MutableFst fst , ProjectType pType ) { if ( pType == ProjectType . INPUT ) { fst . setOutputSymbolsAsCopyFromThatInput ( fst ) ; } else if ( pType == ProjectType . OUTPUT ) { fst . setInputSymbolsAsCopyFromThatOutput ( fst ) ; } for ( int i = 0 ; i < fst . getStateCount ( ) ; i ++ ) { MutableState state = fst . getState ( i ) ; for ( int j = 0 ; j < state . getArcCount ( ) ; j ++ ) { MutableArc a = state . getArc ( j ) ; if ( pType == ProjectType . INPUT ) { a . setOlabel ( a . getIlabel ( ) ) ; } else if ( pType == ProjectType . OUTPUT ) { a . setIlabel ( a . getOlabel ( ) ) ; } } } } | Projects an fst onto its domain or range by either copying each arc s input label to its output label or vice versa . |
37,120 | public static void apply ( MutableFst fst ) { fst . throwIfInvalid ( ) ; IntOpenHashSet accessible = new IntOpenHashSet ( fst . getStateCount ( ) ) ; IntOpenHashSet coaccessible = new IntOpenHashSet ( fst . getStateCount ( ) ) ; dfsForward ( fst . getStartState ( ) , accessible ) ; int numStates = fst . getStateCount ( ) ; for ( int i = 0 ; i < numStates ; i ++ ) { MutableState s = fst . getState ( i ) ; if ( fst . getSemiring ( ) . isNotZero ( s . getFinalWeight ( ) ) ) { dfsBackward ( s , coaccessible ) ; } } if ( accessible . size ( ) == fst . getStateCount ( ) && coaccessible . size ( ) == fst . getStateCount ( ) ) { return ; } ArrayList < MutableState > toDelete = new ArrayList < > ( ) ; int startId = fst . getStartState ( ) . getId ( ) ; for ( int i = 0 ; i < numStates ; i ++ ) { MutableState s = fst . getState ( i ) ; if ( s . getId ( ) == startId ) { continue ; } if ( ! accessible . contains ( s . getId ( ) ) || ! coaccessible . contains ( s . getId ( ) ) ) { toDelete . add ( s ) ; } } fst . deleteStates ( toDelete ) ; } | Trims an Fst removing states and arcs that are not on successful paths . |
37,121 | public MutableState setStart ( MutableState start ) { checkArgument ( start . getId ( ) >= 0 , "must set id before setting start" ) ; throwIfSymbolTableMissingId ( start . getId ( ) ) ; correctStateWeight ( start ) ; this . start = start ; return start ; } | Set the initial state |
37,122 | public void deleteStates ( Collection < MutableState > statesToDelete ) { if ( statesToDelete . isEmpty ( ) ) { return ; } for ( MutableState state : statesToDelete ) { deleteState ( state ) ; } remapStateIds ( ) ; } | Deletes the given states and remaps the existing state ids |
37,123 | private void deleteState ( MutableState state ) { if ( state . getId ( ) == this . start . getId ( ) ) { throw new IllegalArgumentException ( "Cannot delete start state." ) ; } this . states . set ( state . getId ( ) , null ) ; if ( isUsingStateSymbols ( ) ) { stateSymbols . remove ( state . getId ( ) ) ; } for ( MutableArc mutableArc : state . getArcs ( ) ) { mutableArc . getNextState ( ) . removeIncomingState ( state ) ; } for ( MutableState inState : state . getIncomingStates ( ) ) { Iterator < MutableArc > iter = inState . getArcs ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { MutableArc arc = iter . next ( ) ; if ( arc . getNextState ( ) == state ) { iter . remove ( ) ; } } } } | Deletes a state ; |
37,124 | public MutableFst compute ( final Fst fst ) { fst . throwIfInvalid ( ) ; this . semiring = fst . getSemiring ( ) ; this . gallicSemiring = new GallicSemiring ( this . semiring , this . gallicMode ) ; this . unionSemiring = makeUnionRing ( semiring , gallicSemiring , mode ) ; this . inputFst = fst ; this . outputFst = MutableFst . emptyWithCopyOfSymbols ( fst ) ; this . outputStateIdToTuple = HashBiMap . create ( ) ; Deque < DetStateTuple > workQueue = new LinkedList < > ( ) ; Deque < DetElement > finalQueue = new LinkedList < > ( ) ; MutableState initialOutState = outputFst . newStartState ( ) ; DetElement initialElement = new DetElement ( fst . getStartState ( ) . getId ( ) , GallicWeight . createEmptyLabels ( semiring . one ( ) ) ) ; DetStateTuple initialTuple = new DetStateTuple ( initialElement ) ; workQueue . addLast ( initialTuple ) ; this . outputStateIdToTuple . put ( initialOutState . getId ( ) , initialTuple ) ; while ( ! workQueue . isEmpty ( ) ) { DetStateTuple entry = workQueue . removeFirst ( ) ; MutableState outStateForTuple = getOutputStateForStateTuple ( entry ) ; Collection < DetArcWork > arcWorks = groupByInputLabel ( entry ) ; arcWorks . forEach ( this :: normalizeArcWork ) ; for ( DetArcWork arcWork : arcWorks ) { DetStateTuple targetTuple = new DetStateTuple ( arcWork . pendingElements ) ; if ( ! this . outputStateIdToTuple . inverse ( ) . containsKey ( targetTuple ) ) { MutableState newOutState = outputFst . newState ( ) ; this . outputStateIdToTuple . put ( newOutState . getId ( ) , targetTuple ) ; newOutState . setFinalWeight ( computeFinalWeight ( newOutState . getId ( ) , targetTuple , finalQueue ) ) ; workQueue . addLast ( targetTuple ) ; } MutableState targetOutState = getOutputStateForStateTuple ( targetTuple ) ; UnionWeight < GallicWeight > unionWeight = arcWork . computedDivisor ; for ( GallicWeight gallicWeight : unionWeight . getWeights ( ) ) { Preconditions . checkState ( gallicSemiring . isNotZero ( gallicWeight ) , "gallic weight zero computed from group by" , gallicWeight ) ; int oLabel = this . outputEps ; if ( ! gallicWeight . getLabels ( ) . isEmpty ( ) ) { Preconditions . checkState ( gallicWeight . getLabels ( ) . size ( ) == 1 , "cant gave gallic arc weight with more than a single symbol" , gallicWeight ) ; oLabel = gallicWeight . getLabels ( ) . get ( 0 ) ; } outputFst . addArc ( outStateForTuple , arcWork . inputLabel , oLabel , targetOutState , gallicWeight . getWeight ( ) ) ; } } } expandDeferredFinalStates ( finalQueue ) ; return outputFst ; } | Determinizes an FSA or FST . For this algorithm epsilon transitions are treated as regular symbols . |
37,125 | private void normalizeArcWork ( final DetArcWork arcWork ) { Collections . sort ( arcWork . pendingElements ) ; ArrayList < DetElement > deduped = Lists . newArrayList ( ) ; for ( int i = 0 ; i < arcWork . pendingElements . size ( ) ; i ++ ) { DetElement currentElement = arcWork . pendingElements . get ( i ) ; arcWork . computedDivisor = unionSemiring . commonDivisor ( arcWork . computedDivisor , currentElement . residual ) ; if ( deduped . isEmpty ( ) || deduped . get ( deduped . size ( ) - 1 ) . inputStateId != currentElement . inputStateId ) { deduped . add ( currentElement ) ; } else { int lastIndex = deduped . size ( ) - 1 ; DetElement lastElement = deduped . get ( lastIndex ) ; UnionWeight < GallicWeight > merged = unionSemiring . plus ( lastElement . residual , currentElement . residual ) ; deduped . set ( lastIndex , lastElement . withResidual ( merged ) ) ; } } arcWork . pendingElements = deduped ; for ( int i = 0 ; i < arcWork . pendingElements . size ( ) ; i ++ ) { DetElement currentElement = arcWork . pendingElements . get ( i ) ; UnionWeight < GallicWeight > divided = unionSemiring . divide ( currentElement . residual , arcWork . computedDivisor ) ; arcWork . pendingElements . set ( i , currentElement . withResidual ( divided ) ) ; } } | and compute new resulting arc weights |
37,126 | private double computeFinalWeight ( final int outputStateId , final DetStateTuple targetTuple , Deque < DetElement > finalQueue ) { UnionWeight < GallicWeight > result = this . unionSemiring . zero ( ) ; for ( DetElement detElement : targetTuple . getElements ( ) ) { State inputState = this . getInputStateForId ( detElement . inputStateId ) ; if ( this . semiring . isZero ( inputState . getFinalWeight ( ) ) ) { continue ; } UnionWeight < GallicWeight > origFinal = UnionWeight . createSingle ( GallicWeight . createEmptyLabels ( inputState . getFinalWeight ( ) ) ) ; result = this . unionSemiring . plus ( result , this . unionSemiring . times ( detElement . residual , origFinal ) ) ; } if ( this . unionSemiring . isZero ( result ) ) { return this . semiring . zero ( ) ; } if ( result . size ( ) == 1 && result . get ( 0 ) . getLabels ( ) . isEmpty ( ) ) { return result . get ( 0 ) . getWeight ( ) ; } finalQueue . addLast ( new DetElement ( outputStateId , result ) ) ; return this . semiring . zero ( ) ; } | _this_ new outState a final state and instead we queue it into a separate queue for later expansion |
37,127 | private void expandDeferredFinalStates ( Deque < DetElement > finalQueue ) { HashBiMap < Integer , GallicWeight > outputStateIdToFinalSuffix = HashBiMap . create ( ) ; while ( ! finalQueue . isEmpty ( ) ) { DetElement element = finalQueue . removeFirst ( ) ; for ( GallicWeight gallicWeight : element . residual . getWeights ( ) ) { Pair < GallicWeight , GallicWeight > factorized = gallicSemiring . factorize ( gallicWeight ) ; GallicWeight prefix = factorized . getLeft ( ) ; GallicWeight suffix = factorized . getRight ( ) ; if ( ! outputStateIdToFinalSuffix . inverse ( ) . containsKey ( suffix ) ) { MutableState newOutputState = outputFst . newState ( ) ; outputStateIdToFinalSuffix . put ( newOutputState . getId ( ) , suffix ) ; if ( suffix . getLabels ( ) . isEmpty ( ) ) { newOutputState . setFinalWeight ( suffix . getWeight ( ) ) ; } else { finalQueue . addLast ( new DetElement ( newOutputState . getId ( ) , suffix ) ) ; } } Integer outputStateId = outputStateIdToFinalSuffix . inverse ( ) . get ( suffix ) ; MutableState nextState = checkNotNull ( outputFst . getState ( outputStateId ) , "state should exist" , outputStateId ) ; MutableState thisState = checkNotNull ( outputFst . getState ( element . inputStateId ) ) ; Preconditions . checkArgument ( prefix . getLabels ( ) . size ( ) == 1 , "prefix size should be 1" , prefix ) ; int oLabel = prefix . getLabels ( ) . get ( 0 ) ; outputFst . addArc ( thisState , this . outputEps , oLabel , nextState , prefix . getWeight ( ) ) ; } } } | residual primitive weight early in the path ) |
37,128 | public static MutableSymbolTable readStringMap ( ObjectInput in ) throws IOException , ClassNotFoundException { int mapSize = in . readInt ( ) ; MutableSymbolTable syms = new MutableSymbolTable ( ) ; for ( int i = 0 ; i < mapSize ; i ++ ) { String sym = in . readUTF ( ) ; int index = in . readInt ( ) ; syms . put ( sym , index ) ; } return syms ; } | Deserializes a symbol map from an java . io . ObjectInput |
37,129 | public static MutableFst readFstFromBinaryStream ( ObjectInput in ) throws IOException , ClassNotFoundException { int version = in . readInt ( ) ; if ( version < FIRST_VERSION && version > CURRENT_VERSION ) { throw new IllegalArgumentException ( "cant read version fst model " + version ) ; } MutableSymbolTable is = readStringMap ( in ) ; MutableSymbolTable os = readStringMap ( in ) ; MutableSymbolTable ss = null ; if ( in . readBoolean ( ) ) { ss = readStringMap ( in ) ; } return readFstWithTables ( in , is , os , ss ) ; } | Deserializes an Fst from an ObjectInput |
37,130 | private static void writeStringMap ( SymbolTable map , ObjectOutput out ) throws IOException { out . writeInt ( map . size ( ) ) ; for ( ObjectIntCursor < String > cursor : map ) { out . writeUTF ( cursor . key ) ; out . writeInt ( cursor . value ) ; } } | Serializes a symbol map to an ObjectOutput |
37,131 | public static void writeFstToBinaryStream ( Fst fst , ObjectOutput out ) throws IOException { out . writeInt ( CURRENT_VERSION ) ; writeStringMap ( fst . getInputSymbols ( ) , out ) ; writeStringMap ( fst . getOutputSymbols ( ) , out ) ; out . writeBoolean ( fst . isUsingStateSymbols ( ) ) ; if ( fst . isUsingStateSymbols ( ) ) { writeStringMap ( fst . getStateSymbols ( ) , out ) ; } out . writeInt ( fst . getStartState ( ) . getId ( ) ) ; out . writeObject ( fst . getSemiring ( ) ) ; out . writeInt ( fst . getStateCount ( ) ) ; Map < State , Integer > stateMap = new IdentityHashMap < > ( fst . getStateCount ( ) ) ; for ( int i = 0 ; i < fst . getStateCount ( ) ; i ++ ) { State s = fst . getState ( i ) ; out . writeInt ( s . getArcCount ( ) ) ; out . writeDouble ( s . getFinalWeight ( ) ) ; out . writeInt ( s . getId ( ) ) ; stateMap . put ( s , i ) ; } int numStates = fst . getStateCount ( ) ; for ( int i = 0 ; i < numStates ; i ++ ) { State s = fst . getState ( i ) ; int numArcs = s . getArcCount ( ) ; for ( int j = 0 ; j < numArcs ; j ++ ) { Arc a = s . getArc ( j ) ; out . writeInt ( a . getIlabel ( ) ) ; out . writeInt ( a . getOlabel ( ) ) ; out . writeDouble ( a . getWeight ( ) ) ; out . writeInt ( stateMap . get ( a . getNextState ( ) ) ) ; } } } | Serializes the current Fst instance to an ObjectOutput |
37,132 | public static void sortBy ( MutableFst fst , Comparator < Arc > comparator ) { int numStates = fst . getStateCount ( ) ; for ( int i = 0 ; i < numStates ; i ++ ) { MutableState s = fst . getState ( i ) ; s . arcSort ( comparator ) ; } } | Applies the ArcSort on the provided fst . Sorting can be applied either on input or output label based on the provided comparator . |
37,133 | public static boolean isSorted ( State state , Comparator < Arc > comparator ) { return Ordering . from ( comparator ) . isOrdered ( state . getArcs ( ) ) ; } | Returns true if the given state is sorted by the comparator |
37,134 | private static void exportFst ( Fst fst , String filename ) { FileWriter file ; try { file = new FileWriter ( filename ) ; PrintWriter out = new PrintWriter ( file ) ; State start = fst . getStartState ( ) ; out . println ( start . getId ( ) + "\t" + start . getFinalWeight ( ) ) ; int numStates = fst . getStateCount ( ) ; for ( int i = 0 ; i < numStates ; i ++ ) { State s = fst . getState ( i ) ; if ( s . getId ( ) == fst . getStartState ( ) . getId ( ) ) { continue ; } if ( fst . getSemiring ( ) . isNotZero ( s . getFinalWeight ( ) ) || ! omitZeroStates ) { out . println ( s . getId ( ) + "\t" + s . getFinalWeight ( ) ) ; } } MutableSymbolTable . InvertedSymbolTable inputIds = fst . getInputSymbols ( ) . invert ( ) ; MutableSymbolTable . InvertedSymbolTable outputIds = fst . getOutputSymbols ( ) . invert ( ) ; numStates = fst . getStateCount ( ) ; for ( int i = 0 ; i < numStates ; i ++ ) { State s = fst . getState ( i ) ; int numArcs = s . getArcCount ( ) ; for ( int j = 0 ; j < numArcs ; j ++ ) { Arc arc = s . getArc ( j ) ; String isym ; String osym ; if ( useSymbolIdsInText ) { isym = Integer . toString ( arc . getIlabel ( ) ) ; osym = Integer . toString ( arc . getOlabel ( ) ) ; } else { isym = inputIds . keyForId ( arc . getIlabel ( ) ) ; osym = outputIds . keyForId ( arc . getOlabel ( ) ) ; } out . println ( s . getId ( ) + "\t" + arc . getNextState ( ) . getId ( ) + "\t" + isym + "\t" + osym + "\t" + arc . getWeight ( ) ) ; } } out . close ( ) ; } catch ( IOException e ) { throw Throwables . propagate ( e ) ; } } | Exports an fst to the openfst text format |
37,135 | private static void exportSymbols ( SymbolTable syms , String filename ) { if ( syms == null ) { return ; } try ( PrintWriter out = new PrintWriter ( new FileWriter ( filename ) ) ) { for ( ObjectIntCursor < String > sym : syms ) { out . println ( sym . key + "\t" + sym . value ) ; } } catch ( IOException e ) { throw Throwables . propagate ( e ) ; } } | Exports a symbols map to the openfst text format |
37,136 | private static Optional < MutableSymbolTable > importSymbols ( String filename ) { URL resource ; try { resource = Resources . getResource ( filename ) ; } catch ( IllegalArgumentException e ) { return Optional . absent ( ) ; } return importSymbolsFrom ( asCharSource ( resource , Charsets . UTF_8 ) ) ; } | Imports an openfst s symbols file |
37,137 | public static < W , S extends GenericSemiring < W > > UnionSemiring < W , S > makeForOrdering ( S weightSemiring , Ordering < W > ordering , MergeStrategy < W > merge ) { return makeForOrdering ( weightSemiring , ordering , merge , UnionMode . NORMAL ) ; } | Creates a new union semirng for the given underlying weight semiring and ordering |
37,138 | public GallicWeight commonDivisor ( GallicWeight a , GallicWeight b ) { double newWeight = this . weightSemiring . plus ( a . getWeight ( ) , b . getWeight ( ) ) ; if ( isZero ( a ) ) { if ( isZero ( b ) ) { return zero ; } if ( b . getLabels ( ) . isEmpty ( ) ) { return GallicWeight . create ( GallicWeight . EMPTY , newWeight ) ; } return GallicWeight . createSingleLabel ( b . getLabels ( ) . get ( 0 ) , newWeight ) ; } else if ( isZero ( b ) ) { if ( a . getLabels ( ) . isEmpty ( ) ) { return GallicWeight . create ( GallicWeight . EMPTY , newWeight ) ; } return GallicWeight . createSingleLabel ( a . getLabels ( ) . get ( 0 ) , newWeight ) ; } else { if ( a . getLabels ( ) . isEmpty ( ) || b . getLabels ( ) . isEmpty ( ) ) { return GallicWeight . create ( GallicWeight . EMPTY , newWeight ) ; } if ( a . getLabels ( ) . get ( 0 ) == b . getLabels ( ) . get ( 0 ) ) { return GallicWeight . createSingleLabel ( a . getLabels ( ) . get ( 0 ) , newWeight ) ; } return GallicWeight . create ( GallicWeight . EMPTY , newWeight ) ; } } | In this gallic semiring we restrict the common divisor to only be the first character in the stringweight In more general real - time FSTs that support substrings this could be longer but openfst doesn t support this and we don t support this |
37,139 | public static MutableFst reverse ( Fst infst ) { infst . throwIfInvalid ( ) ; MutableFst fst = ExtendFinal . apply ( infst ) ; Semiring semiring = fst . getSemiring ( ) ; MutableFst result = new MutableFst ( fst . getStateCount ( ) , semiring ) ; result . setInputSymbolsAsCopy ( fst . getInputSymbols ( ) ) ; result . setOutputSymbolsAsCopy ( fst . getOutputSymbols ( ) ) ; MutableState [ ] stateMap = initStateMap ( fst , semiring , result ) ; for ( int i = 0 ; i < fst . getStateCount ( ) ; i ++ ) { State oldState = fst . getState ( i ) ; MutableState newState = stateMap [ oldState . getId ( ) ] ; for ( int j = 0 ; j < oldState . getArcCount ( ) ; j ++ ) { Arc oldArc = oldState . getArc ( j ) ; MutableState newNextState = stateMap [ oldArc . getNextState ( ) . getId ( ) ] ; double newWeight = semiring . reverse ( oldArc . getWeight ( ) ) ; result . addArc ( newNextState , oldArc . getIlabel ( ) , oldArc . getOlabel ( ) , newState , newWeight ) ; } } return result ; } | Reverses an fst |
37,140 | public static MutableFst apply ( Fst fst ) { fst . throwIfInvalid ( ) ; MutableFst copy = MutableFst . copyFrom ( fst ) ; Semiring semiring = copy . getSemiring ( ) ; ArrayList < MutableState > resultStates = initResultStates ( copy , semiring ) ; MutableState newFinal = new MutableState ( semiring . one ( ) ) ; copy . addState ( newFinal ) ; int epsILabel = copy . getInputSymbols ( ) . get ( Fst . EPS ) ; int epsOLabel = copy . getOutputSymbols ( ) . get ( Fst . EPS ) ; for ( MutableState s : resultStates ) { copy . addArc ( s , epsILabel , epsOLabel , newFinal , s . getFinalWeight ( ) ) ; s . setFinalWeight ( semiring . zero ( ) ) ; } return copy ; } | Creates a new FST that is a copy of the existing with a new signle final state |
37,141 | public static WriteableSymbolTable symbolTableEffectiveCopy ( SymbolTable syms ) { if ( syms instanceof ImmutableSymbolTable ) { return new UnionSymbolTable ( syms ) ; } if ( syms instanceof UnionSymbolTable ) { return UnionSymbolTable . copyFrom ( ( UnionSymbolTable ) syms ) ; } if ( syms instanceof FrozenSymbolTable ) { return ( FrozenSymbolTable ) syms ; } return new MutableSymbolTable ( syms ) ; } | Returns an effective copy of the given symbol table which might be a unioned symbol table that is just a mutable filter on top of a backing table which is treated as immutable NOTE a frozen symbol table indicates that you do NOT want writes to be allowed |
37,142 | public static MutableFst remove ( Fst fst ) { Preconditions . checkNotNull ( fst ) ; Preconditions . checkNotNull ( fst . getSemiring ( ) ) ; Semiring semiring = fst . getSemiring ( ) ; MutableFst result = MutableFst . emptyWithCopyOfSymbols ( fst ) ; int iEps = fst . getInputSymbols ( ) . get ( Fst . EPS ) ; int oEps = fst . getOutputSymbols ( ) . get ( Fst . EPS ) ; @ SuppressWarnings ( "unchecked" ) HashMap < Integer , Double > [ ] closure = new HashMap [ fst . getStateCount ( ) ] ; MutableState [ ] oldToNewStateMap = new MutableState [ fst . getStateCount ( ) ] ; State [ ] newToOldStateMap = new State [ fst . getStateCount ( ) ] ; initResultStates ( fst , result , oldToNewStateMap , newToOldStateMap ) ; addNonEpsilonArcs ( fst , result , iEps , oEps , closure , oldToNewStateMap ) ; for ( int i = 0 ; i < result . getStateCount ( ) ; i ++ ) { MutableState state = result . getState ( i ) ; State oldState = newToOldStateMap [ state . getId ( ) ] ; if ( closure [ oldState . getId ( ) ] == null ) { continue ; } for ( Integer pathFinalStateIndex : closure [ oldState . getId ( ) ] . keySet ( ) ) { State closureState = fst . getState ( pathFinalStateIndex ) ; if ( semiring . isNotZero ( closureState . getFinalWeight ( ) ) ) { Double prevWeight = getPathWeight ( oldState , closureState , closure ) ; Preconditions . checkNotNull ( prevWeight , "problem with prev weight on closure from %s" , oldState ) ; state . setFinalWeight ( semiring . plus ( state . getFinalWeight ( ) , semiring . times ( prevWeight , closureState . getFinalWeight ( ) ) ) ) ; } for ( int j = 0 ; j < closureState . getArcCount ( ) ; j ++ ) { Arc arc = closureState . getArc ( j ) ; if ( ( arc . getIlabel ( ) != iEps ) || ( arc . getOlabel ( ) != oEps ) ) { Double pathWeight = getPathWeight ( oldState , closureState , closure ) ; Preconditions . checkNotNull ( pathWeight , "problem with prev weight on closure from %s" , oldState ) ; double newWeight = semiring . times ( arc . getWeight ( ) , pathWeight ) ; MutableState nextState = oldToNewStateMap [ arc . getNextState ( ) . getId ( ) ] ; result . addArc ( state , arc . getIlabel ( ) , arc . getOlabel ( ) , nextState , newWeight ) ; } } } } Connect . apply ( result ) ; ArcSort . sortByInput ( result ) ; return result ; } | Removes epsilon transitions from an fst . Returns a new epsilon - free fst and does not modify the original fst |
37,143 | private static void put ( State fromState , State toState , double weight , HashMap < Integer , Double > [ ] closure ) { HashMap < Integer , Double > maybe = closure [ fromState . getId ( ) ] ; if ( maybe == null ) { maybe = new HashMap < Integer , Double > ( ) ; closure [ fromState . getId ( ) ] = maybe ; } maybe . put ( toState . getId ( ) , weight ) ; } | Put a new state in the epsilon closure |
37,144 | private static void add ( State fromState , State toState , double weight , HashMap < Integer , Double > [ ] closure , Semiring semiring ) { Double old = getPathWeight ( fromState , toState , closure ) ; if ( old == null ) { put ( fromState , toState , weight , closure ) ; } else { put ( fromState , toState , semiring . plus ( weight , old ) , closure ) ; } } | Add a state in the epsilon closure |
37,145 | private static void calculateClosure ( Fst fst , State state , HashMap < Integer , Double > [ ] closure , Semiring semiring , int iEps , int oEps ) { for ( int j = 0 ; j < state . getArcCount ( ) ; j ++ ) { Arc arc = state . getArc ( j ) ; if ( ( arc . getIlabel ( ) != iEps ) || ( arc . getOlabel ( ) != oEps ) ) { continue ; } int nextStateId = arc . getNextState ( ) . getId ( ) ; if ( closure [ nextStateId ] == null ) { calculateClosure ( fst , arc . getNextState ( ) , closure , semiring , iEps , oEps ) ; } HashMap < Integer , Double > closureEntry = closure [ nextStateId ] ; if ( closureEntry != null ) { for ( Integer pathFinalStateIndex : closureEntry . keySet ( ) ) { State pathFinalState = fst . getState ( pathFinalStateIndex ) ; Double prevPathWeight = getPathWeight ( arc . getNextState ( ) , pathFinalState , closure ) ; Preconditions . checkNotNull ( prevPathWeight , "prev arc %s never set in closure" , arc ) ; double newPathWeight = semiring . times ( prevPathWeight , arc . getWeight ( ) ) ; add ( state , pathFinalState , newPathWeight , closure , semiring ) ; } } add ( state , arc . getNextState ( ) , arc . getWeight ( ) , closure , semiring ) ; } } | Calculate the epsilon closure |
37,146 | private static Double getPathWeight ( State inState , State outState , HashMap < Integer , Double > [ ] closure ) { if ( closure [ inState . getId ( ) ] != null ) { return closure [ inState . getId ( ) ] . get ( outState . getId ( ) ) ; } return null ; } | Get an epsilon path s cost in epsilon closure |
37,147 | public static int maxIdIn ( SymbolTable table ) { int max = 0 ; for ( ObjectIntCursor < String > cursor : table ) { max = Math . max ( max , cursor . value ) ; } return max ; } | Returns the current max id mapped in this symbol table or 0 if this has no mappings |
37,148 | public int get ( String symbol ) { int id = symbolToId . getOrDefault ( symbol , - 1 ) ; if ( id < 0 ) { throw new IllegalArgumentException ( "No symbol exists for key " + symbol ) ; } return id ; } | Returns the id of the symbol or throws an exception if this symbol isnt in the table |
37,149 | public static InetAddress getAddress ( ) { try { return InetAddress . getByAddress ( new byte [ ] { 0 , 0 , 0 , 0 } ) ; } catch ( Exception e ) { System . err . println ( "Error" ) ; } return null ; } | This method returns the address of the machine . It is needed to successfully communicate with emulators hosted into other machines . |
37,150 | public void setCalendar ( int year , int month , int dayOfMonth , int hour , int minute , int second ) { this . year = year ; this . month = month ; this . dayOfMonth = dayOfMonth ; this . hour = hour ; this . minute = minute ; this . second = second ; this . createCalendar ( ) ; } | It sets the simulation time . |
37,151 | public void addValue ( long newValue ) { InApplicationMonitor . getInstance ( ) . addTimerMeasurement ( timerName , newValue ) ; if ( newValue > currentMaxValue ) { currentMaxValue = newValue ; } long binIndex ; if ( newValue > maxLimit ) { binIndex = maxLimit / factor ; } else { binIndex = newValue / factor ; } String binName = getBinName ( binIndex ) ; InApplicationMonitor . getInstance ( ) . incrementCounter ( binName ) ; } | adds a new value to the InApplicationMonitor grouping it into the appropriate bin . |
37,152 | public boolean evaluate ( Agent agent ) { long t = agent . getAgentsAppState ( ) . getPHAInterface ( ) . getSimTime ( ) . getTimeInMillis ( ) ; if ( t != timestamp ) { timestamp = t ; evaluation = simpleEvaluation ( agent ) ; } return evaluation ; } | It tells if the condition is met |
37,153 | private void registerJMXStuff ( ) { LOG . info ( "registering InApplicationMonitorDynamicMBean on JMX server" ) ; try { jmxBeanRegistrationHelper . registerMBeanOnJMX ( this , "InApplicationMonitor" , null ) ; } catch ( Exception e ) { LOG . error ( "could not register MBean server : " , e ) ; } } | registers the InApplicationMonitor as JMX MBean on the running JMX server - if no JMX server is running one is started automagically . |
37,154 | public static Geometry createCube ( Vector3f dimensions , ColorRGBA color ) { checkInit ( ) ; Box b = new Box ( dimensions . getX ( ) , dimensions . getY ( ) , dimensions . getZ ( ) ) ; Geometry geom = new Geometry ( "Box" , b ) ; Material mat = new Material ( assetManager , "Common/MatDefs/Misc/Unshaded.j3md" ) ; mat . setColor ( "Color" , color ) ; geom . setMaterial ( mat ) ; return geom ; } | Creates a cube given its dimensions and its color |
37,155 | public static Geometry createShape ( String name , Mesh shape , ColorRGBA color ) { checkInit ( ) ; Geometry g = new Geometry ( name , shape ) ; Material mat = new Material ( assetManager , "Common/MatDefs/Misc/Unshaded.j3md" ) ; mat . getAdditionalRenderState ( ) . setWireframe ( true ) ; mat . setColor ( "Color" , color ) ; g . setMaterial ( mat ) ; return g ; } | Creates a geometry given its name its mesh and its color |
37,156 | public static BitmapText attachAName ( Node node , String name ) { checkInit ( ) ; BitmapFont guiFont = assetManager . loadFont ( "Interface/Fonts/Default.fnt" ) ; BitmapText ch = new BitmapText ( guiFont , false ) ; ch . setName ( "BitmapText" ) ; ch . setSize ( guiFont . getCharSet ( ) . getRenderedSize ( ) * 0.02f ) ; ch . setText ( name ) ; ch . setColor ( new ColorRGBA ( 0f , 0f , 0f , 1f ) ) ; ch . getLocalScale ( ) . divideLocal ( node . getLocalScale ( ) ) ; BillboardControl control = new BillboardControl ( ) ; ch . addControl ( control ) ; node . attachChild ( ch ) ; return ch ; } | Creates a geometry with the same name of the given node . It adds a controller called BillboardControl that turns the name of the node in order to look at the camera . |
37,157 | public void setFilePath ( String filePath ) { this . filePath = filePath ; if ( ! this . filePath . endsWith ( File . separator ) ) { this . filePath += File . separator ; } } | Set the file path to store the screenshot . Include the seperator at the end of the path . Use an emptry string to use the application folder . Use NULL to use the system default storage folder . |
37,158 | public void addReportableObserver ( final ReportableObserver reportableObserver ) { reportableObservers . add ( reportableObserver ) ; LOGGER . info ( "registering new ReportableObserver (" + reportableObserver . getClass ( ) . getName ( ) + ")" ) ; reportInto ( new ReportVisitor ( ) { public void notifyReportableObserver ( Reportable reportable ) { reportableObserver . addNewReportable ( reportable ) ; } public void reportCounter ( Counter counter ) { notifyReportableObserver ( counter ) ; } public void reportTimer ( Timer timer ) { notifyReportableObserver ( timer ) ; } public void reportStateValue ( StateValueProvider stateValueProvider ) { notifyReportableObserver ( stateValueProvider ) ; } public void reportMultiValue ( MultiValueProvider multiValueProvider ) { notifyReportableObserver ( multiValueProvider ) ; } public void reportHistorizableList ( HistorizableList historizableList ) { notifyReportableObserver ( historizableList ) ; } public void reportVersion ( Version version ) { notifyReportableObserver ( version ) ; } } ) ; } | adds a new ReportableObserver that wants to be notified about new Reportables that are registered on the InApplicationMonitor |
37,159 | HistorizableList getHistorizableList ( final String name ) { return historizableLists . get ( name , new Monitors . Factory < HistorizableList > ( ) { public HistorizableList createMonitor ( ) { return new HistorizableList ( name , maxHistoryEntriesToKeep ) ; } } ) ; } | internally used method to retrieve or create and register a named HistorizableList . |
37,160 | public void initializeCounter ( String name ) { String escapedName = keyHandler . handle ( name ) ; for ( MonitorPlugin p : getPlugins ( ) ) { p . initializeCounter ( escapedName ) ; } } | If you want to ensure existance of a counter for example you want to prevent spelling errors in an operational monitoring configuration you may initialize a counter using this method . The plugins will decide how to handle this initialization . |
37,161 | public void registerAllPossibleTransition ( Automaton [ ] states ) { for ( int i = 0 ; i < states . length ; i ++ ) { for ( int j = i ; j < states . length ; j ++ ) { registerTransition ( states [ i ] , states [ j ] ) ; registerTransition ( states [ j ] , states [ i ] ) ; } } } | Pasandole un array genera todas las transiciones posibles entre los estados . |
37,162 | public ArrayList < Transition > possibleNextStates ( Automaton source ) { ArrayList < Transition > r = possibleTransitions . get ( source ) ; if ( r == null ) { throw new UnsupportedOperationException ( "Not transitions registered from " + source . getName ( ) + ", automaton " + this . getName ( ) ) ; } ArrayList < Transition > activatedTransitions = new ArrayList < Transition > ( ) ; for ( Transition t : r ) { if ( t . evaluate ( ) ) { activatedTransitions . add ( t ) ; } } ; return activatedTransitions ; } | Dado un estado se devuelve una lista con los posibles estados que le siguen en el protocolo . |
37,163 | public boolean createFile ( ) { try { try ( FileWriter newDic = new FileWriter ( path + "/" + name + "." + FILE_EXTENSION ) ; BufferedWriter bufWriter = new BufferedWriter ( newDic ) ) { bufWriter . write ( HEAD ) ; if ( sentences . size ( ) > 0 ) { bufWriter . write ( "public <sentence> = (" + sentences . get ( 0 ) ) ; for ( int i = 1 ; i < sentences . size ( ) ; i ++ ) { bufWriter . write ( " | " + sentences . get ( i ) ) ; } bufWriter . write ( " );\n" ) ; } bufWriter . flush ( ) ; } return true ; } catch ( IOException ex ) { Logger . getLogger ( GrammarFacilitator . class . getName ( ) ) . log ( Level . SEVERE , null , ex ) ; } return false ; } | Create a file with the JSGF Grammar |
37,164 | public void validate ( ) { if ( this . encoding == null ) { throw new IllegalArgumentException ( "File encoding must not be null!" ) ; } Charset . forName ( this . encoding ) ; if ( this . textQualifier == this . fieldDelimiter ) { throw new IllegalStateException ( "Field delimiter and text qualifier can not be equal!" ) ; } if ( StringUtil . isBlank ( this . fileMask ) ) { throw new IllegalArgumentException ( "File mask must not be blank!" ) ; } if ( StringUtil . isBlank ( this . sourcePath ) ) { throw new IllegalArgumentException ( "Source path must not be blank!" ) ; } if ( this . keyColumnNames == null || this . keyColumnNames . length == 0 ) { throw new IllegalArgumentException ( "key column name must not be blank!" ) ; } if ( this . fields == null || this . fields . length == 0 ) { throw new IllegalArgumentException ( "Column names must not be blank!" ) ; } if ( StringUtil . isBlank ( this . keyseparator ) ) { throw new IllegalArgumentException ( "File mask must not be blank!" ) ; } } | Determine if all the values are valid . |
37,165 | public void run ( ) { try { StringBuffer sb = this . generateReport ( ) ; ingenias . editor . Log . getInstance ( ) . log ( "Statistics of usage of meta-model entities and relationships" ) ; ingenias . editor . Log . getInstance ( ) . log ( "Name Number of times it appears" ) ; ingenias . editor . Log . getInstance ( ) . log ( "---- --------------------------" ) ; ingenias . editor . Log . getInstance ( ) . log ( sb . toString ( ) ) ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; } } | It creates stats of usage by traversing diagrams of your specification . Resulting report appears in standard output or in the IDE |
37,166 | public static void main ( String [ ] args ) { Advanced app = new Advanced ( ) ; AppSettings settings = new AppSettings ( true ) ; settings . setAudioRenderer ( AurellemSystemDelegate . SEND ) ; JmeSystem . setSystemDelegate ( new AurellemSystemDelegate ( ) ) ; app . setSettings ( settings ) ; app . setShowSettings ( false ) ; app . setPauseOnLostFocus ( false ) ; app . start ( ) ; } | You will see three grey cubes a blue sphere and a path which circles each cube . The blue sphere is generating a constant monotone sound as it moves along the track . Each cube is listening for sound ; when a cube hears sound whose intensity is greater than a certain threshold it changes its color from grey to green . |
37,167 | public void add ( SensorListener sensorListener ) { if ( ! listeners . contains ( sensorListener ) ) { listeners . add ( sensorListener ) ; if ( ! isEnabled ( ) ) { setEnabled ( true ) ; } } } | Adds a sensor listener and the sensor is enabled if it was disabled in order to feed data to the listener |
37,168 | public void remove ( SensorListener sensorListener ) { listeners . remove ( sensorListener ) ; if ( listeners . isEmpty ( ) && isEnabled ( ) ) { setEnabled ( false ) ; } } | Removes a listener and if there are not more listener the sensor is disabled in order to save resources |
37,169 | public Set < String > getDeadlockedThreads ( ) { final long [ ] threadIds = threads . findDeadlockedThreads ( ) ; if ( threadIds != null ) { final Set < String > threads = new HashSet < String > ( ) ; for ( ThreadInfo info : this . threads . getThreadInfo ( threadIds , MAX_STACK_TRACE_DEPTH ) ) { final StringBuilder stackTrace = new StringBuilder ( ) ; for ( StackTraceElement element : info . getStackTrace ( ) ) { stackTrace . append ( "\t at " ) . append ( element . toString ( ) ) . append ( '\n' ) ; } threads . add ( String . format ( "%s locked on %s (owned by %s):\n%s" , info . getThreadName ( ) , info . getLockName ( ) , info . getLockOwnerName ( ) , stackTrace . toString ( ) ) ) ; } return Collections . unmodifiableSet ( threads ) ; } return Collections . emptySet ( ) ; } | Returns a set of strings describing deadlocked threads if any are deadlocked . |
37,170 | private void filter ( Vector3f acc ) { float threshold = 15f ; if ( acc . x > threshold ) { acc . x = threshold ; } else if ( acc . x < - threshold ) { acc . x = - threshold ; } if ( acc . y > threshold ) { acc . y = threshold ; } else if ( acc . y < - threshold ) { acc . y = - threshold ; } if ( acc . z > threshold ) { acc . z = threshold ; } else if ( acc . z < - threshold ) { acc . z = - threshold ; } } | remove pointed values |
37,171 | @ SuppressWarnings ( "unchecked" ) public static < E > E wrapObject ( final Class < E > clazz , final Object target , final TimingReporter timingReporter ) { return ( E ) Proxy . newProxyInstance ( GenericMonitoringWrapper . class . getClassLoader ( ) , new Class [ ] { clazz } , new GenericMonitoringWrapper < E > ( clazz , target , timingReporter ) ) ; } | Wraps the given object and returns the reporting proxy . Uses the given timing reporter to report timings . |
37,172 | public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { final long startTime = System . currentTimeMillis ( ) ; Object result = null ; try { result = method . invoke ( target , args ) ; if ( ( result != null ) && ! method . getReturnType ( ) . equals ( Void . TYPE ) && method . getReturnType ( ) . isInterface ( ) ) { result = wrapObject ( method . getReturnType ( ) , result , reporter ) ; } } catch ( InvocationTargetException t ) { if ( t . getCause ( ) != null ) { throw t . getCause ( ) ; } } finally { final long endTime = System . currentTimeMillis ( ) ; reporter . reportTimedOperation ( targetClass , method , startTime , endTime ) ; } return result ; } | Handles method invocations on the generated proxy . Measures the time needed to execute the given method on the wrapped object . |
37,173 | private boolean areNextStatesAvailable ( Automaton source ) { ArrayList < Transition > r = possibleTransitions . get ( source ) ; if ( r != null ) { for ( Transition t : r ) { if ( t . evaluate ( ) ) { return true ; } } } return false ; } | Return true if there are transitions available as true . |
37,174 | public static boolean isMultiListener ( String [ ] args ) { for ( int i = 0 ; i < args . length ; i ++ ) { if ( args [ i ] . equals ( "-ml" ) ) { return true ; } } return false ; } | Checks if arguments contains multilisterner option - lm |
37,175 | public static Collection < ? extends GraphEntity > getAscendantsOfRole ( GraphEntity ge ) { Vector < GraphEntity > allAscendants = new Vector < GraphEntity > ( ) ; try { Vector < GraphEntity > ascendants = Utils . getRelatedElementsVector ( ge , "ARoleInheritance" , "ARoleInheritancetarget" ) ; while ( ! ascendants . isEmpty ( ) ) { allAscendants . addAll ( ascendants ) ; ascendants . clear ( ) ; for ( GraphEntity ascendant : allAscendants ) { ascendants . addAll ( Utils . getRelatedElementsVector ( ascendant , "ARoleInheritance" , "ARoleInheritancetarget" ) ) ; } ascendants . removeAll ( allAscendants ) ; } } catch ( NullEntity e ) { e . printStackTrace ( ) ; } return allAscendants ; } | It obtains all ascendants of a role through the ARoleInheritance relationship . |
37,176 | public static Vector getRelatedElementsVector ( String pathname , GraphEntity element , String relationshipname , String role ) throws NullEntity { Vector rels = element . getAllRelationships ( ) ; Enumeration enumeration = rels . elements ( ) ; Vector related = new Vector ( ) ; while ( enumeration . hasMoreElements ( ) ) { GraphRelationship gr = ( GraphRelationship ) enumeration . nextElement ( ) ; String [ ] path = gr . getGraph ( ) . getPath ( ) ; boolean found = false ; for ( int k = 0 ; k < path . length && ! found ; k ++ ) { found = path [ k ] . toLowerCase ( ) . indexOf ( pathname ) >= 0 ; } if ( found && gr . getType ( ) . toLowerCase ( ) . equals ( relationshipname . toLowerCase ( ) ) ) { GraphRole [ ] roles = gr . getRoles ( ) ; for ( int k = 0 ; k < roles . length ; k ++ ) { if ( roles [ k ] . getName ( ) . toLowerCase ( ) . equals ( role . toLowerCase ( ) ) ) { related . add ( roles [ k ] . getPlayer ( ) ) ; } } } } return new Vector ( new HashSet ( related ) ) ; } | It obtains all elements related with element with relationshipname and occupying the extreme role . Also the association where these elements appear must be allocated in the package whose pathname matches the pathname parameter |
37,177 | public static GraphEntity [ ] toGEArray ( Object [ ] o ) { GraphEntity [ ] result = new GraphEntity [ o . length ] ; System . arraycopy ( o , 0 , result , 0 , o . length ) ; return result ; } | It casts an array of objets to an array of GraphEntity |
37,178 | public static GraphRelationship [ ] toGRArray ( Object [ ] o ) { GraphRelationship [ ] result = new GraphRelationship [ o . length ] ; System . arraycopy ( o , 0 , result , 0 , o . length ) ; return result ; } | It casts an array of objets to an array of GraphRelationship |
37,179 | public static GraphRole [ ] toGRoArray ( Object [ ] o ) { GraphRole [ ] result = new GraphRole [ o . length ] ; System . arraycopy ( o , 0 , result , 0 , o . length ) ; return result ; } | It casts an array of objets to an array of GraphRole |
37,180 | public static GraphEntity [ ] generateEntitiesOfType ( String type , Browser browser ) throws NotInitialised { Graph [ ] gs = browser . getGraphs ( ) ; Sequences p = new Sequences ( ) ; GraphEntity [ ] ges = browser . getAllEntities ( ) ; HashSet actors = new HashSet ( ) ; for ( int k = 0 ; k < ges . length ; k ++ ) { if ( ges [ k ] . getType ( ) . equals ( type ) ) { actors . add ( ges [ k ] ) ; } } return toGEArray ( actors . toArray ( ) ) ; } | It obtains all entities in the specification whose type represented as string is the same as the string passed as parameter |
37,181 | public static GraphRole [ ] getRelatedElementsRoles ( GraphEntity element , String relationshipname , String role ) { Vector rels = element . getAllRelationships ( ) ; Enumeration enumeration = rels . elements ( ) ; Vector related = new Vector ( ) ; while ( enumeration . hasMoreElements ( ) ) { GraphRelationship gr = ( GraphRelationship ) enumeration . nextElement ( ) ; if ( gr . getType ( ) . toLowerCase ( ) . equals ( relationshipname . toLowerCase ( ) ) ) { GraphRole [ ] roles = gr . getRoles ( ) ; for ( int k = 0 ; k < roles . length ; k ++ ) { if ( roles [ k ] . getName ( ) . toLowerCase ( ) . equals ( role . toLowerCase ( ) ) ) { related . add ( roles [ k ] ) ; } } } } return toGRoArray ( related . toArray ( ) ) ; } | It obtains the extremes of the association of type relationshipname where one of their roles is role and originated in the element |
37,182 | public static List < GraphEntity > getEntities ( Graph g , String typeName ) throws NullEntity { GraphEntity [ ] ge = g . getEntities ( ) ; List < GraphEntity > result = new ArrayList < > ( ) ; for ( int k = 0 ; k < ge . length ; k ++ ) { if ( ge [ k ] . getType ( ) . equals ( typeName ) ) { result . add ( ge [ k ] ) ; } } return result ; } | It obtains the entities in the graph g whose type is the same as typeName . |
37,183 | public static void listAllVoices ( ) { System . out . println ( ) ; System . out . println ( "All voices available:" ) ; VoiceManager voiceManager = VoiceManager . getInstance ( ) ; Voice [ ] voices = voiceManager . getVoices ( ) ; for ( int i = 0 ; i < voices . length ; i ++ ) { System . out . println ( " " + voices [ i ] . getName ( ) + " (" + voices [ i ] . getDomain ( ) + " domain)" ) ; } } | Example of how to list all the known voices . |
37,184 | private void newFilter ( ) { RowFilter < MyTableModel , Object > rf = null ; try { rf = RowFilter . regexFilter ( filterText . getText ( ) , 0 ) ; } catch ( java . util . regex . PatternSyntaxException e ) { return ; } sorter . setRowFilter ( rf ) ; } | Update the row filter regular expression from the expression in the text box . |
37,185 | private void checkForError ( JsonNode resp ) throws WePayException { JsonNode errorNode = resp . get ( "error" ) ; if ( errorNode != null ) throw new WePayException ( errorNode . asText ( ) , resp . path ( "error_description" ) . asText ( ) , resp . path ( "error_code" ) . asInt ( ) ) ; } | If the response node is recognized as an error throw a WePayException |
37,186 | private HttpURLConnection getConnection ( String uri , String postJson , String token ) throws IOException { int tries = 0 ; IOException last = null ; while ( tries ++ <= retries ) { try { return getConnectionOnce ( uri , postJson , token ) ; } catch ( IOException ex ) { last = ex ; } } throw last ; } | Common functionality for posting data . Smart about retries . |
37,187 | private HttpURLConnection getConnectionOnce ( String uri , String postJson , String token ) throws IOException { URL url = new URL ( uri ) ; HttpURLConnection conn = ( HttpURLConnection ) url . openConnection ( ) ; if ( timeout > 0 ) { conn . setReadTimeout ( timeout ) ; conn . setConnectTimeout ( timeout ) ; } if ( postJson != null && postJson . equals ( "{}" ) ) postJson = null ; if ( postJson != null ) { conn . setDoOutput ( true ) ; } conn . setRequestProperty ( "Content-Type" , "application/json; charset=" + UTF8 . name ( ) ) ; conn . setRequestProperty ( "User-Agent" , "WePay Java SDK" ) ; if ( token != null ) { conn . setRequestProperty ( "Authorization" , "Bearer " + token ) ; } if ( postJson != null ) { OutputStreamWriter writer = new OutputStreamWriter ( conn . getOutputStream ( ) , UTF8 ) ; writer . write ( postJson ) ; writer . close ( ) ; } return conn ; } | Sets up the headers and writes the post data . |
37,188 | public static void premain ( final String agentArgs , final Instrumentation instrumentation ) { System . out . println ( "Initialiting Appmon4jAgent" ) ; Appmon4JAgentConfiguration configuration = null ; try { configuration = Appmon4JAgentConfiguration . load ( agentArgs ) ; } catch ( Exception e ) { System . err . println ( "failed to load appmon4j agent configuration from " + agentArgs + "." ) ; e . printStackTrace ( ) ; } if ( configuration != null ) { new Appmon4JAgent ( configuration , instrumentation ) ; } else { System . err . println ( "appmon4j Agent: Unable to start up. No valid configuration found. Will do nothing. " ) ; } } | The premain method to be implemented by java agents to provide an entry point for the instrumentation . |
37,189 | public static double stdDeviation ( final long n , final double sum , final double sumOfSquares ) { double stdDev = 0 ; if ( n > 1 ) { final double numerator = sumOfSquares - ( ( sum * sum ) / n ) ; stdDev = java . lang . Math . sqrt ( numerator / ( n - 1 ) ) ; } return stdDev ; } | Calculate the standard deviation from an amount of values n a sum and a sum of squares . |
37,190 | public static void getScreenShotABGR ( ByteBuffer bgraBuf , BufferedImage out ) { WritableRaster wr = out . getRaster ( ) ; DataBufferByte db = ( DataBufferByte ) wr . getDataBuffer ( ) ; byte [ ] cpuArray = db . getData ( ) ; bgraBuf . clear ( ) ; bgraBuf . get ( cpuArray ) ; bgraBuf . clear ( ) ; int width = wr . getWidth ( ) ; int height = wr . getHeight ( ) ; for ( int y = 0 ; y < height / 2 ; y ++ ) { for ( int x = 0 ; x < width ; x ++ ) { int inPtr = ( y * width + x ) * 4 ; int outPtr = ( ( height - y - 1 ) * width + x ) * 4 ; byte b1 = cpuArray [ inPtr + 0 ] ; byte g1 = cpuArray [ inPtr + 1 ] ; byte r1 = cpuArray [ inPtr + 2 ] ; byte a1 = cpuArray [ inPtr + 3 ] ; byte b2 = cpuArray [ outPtr + 0 ] ; byte g2 = cpuArray [ outPtr + 1 ] ; byte r2 = cpuArray [ outPtr + 2 ] ; byte a2 = cpuArray [ outPtr + 3 ] ; cpuArray [ outPtr + 0 ] = a1 ; cpuArray [ outPtr + 1 ] = b1 ; cpuArray [ outPtr + 2 ] = g1 ; cpuArray [ outPtr + 3 ] = r1 ; cpuArray [ inPtr + 0 ] = a2 ; cpuArray [ inPtr + 1 ] = b2 ; cpuArray [ inPtr + 2 ] = g2 ; cpuArray [ inPtr + 3 ] = r2 ; } } } | Good format for java swing . |
37,191 | @ SuppressWarnings ( "unchecked" ) public C downstreamConsumerFactory ( Supplier < Consumer < String > > downstreamConsumerFactory ) { this . downstreamConsumerFactory = requireNonNull ( downstreamConsumerFactory ) ; return ( C ) this ; } | Sets a downstream consumer s factory to this builder object . |
37,192 | private static void appendMetaColumns ( StringBuilder buffer , MetadataColumnDefinition [ ] values ) { for ( MetadataColumnDefinition column : values ) { buffer . append ( ", " ) . append ( column . getColumnNamePrefix ( ) ) ; } } | Append metric and entity metadata columns to series requests . This method must not be used while processing meta tables . |
37,193 | static Collection < MetricLocation > prepareGetMetricUrls ( List < String > metricMasks , String tableFilter , boolean underscoreAsLiteral ) { if ( WildcardsUtil . isRetrieveAllPattern ( tableFilter ) || tableFilter . isEmpty ( ) ) { if ( metricMasks . isEmpty ( ) ) { return Collections . emptyList ( ) ; } else { return buildPatternDisjunction ( metricMasks , underscoreAsLiteral ) ; } } else { return Collections . singletonList ( buildAtsdPatternUrl ( tableFilter , underscoreAsLiteral ) ) ; } } | Prepare URL to retrieve metrics |
37,194 | private static String [ ] splitOnTokens ( String text , String oneAnySymbolStr , String noneOrMoreSymbolsStr ) { if ( ! hasWildcards ( text , ONE_ANY_SYMBOL , NONE_OR_MORE_SYMBOLS ) ) { return new String [ ] { text } ; } List < String > list = new ArrayList < > ( ) ; StringBuilder buffer = new StringBuilder ( ) ; boolean escapeMode = false ; final int length = text . length ( ) ; for ( int i = 0 ; i < length ; i ++ ) { final char current = text . charAt ( i ) ; switch ( current ) { case ESCAPE_CHAR : if ( escapeMode ) { buffer . append ( current ) ; } else { escapeMode = true ; } break ; case ONE_ANY_SYMBOL : if ( escapeMode ) { buffer . append ( current ) ; escapeMode = false ; } else { flushBuffer ( buffer , list ) ; if ( ! list . isEmpty ( ) && noneOrMoreSymbolsStr . equals ( list . get ( list . size ( ) - 1 ) ) ) { list . set ( list . size ( ) - 1 , oneAnySymbolStr ) ; list . add ( noneOrMoreSymbolsStr ) ; } else { list . add ( oneAnySymbolStr ) ; } } break ; case NONE_OR_MORE_SYMBOLS : if ( escapeMode ) { buffer . append ( current ) ; escapeMode = false ; } else { flushBuffer ( buffer , list ) ; if ( list . isEmpty ( ) || ! noneOrMoreSymbolsStr . equals ( list . get ( list . size ( ) - 1 ) ) ) { list . add ( noneOrMoreSymbolsStr ) ; } } break ; default : if ( escapeMode ) { buffer . append ( ESCAPE_CHAR ) ; escapeMode = false ; } buffer . append ( current ) ; } } if ( escapeMode ) { buffer . append ( ESCAPE_CHAR ) ; } if ( buffer . length ( ) != 0 ) { list . add ( buffer . toString ( ) ) ; } return list . toArray ( ArrayUtils . EMPTY_STRING_ARRAY ) ; } | Splits a string into a number of tokens . The text is split by _ and % . Multiple % are collapsed into a single % patterns like %_ will be transferred to _% |
37,195 | public boolean onTouchEvent ( final MotionEvent event ) { final Spannable text = ( Spannable ) getText ( ) ; if ( text != null ) { if ( event . getAction ( ) == MotionEvent . ACTION_DOWN ) { final Layout layout = getLayout ( ) ; if ( layout != null ) { final int line = getLineAtCoordinate ( layout , event . getY ( ) ) ; final int pos = getOffsetAtCoordinate ( layout , line , event . getX ( ) ) ; final ClickableSpan [ ] links = text . getSpans ( pos , pos , ClickableSpan . class ) ; if ( links != null && links . length > 0 ) { links [ 0 ] . onClick ( this ) ; return true ; } } } } return super . onTouchEvent ( event ) ; } | We want our text to be selectable but we still want links to be clickable . |
37,196 | protected void installDefaults ( ) { updateStyle ( splitPane ) ; setOrientation ( splitPane . getOrientation ( ) ) ; setContinuousLayout ( splitPane . isContinuousLayout ( ) ) ; resetLayoutManager ( ) ; if ( nonContinuousLayoutDivider == null ) { setNonContinuousLayoutDivider ( createDefaultNonContinuousLayoutDivider ( ) , true ) ; } else { setNonContinuousLayoutDivider ( nonContinuousLayoutDivider , true ) ; } if ( managingFocusForwardTraversalKeys == null ) { managingFocusForwardTraversalKeys = new HashSet ( ) ; managingFocusForwardTraversalKeys . add ( KeyStroke . getKeyStroke ( KeyEvent . VK_TAB , 0 ) ) ; } splitPane . setFocusTraversalKeys ( KeyboardFocusManager . FORWARD_TRAVERSAL_KEYS , managingFocusForwardTraversalKeys ) ; if ( managingFocusBackwardTraversalKeys == null ) { managingFocusBackwardTraversalKeys = new HashSet ( ) ; managingFocusBackwardTraversalKeys . add ( KeyStroke . getKeyStroke ( KeyEvent . VK_TAB , InputEvent . SHIFT_MASK ) ) ; } splitPane . setFocusTraversalKeys ( KeyboardFocusManager . BACKWARD_TRAVERSAL_KEYS , managingFocusBackwardTraversalKeys ) ; } | Installs the UI defaults . |
37,197 | protected void uninstallDefaults ( ) { SeaGlassContext context = getContext ( splitPane , ENABLED ) ; style . uninstallDefaults ( context ) ; context . dispose ( ) ; style = null ; context = getContext ( splitPane , Region . SPLIT_PANE_DIVIDER , ENABLED ) ; dividerStyle . uninstallDefaults ( context ) ; context . dispose ( ) ; dividerStyle = null ; super . uninstallDefaults ( ) ; } | Uninstalls the UI defaults . |
37,198 | public BasicSplitPaneDivider createDefaultDivider ( ) { SeaGlassSplitPaneDivider divider = new SeaGlassSplitPaneDivider ( this ) ; divider . setDividerSize ( splitPane . getDividerSize ( ) ) ; return divider ; } | Creates the default divider . |
37,199 | public void paint ( Graphics2D g ) { g . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , RenderingHints . VALUE_ANTIALIAS_ON ) ; origAlpha = 1.0f ; Composite origComposite = g . getComposite ( ) ; if ( origComposite instanceof AlphaComposite ) { AlphaComposite origAlphaComposite = ( AlphaComposite ) origComposite ; if ( origAlphaComposite . getRule ( ) == AlphaComposite . SRC_OVER ) { origAlpha = origAlphaComposite . getAlpha ( ) ; } } AffineTransform trans_0 = g . getTransform ( ) ; paintRootGraphicsNode_0 ( g ) ; g . setTransform ( trans_0 ) ; } | Paints the transcoded SVG image on the specified graphics context . You can install a custom transformation on the graphics context to scale the image . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.