idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
140,300 | public boolean add ( Collection < BtrpElement > elems ) { boolean ret = false ; for ( BtrpElement el : elems ) { ret |= add ( el ) ; } return ret ; } | Add a collection of nodes or elements . | 45 | 8 |
140,301 | public boolean add ( BtrpElement el ) { switch ( el . type ( ) ) { case VM : if ( ! this . vms . add ( ( VM ) el . getElement ( ) ) ) { return false ; } break ; case NODE : if ( ! this . nodes . add ( ( Node ) el . getElement ( ) ) ) { return false ; } break ; default : return false ; } return true ; } | Add a VM or a node to the script . | 92 | 10 |
140,302 | public List < BtrpOperand > getImportables ( String ns ) { List < BtrpOperand > importable = new ArrayList <> ( ) ; for ( String symbol : getExported ( ) ) { if ( canImport ( symbol , ns ) ) { importable . add ( getImportable ( symbol , ns ) ) ; } } return importable ; } | Get all the operand a given script can import | 81 | 10 |
140,303 | public BtrpOperand getImportable ( String label , String namespace ) { if ( canImport ( label , namespace ) ) { return exported . get ( label ) ; } return null ; } | Get the exported operand from its label . | 41 | 9 |
140,304 | public boolean canImport ( String label , String namespace ) { if ( ! exported . containsKey ( label ) ) { return false ; } Set < String > scopes = exportScopes . get ( label ) ; for ( String scope : scopes ) { if ( scope . equals ( namespace ) ) { return true ; } else if ( scope . endsWith ( "*" ) && namespace . startsWith ( scope . substring ( 0 , scope . length ( ) - 1 ) ) ) { return true ; } } return false ; } | Indicates whether a namespace can import an exported variable or not . To be imported the label must point to an exported variable with no import restrictions or with a given namespace compatible with the restrictions . | 112 | 38 |
140,305 | public String fullyQualifiedSymbolName ( String name ) { if ( name . equals ( SymbolsTable . ME ) ) { return "$" . concat ( id ( ) ) ; } else if ( name . startsWith ( "$" ) ) { return "$" + id ( ) + ' ' + name . substring ( 1 ) ; } return id ( ) + ' ' + name ; } | Get the fully qualified name of a symbol . | 84 | 9 |
140,306 | public String prettyDependencies ( ) { StringBuilder b = new StringBuilder ( ) ; b . append ( id ( ) ) . append ( ' ' ) ; for ( Iterator < Script > ite = dependencies . iterator ( ) ; ite . hasNext ( ) ; ) { Script n = ite . next ( ) ; prettyDependencies ( b , ! ite . hasNext ( ) , 0 , n ) ; } return b . toString ( ) ; } | Textual representation for the dependencies . | 101 | 7 |
140,307 | public void addNode ( Node n ) { try { structure . addNode ( n ) ; for ( NodeListener listener : nodeListeners ) listener . onInsert ( n ) ; } catch ( DuplicatedNodeException e ) { duplicatedNodesCounter ++ ; } } | Adds a new node to the graph given the Node object . If a node already exists with an id equal to the given node a DuplicatedNodeException is thrown . | 56 | 33 |
140,308 | public void addEdge ( Edge e ) { structure . addEdge ( e ) ; for ( EdgeListener listener : edgeListeners ) listener . onInsert ( ) ; } | Adds a new edge to this graph given a new Edge object . It uses the GraphStructure attribute s addEdge method to add the new edge to this graph . If one of the node ids of the given Edge object does not exists in this graph a NodeNotFoundException is thrown . Otherwise the edge is successfully added to this graph . | 35 | 69 |
140,309 | public Iterator < Long > getNeighborhoodIterator ( final long id ) { return new Iterator < Long > ( ) { Iterator < Edge > iter = structure . getExistingOutEdgesIterator ( id ) ; @ Override public boolean hasNext ( ) { return iter . hasNext ( ) ; } @ Override public Long next ( ) { Edge e = iter . next ( ) ; return e . getFromNodeId ( ) == id ? e . getToNodeId ( ) : e . getFromNodeId ( ) ; } } ; } | Gets the neighborhood from a node represented by a given id . If the graph has any Node object with the given id this function returns an Iterator object representing all the neighboring Node objects to the given node . The neighboring nodes are given according to the outgoing edges of the Node object of the graph that has the given id . | 118 | 65 |
140,310 | public static JSONObject toJSON ( Attributes attributes ) { JSONObject res = new JSONObject ( ) ; JSONObject vms = new JSONObject ( ) ; JSONObject nodes = new JSONObject ( ) ; for ( Element e : attributes . getDefined ( ) ) { JSONObject el = new JSONObject ( ) ; for ( String k : attributes . getKeys ( e ) ) { el . put ( k , attributes . get ( e , k ) ) ; } if ( e instanceof VM ) { vms . put ( Integer . toString ( e . id ( ) ) , el ) ; } else { nodes . put ( Integer . toString ( e . id ( ) ) , el ) ; } } res . put ( "vms" , vms ) ; res . put ( "nodes" , nodes ) ; return res ; } | Serialise attributes . | 178 | 4 |
140,311 | private void fullKnapsack ( ) throws ContradictionException { for ( int bin = 0 ; bin < prop . nbBins ; bin ++ ) { for ( int d = 0 ; d < prop . nbDims ; d ++ ) { knapsack ( bin , d ) ; } } } | Propagate a knapsack on every node and every dimension . | 66 | 13 |
140,312 | public void postInitialize ( ) throws ContradictionException { final int [ ] biggest = new int [ prop . nbDims ] ; for ( int i = 0 ; i < prop . bins . length ; i ++ ) { for ( int d = 0 ; d < prop . nbDims ; d ++ ) { biggest [ d ] = Math . max ( biggest [ d ] , prop . iSizes [ d ] [ i ] ) ; } if ( ! prop . bins [ i ] . isInstantiated ( ) ) { final DisposableValueIterator it = prop . bins [ i ] . getValueIterator ( true ) ; try { while ( it . hasNext ( ) ) { candidate . get ( it . next ( ) ) . set ( i ) ; } } finally { it . dispose ( ) ; } } } for ( int b = 0 ; b < prop . nbBins ; b ++ ) { for ( int d = 0 ; d < prop . nbDims ; d ++ ) { dynBiggest [ d ] [ b ] = prop . getVars ( ) [ 0 ] . getEnvironment ( ) . makeInt ( biggest [ d ] ) ; } } fullKnapsack ( ) ; } | initialize the lists of candidates . | 262 | 7 |
140,313 | @ SuppressWarnings ( "squid:S3346" ) public void postRemoveItem ( int item , int bin ) { assert candidate . get ( bin ) . get ( item ) ; candidate . get ( bin ) . clear ( item ) ; } | update the candidate list of a bin when an item is removed | 55 | 12 |
140,314 | private void knapsack ( int bin , int d ) throws ContradictionException { final int maxLoad = prop . loads [ d ] [ bin ] . getUB ( ) ; final int free = maxLoad - prop . assignedLoad [ d ] [ bin ] . get ( ) ; if ( free >= dynBiggest [ d ] [ bin ] . get ( ) ) { // fail fast. The remaining space > the biggest item. return ; } if ( free > 0 ) { // The bin is not full and some items exceeds the remaining space. We // get rid of them // In parallel, we set the new biggest candidate item for that // (bin,dimension) int newMax = - 1 ; for ( int i = candidate . get ( bin ) . nextSetBit ( 0 ) ; i >= 0 ; i = candidate . get ( bin ) . nextSetBit ( i + 1 ) ) { if ( prop . iSizes [ d ] [ i ] > free ) { if ( prop . bins [ i ] . removeValue ( bin , prop ) ) { prop . removeItem ( i , bin ) ; if ( prop . bins [ i ] . isInstantiated ( ) ) { prop . assignItem ( i , prop . bins [ i ] . getValue ( ) ) ; } } } else { // The item is still a candidate, we just update the biggest value. newMax = Math . max ( newMax , prop . iSizes [ d ] [ i ] ) ; } } dynBiggest [ d ] [ bin ] . set ( newMax ) ; } } | Propagate a knapsack on a given dimension and bin . If the usage of an item exceeds the bin free capacity it is filtered out . | 333 | 29 |
140,315 | public void add ( Metrics m ) { timeCount += m . timeCount ; readingTimeCount += m . readingTimeCount ; nodes += m . nodes ; backtracks += m . backtracks ; fails += m . fails ; restarts += m . restarts ; } | Add metrics . All the metrics are aggregated to the current instance | 56 | 13 |
140,316 | protected String generateCacheKey ( HttpServletRequest request , Map < String , ICacheKeyGenerator > cacheKeyGenerators ) throws IOException { String cacheKey = null ; if ( cacheKeyGenerators != null ) { // First, decompose any composite cache key generators into their // constituent cache key generators so that we can combine them // more effectively. Use TreeMap to get predictable ordering of // keys. Map < String , ICacheKeyGenerator > gens = new TreeMap < String , ICacheKeyGenerator > ( ) ; for ( ICacheKeyGenerator gen : cacheKeyGenerators . values ( ) ) { List < ICacheKeyGenerator > constituentGens = gen . getCacheKeyGenerators ( request ) ; addCacheKeyGenerators ( gens , constituentGens == null ? Arrays . asList ( new ICacheKeyGenerator [ ] { gen } ) : constituentGens ) ; } cacheKey = KeyGenUtil . generateKey ( request , gens . values ( ) ) ; } return cacheKey ; } | Generates a cache key for the layer . | 223 | 9 |
140,317 | private void readObject ( ObjectInputStream in ) throws IOException , ClassNotFoundException { // Call the default implementation to de-serialize our object in . defaultReadObject ( ) ; // init transients _validateLastModified = new AtomicBoolean ( true ) ; _cacheKeyGenMutex = new Semaphore ( 1 ) ; _isReportCacheInfo = false ; } | De - serialize this object from an ObjectInputStream | 82 | 11 |
140,318 | protected long getLastModified ( IAggregator aggregator , ModuleList modules ) { long result = 0L ; for ( ModuleList . ModuleListEntry entry : modules ) { IResource resource = entry . getModule ( ) . getResource ( aggregator ) ; long lastMod = resource . lastModified ( ) ; result = Math . max ( result , lastMod ) ; } return result ; } | Returns the newest last modified time of the files in the list | 85 | 12 |
140,319 | public static void verify ( short value , Path path ) { Approval . of ( short . class ) . withReporter ( reporter ) . build ( ) . verify ( value , path ) ; } | An overload for verifying a single short value . This will call the approval object with proper reporter and use the path for verification . | 41 | 25 |
140,320 | public static String prettyType ( BtrpOperand o ) { if ( o == IgnorableOperand . getInstance ( ) ) { return "??" ; } return prettyType ( o . degree ( ) , o . type ( ) ) ; } | Generate a pretty type for an operand . | 53 | 10 |
140,321 | public static String prettyType ( int degree , Type t ) { StringBuilder b = new StringBuilder ( ) ; for ( int i = degree ; i > 0 ; i -- ) { b . append ( "set<" ) ; } b . append ( t . toString ( ) . toLowerCase ( ) ) ; for ( int i = 0 ; i < degree ; i ++ ) { b . append ( ">" ) ; } return b . toString ( ) ; } | Pretty textual representation of a given element type . | 100 | 9 |
140,322 | @ Override public void addDim ( List < IntVar > c , int [ ] cUse , IntVar [ ] dUse ) { capacities . add ( c ) ; cUsages . add ( cUse ) ; dUsages . add ( dUse ) ; } | Add a dimension . | 57 | 4 |
140,323 | @ Override @ SuppressWarnings ( "squid:S3346" ) public boolean beforeSolve ( ReconfigurationProblem rp ) { super . beforeSolve ( rp ) ; if ( rp . getSourceModel ( ) . getMapping ( ) . getNbNodes ( ) == 0 || capacities . isEmpty ( ) ) { return true ; } int nbDims = capacities . size ( ) ; int nbRes = capacities . get ( 0 ) . size ( ) ; //We get the UB of the node capacity and the LB for the VM usage. int [ ] [ ] capas = new int [ nbRes ] [ nbDims ] ; int d = 0 ; for ( List < IntVar > capaDim : capacities ) { assert capaDim . size ( ) == nbRes ; for ( int j = 0 ; j < capaDim . size ( ) ; j ++ ) { capas [ j ] [ d ] = capaDim . get ( j ) . getUB ( ) ; } d ++ ; } assert cUsages . size ( ) == nbDims ; int nbCHosts = cUsages . get ( 0 ) . length ; int [ ] [ ] cUses = new int [ nbCHosts ] [ nbDims ] ; d = 0 ; for ( int [ ] cUseDim : cUsages ) { assert cUseDim . length == nbCHosts ; for ( int i = 0 ; i < nbCHosts ; i ++ ) { cUses [ i ] [ d ] = cUseDim [ i ] ; } d ++ ; } assert dUsages . size ( ) == nbDims ; int nbDHosts = dUsages . get ( 0 ) . length ; int [ ] [ ] dUses = new int [ nbDHosts ] [ nbDims ] ; d = 0 ; for ( IntVar [ ] dUseDim : dUsages ) { assert dUseDim . length == nbDHosts ; for ( int j = 0 ; j < nbDHosts ; j ++ ) { dUses [ j ] [ d ] = dUseDim [ j ] . getLB ( ) ; } d ++ ; } symmetryBreakingForStayingVMs ( rp ) ; IntVar [ ] earlyStarts = rp . getNodeActions ( ) . stream ( ) . map ( NodeTransition :: getHostingStart ) . toArray ( IntVar [ ] :: new ) ; IntVar [ ] lastEnd = rp . getNodeActions ( ) . stream ( ) . map ( NodeTransition :: getHostingEnd ) . toArray ( IntVar [ ] :: new ) ; rp . getModel ( ) . post ( new TaskScheduler ( earlyStarts , lastEnd , capas , cHosts , cUses , cEnds , dHosts , dUses , dStarts , associations ) ) ; return true ; } | Build the constraint . | 654 | 4 |
140,324 | private boolean symmetryBreakingForStayingVMs ( ReconfigurationProblem rp ) { for ( VM vm : rp . getFutureRunningVMs ( ) ) { VMTransition a = rp . getVMAction ( vm ) ; Slice dSlice = a . getDSlice ( ) ; Slice cSlice = a . getCSlice ( ) ; if ( dSlice != null && cSlice != null ) { BoolVar stay = ( ( KeepRunningVM ) a ) . isStaying ( ) ; Boolean ret = strictlyDecreasingOrUnchanged ( vm ) ; if ( Boolean . TRUE . equals ( ret ) && ! zeroDuration ( rp , stay , cSlice ) ) { return false ; //Else, the resource usage is decreasing, so // we set the cSlice duration to 0 to directly reduces the resource allocation } else if ( Boolean . FALSE . equals ( ret ) && ! zeroDuration ( rp , stay , dSlice ) ) { //If the resource usage will be increasing //Then the duration of the dSlice can be set to 0 //(the allocation will be performed at the end of the reconfiguration process) return false ; } } } return true ; } | Symmetry breaking for VMs that stay running on the same node . | 261 | 15 |
140,325 | protected StringBuilder getPath ( StringBuilder path , int startIndex , boolean addPoint ) { boolean simple = true ; if ( key != null ) { if ( addPoint && path . length ( ) > 0 ) { path . insert ( 0 , ' ' ) ; } if ( key instanceof Integer ) { path . insert ( 0 , ' ' ) ; if ( startIndex == 0 ) { path . insert ( 0 , key ) ; } else { path . insert ( 0 , startIndex + ( int ) key ) ; } path . insert ( 0 , ' ' ) ; simple = false ; } else { path . insert ( 0 , key ) ; } } if ( parent != null ) { parent . getPath ( path , startIndex , simple ) ; } return path ; } | Recursive path - builder method . | 163 | 7 |
140,326 | public Tree setType ( Class < ? > type ) { if ( value == null || value . getClass ( ) == type ) { return this ; } value = DataConverterRegistry . convert ( type , value ) ; if ( parent != null && key != null ) { if ( key instanceof String ) { parent . putObjectInternal ( ( String ) key , value , false ) ; } else { parent . remove ( ( int ) key ) ; parent . insertObjectInternal ( ( int ) key , value ) ; } } return this ; } | Sets this node s type and converts the value into the specified type . | 116 | 15 |
140,327 | public Tree insert ( int index , byte [ ] value , boolean asBase64String ) { if ( asBase64String ) { return insertObjectInternal ( index , BASE64 . encode ( value ) ) ; } return insertObjectInternal ( index , value ) ; } | Inserts the specified byte array at the specified position in this List . | 55 | 14 |
140,328 | public Tree putObject ( String path , Object value ) { return putObjectInternal ( path , getNodeValue ( value ) , false ) ; } | Puts a node with the specified value into the specified path . | 30 | 13 |
140,329 | public static Instance readInstance ( File f ) { try ( Reader in = makeIn ( f ) ) { return readInstance ( in ) ; } catch ( IOException e ) { throw new IllegalArgumentException ( e ) ; } } | Read an instance from a file . A file ending with . gz is uncompressed first | 50 | 18 |
140,330 | public static Instance readInstance ( Reader r ) { try { InstanceConverter c = new InstanceConverter ( ) ; return c . fromJSON ( r ) ; } catch ( JSONConverterException e ) { throw new IllegalArgumentException ( e ) ; } } | Read an instance . | 61 | 4 |
140,331 | public static void write ( Instance instance , File f ) { try ( OutputStreamWriter out = makeOut ( f ) ) { write ( instance , out ) ; } catch ( IOException e ) { throw new IllegalArgumentException ( e ) ; } } | Write an instance . | 54 | 4 |
140,332 | public static void write ( Instance instance , Appendable a ) { try { InstanceConverter c = new InstanceConverter ( ) ; c . toJSON ( instance ) . writeJSONString ( a ) ; } catch ( IOException | JSONConverterException e ) { throw new IllegalArgumentException ( e ) ; } } | Write an instance | 74 | 3 |
140,333 | public static ReconfigurationPlan readReconfigurationPlan ( File f ) { try ( Reader in = makeIn ( f ) ) { return readReconfigurationPlan ( in ) ; } catch ( IOException e ) { throw new IllegalArgumentException ( e ) ; } } | Read a reconfiguration plan from a file . A file ending with . gz is uncompressed first | 60 | 21 |
140,334 | public static ReconfigurationPlan readReconfigurationPlan ( Reader r ) { try { ReconfigurationPlanConverter c = new ReconfigurationPlanConverter ( ) ; return c . fromJSON ( r ) ; } catch ( JSONConverterException e ) { throw new IllegalArgumentException ( e ) ; } } | Read a plan . | 71 | 4 |
140,335 | public Collection < Node > getAssociatedPGroup ( Node u ) { for ( Collection < Node > pGrp : pGroups ) { if ( pGrp . contains ( u ) ) { return pGrp ; } } return Collections . emptySet ( ) ; } | Get the group of nodes associated to a given node . | 57 | 11 |
140,336 | static public Collection < URI > removeRedundantPaths ( Collection < URI > uris ) { List < URI > result = new ArrayList < URI > ( ) ; for ( URI uri : uris ) { String path = uri . getPath ( ) ; if ( ! path . endsWith ( "/" ) ) { //$NON-NLS-1$ path += "/" ; //$NON-NLS-1$ } boolean addIt = true ; for ( int i = 0 ; i < result . size ( ) ; i ++ ) { URI testUri = result . get ( i ) ; if ( ! StringUtils . equals ( testUri . getScheme ( ) , uri . getScheme ( ) ) || ! StringUtils . equals ( testUri . getHost ( ) , uri . getHost ( ) ) || testUri . getPort ( ) != uri . getPort ( ) ) { continue ; } String test = testUri . getPath ( ) ; if ( ! test . endsWith ( "/" ) ) { //$NON-NLS-1$ test += "/" ; //$NON-NLS-1$ } if ( path . equals ( test ) || path . startsWith ( test ) ) { addIt = false ; break ; } else if ( test . startsWith ( path ) ) { result . remove ( i ) ; } } if ( addIt ) result . add ( uri ) ; } // Now copy the trimmed list back to the original return result ; } | Removes URIs containing duplicate and non - orthogonal paths so that the collection contains only unique and non - overlapping paths . | 334 | 26 |
140,337 | static Object convert ( Object object , Class < ? > otherType ) { if ( otherType == BigDecimal . class ) { if ( object instanceof BigInteger ) { return new BigDecimal ( ( BigInteger ) object ) ; } else if ( object instanceof Number ) { return BigDecimal . valueOf ( ( ( Number ) object ) . doubleValue ( ) ) ; } } else if ( otherType == BigInteger . class ) { if ( ! ( object instanceof BigDecimal ) && ( object instanceof Number ) ) { return BigInteger . valueOf ( ( ( Number ) object ) . longValue ( ) ) ; } } return object ; } | This method converts the given value to a more common type . | 140 | 12 |
140,338 | public InputStream getInputStream ( HttpServletRequest request , MutableObject < byte [ ] > sourceMapResult ) throws IOException { // Check bytes before filename when reading and reverse order when setting. // The following local variables intentionally hide the instance variables. byte [ ] bytes = this . bytes ; byte [ ] sourceMap = this . sourceMap ; String filename = this . filename ; InputStream result = null ; if ( bytes != null ) { // Cache data is already in memory. Don't need to de-serialize it. result = new ByteArrayInputStream ( bytes ) ; if ( sourceMapResult != null && sourceMapSize > 0 ) { sourceMapResult . setValue ( sourceMap ) ; } } else if ( filename != null ) { // De-serialize data from cache ICacheManager cmgr = ( ( IAggregator ) request . getAttribute ( IAggregator . AGGREGATOR_REQATTRNAME ) ) . getCacheManager ( ) ; File file = new File ( cmgr . getCacheDir ( ) , filename ) ; if ( sourceMapSize == 0 ) { // No source map data in cache entry so just stream the file. result = new FileInputStream ( file ) ; } else { // Entry contains source map data so that means it's a serialized CacheData // instance. De-serialize the object and extract the data. CacheData data ; ObjectInputStream is = new ObjectInputStream ( new FileInputStream ( file ) ) ; try { data = ( CacheData ) is . readObject ( ) ; } catch ( ClassNotFoundException e ) { throw new IOException ( e . getMessage ( ) , e ) ; } finally { IOUtils . closeQuietly ( is ) ; } bytes = data . bytes ; sourceMap = data . sourceMap ; if ( sourceMapResult != null ) { sourceMapResult . setValue ( sourceMap ) ; } result = new ByteArrayInputStream ( bytes ) ; } } else { throw new IOException ( ) ; } return result ; } | Return an input stream to the layer . Has side effect of setting the appropriate Content - Type Content - Length and Content - Encoding headers in the response . | 435 | 31 |
140,339 | public InputStream tryGetInputStream ( HttpServletRequest request , MutableObject < byte [ ] > sourceMapResult ) throws IOException { InputStream result = null ; // Check bytes before filename when reading and reverse order when setting if ( bytes != null || filename != null ) { try { result = getInputStream ( request , sourceMapResult ) ; } catch ( Exception e ) { if ( LayerImpl . log . isLoggable ( Level . SEVERE ) ) { LayerImpl . log . log ( Level . SEVERE , e . getMessage ( ) , e ) ; } // just return null } } return result ; } | Can fail by returning null but won t throw an exception . | 136 | 12 |
140,340 | public void setData ( byte [ ] bytes , byte [ ] sourceMap ) { this . sourceMap = sourceMap ; sourceMapSize = sourceMap != null ? sourceMap . length : 0 ; setBytes ( bytes ) ; } | Sets the contents of the cache entry with source map info . | 48 | 13 |
140,341 | public synchronized void delete ( final ICacheManager mgr ) { delete = true ; if ( filename != null ) { mgr . deleteFileDelayed ( filename ) ; } } | Delete the cached build after the specified delay in minues | 37 | 11 |
140,342 | public void persist ( final ICacheManager mgr ) throws IOException { if ( delete ) return ; if ( sourceMapSize == 0 ) { // No source map. Just stream the file mgr . createCacheFileAsync ( "layer." , //$NON-NLS-1$ new ByteArrayInputStream ( bytes ) , new CreateCompletionCallback ( mgr ) ) ; } else { // cache entry contains source map info. Create a CacheData instance // and serialize object. Object data = new CacheData ( bytes , sourceMap ) ; mgr . externalizeCacheObjectAsync ( "layer." , //$NON-NLS-1$ data , new CreateCompletionCallback ( mgr ) ) ; } } | Asynchronously write the layer build content to disk and set filename to the name of the cache files when done . | 154 | 23 |
140,343 | public void register ( ConstraintConverter < ? extends Constraint > c ) { java2json . put ( c . getSupportedConstraint ( ) , c ) ; json2java . put ( c . getJSONId ( ) , c ) ; } | Register a converter for a specific constraint . | 57 | 8 |
140,344 | public Constraint fromJSON ( Model mo , JSONObject in ) throws JSONConverterException { checkKeys ( in , "id" ) ; Object id = in . get ( "id" ) ; ConstraintConverter < ? extends Constraint > c = json2java . get ( id . toString ( ) ) ; if ( c == null ) { throw new JSONConverterException ( "No converter available for a constraint having id '" + id + "'" ) ; } return c . fromJSON ( mo , in ) ; } | Convert a json - encoded constraint . | 118 | 8 |
140,345 | public JSONObject toJSON ( Constraint o ) throws JSONConverterException { ConstraintConverter c = java2json . get ( o . getClass ( ) ) ; if ( c == null ) { throw new JSONConverterException ( "No converter available for a constraint with the '" + o . getClass ( ) + "' className" ) ; } return c . toJSON ( o ) ; } | Serialise a constraint . | 91 | 5 |
140,346 | public List < SatConstraint > listFromJSON ( Model mo , JSONArray in ) throws JSONConverterException { List < SatConstraint > l = new ArrayList <> ( in . size ( ) ) ; for ( Object o : in ) { if ( ! ( o instanceof JSONObject ) ) { throw new JSONConverterException ( "Expected an array of JSONObject but got an array of " + o . getClass ( ) . getName ( ) ) ; } l . add ( ( SatConstraint ) fromJSON ( mo , ( JSONObject ) o ) ) ; } return l ; } | Convert a list of json - encoded sat - constraints . | 133 | 12 |
140,347 | public JSONArray toJSON ( Collection < SatConstraint > e ) throws JSONConverterException { JSONArray arr = new JSONArray ( ) ; for ( SatConstraint cstr : e ) { arr . add ( toJSON ( cstr ) ) ; } return arr ; } | Serialise a list of sat - constraints . | 61 | 9 |
140,348 | public synchronized void clear ( ) { _layerCache . clear ( ) ; _moduleCache . clear ( ) ; _gzipCache . clear ( ) ; for ( IGenericCache cache : _namedCaches . values ( ) ) { cache . clear ( ) ; } } | Help out the GC by clearing out the cache maps . | 57 | 11 |
140,349 | public String toGrammarRules ( ) { StringBuffer sb = new StringBuffer ( ) ; System . out . println ( "R0 -> " + this . r0String ) ; for ( int i = 1 ; i <= this . theRules . size ( ) ; i ++ ) { RePairRule r = this . theRules . get ( i ) ; sb . append ( THE_R ) . append ( r . ruleNumber ) . append ( " -> " ) . append ( r . toRuleString ( ) ) . append ( " : " ) . append ( r . expandedRuleString ) . append ( ", " ) . append ( r . occurrences ) . append ( "\n" ) ; } return sb . toString ( ) ; } | Prints out the grammar as text . | 161 | 8 |
140,350 | public GrammarRules toGrammarRulesData ( ) { GrammarRules res = new GrammarRules ( ) ; GrammarRuleRecord r0 = new GrammarRuleRecord ( ) ; r0 . setRuleNumber ( 0 ) ; r0 . setRuleString ( this . r0String ) ; r0 . setExpandedRuleString ( this . r0ExpandedString ) ; r0 . setOccurrences ( new int [ ] { 0 } ) ; r0 . setMeanLength ( - 1 ) ; r0 . setMinMaxLength ( new int [ ] { - 1 } ) ; res . addRule ( r0 ) ; for ( RePairRule rule : theRules . values ( ) ) { // System.out.println("processing the rule " + rule.ruleNumber); GrammarRuleRecord rec = new GrammarRuleRecord ( ) ; rec . setRuleNumber ( rule . ruleNumber ) ; rec . setRuleString ( rule . toRuleString ( ) ) ; rec . setExpandedRuleString ( rule . expandedRuleString ) ; rec . setRuleYield ( countSpaces ( rule . expandedRuleString ) ) ; rec . setOccurrences ( rule . getOccurrences ( ) ) ; rec . setRuleIntervals ( rule . getRuleIntervals ( ) ) ; rec . setRuleLevel ( rule . getLevel ( ) ) ; rec . setMinMaxLength ( rule . getLengths ( ) ) ; rec . setMeanLength ( mean ( rule . getRuleIntervals ( ) ) ) ; res . addRule ( rec ) ; } // count the rule use for ( GrammarRuleRecord r : res ) { String str = r . getRuleString ( ) ; String [ ] tokens = str . split ( "\\s+" ) ; for ( String t : tokens ) { if ( t . startsWith ( "R" ) ) { Integer ruleId = Integer . valueOf ( t . substring ( 1 ) ) ; GrammarRuleRecord rr = res . get ( ruleId ) ; // System.out.print(rr.getRuleUseFrequency() + " "); int newFreq = rr . getRuleUseFrequency ( ) + 1 ; rr . setRuleUseFrequency ( newFreq ) ; // System.out.println(rr.getRuleUseFrequency()); } } } return res ; } | Build a grammarviz - portable grammar object . | 509 | 10 |
140,351 | public void buildIntervals ( SAXRecords records , double [ ] originalTimeSeries , int slidingWindowSize ) { records . buildIndex ( ) ; for ( int ruleIdx = 1 ; ruleIdx <= this . theRules . size ( ) ; ruleIdx ++ ) { RePairRule rr = this . theRules . get ( ruleIdx ) ; String [ ] split = rr . expandedRuleString . split ( " " ) ; for ( int strPos : rr . getOccurrences ( ) ) { Integer tsPos = records . mapStringIndexToTSPosition ( strPos + split . length - 1 ) ; if ( null == tsPos ) { rr . ruleIntervals . add ( new RuleInterval ( records . mapStringIndexToTSPosition ( strPos ) , originalTimeSeries . length + 1 ) ) ; // +1 cause right point is excluded } else { rr . ruleIntervals . add ( new RuleInterval ( records . mapStringIndexToTSPosition ( strPos ) , records . mapStringIndexToTSPosition ( strPos + split . length - 1 ) + slidingWindowSize ) ) ; } } } } | Builds a table of intervals corresponding to the grammar rules . | 253 | 12 |
140,352 | private static Class < ? > fromPrimitive ( Class < ? > clazz ) { Class < ? > clazz2 = PRIMITIVE_TO_CLASS . get ( clazz ) ; return clazz2 == null ? clazz : clazz2 ; } | Converts and returns the specified class if it represents a primitive to the associated non - primitive class or else returns the specified class if it is not a primitive . | 56 | 32 |
140,353 | private static DiagnosticGroup findNamedDiagnosticGroup ( String name ) { final String sourceMethod = "findNamedDiagnosticGroup" ; //$NON-NLS-1$ final boolean isTraceLogging = log . isLoggable ( Level . FINER ) ; if ( isTraceLogging ) { log . entering ( sourceClass , sourceMethod , new Object [ ] { name } ) ; } DiagnosticGroup result = null ; Class < DiagnosticGroups > clazz = DiagnosticGroups . class ; // iterate through the public static fields looking for a match Field [ ] fields = clazz . getDeclaredFields ( ) ; for ( Field field : fields ) { int modifier = field . getModifiers ( ) ; if ( field . getType ( ) . isAssignableFrom ( DiagnosticGroup . class ) && ( modifier & Modifier . STATIC ) != 0 && ( modifier & Modifier . PUBLIC ) != 0 && field . getName ( ) . equals ( name ) ) { try { result = ( DiagnosticGroup ) field . get ( null ) ; break ; } catch ( Exception e ) { // Shouldn't ever happen with public static fields if ( log . isLoggable ( Level . WARNING ) ) { log . logp ( Level . WARNING , sourceClass , sourceMethod , e . getMessage ( ) , e ) ; } } } } if ( isTraceLogging ) { log . exiting ( sourceMethod , sourceMethod , result ) ; } return result ; } | Tries to match the provided name with a named Diagnostic group defined in the DiagnosticGroups class . | 327 | 22 |
140,354 | protected String postcss ( HttpServletRequest request , String css , IResource res ) throws IOException { if ( threadScopes == null ) { return css ; } Context cx = Context . enter ( ) ; Scriptable threadScope = null ; String result = null ; try { threadScope = threadScopes . poll ( SCOPE_POOL_TIMEOUT_SECONDS , TimeUnit . SECONDS ) ; if ( threadScope == null ) { throw new TimeoutException ( "Timeout waiting for thread scope" ) ; //$NON-NLS-1$ } Scriptable scope = cx . newObject ( threadScope ) ; scope . setParentScope ( threadScope ) ; Scriptable postcssInstance = ( Scriptable ) threadScope . get ( POSTCSS_INSTANCE , scope ) ; Function postcssProcessor = ( Function ) postcssInstance . getPrototype ( ) . get ( PROCESS , postcssInstance ) ; Object processed = postcssProcessor . call ( cx , scope , postcssInstance , new Object [ ] { css , postcssOptions } ) ; result = Context . toString ( processed ) ; } catch ( JavaScriptException e ) { // Add module info String message = "Error parsing " + res . getURI ( ) + "\r\n" + e . getMessage ( ) ; //$NON-NLS-1$ //$NON-NLS-2$ throw new IOException ( message , e ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; } catch ( TimeoutException e ) { throw new RuntimeException ( e ) ; } finally { if ( threadScope != null ) { // put the thread scope back in the queue now that we're done with it threadScopes . add ( threadScope ) ; } Context . exit ( ) ; } return result ; } | Runs given CSS through PostCSS processor for minification and any other processing by configured plugins . | 396 | 19 |
140,355 | protected Scriptable createThreadScope ( Context cx , Scriptable protoScope ) { // Create the scope object Scriptable scope = cx . newObject ( protoScope ) ; scope . setPrototype ( protoScope ) ; scope . setParentScope ( null ) ; // Set "global" variable to point to global scope scope . put ( "global" , scope , scope ) ; //$NON-NLS-1$ // Evaluate PostCSS javascript postcssJsScript . exec ( cx , scope ) ; // Initialize the plugins array that we pass to PostCSS NativeArray plugins = ( NativeArray ) cx . newArray ( scope , 0 ) ; // Get reference to Array.prototype.push() so that we can add elements Function pushFn = ( Function ) plugins . getPrototype ( ) . get ( "push" , scope ) ; //$NON-NLS-1$ /* * Now load and initialize plugins */ for ( PluginInfo info : pluginInfoList ) { // Set up new scope for defining the module so that module.exports is not shared between plugins Scriptable defineScope = cx . newObject ( scope ) ; defineScope . setParentScope ( scope ) ; amdDefineShimScript . exec ( cx , defineScope ) ; Scriptable moduleVar = ( Scriptable ) defineScope . get ( MODULE , defineScope ) ; info . moduleScript . exec ( cx , defineScope ) ; // Retrieve the module reference and initialize the plugin Function module = ( Function ) moduleVar . get ( EXPORTS , moduleVar ) ; Scriptable plugin = ( Scriptable ) info . initializer . call ( cx , scope , scope , new Object [ ] { module } ) ; // Add the plugin to the array pushFn . call ( cx , scope , plugins , new Object [ ] { plugin } ) ; } // Create an instance of the PostCSS processor and save to a variable in thread scope Function postcss = ( Function ) scope . get ( POSTCSS , scope ) ; postcssOptions = ( Scriptable ) Context . javaToJS ( POSTCSS_OPTIONS , scope ) ; Scriptable postcssInstance = ( Scriptable ) postcss . call ( cx , scope , scope , new Object [ ] { plugins } ) ; scope . put ( POSTCSS_INSTANCE , scope , postcssInstance ) ; return scope ; } | Creates a thread scope for the PostCSS processor and it s plugins . Thread scopes allow PostCSS to process multiple CSS modules concurrently each executing in a separate thread without interfering with each other . | 492 | 39 |
140,356 | public String dequote ( String in ) { String result = in . trim ( ) ; if ( result . charAt ( 0 ) == ' ' && result . charAt ( result . length ( ) - 1 ) == ' ' ) { return result . substring ( 1 , result . length ( ) - 1 ) ; } if ( result . charAt ( 0 ) == ' ' && result . charAt ( result . length ( ) - 1 ) == ' ' ) { return result . substring ( 1 , result . length ( ) - 1 ) ; } return result ; } | Removes single or double quotes from a quoted string . The entire string is expected to be quoted with possible leading or trailing whitespace . If the string is not quoted then it is returned unmodified . | 120 | 40 |
140,357 | public tr tr ( int index ) { while ( trList . size ( ) <= index ) { trList . add ( new tr ( ) ) ; } return trList . get ( index ) ; } | Get tr of specified index . If there no tr at the specified index new tr will be created . | 42 | 20 |
140,358 | public tr addTr ( Map < String , Object > attrMap ) { tr tr = new tr ( ) ; tr . setAttr ( attrMap ) ; trList . add ( tr ) ; return tr ; } | add new tr having specified attributes . | 47 | 7 |
140,359 | public < T extends AbstractJaxb > TableBuilder addTr ( List < Object > tdList ) throws TagTypeUnmatchException { return addTr ( tdList , null ) ; } | add new tr having td tags that has content of each value of list . | 39 | 15 |
140,360 | @ SuppressWarnings ( "unchecked" ) public < T extends AbstractJaxb > TableBuilder addTr ( List < Object > tdList , Map < String , Object > attrMap ) throws TagTypeUnmatchException { tr tr = new tr ( ) ; tr . setAttr ( attrMap ) ; for ( Object obj : tdList ) { if ( obj instanceof String ) { tr . addTd ( ( String ) obj ) ; } else if ( obj instanceof AbstractJaxb ) { tr . addTd ( ( T ) obj ) ; } else { throw new TagTypeUnmatchException ( "String or other tag object expected but tdList contains " + obj . getClass ( ) . getName ( ) ) ; } } trList . add ( tr ) ; return this ; } | add new tr having td tags that has content of each value of list . The new tr tag have specifed attributes . | 174 | 25 |
140,361 | public tbody tbody ( int index ) { while ( tbodyList . size ( ) <= index ) { tbodyList . add ( new tbody ( ) ) ; } return tbodyList . get ( index ) ; } | Get tbody at specified index | 48 | 6 |
140,362 | public TableBuilder addTbody ( List < List < Object > > trList ) throws TagTypeUnmatchException { addTbody ( trList , null ) ; return this ; } | add new tbody into table having tr td tags | 38 | 10 |
140,363 | public Table build ( ) { Table table = new Table ( ) ; Thead _thead = thead . buildThead ( ) ; if ( _thead != null ) { table . setThead ( _thead ) ; } Tfoot _tfoot = tfoot . buildTfoot ( ) ; if ( _tfoot != null ) { table . setTfoot ( _tfoot ) ; } for ( tbody _tbody : tbodyList ) { table . getTbody ( ) . add ( _tbody . buildTbody ( ) ) ; } for ( tr _tr : trList ) { table . getTr ( ) . add ( _tr . buildTr ( ) ) ; } return table ; } | build table tag object finally . | 154 | 6 |
140,364 | protected String getVersion ( ) { Manifest manifest = ManifestLoader . loadManifest ( getClass ( ) ) ; String versionNumber = null ; if ( manifest != null ) { versionNumber = ManifestLoader . getValue ( manifest , Attributes . Name . IMPLEMENTATION_VERSION ) ; if ( versionNumber == null ) { versionNumber = ManifestLoader . getValue ( manifest , Attributes . Name . SPECIFICATION_VERSION ) ; } } if ( versionNumber == null ) { versionNumber = SNAPSHOT ; } return versionNumber ; } | This method gets the Version of this program . | 112 | 9 |
140,365 | protected void setValueInternal ( String argument , char separator , GenericType < ? > propertyType ) { if ( this . valueAlreadySet ) { CliOptionDuplicateException exception = new CliOptionDuplicateException ( getParameterContainer ( ) . getName ( ) ) ; CliStyleHandling . EXCEPTION . handle ( getLogger ( ) , exception ) ; } // TODO: separator currently ignored! Object value = getDependencies ( ) . getConverter ( ) . convertValue ( argument , getParameterContainer ( ) , propertyType . getAssignmentClass ( ) , propertyType ) ; setValueInternal ( value ) ; this . valueAlreadySet = true ; } | This method parses container value as from a single argument and sets it as new object . | 150 | 18 |
140,366 | public static TIntIntHashMap makeVMIndex ( Collection < Instance > instances ) { TIntIntHashMap index = new TIntIntHashMap ( ) ; int p = 0 ; for ( Instance i : instances ) { Mapping m = i . getModel ( ) . getMapping ( ) ; for ( Node n : m . getOnlineNodes ( ) ) { for ( VM v : m . getRunningVMs ( n ) ) { index . put ( v . id ( ) , p ) ; } for ( VM v : m . getSleepingVMs ( n ) ) { index . put ( v . id ( ) , p ) ; } } for ( VM v : m . getReadyVMs ( ) ) { index . put ( v . id ( ) , p ) ; } p ++ ; } return index ; } | Make an index revealing the position of each VM in a collection of disjoint instances | 181 | 17 |
140,367 | public static TIntIntHashMap makeNodeIndex ( Collection < Instance > instances ) { TIntIntHashMap index = new TIntIntHashMap ( ) ; int p = 0 ; for ( Instance i : instances ) { Mapping m = i . getModel ( ) . getMapping ( ) ; for ( Node n : m . getOfflineNodes ( ) ) { index . put ( n . id ( ) , p ) ; } for ( Node n : m . getOnlineNodes ( ) ) { index . put ( n . id ( ) , p ) ; } p ++ ; } return index ; } | Make an index revealing the position of each node in a collection of disjoint instances | 132 | 17 |
140,368 | public void initialize ( AbstractDetectorStreamProvider provider , DetectorStreamProcessor lastProcessor ) { List < DetectorStreamProcessorFactory > factoryList = provider . getProcessorFactoryList ( ) ; int factoryCount = factoryList . size ( ) ; DetectorStreamBufferImpl buffer = new DetectorStreamBufferImpl ( lastProcessor , null , this . byteArrayPool ) ; for ( int factoryIndex = factoryCount - 1 ; factoryIndex >= 0 ; factoryIndex -- ) { DetectorStreamProcessorFactory factory = factoryList . get ( factoryIndex ) ; DetectorStreamProcessor processor = factory . createProcessor ( ) ; buffer = new DetectorStreamBufferImpl ( processor , buffer , this . byteArrayPool ) ; } this . firstBuffer = buffer ; } | This method initializes this class . It has to be called to complete the construction . | 163 | 17 |
140,369 | @ Override protected String doInBackground ( String ... params ) { // get the string from params, which is an array String user = params [ 0 ] ; String password = params [ 1 ] ; String bugTitle = params [ 2 ] ; String bugDescription = params [ 3 ] ; String deviceInfo = params [ 4 ] ; String targetUser = params [ 5 ] ; String targetRepository = params [ 6 ] ; String extraInfo = params [ 7 ] ; String gitToken = params [ 8 ] ; IssueService service ; if ( user . equals ( "" ) ) { service = new IssueService ( new GitHubClient ( ) . setOAuth2Token ( gitToken ) ) ; } else { service = new IssueService ( new GitHubClient ( ) . setCredentials ( user , password ) ) ; } Issue issue = new Issue ( ) . setTitle ( bugTitle ) . setBody ( bugDescription + "\n\n" + deviceInfo + "\n\nExtra Info: " + extraInfo ) ; try { issue = service . createIssue ( targetUser , targetRepository , issue ) ; return "ok" ; } catch ( IOException e ) { e . printStackTrace ( ) ; return e . toString ( ) ; } } | This is run in a background thread | 263 | 7 |
140,370 | @ Override protected void onPostExecute ( String result ) { super . onPostExecute ( result ) ; if ( result . equals ( "ok" ) ) { progress . dismiss ( ) ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . LOLLIPOP ) { mActivity . showDoneAnimation ( ) ; } else { ( ( Activity ) mContext ) . finish ( ) ; } } else if ( result . equals ( "org.eclipse.egit.github.core.client.RequestException: Bad credentials (401)" ) ) { progress . dismiss ( ) ; new AlertDialog . Builder ( mContext ) . setTitle ( "Unable to send report" ) . setMessage ( "Wrong username or password or invalid access token." ) . setPositiveButton ( "Try again" , new DialogInterface . OnClickListener ( ) { public void onClick ( DialogInterface dialog , int which ) { // do nothing } } ) . setIcon ( R . drawable . gittyreporter_ic_mood_bad_black_24dp ) . show ( ) ; } else { progress . dismiss ( ) ; new AlertDialog . Builder ( mContext ) . setTitle ( "Unable to send report" ) . setMessage ( "An unexpected error occurred. If the problem persists, contact the app developer." ) . setPositiveButton ( android . R . string . ok , new DialogInterface . OnClickListener ( ) { public void onClick ( DialogInterface dialog , int which ) { ( ( Activity ) mContext ) . finish ( ) ; } } ) . setIcon ( R . drawable . gittyreporter_ic_mood_bad_black_24dp ) . show ( ) ; } } | This runs in UI when background thread finishes | 381 | 8 |
140,371 | public static void main ( String [ ] args ) throws Exception { getparseArticle ( ) ; geoparseUppercaseArticle ( ) ; resolveStanfordEntities ( ) ; // And we're done... System . out . println ( "\n\"That's all folks!\"" ) ; } | Run this after installing and configuring CLAVIN to get a sense of how to use it in a few different ways . | 61 | 25 |
140,372 | private static void getparseArticle ( ) throws Exception { // Instantiate a CLAVIN GeoParser using the StanfordExtractor GeoParser parser = GeoParserFactory . getDefault ( "./IndexDirectory" , new StanfordExtractor ( ) , 1 , 1 , false ) ; // Unstructured text file about Somalia to be geoparsed File inputFile = new File ( "src/test/resources/sample-docs/Somalia-doc.txt" ) ; // Grab the contents of the text file as a String String inputString = TextUtils . fileToString ( inputFile ) ; // Parse location names in the text into geographic entities List < ResolvedLocation > resolvedLocations = parser . parse ( inputString ) ; // Display the ResolvedLocations found for the location names for ( ResolvedLocation resolvedLocation : resolvedLocations ) System . out . println ( resolvedLocation ) ; } | Standard usage of CLAVIN . Instantiate a default GeoParser give it some text check out the locations it extracts and resolves . | 188 | 26 |
140,373 | private static void resolveStanfordEntities ( ) throws IOException , ClavinException { /*##################################################################### * * Start with Stanford NER -- no need to get CLAVIN involved for now. * *###################################################################*/ // instantiate Stanford NER entity extractor InputStream mpis = WorkflowDemoNERD . class . getClassLoader ( ) . getResourceAsStream ( "models/english.all.3class.distsim.prop" ) ; Properties mp = new Properties ( ) ; mp . load ( mpis ) ; AbstractSequenceClassifier < CoreMap > namedEntityRecognizer = CRFClassifier . getJarClassifier ( "/models/english.all.3class.distsim.crf.ser.gz" , mp ) ; // Unstructured text file about Somalia to be geoparsed File inputFile = new File ( "src/test/resources/sample-docs/Somalia-doc.txt" ) ; // Grab the contents of the text file as a String String inputString = TextUtils . fileToString ( inputFile ) ; // extract entities from input text using Stanford NER List < Triple < String , Integer , Integer > > entitiesFromNER = namedEntityRecognizer . classifyToCharacterOffsets ( inputString ) ; /*##################################################################### * * Now, CLAVIN comes into play... * *###################################################################*/ // convert Stanford NER output to ClavinLocationResolver input List < LocationOccurrence > locationsForCLAVIN = convertNERtoCLAVIN ( entitiesFromNER , inputString ) ; // instantiate the CLAVIN location resolver ClavinLocationResolver clavinLocationResolver = new ClavinLocationResolver ( new LuceneGazetteer ( new File ( "./IndexDirectory" ) ) ) ; // resolve location entities extracted from input text List < ResolvedLocation > resolvedLocations = clavinLocationResolver . resolveLocations ( locationsForCLAVIN , 1 , 1 , false ) ; // Display the ResolvedLocations found for the location names for ( ResolvedLocation resolvedLocation : resolvedLocations ) System . out . println ( resolvedLocation ) ; } | Sometimes you might already be using Stanford NER elsewhere in your application and you d like to just pass the output from Stanford NER directly into CLAVIN without having to re - run the input through Stanford NER just to use CLAVIN . This example shows you how to very easily do exactly that . | 461 | 62 |
140,374 | public Set < String > getDependentFeatures ( ) throws IOException { final boolean entryExitLogging = log . isLoggable ( Level . FINER ) ; final String methodName = "getDependentFeatures" ; //$NON-NLS-1$ if ( entryExitLogging ) { log . entering ( DependencyList . class . getName ( ) , methodName ) ; } if ( ! initialized ) { initialize ( ) ; } if ( entryExitLogging ) { log . exiting ( DependencyList . class . getName ( ) , methodName , dependentFeatures ) ; } return dependentFeatures ; } | Returns the set of features that were discovered when evaluating has! plugin expressions or aliases when expanding the dependencies . This information may be required by the cache manager in order to properly idenify cached responses . | 132 | 40 |
140,375 | public void setLabel ( String label ) { final boolean entryExitLogging = log . isLoggable ( Level . FINER ) ; final String methodName = "setLabel" ; //$NON-NLS-1$ if ( entryExitLogging ) { log . entering ( DependencyList . class . getName ( ) , methodName , new Object [ ] { label } ) ; } this . label = label ; if ( entryExitLogging ) { log . exiting ( DependencyList . class . getName ( ) , methodName ) ; } } | Associates an arbitrary text string with this object . | 120 | 11 |
140,376 | synchronized void initialize ( ) throws IOException { if ( initialized ) { return ; } final boolean traceLogging = log . isLoggable ( Level . FINEST ) ; final boolean entryExitLogging = log . isLoggable ( Level . FINER ) ; final String methodName = "initialize" ; //$NON-NLS-1$ if ( entryExitLogging ) { log . entering ( DependencyList . class . getName ( ) , methodName ) ; } // A call to getDeclaredDependencies is made to ensure that the time stamp calculated to mark the beginning of finding the expanded //dependencies is done only after forming the dependency map is completed. aggr . getDependencies ( ) . getDelcaredDependencies ( "require" ) ; //$NON-NLS-1$ long stamp = aggr . getDependencies ( ) . getLastModified ( ) ; // save time stamp try { explicitDeps = new ModuleDeps ( ) ; expandedDeps = new ModuleDeps ( ) ; if ( traceLogging ) { log . finest ( "dependent features = " + dependentFeatures ) ; //$NON-NLS-1$ } for ( String name : names ) { processDep ( name , explicitDeps , null , new HashSet < String > ( ) , null ) ; } // Now expand the explicit dependencies resolveAliases = true ; for ( Map . Entry < String , ModuleDepInfo > entry : explicitDeps . entrySet ( ) ) { expandDependencies ( entry . getKey ( ) , entry . getValue ( ) , expandedDeps ) ; } expandedDeps . keySet ( ) . removeAll ( IDependencies . excludes ) ; // Resolve feature conditionals based on the specified feature set. This is // necessary because we don't specify features when doing has! plugin branching // so that dependent features that are discovered by has! plugin branching don't // vary based on the specified features. explicitDeps . resolveWith ( features , coerceUndefinedToFalse ) ; expandedDeps . resolveWith ( features , coerceUndefinedToFalse ) ; if ( traceLogging ) { log . finest ( "explicitDeps after applying features: " + explicitDeps ) ; //$NON-NLS-1$ log . finest ( "expandedDeps after applying features: " + expandedDeps ) ; //$NON-NLS-1$ } if ( stamp != aggr . getDependencies ( ) . getLastModified ( ) ) { // if time stamp has changed, that means that dependencies have been // updated while we were processing them. Throw an exception to avoid // caching the response with possibly corrupt dependency info. throw new IllegalStateException ( "" + stamp + "!=" + aggr . getDependencies ( ) . getLastModified ( ) ) ; //$NON-NLS-1$ //$NON-NLS-2$ } } finally { initialized = true ; } if ( entryExitLogging ) { log . exiting ( DependencyList . class . getName ( ) , methodName ) ; } } | Internal method called to resolve dependencies the first time one of the accessor methods is called . This is done in order to make object creation light - weight and to avoid the possibility of throwing an exception in the object constructor . | 674 | 44 |
140,377 | void expandDependencies ( String name , ModuleDepInfo depInfo , ModuleDeps expandedDependencies ) throws IOException { final String methodName = "expandDependencies" ; //$NON-NLS-1$ final boolean traceLogging = log . isLoggable ( Level . FINEST ) ; final boolean entryExitLogging = log . isLoggable ( Level . FINER ) ; if ( entryExitLogging ) { log . entering ( DependencyList . class . getName ( ) , methodName , new Object [ ] { name , depInfo , expandedDependencies } ) ; } List < String > dependencies = new ArrayList < String > ( ) ; List < String > declaredDeps = aggr . getDependencies ( ) . getDelcaredDependencies ( name ) ; if ( traceLogging ) { log . finest ( "declaredDeps for " + name + " = " + declaredDeps ) ; //$NON-NLS-1$ //$NON-NLS-2$ } if ( declaredDeps != null ) { dependencies . addAll ( declaredDeps ) ; } if ( includeRequireDeps ) { List < String > requireDeps = aggr . getDependencies ( ) . getRequireDependencies ( name ) ; if ( requireDeps != null && requireDeps . size ( ) > 0 ) { if ( traceLogging ) { log . finest ( "requireDeps for " + name + " = " + requireDeps ) ; //$NON-NLS-1$ //$NON-NLS-2$ } dependencies . addAll ( requireDeps ) ; } } if ( dependencies != null ) { for ( String dep : dependencies ) { ModuleDeps moduleDeps = new ModuleDeps ( ) ; processDep ( dep , moduleDeps , depInfo , new HashSet < String > ( ) , name ) ; for ( Map . Entry < String , ModuleDepInfo > entry : moduleDeps . entrySet ( ) ) { if ( traceLogging ) { log . finest ( "Adding " + entry + " to expandedDependencies" ) ; //$NON-NLS-1$ //$NON-NLS-2$ } if ( expandedDependencies . add ( entry . getKey ( ) , new ModuleDepInfo ( entry . getValue ( ) ) ) ) { expandDependencies ( entry . getKey ( ) , entry . getValue ( ) , expandedDependencies ) ; } } } } if ( entryExitLogging ) { log . exiting ( DependencyList . class . getName ( ) , methodName ) ; } } | Expands the nested dependencies for the specified module | 579 | 9 |
140,378 | private Model makeModel ( ) { Model mo = new DefaultModel ( ) ; Mapping mapping = mo . getMapping ( ) ; int nbNodes = 300 ; int nbVMs = 6 * nbNodes ; //Memory usage/consumption in GB ShareableResource rcMem = new ShareableResource ( "mem" ) ; //A resource representing the bandwidth usage/consumption of the elements in GB ShareableResource rcBW = new ShareableResource ( "bandwidth" ) ; nodes = new ArrayList <> ( nbNodes ) ; for ( int i = 0 ; i < nbNodes ; i ++ ) { Node n = mo . newNode ( ) ; nodes . add ( n ) ; mapping . addOnlineNode ( n ) ; //Each node provides a 10GB bandwidth and 32 GB RAM to its VMs rcBW . setCapacity ( n , 10 ) ; rcMem . setCapacity ( n , 32 ) ; } for ( int i = 0 ; i < nbVMs ; i ++ ) { VM vm = mo . newVM ( ) ; //Basic balancing through a round-robin: 6 VMs per node mapping . addRunningVM ( vm , nodes . get ( i % nodes . size ( ) ) ) ; //Each VM uses currently a 1GB bandwidth and 1,2 or 3 GB RAM rcBW . setConsumption ( vm , 1 ) ; rcMem . setConsumption ( vm , i % 5 + 1 ) ; } mo . attach ( rcBW ) ; mo . attach ( rcMem ) ; return mo ; } | A default model with 500 nodes hosting 3000 VMs . 6 VMs per node Each node has a 10GB network interface and 32 GB RAM Each VM consumes 1GB Bandwidth and between 1 to 5 GB RAM | 335 | 42 |
140,379 | @ Override public boolean applyAction ( Model c ) { if ( c . getMapping ( ) . isOffline ( node ) ) { c . getMapping ( ) . addOnlineNode ( node ) ; return true ; } return false ; } | Put the node online on the model . | 52 | 8 |
140,380 | @ Override public boolean applyAction ( Model m ) { Mapping map = m . getMapping ( ) ; if ( map . isOnline ( node ) && map . isRunning ( vm ) && map . getVMLocation ( vm ) . equals ( node ) ) { map . addReadyVM ( vm ) ; return true ; } return false ; } | Apply the action by removing the virtual machine from the model . | 75 | 12 |
140,381 | static String formatMessage ( String fmt , Object [ ] args ) { MessageFormat formatter = new MessageFormat ( fmt ) ; Format [ ] formats = formatter . getFormatsByArgumentIndex ( ) ; StringBuffer msg = new StringBuffer ( ) ; formatter . format ( args , msg , null ) ; if ( args . length > formats . length ) { // We have extra arguements that were not included in the format string. // Append them to the result for ( int i = formats . length ; i < args . length ; i ++ ) { msg . append ( i == formats . length ? ": " : ", " ) //$NON-NLS-1$ //$NON-NLS-2$ . append ( args [ i ] . toString ( ) ) ; } } return msg . toString ( ) ; } | Formats the specified string using the specified arguments . If the argument array contains more elements than the format string can accommodate then the additional arguments are appended to the end of the formatted string . | 181 | 38 |
140,382 | static void logResuming ( String callerClass , String callerMethod , Object waitObj , long start ) { long elapsed = ( System . currentTimeMillis ( ) - start ) / 1000 ; log . logp ( Level . WARNING , callerClass , callerMethod , Messages . SignalUtil_2 , new Object [ ] { Thread . currentThread ( ) . getId ( ) , elapsed , waitObj } ) ; } | Logs a warning level message indicating that a thread which has previously been reported as stuck is now resuming . | 88 | 22 |
140,383 | protected boolean writeResponse ( InputStream in , HttpServletRequest request , HttpServletResponse response ) throws IOException { final String sourceMethod = "writeResponse" ; //$NON-NLS-1$ final boolean isTraceLogging = log . isLoggable ( Level . FINER ) ; if ( isTraceLogging ) { log . entering ( AbstractAggregatorImpl . class . getName ( ) , sourceMethod , new Object [ ] { in , response } ) ; } boolean success = true ; int n = 0 ; byte [ ] buffer = new byte [ 4096 ] ; OutputStream out = response . getOutputStream ( ) ; try { while ( - 1 != ( n = in . read ( buffer ) ) ) { try { out . write ( buffer , 0 , n ) ; } catch ( IOException e ) { // Error writing to the output stream, probably because the connection // was closed by the client. Don't attempt to write anything else to // the response and just log the error using FINE level logging. logException ( request , Level . FINE , sourceMethod , e ) ; success = false ; break ; } } } finally { IOUtils . closeQuietly ( in ) ; IOUtils . closeQuietly ( out ) ; } if ( isTraceLogging ) { log . exiting ( AbstractAggregatorImpl . class . getName ( ) , sourceMethod , success ) ; } return success ; } | Writes the response to the response object . IOExceptions that occur when writing to the response output stream are not propagated but are handled internally . Such exceptions are assumed to be caused by the client closing the connection and are not real errors . | 314 | 49 |
140,384 | void logException ( HttpServletRequest req , Level level , String sourceMethod , Throwable t ) { if ( log . isLoggable ( level ) ) { StringBuffer sb = new StringBuffer ( ) ; // add the request URI and query args String uri = req . getRequestURI ( ) ; if ( uri != null ) { sb . append ( uri ) ; String queryArgs = req . getQueryString ( ) ; if ( queryArgs != null ) { sb . append ( "?" ) . append ( queryArgs ) ; //$NON-NLS-1$ } } // append the exception class name sb . append ( ": " ) . append ( t . getClass ( ) . getName ( ) ) ; //$NON-NLS-1$ // append the exception message sb . append ( " - " ) . append ( t . getMessage ( ) != null ? t . getMessage ( ) : "null" ) ; //$NON-NLS-1$//$NON-NLS-2$ log . logp ( level , AbstractAggregatorImpl . class . getName ( ) , sourceMethod , sb . toString ( ) , t ) ; } } | Formats and logs an exception log message including the request url query args the exception class name and exception message . | 266 | 22 |
140,385 | public String getPropValue ( String propName ) { String propValue = null ; propValue = System . getProperty ( propName ) ; IServiceReference [ ] refs = null ; if ( propValue == null ) { try { refs = getPlatformServices ( ) . getServiceReferences ( IVariableResolver . class . getName ( ) , "(name=" + getName ( ) + ")" ) ; //$NON-NLS-1$ //$NON-NLS-2$ } catch ( PlatformServicesException e ) { if ( log . isLoggable ( Level . SEVERE ) ) { log . log ( Level . SEVERE , e . getMessage ( ) , e ) ; } } if ( refs != null ) { for ( IServiceReference sr : refs ) { IVariableResolver resolver = ( IVariableResolver ) getPlatformServices ( ) . getService ( sr ) ; try { propValue = resolver . resolve ( propName ) ; if ( propValue != null ) { break ; } } finally { getPlatformServices ( ) . ungetService ( sr ) ; } } } } return propValue ; } | Returns the value for the property name used by the aggregator . By default it returns the system property indicated by the specified key . This method may be overriden by the platform dependent implementation of the aggregator . | 254 | 43 |
140,386 | protected void notifyRequestListeners ( RequestNotifierAction action , HttpServletRequest req , HttpServletResponse resp ) throws IOException { // notify any listeners that the config has been updated IServiceReference [ ] refs = null ; try { refs = getPlatformServices ( ) . getServiceReferences ( IRequestListener . class . getName ( ) , "(name=" + getName ( ) + ")" ) ; //$NON-NLS-1$ //$NON-NLS-2$ } catch ( PlatformServicesException e ) { if ( log . isLoggable ( Level . SEVERE ) ) { log . log ( Level . SEVERE , e . getMessage ( ) , e ) ; } } if ( refs != null ) { for ( IServiceReference ref : refs ) { IRequestListener listener = ( IRequestListener ) getPlatformServices ( ) . getService ( ref ) ; try { if ( action == RequestNotifierAction . start ) { listener . startRequest ( req , resp ) ; } else { listener . endRequest ( req , resp ) ; } } finally { getPlatformServices ( ) . ungetService ( ref ) ; } } } } | Calls the registered request notifier listeners . | 259 | 9 |
140,387 | protected void notifyConfigListeners ( long seq ) throws IOException { IServiceReference [ ] refs = null ; try { refs = getPlatformServices ( ) . getServiceReferences ( IConfigListener . class . getName ( ) , "(name=" + getName ( ) + ")" ) ; //$NON-NLS-1$ //$NON-NLS-2$ } catch ( PlatformServicesException e ) { if ( log . isLoggable ( Level . SEVERE ) ) { log . log ( Level . SEVERE , e . getMessage ( ) , e ) ; } } if ( refs != null ) { for ( IServiceReference ref : refs ) { IConfigListener listener = ( IConfigListener ) getPlatformServices ( ) . getService ( ref ) ; if ( listener != null ) { try { listener . configLoaded ( config , seq ) ; } catch ( Throwable t ) { if ( log . isLoggable ( Level . SEVERE ) ) { log . log ( Level . SEVERE , t . getMessage ( ) , t ) ; } throw new IOException ( t ) ; } finally { getPlatformServices ( ) . ungetService ( ref ) ; } } } } } | Call the registered config change listeners | 269 | 6 |
140,388 | protected void registerExtension ( IAggregatorExtension ext , IAggregatorExtension before ) { final String sourceMethod = "registerExtension" ; //$NON-NLS-1$ boolean isTraceLogging = log . isLoggable ( Level . FINER ) ; if ( isTraceLogging ) { log . entering ( AbstractAggregatorImpl . class . getName ( ) , sourceMethod , new Object [ ] { ext , before } ) ; } // validate type String id = ext . getExtensionPointId ( ) ; if ( IHttpTransportExtensionPoint . ID . equals ( id ) ) { if ( before != null ) { throw new IllegalArgumentException ( before . getExtensionPointId ( ) ) ; } httpTransportExtension = ext ; } else { List < IAggregatorExtension > list ; if ( IResourceFactoryExtensionPoint . ID . equals ( id ) ) { list = resourceFactoryExtensions ; } else if ( IResourceConverterExtensionPoint . ID . equals ( id ) ) { list = resourceConverterExtensions ; } else if ( IModuleBuilderExtensionPoint . ID . equals ( id ) ) { list = moduleBuilderExtensions ; } else if ( IServiceProviderExtensionPoint . ID . equals ( id ) ) { list = serviceProviderExtensions ; } else { throw new IllegalArgumentException ( id ) ; } if ( before == null ) { list . add ( ext ) ; } else { // find the extension to insert the item in front of boolean inserted = false ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) { if ( list . get ( i ) == before ) { list . add ( i , ext ) ; inserted = true ; break ; } } if ( ! inserted ) { throw new IllegalArgumentException ( ) ; } } // If this is a service provider extension then register the specified service with the // OSGi service registry if an interface name is provided. if ( IServiceProviderExtensionPoint . ID . equals ( id ) ) { String interfaceName = ext . getAttribute ( IServiceProviderExtensionPoint . SERVICE_ATTRIBUTE ) ; if ( interfaceName != null ) { try { Dictionary < String , String > props = new Hashtable < String , String > ( ) ; // Copy init-params from extension to service dictionary Set < String > attributeNames = new HashSet < String > ( ext . getAttributeNames ( ) ) ; attributeNames . removeAll ( Arrays . asList ( new String [ ] { "class" , IServiceProviderExtensionPoint . SERVICE_ATTRIBUTE } ) ) ; //$NON-NLS-1$ for ( String propName : attributeNames ) { props . put ( propName , ext . getAttribute ( propName ) ) ; } // Set name property to aggregator name props . put ( "name" , getName ( ) ) ; //$NON-NLS-1$ registrations . add ( getPlatformServices ( ) . registerService ( interfaceName , ext . getInstance ( ) , props ) ) ; } catch ( Exception e ) { if ( log . isLoggable ( Level . WARNING ) ) { log . log ( Level . WARNING , e . getMessage ( ) , e ) ; } } } } } if ( isTraceLogging ) { log . exiting ( AbstractAggregatorImpl . class . getName ( ) , sourceMethod ) ; } } | Adds the specified extension to the list of registered extensions . | 751 | 11 |
140,389 | public void initialize ( IConfig config ) throws Exception { // Check last-modified times of resources in the overrides folders. These resources // are considered to be dynamic in a production environment and we want to // detect new/changed resources in these folders on startup so that we can clear // caches, etc. OverrideFoldersTreeWalker walker = new OverrideFoldersTreeWalker ( this , config ) ; walker . walkTree ( ) ; cacheMgr = newCacheManager ( walker . getLastModified ( ) ) ; deps = newDependencies ( walker . getLastModifiedJS ( ) ) ; resourcePaths = getPathsAndAliases ( getInitParams ( ) ) ; // Notify listeners this . config = config ; notifyConfigListeners ( 1 ) ; } | This method does some initialization for the aggregator servlet . This method is called from platform dependent Aggregator implementation during its initialization . | 171 | 27 |
140,390 | protected Map < String , URI > getPathsAndAliases ( InitParams initParams ) { final String sourceMethod = "getPahtsAndAliases" ; //$NON-NLS-1$ boolean isTraceLogging = log . isLoggable ( Level . FINER ) ; if ( isTraceLogging ) { log . entering ( AbstractAggregatorImpl . class . getName ( ) , sourceMethod , new Object [ ] { initParams } ) ; } Map < String , URI > resourcePaths = new HashMap < String , URI > ( ) ; List < String > aliases = initParams . getValues ( InitParams . ALIAS_INITPARAM ) ; for ( String alias : aliases ) { addAlias ( alias , null , "alias" , resourcePaths ) ; //$NON-NLS-1$ } List < String > resourceIds = initParams . getValues ( InitParams . RESOURCEID_INITPARAM ) ; for ( String resourceId : resourceIds ) { aliases = initParams . getValues ( resourceId + ":alias" ) ; //$NON-NLS-1$ List < String > baseNames = initParams . getValues ( resourceId + ":base-name" ) ; //$NON-NLS-1$ if ( aliases == null || aliases . size ( ) != 1 ) { throw new IllegalArgumentException ( resourceId + ":aliases" ) ; //$NON-NLS-1$ } if ( baseNames == null || baseNames . size ( ) != 1 ) { throw new IllegalArgumentException ( resourceId + ":base-name" ) ; //$NON-NLS-1$ } String alias = aliases . get ( 0 ) ; String baseName = baseNames . get ( 0 ) ; // make sure not root path boolean isPathComp = false ; for ( String part : alias . split ( "/" ) ) { //$NON-NLS-1$ if ( part . length ( ) > 0 ) { isPathComp = true ; break ; } } // Make sure basename doesn't start with '/' if ( baseName . startsWith ( "/" ) ) { //$NON-NLS-1$ throw new IllegalArgumentException ( "Root relative base-name not allowed: " + baseName ) ; //$NON-NLS-1$ } if ( ! isPathComp ) { throw new IllegalArgumentException ( resourceId + ":alias = " + alias ) ; //$NON-NLS-1$ } addAlias ( alias , URI . create ( baseName ) , resourceId + ":alias" , resourcePaths ) ; //$NON-NLS-1$ } if ( isTraceLogging ) { log . exiting ( AbstractAggregatorImpl . class . getName ( ) , sourceMethod , resourcePaths ) ; } return Collections . unmodifiableMap ( resourcePaths ) ; } | Returns a mapping of resource aliases to IResources defined in the init - params . If the IResource is null then the alias is for the aggregator itself rather than a resource location . | 653 | 37 |
140,391 | @ SuppressWarnings ( { "unchecked" , "rawtypes" } ) protected void registerLayerListener ( ) { Dictionary dict = new Properties ( ) ; dict . put ( "name" , getName ( ) ) ; //$NON-NLS-1$ registrations . add ( getPlatformServices ( ) . registerService ( ILayerListener . class . getName ( ) , new AggregatorLayerListener ( this ) , dict ) ) ; } | Registers the layer listener | 98 | 5 |
140,392 | public BooleanTerm andWith ( BooleanTerm other ) { if ( isFalse ( ) || other . isFalse ( ) ) { // anding with false, the result is false return BooleanTerm . FALSE ; } if ( other . isTrue ( ) ) { // anding with true, the result is unchanged return this ; } if ( isTrue ( ) ) { // anding with true, other is unchanged return other ; } Set < BooleanVar > result = new HashSet < BooleanVar > ( this ) ; for ( BooleanVar var : other ) { if ( result . contains ( var . negate ( ) ) ) { // If the same term has the same var with opposite states // then the resulting term is false; return BooleanTerm . FALSE ; } result . add ( var ) ; } return new BooleanTerm ( result ) ; } | Returns the logical AND of this term with the specified term . | 173 | 12 |
140,393 | static public byte [ ] zip ( InputStream in ) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; VariableGZIPOutputStream compress = new VariableGZIPOutputStream ( bos , 10240 ) ; // is 10k too big? compress . setLevel ( Deflater . BEST_COMPRESSION ) ; Writer writer = new OutputStreamWriter ( compress , "UTF-8" ) ; //$NON-NLS-1$ // Copy the data from the input stream to the output, compressing as we go. CopyUtil . copy ( in , writer ) ; return bos . toByteArray ( ) ; } | Returns a byte array containing the gzipped contents of the input stream | 139 | 14 |
140,394 | static public byte [ ] unzip ( InputStream in ) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; CopyUtil . copy ( new GZIPInputStream ( in ) , bos ) ; return bos . toByteArray ( ) ; } | Returns the unzipped contents of the zipped input stream in a byte array | 59 | 16 |
140,395 | public static String bind ( String message , Object binding ) { return internalBind ( message , null , String . valueOf ( binding ) , null ) ; } | Bind the given message s substitution locations with the given string value . | 32 | 13 |
140,396 | public static void initializeMessages ( final String bundleName , final Class clazz ) { if ( System . getSecurityManager ( ) == null ) { load ( bundleName , clazz ) ; return ; } AccessController . doPrivileged ( new PrivilegedAction ( ) { public Object run ( ) { load ( bundleName , clazz ) ; return null ; } } ) ; } | Initialize the given class with the values from the specified message bundle . | 80 | 14 |
140,397 | private Number parseNumber ( String numberValue , Object valueSource ) throws WrongValueTypeException { try { Double d = Double . valueOf ( numberValue ) ; return this . mathUtil . toSimplestNumber ( d ) ; } catch ( NumberFormatException e ) { throw new WrongValueTypeException ( e , numberValue , valueSource , Number . class ) ; } } | This method parses a numeric value . | 80 | 8 |
140,398 | public List < LocationOccurrence > extractLocationNames ( String text ) { if ( text == null ) throw new IllegalArgumentException ( "text input to extractLocationNames should not be null" ) ; // extract entities as <Entity Type, Start Index, Stop Index> return convertNERtoCLAVIN ( namedEntityRecognizer . classifyToCharacterOffsets ( text ) , text ) ; } | Get extracted locations from a plain - text body . | 83 | 10 |
140,399 | public static List < LocationOccurrence > convertNERtoCLAVIN ( List < Triple < String , Integer , Integer > > entities , String text ) { List < LocationOccurrence > locations = new ArrayList < LocationOccurrence > ( ) ; if ( entities != null ) { // iterate over each entity Triple for ( Triple < String , Integer , Integer > entity : entities ) { // check if the entity is a "Location" if ( entity . first . equalsIgnoreCase ( "LOCATION" ) ) { // build a LocationOccurrence object locations . add ( new LocationOccurrence ( text . substring ( entity . second , entity . third ) , entity . second ) ) ; } } } return locations ; } | Converts output from Stanford NER to input required by CLAVIN resolver . | 151 | 17 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.