idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
11,500
public Optional < Object > getContextForToken ( String key , String token ) { Object context = validateTokenAndGetContext ( key , token ) . second ( ) ; return null != context ? Optional . of ( context ) : Optional . absent ( ) ; }
Validate a short lived token and returning the associated context The token is removed if found and valid .
54
20
11,501
public Object put ( Object key , Object value ) { long objectStamp = System . currentTimeMillis ( ) ; synchronized ( objects ) { objectTimeStamps . put ( key , objectStamp ) ; if ( nextTimeSomeExpired == NO_OBJECTS ) { nextTimeSomeExpired = objectStamp ; } return objects . put ( key , value ) ; } }
Method to store value in cache if this value first in cache - also mark nextTimeSomeExpired as its creating time ;
83
25
11,502
public Object remove ( Object key ) { synchronized ( objects ) { Object remove = objects . remove ( key ) ; objectTimeStamps . remove ( key ) ; if ( remove != null ) { findNextExpireTime ( ) ; } return remove ; } }
When we remove any object we must found again nextTimeSomeExpired .
54
15
11,503
private void findNextExpireTime ( ) { if ( objects . size ( ) == 0 ) { nextTimeSomeExpired = NO_OBJECTS ; } else { nextTimeSomeExpired = NO_OBJECTS ; Collection < Long > longs = null ; synchronized ( objects ) { longs = new ArrayList ( objectTimeStamps . values ( ) ) ; } for ( Iterator < Long > iterator = longs . iterator ( ) ; iterator . hasNext ( ) ; ) { Long next = iterator . next ( ) + timeToLive ; if ( nextTimeSomeExpired == NO_OBJECTS || next < nextTimeSomeExpired ) { nextTimeSomeExpired = next ; } } } }
Internal - use method finds out when next object will expire and store this as nextTimeSomeExpired . If there s no items in cache - let s store NO_OBJECTS
156
38
11,504
@ SuppressWarnings ( "unchecked" ) public static < M extends Enum < M > > void attach ( Service service , String milestore , ServiceMilestone . Evaluation evaluation ) throws Exception { for ( Field field : Beans . getKnownInstanceFields ( service . getClass ( ) ) ) { if ( ServiceMilestone . class . isAssignableFrom ( field . getType ( ) ) ) { try { ( ( ServiceMilestone < M > ) field . get ( service ) ) . attach ( Enum . valueOf ( ( Class < M > ) getMilestoneEnum ( field . getDeclaringClass ( ) ) , milestore ) , evaluation ) ; return ; } catch ( ClassNotFoundException x ) { // No Milestone enum class found // keep looking } catch ( IllegalArgumentException x ) { // No enum constant as named // keep looking } } } throw new IllegalArgumentException ( "NoSuchMilestone" ) ; }
Attaches a ServiceMilestone . Evaluation onto a service .
206
12
11,505
public void attach ( M m , Evaluation eval ) { _evaluations [ m . ordinal ( ) ] = _evaluations [ m . ordinal ( ) ] == null ? eval : new CompoundMilestoneEvaluation ( eval , _evaluations [ m . ordinal ( ) ] ) ; }
Attaches a ServiceMilestone . Evaluation .
64
9
11,506
public void detach ( M m , Evaluation eval ) { _evaluations [ m . ordinal ( ) ] = CompoundMilestoneEvaluation . cleanse ( _evaluations [ m . ordinal ( ) ] , eval ) ; }
Detaches a ServiceMilestone . Evaluation .
50
9
11,507
@ SuppressWarnings ( "unchecked" ) public Recommendation evaluate ( M milestone , DataBinder binder , Reifier dict , Persistence persist ) { Evaluation evaluation = _evaluations [ milestone . ordinal ( ) ] ; return evaluation != null ? evaluation . evaluate ( ( Class < M > ) milestone . getClass ( ) , milestone . toString ( ) , binder , dict , persist ) : Recommendation . CONTINUE ; }
Executes evaluations at a milestone .
94
7
11,508
@ Programmatic public DocumentType findByReference ( final String reference ) { return queryResultsCache . execute ( ( ) -> repositoryService . firstMatch ( new QueryDefault <> ( DocumentType . class , "findByReference" , "reference" , reference ) ) , DocumentTypeRepository . class , "findByReference" , reference ) ; }
region > findByReference
73
5
11,509
public Name xClassName ( Type t ) { if ( t . hasTag ( CLASS ) ) { return names . fromUtf ( externalize ( t . tsym . flatName ( ) ) ) ; } else if ( t . hasTag ( ARRAY ) ) { return typeSig ( types . erasure ( t ) ) ; } else { throw new AssertionError ( "xClassName" ) ; } }
Given a type t return the extended class name of its erasure in external representation .
90
17
11,510
Name fieldName ( Symbol sym ) { if ( scramble && ( sym . flags ( ) & PRIVATE ) != 0 || scrambleAll && ( sym . flags ( ) & ( PROTECTED | PUBLIC ) ) == 0 ) return names . fromString ( "_$" + sym . name . getIndex ( ) ) ; else return sym . name ; }
Given a field return its name .
74
7
11,511
void writeMethod ( MethodSymbol m ) { int flags = adjustFlags ( m . flags ( ) ) ; databuf . appendChar ( flags ) ; if ( dumpMethodModifiers ) { PrintWriter pw = log . getWriter ( Log . WriterKind . ERROR ) ; pw . println ( "METHOD " + fieldName ( m ) ) ; pw . println ( "---" + flagNames ( m . flags ( ) ) ) ; } databuf . appendChar ( pool . put ( fieldName ( m ) ) ) ; databuf . appendChar ( pool . put ( typeSig ( m . externalType ( types ) ) ) ) ; int acountIdx = beginAttrs ( ) ; int acount = 0 ; if ( m . code != null ) { int alenIdx = writeAttr ( names . Code ) ; writeCode ( m . code ) ; m . code = null ; // to conserve space endAttr ( alenIdx ) ; acount ++ ; } List < Type > thrown = m . erasure ( types ) . getThrownTypes ( ) ; if ( thrown . nonEmpty ( ) ) { int alenIdx = writeAttr ( names . Exceptions ) ; databuf . appendChar ( thrown . length ( ) ) ; for ( List < Type > l = thrown ; l . nonEmpty ( ) ; l = l . tail ) databuf . appendChar ( pool . put ( l . head . tsym ) ) ; endAttr ( alenIdx ) ; acount ++ ; } if ( m . defaultValue != null ) { int alenIdx = writeAttr ( names . AnnotationDefault ) ; m . defaultValue . accept ( awriter ) ; endAttr ( alenIdx ) ; acount ++ ; } if ( options . isSet ( PARAMETERS ) ) acount += writeMethodParametersAttr ( m ) ; acount += writeMemberAttrs ( m ) ; acount += writeParameterAttrs ( m ) ; endAttrs ( acountIdx , acount ) ; }
Write method symbol entering all references into constant pool .
449
10
11,512
public static Set < String > getPrimaryKey ( DatabaseMetaData metadata , String tableName ) throws Exception { Set < String > columns = new HashSet < String > ( ) ; ResultSet keys = metadata . getPrimaryKeys ( metadata . getConnection ( ) . getCatalog ( ) , metadata . getUserName ( ) , tableName ) ; while ( keys . next ( ) ) { columns . add ( keys . getString ( PRIMARY_PK_COL_NAME ) ) ; } keys . close ( ) ; return columns ; }
Returns a table s primary key columns as a Set of strings .
112
13
11,513
public static Map < String , ForeignKey > getExportedKeys ( DatabaseMetaData metadata , String tableName ) throws Exception { ResultSet keys = metadata . getExportedKeys ( metadata . getConnection ( ) . getCatalog ( ) , metadata . getUserName ( ) , tableName ) ; Map < String , ForeignKey > map = new HashMap < String , ForeignKey > ( ) ; while ( keys . next ( ) ) { String table = keys . getString ( EXPORTED_FK_TAB_NAME ) ; String name = keys . getString ( EXPORTED_FK_KEY_NAME ) ; if ( name == null || name . length ( ) == 0 ) name = "UNNAMED_FK_" + table ; ForeignKey key = map . get ( name ) ; if ( key == null ) { map . put ( name , key = new ForeignKey ( table ) ) ; } key . add ( keys . getString ( EXPORTED_FK_COL_NAME ) ) ; } keys . close ( ) ; return map ; }
Returns a table s exported keys and their columns as a Map from the key name to the ForeignKey object .
225
22
11,514
public static Map < String , ForeignKey > getForeignKeys ( DatabaseMetaData metadata , String tableName ) throws Exception { ResultSet keys = metadata . getImportedKeys ( metadata . getConnection ( ) . getCatalog ( ) , metadata . getUserName ( ) , tableName ) ; Map < String , ForeignKey > map = new HashMap < String , ForeignKey > ( ) ; while ( keys . next ( ) ) { String table = keys . getString ( IMPORTED_PK_TAB_NAME ) ; String name = keys . getString ( IMPORTED_FK_KEY_NAME ) ; if ( name == null || name . length ( ) == 0 ) name = "UNNAMED_FK_" + table ; ForeignKey key = map . get ( name ) ; if ( key == null ) { map . put ( name , key = new ForeignKey ( table ) ) ; } key . add ( keys . getString ( IMPORTED_FK_COL_NAME ) ) ; } keys . close ( ) ; return map ; }
Returns a table s foreign keys and their columns as a Map from the key name to the ForeignKey object .
224
22
11,515
public static List < Column > getColumns ( DatabaseMetaData metadata , String tableName ) throws Exception { List < Column > columns = new ArrayList < Column > ( ) ; PreparedStatement stmt = metadata . getConnection ( ) . prepareStatement ( "SELECT * FROM " + tableName ) ; ResultSetMetaData rsmeta = stmt . getMetaData ( ) ; for ( int i = 1 , ii = rsmeta . getColumnCount ( ) ; i <= ii ; ++ i ) { columns . add ( new Column ( rsmeta , i ) ) ; } stmt . close ( ) ; return columns ; }
Returns a table s columns
131
5
11,516
public static Table getTable ( DatabaseMetaData metadata , String tableName ) throws Exception { return new Table ( tableName , getPrimaryKey ( metadata , tableName ) , getForeignKeys ( metadata , tableName ) , getExportedKeys ( metadata , tableName ) , getColumns ( metadata , tableName ) ) ; }
Returns a table s structure
68
5
11,517
public static String getClassName ( ResultSetMetaData meta , int index ) throws SQLException { switch ( meta . getColumnType ( index ) ) { case Types . NUMERIC : int precision = meta . getPrecision ( index ) ; if ( meta . getScale ( index ) == 0 ) { if ( precision > 18 ) { return "java.math.BigInteger" ; } else if ( precision > 9 ) { return "java.lang.Long" ; } else if ( precision > 4 ) { return "java.lang.Integer" ; } else if ( precision > 2 ) { return "java.lang.Short" ; } else { return "java.lang.Byte" ; } } else { if ( precision > 16 ) { return "java.math.BigDecimal" ; } else if ( precision > 7 ) { return "java.lang.Double" ; } else { return "java.lang.Float" ; } } case Types . TIMESTAMP : if ( meta . getScale ( index ) == 0 ) { return "java.sql.Date" ; } else { return "java.sql.Timestamp" ; } default : return meta . getColumnClassName ( index ) ; } }
Returns a column s java class name .
261
8
11,518
public void add ( Collection < Monitor > monitors ) { for ( Monitor monitor : monitors ) this . monitors . put ( monitor . getId ( ) , monitor ) ; }
Adds the monitor list to the monitors for the account .
35
11
11,519
public LabelCache labels ( String monitorId ) { LabelCache cache = labels . get ( monitorId ) ; if ( cache == null ) labels . put ( monitorId , cache = new LabelCache ( monitorId ) ) ; return cache ; }
Returns the cache of labels for the given monitor creating one if it doesn t exist .
50
17
11,520
public TabbedPanel put ( Widget widget , String name , int index ) { if ( index < 0 || index >= content . length ) throw new IndexOutOfBoundsException ( ) ; if ( widget == null ) return this ; attach ( widget ) ; content [ index ] = new Tab ( widget , name ) ; this . sendElement ( ) ; return this ; }
Puts new widget to the container
78
7
11,521
@ Nonnull public final EChange setAddress ( @ Nonnull final String sAddress ) { ValueEnforcer . notNull ( sAddress , "Address" ) ; final String sRealAddress = EmailAddressHelper . getUnifiedEmailAddress ( sAddress ) ; if ( EqualsHelper . equals ( sRealAddress , m_sAddress ) ) return EChange . UNCHANGED ; // Check only without MX record check here, because this is a performance // bottleneck when having multiple customers if ( sRealAddress != null && ! EmailAddressHelper . isValid ( sRealAddress ) ) { if ( LOGGER . isErrorEnabled ( ) ) LOGGER . error ( "Found an illegal email address: '" + sRealAddress + "'" ) ; return EChange . UNCHANGED ; } m_sAddress = sRealAddress ; return EChange . CHANGED ; }
Set the address part of the email address . Performs a validity check of the email address .
185
19
11,522
public static void preRegister ( Context context ) { context . put ( JavaFileManager . class , new Context . Factory < JavaFileManager > ( ) { public JavaFileManager make ( Context c ) { return new JavacFileManager ( c , true , null ) ; } } ) ; }
Register a Context . Factory to create a JavacFileManager .
61
13
11,523
private void listDirectory ( File directory , RelativeDirectory subdirectory , Set < JavaFileObject . Kind > fileKinds , boolean recurse , ListBuffer < JavaFileObject > resultList ) { File d = subdirectory . getFile ( directory ) ; if ( ! caseMapCheck ( d , subdirectory ) ) return ; File [ ] files = d . listFiles ( ) ; if ( files == null ) return ; if ( sortFiles != null ) Arrays . sort ( files , sortFiles ) ; for ( File f : files ) { String fname = f . getName ( ) ; if ( f . isDirectory ( ) ) { if ( recurse && SourceVersion . isIdentifier ( fname ) ) { listDirectory ( directory , new RelativeDirectory ( subdirectory , fname ) , fileKinds , recurse , resultList ) ; } } else { if ( isValidFile ( fname , fileKinds ) ) { JavaFileObject fe = new RegularFileObject ( this , fname , new File ( d , fname ) ) ; resultList . append ( fe ) ; } } } }
Insert all files in subdirectory subdirectory of directory directory which match fileKinds into resultList
234
19
11,524
private void listArchive ( Archive archive , RelativeDirectory subdirectory , Set < JavaFileObject . Kind > fileKinds , boolean recurse , ListBuffer < JavaFileObject > resultList ) { // Get the files directly in the subdir List < String > files = archive . getFiles ( subdirectory ) ; if ( files != null ) { for ( ; ! files . isEmpty ( ) ; files = files . tail ) { String file = files . head ; if ( isValidFile ( file , fileKinds ) ) { resultList . append ( archive . getFileObject ( subdirectory , file ) ) ; } } } if ( recurse ) { for ( RelativeDirectory s : archive . getSubdirectories ( ) ) { if ( subdirectory . contains ( s ) ) { // Because the archive map is a flat list of directories, // the enclosing loop will pick up all child subdirectories. // Therefore, there is no need to recurse deeper. listArchive ( archive , s , fileKinds , false , resultList ) ; } } } }
Insert all files in subdirectory subdirectory of archive archive which match fileKinds into resultList
225
19
11,525
private void listContainer ( File container , RelativeDirectory subdirectory , Set < JavaFileObject . Kind > fileKinds , boolean recurse , ListBuffer < JavaFileObject > resultList ) { Archive archive = archives . get ( container ) ; if ( archive == null ) { // archives are not created for directories. if ( fsInfo . isDirectory ( container ) ) { listDirectory ( container , subdirectory , fileKinds , recurse , resultList ) ; return ; } // Not a directory; either a file or non-existant, create the archive try { archive = openArchive ( container ) ; } catch ( IOException ex ) { log . error ( "error.reading.file" , container , getMessage ( ex ) ) ; return ; } } listArchive ( archive , subdirectory , fileKinds , recurse , resultList ) ; }
container is a directory a zip file or a non - existant path . Insert all files in subdirectory subdirectory of container which match fileKinds into resultList
181
33
11,526
private Archive openArchive ( File zipFileName , boolean useOptimizedZip ) throws IOException { File origZipFileName = zipFileName ; if ( symbolFileEnabled && locations . isDefaultBootClassPathRtJar ( zipFileName ) ) { File file = zipFileName . getParentFile ( ) . getParentFile ( ) ; // ${java.home} if ( new File ( file . getName ( ) ) . equals ( new File ( "jre" ) ) ) file = file . getParentFile ( ) ; // file == ${jdk.home} for ( String name : symbolFileLocation ) file = new File ( file , name ) ; // file == ${jdk.home}/lib/ct.sym if ( file . exists ( ) ) zipFileName = file ; } Archive archive ; try { ZipFile zdir = null ; boolean usePreindexedCache = false ; String preindexCacheLocation = null ; if ( ! useOptimizedZip ) { zdir = new ZipFile ( zipFileName ) ; } else { usePreindexedCache = options . isSet ( "usezipindex" ) ; preindexCacheLocation = options . get ( "java.io.tmpdir" ) ; String optCacheLoc = options . get ( "cachezipindexdir" ) ; if ( optCacheLoc != null && optCacheLoc . length ( ) != 0 ) { if ( optCacheLoc . startsWith ( "\"" ) ) { if ( optCacheLoc . endsWith ( "\"" ) ) { optCacheLoc = optCacheLoc . substring ( 1 , optCacheLoc . length ( ) - 1 ) ; } else { optCacheLoc = optCacheLoc . substring ( 1 ) ; } } File cacheDir = new File ( optCacheLoc ) ; if ( cacheDir . exists ( ) && cacheDir . canWrite ( ) ) { preindexCacheLocation = optCacheLoc ; if ( ! preindexCacheLocation . endsWith ( "/" ) && ! preindexCacheLocation . endsWith ( File . separator ) ) { preindexCacheLocation += File . separator ; } } } } if ( origZipFileName == zipFileName ) { if ( ! useOptimizedZip ) { archive = new ZipArchive ( this , zdir ) ; } else { archive = new ZipFileIndexArchive ( this , zipFileIndexCache . getZipFileIndex ( zipFileName , null , usePreindexedCache , preindexCacheLocation , options . isSet ( "writezipindexfiles" ) ) ) ; } } else { if ( ! useOptimizedZip ) { archive = new SymbolArchive ( this , origZipFileName , zdir , symbolFilePrefix ) ; } else { archive = new ZipFileIndexArchive ( this , zipFileIndexCache . getZipFileIndex ( zipFileName , symbolFilePrefix , usePreindexedCache , preindexCacheLocation , options . isSet ( "writezipindexfiles" ) ) ) ; } } } catch ( FileNotFoundException ex ) { archive = new MissingArchive ( zipFileName ) ; } catch ( ZipFileIndex . ZipFormatException zfe ) { throw zfe ; } catch ( IOException ex ) { if ( zipFileName . exists ( ) ) log . error ( "error.reading.file" , zipFileName , getMessage ( ex ) ) ; archive = new MissingArchive ( zipFileName ) ; } archives . put ( origZipFileName , archive ) ; return archive ; }
Open a new zip file directory and cache it .
756
10
11,527
public void add ( Collection < KeyTransaction > keyTransactions ) { for ( KeyTransaction keyTransaction : keyTransactions ) this . keyTransactions . put ( keyTransaction . getId ( ) , keyTransaction ) ; }
Adds the key transaction list to the key transactions for the account .
46
13
11,528
@ Nullable public static VATINStructure getFromValidVATIN ( @ Nullable final String sVATIN ) { if ( StringHelper . getLength ( sVATIN ) > 2 ) for ( final VATINStructure aStructure : s_aList ) if ( aStructure . isValid ( sVATIN ) ) return aStructure ; return null ; }
Determine the structure for a given VATIN .
83
11
11,529
@ Nullable public static VATINStructure getFromVATINCountry ( @ Nullable final String sVATIN ) { if ( StringHelper . getLength ( sVATIN ) >= 2 ) { final String sCountry = sVATIN . substring ( 0 , 2 ) ; for ( final VATINStructure aStructure : s_aList ) if ( aStructure . getExamples ( ) . get ( 0 ) . substring ( 0 , 2 ) . equalsIgnoreCase ( sCountry ) ) return aStructure ; } return null ; }
Resolve the VATIN structure only from the country part of the given VATIN . This should help indicate how the VATIN is valid .
121
28
11,530
protected Iterable < JavaFileObject > wrap ( Iterable < JavaFileObject > fileObjects ) { List < JavaFileObject > mapped = new ArrayList < JavaFileObject > ( ) ; for ( JavaFileObject fileObject : fileObjects ) mapped . ( wrap ( fileObject ) ) ; return Collections . unmodifiableList ( mapped ) ; }
This implementation maps the given list of file objects by calling wrap on each . Subclasses may override this behavior .
75
22
11,531
public static Control createInstance ( ControlVersion version ) { switch ( version ) { case _0_24 : return new Control0_24 ( ) ; case _0_25 : return new Control0_25 ( ) ; default : throw new IllegalArgumentException ( "Unknown control version: " + version ) ; } }
Create a new instance of the frontend network control for the desired version .
67
15
11,532
protected final void attach ( Attachable widget ) { if ( user != null ) { widget . addTo ( user ) ; } else { if ( waitingForUser == null ) waitingForUser = new LinkedList < Attachable > ( ) ; waitingForUser . add ( widget ) ; } }
Used to declare that instance of widget is held by this widget . If this widget is container it must invoke this method for all widgets it stores
62
28
11,533
public org . jbundle . util . osgi . ClassFinder getClassFinder ( Object context ) { if ( ! classServiceAvailable ) return null ; try { if ( classFinder == null ) { Class . forName ( "org.osgi.framework.BundleActivator" ) ; // This tests to see if osgi exists //classFinder = (org.jbundle.util.osgi.ClassFinder)org.jbundle.util.osgi.finder.ClassFinderActivator.getClassFinder(context, -1); try { // Use reflection so the smart jvm's don't try to retrieve this class. Class < ? > clazz = Class . forName ( "org.jbundle.util.osgi.finder.ClassFinderActivator" ) ; // This tests to see if osgi exists if ( clazz != null ) { java . lang . reflect . Method method = clazz . getMethod ( "getClassFinder" , Object . class , int . class ) ; if ( method != null ) classFinder = ( org . jbundle . util . osgi . ClassFinder ) method . invoke ( null , context , - 1 ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } } return classFinder ; } catch ( ClassNotFoundException ex ) { classServiceAvailable = false ; // Osgi is not installed, no need to keep trying return null ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; return null ; } }
Doesn t need to be static since this is only created once
339
13
11,534
public final ResourceBundle getResourceBundle ( String className , Locale locale , String version , ClassLoader classLoader ) throws MissingResourceException { MissingResourceException ex = null ; ResourceBundle resourceBundle = null ; try { resourceBundle = ResourceBundle . getBundle ( className , locale ) ; } catch ( MissingResourceException e ) { ex = e ; } if ( resourceBundle == null ) { try { if ( this . getClassFinder ( null ) != null ) resourceBundle = this . getClassFinder ( null ) . findResourceBundle ( className , locale , version ) ; // Try to find this class in the obr repos } catch ( MissingResourceException e ) { ex = e ; } } if ( resourceBundle == null ) if ( ex != null ) throw ex ; return resourceBundle ; }
Gets a resource bundle using the specified base name and locale
183
12
11,535
public static String getFullClassName ( String packageName , String className ) { return ClassServiceUtility . getFullClassName ( null , packageName , className ) ; }
If class name starts with . append base package .
38
10
11,536
public String find ( String name ) { String value = null ; for ( DataBinder top = this ; top != null && ( value = top . get ( name ) ) == null ; top = top . getLower ( ) ) ; return value ; }
Finds a string value from all data binders starting from the current binder searching downwards .
53
19
11,537
public String put ( String name , String value , String alternative ) { return put ( name , value != null ? value : alternative ) ; }
Puts a new string value into this binder but using an alternative value if the given one is null .
29
22
11,538
public CachedResultSet putResultSet ( String name , CachedResultSet rs ) { return _rsets . put ( name , rs ) ; }
Puts a new result set into this binder .
32
11
11,539
@ SuppressWarnings ( "unchecked" ) public < T , V > T putNamedObject ( String name , V object ) { return ( T ) _named . put ( name , object ) ; }
Puts a named object into this binder returning the original object under the name if any .
46
19
11,540
@ SuppressWarnings ( "unchecked" ) public < T > T getNamedObject ( String name ) { return ( T ) _named . get ( name ) ; }
Retrieves a named object from this binder .
39
11
11,541
public < T > T getNamedObject ( String name , Class < T > type ) { return type . cast ( _named . get ( name ) ) ; }
Retrieves a named object of a specific type from this binder .
35
15
11,542
public < K , V > Map < K , V > map ( String name , Class < K > ktype , Class < V > vtype ) { Map < K , V > map = getNamedObject ( name ) ; if ( map == null ) putNamedObject ( name , map = new HashMap < K , V > ( ) ) ; return map ; }
Introduces a HashMap under the given name if one does not exist yet .
79
16
11,543
public < K , V > Multimap < K , V > mul ( String name , Class < K > ktype , Class < V > vtype ) { Multimap < K , V > map = getNamedObject ( name ) ; if ( map == null ) putNamedObject ( name , map = new Multimap < K , V > ( ) ) ; return map ; }
Introduces a Multimap under the given name if one does not exist yet .
84
17
11,544
@ Override public DataBinder process ( ResultSet rset ) throws Exception { try { if ( rset . next ( ) ) { ResultSetMetaData meta = rset . getMetaData ( ) ; int width = meta . getColumnCount ( ) ; for ( int i = 1 ; i <= width ; ++ i ) { Object value = rset . getObject ( i ) ; if ( value != null ) { put ( Strings . toLowerCamelCase ( meta . getColumnLabel ( i ) , ' ' ) , value . toString ( ) ) ; } } } else { throw new NoSuchElementException ( "NoSuchRow" ) ; } return this ; } finally { rset . close ( ) ; } }
Fills the data binder with columns in the current row of a result set .
156
17
11,545
public DataBinder put ( Object object ) throws Exception { for ( Field field : Beans . getKnownInstanceFields ( object . getClass ( ) ) ) { Object value = field . get ( object ) ; if ( value != null ) { put ( field . getName ( ) , value . toString ( ) ) ; } } return this ; }
Fills the data binder with non - static non - transient fields of an Object excluding null values .
74
21
11,546
public < T extends DataObject > DataBinder put ( T object , String ... names ) throws Exception { Class < ? > type = object . getClass ( ) ; Object value ; for ( String name : names ) { Field field = Beans . getKnownField ( type , name ) ; if ( ! Modifier . isStatic ( field . getModifiers ( ) ) && ! Modifier . isTransient ( field . getModifiers ( ) ) && ( value = field . get ( object ) ) != null ) { put ( field . getName ( ) , value . toString ( ) ) ; } } return this ; }
Fills the data binder with a subset of non - static non - transient fields of an Object excluding null values .
132
24
11,547
public DataBinder load ( String [ ] args , int offset ) { for ( int i = offset ; i < args . length ; ++ i ) { int equal = args [ i ] . indexOf ( ' ' ) ; if ( equal > 0 ) { put ( args [ i ] . substring ( 0 , equal ) , args [ i ] . substring ( equal + 1 ) ) ; } else { throw new RuntimeException ( "***InvalidParameter{" + args [ i ] + ' ' ) ; } } return this ; }
Loads parameters from an array of strings each in the form of name = value .
112
17
11,548
public DataBinder load ( String filename ) throws IOException { Properties props = new Properties ( ) ; Reader reader = new FileReader ( filename ) ; props . load ( reader ) ; reader . close ( ) ; return load ( props ) ; }
Loads parameters from a property file .
51
8
11,549
public DataBinder load ( Properties props ) { Enumeration < ? > enumeration = props . propertyNames ( ) ; while ( enumeration . hasMoreElements ( ) ) { String key = ( String ) enumeration . nextElement ( ) ; put ( key , props . getProperty ( key ) ) ; } return this ; }
Loads parameters from a Properties object .
71
8
11,550
public int estimateMaximumBytes ( ) { int count = this . size ( ) ; for ( String key : _rsets . keySet ( ) ) { CachedResultSet crs = _rsets . get ( key ) ; if ( crs . rows != null ) { count += crs . columns . length * crs . rows . size ( ) ; } } return count * 64 ; }
Provides a very rough estimate of how big a JSON representative of this binder might be .
84
19
11,551
public String toJSON ( ) { JSONBuilder jb = new JSONBuilder ( estimateMaximumBytes ( ) ) . append ( ' ' ) ; appendParams ( jb ) . append ( ' ' ) ; appendTables ( jb ) ; jb . append ( ' ' ) ; return jb . toString ( ) ; }
Returns a JSON string representing the contents of this data binder excluding named objects .
70
16
11,552
private static long getDateForHour ( long dt , TimeZone tz , int hour , int dayoffset ) { Calendar c = getCalendar ( tz ) ; c . setTimeInMillis ( dt ) ; int dd = c . get ( Calendar . DAY_OF_MONTH ) ; int mm = c . get ( Calendar . MONTH ) ; int yy = c . get ( Calendar . YEAR ) ; c . set ( yy , mm , dd , hour , 0 , 0 ) ; c . set ( Calendar . MILLISECOND , 0 ) ; if ( dayoffset != 0 ) c . add ( Calendar . DAY_OF_MONTH , dayoffset ) ; return c . getTimeInMillis ( ) ; }
Returns the date for the given hour .
159
8
11,553
public static Calendar getCalendar ( TimeZone tz , Locale locale ) { if ( tz == null ) tz = getCurrentTimeZone ( ) ; if ( locale == null ) locale = getCurrentLocale ( ) ; return Calendar . getInstance ( tz , locale ) ; }
Returns a new calendar object using the given timezone and locale .
62
13
11,554
public static Locale getLocale ( String country ) { if ( country == null || country . length ( ) == 0 ) country = Locale . getDefault ( ) . getCountry ( ) ; List < Locale > locales = LocaleUtils . languagesByCountry ( country ) ; Locale locale = Locale . getDefault ( ) ; if ( locales . size ( ) > 0 ) locale = locales . get ( 0 ) ; // Use the first locale that matches the country return locale ; }
Returns the locale for the given country .
107
8
11,555
public static void setCalendarData ( Calendar calendar , Locale locale ) { int [ ] array = ( int [ ] ) localeData . get ( locale ) ; if ( array == null ) { Calendar c = Calendar . getInstance ( locale ) ; array = new int [ 2 ] ; array [ 0 ] = c . getFirstDayOfWeek ( ) ; array [ 1 ] = c . getMinimalDaysInFirstWeek ( ) ; localeData . putIfAbsent ( locale , array ) ; } calendar . setFirstDayOfWeek ( array [ 0 ] ) ; calendar . setMinimalDaysInFirstWeek ( array [ 1 ] ) ; }
Set the attributes of the given calendar from the given locale .
137
12
11,556
public static Date addDays ( long dt , int days ) { Calendar c = getCalendar ( ) ; if ( dt > 0L ) c . setTimeInMillis ( dt ) ; c . add ( Calendar . DATE , days ) ; return c . getTime ( ) ; }
Returns the given date adding the given number of days .
64
11
11,557
public static long convertToUtc ( long millis , String tz ) { long ret = millis ; if ( tz != null && tz . length ( ) > 0 ) { DateTime dt = new DateTime ( millis , DateTimeZone . forID ( tz ) ) ; ret = dt . withZoneRetainFields ( DateTimeZone . forID ( "UTC" ) ) . getMillis ( ) ; } return ret ; }
Returns the given date converted to UTC using the given timezone .
100
13
11,558
private static String fork ( String sjavac , String portfile , String logfile , int poolsize , int keepalive , final PrintStream err , String stdouterrfile , String background ) throws IOException , ProblemException { if ( stdouterrfile != null && stdouterrfile . trim ( ) . equals ( "" ) ) { stdouterrfile = null ; } final String startserver = "--startserver:portfile=" + portfile + ",logfile=" + logfile + ",stdouterrfile=" + stdouterrfile + ",poolsize=" + poolsize + ",keepalive=" + keepalive ; if ( background . equals ( "true" ) ) { sjavac += "%20" + startserver ; sjavac = sjavac . replaceAll ( "%20" , " " ) ; sjavac = sjavac . replaceAll ( "%2C" , "," ) ; // If the java/sh/cmd launcher fails the failure will be captured by stdouterr because of the redirection here. String [ ] cmd = { "/bin/sh" , "-c" , sjavac + " >> " + stdouterrfile + " 2>&1" } ; if ( ! ( new File ( "/bin/sh" ) ) . canExecute ( ) ) { ArrayList < String > wincmd = new ArrayList < String > ( ) ; wincmd . add ( "cmd" ) ; wincmd . add ( "/c" ) ; wincmd . add ( "start" ) ; wincmd . add ( "cmd" ) ; wincmd . add ( "/c" ) ; wincmd . add ( sjavac + " >> " + stdouterrfile + " 2>&1" ) ; cmd = wincmd . toArray ( new String [ wincmd . size ( ) ] ) ; } Process pp = null ; try { pp = Runtime . getRuntime ( ) . exec ( cmd ) ; } catch ( Exception e ) { e . printStackTrace ( err ) ; e . printStackTrace ( new PrintWriter ( stdouterrfile ) ) ; } StringBuilder rs = new StringBuilder ( ) ; for ( String s : cmd ) { rs . append ( s + " " ) ; } return rs . toString ( ) ; } // Do not spawn a background server, instead run it within the same JVM. Thread t = new Thread ( ) { @ Override public void run ( ) { try { JavacServer . startServer ( startserver , err ) ; } catch ( Throwable t ) { t . printStackTrace ( err ) ; } } } ; t . start ( ) ; return "" ; }
Fork a background process . Returns the command line used that can be printed if something failed .
580
19
11,559
public static SysInfo connectGetSysInfo ( String serverSettings , PrintStream out , PrintStream err ) { SysInfo sysinfo = new SysInfo ( - 1 , - 1 ) ; String id = Util . extractStringOption ( "id" , serverSettings ) ; String portfile = Util . extractStringOption ( "portfile" , serverSettings ) ; try { PortFile pf = getPortFile ( portfile ) ; useServer ( serverSettings , new String [ 0 ] , new HashSet < URI > ( ) , new HashSet < URI > ( ) , new HashMap < URI , Set < String > > ( ) , new HashMap < String , Set < URI > > ( ) , new HashMap < String , Set < String > > ( ) , new HashMap < String , String > ( ) , sysinfo , out , err ) ; } catch ( Exception e ) { e . printStackTrace ( err ) ; } return sysinfo ; }
Make a request to the server only to get the maximum possible heap size to use for compilations .
208
21
11,560
private void run ( PortFile portFile , PrintStream err , int keepalive ) { boolean fileDeleted = false ; long timeSinceLastCompile ; try { // Every 5 second (check_portfile_interval) we test if the portfile has disappeared => quit // Or if the last request was finished more than 125 seconds ago => quit // 125 = seconds_of_inactivity_before_shutdown+check_portfile_interval serverSocket . setSoTimeout ( CHECK_PORTFILE_INTERVAL * 1000 ) ; for ( ; ; ) { try { Socket s = serverSocket . accept ( ) ; CompilerThread ct = compilerPool . grabCompilerThread ( ) ; ct . setSocket ( s ) ; compilerPool . execute ( ct ) ; flushLog ( ) ; } catch ( java . net . SocketTimeoutException e ) { if ( compilerPool . numActiveRequests ( ) > 0 ) { // Never quit while there are active requests! continue ; } // If this is the timeout after the portfile // has been deleted by us. Then we truly stop. if ( fileDeleted ) { log ( "Quitting because of " + ( keepalive + CHECK_PORTFILE_INTERVAL ) + " seconds of inactivity!" ) ; break ; } // Check if the portfile is still there. if ( ! portFile . exists ( ) ) { // Time to quit because the portfile was deleted by another // process, probably by the makefile that is done building. log ( "Quitting because portfile was deleted!" ) ; flushLog ( ) ; break ; } // Check if portfile.stop is still there. if ( portFile . markedForStop ( ) ) { // Time to quit because another process touched the file // server.port.stop to signal that the server should stop. // This is necessary on some operating systems that lock // the port file hard! log ( "Quitting because a portfile.stop file was found!" ) ; portFile . delete ( ) ; flushLog ( ) ; break ; } // Does the portfile still point to me? if ( ! portFile . stillMyValues ( ) ) { // Time to quit because another build has started. log ( "Quitting because portfile is now owned by another javac server!" ) ; flushLog ( ) ; break ; } // Check how long since the last request finished. long diff = System . currentTimeMillis ( ) - compilerPool . lastRequestFinished ( ) ; if ( diff < keepalive * 1000 ) { // Do not quit if we have waited less than 120 seconds. continue ; } // Ok, time to quit because of inactivity. Perhaps the build // was killed and the portfile not cleaned up properly. portFile . delete ( ) ; fileDeleted = true ; log ( "" + keepalive + " seconds of inactivity quitting in " + CHECK_PORTFILE_INTERVAL + " seconds!" ) ; flushLog ( ) ; // Now we have a second 5 second grace // period where javac remote requests // that have loaded the data from the // recently deleted portfile can connect // and complete their requests. } } } catch ( Exception e ) { e . printStackTrace ( err ) ; e . printStackTrace ( theLog ) ; flushLog ( ) ; } finally { compilerPool . shutdown ( ) ; } long realTime = System . currentTimeMillis ( ) - serverStart ; log ( "Shutting down." ) ; log ( "Total wall clock time " + realTime + "ms build time " + totalBuildTime + "ms" ) ; flushLog ( ) ; }
Run the server thread until it exits . Either because of inactivity or because the port file has been deleted by someone else or overtaken by some other javac server .
774
35
11,561
public < T extends Object > void writeValue ( T value ) throws IOException { writeValue ( value , ( Class < T > ) value . getClass ( ) ) ; }
Value can not be null
37
5
11,562
private void deserializeFromStream ( final InputStream in ) throws IOException { final byte [ ] dateTimeBytes = new byte [ 8 ] ; in . read ( dateTimeBytes , 0 , 8 ) ; eventDateTime = new DateTime ( ByteBuffer . wrap ( dateTimeBytes ) . getLong ( 0 ) ) ; final byte [ ] sizeGranularityInBytes = new byte [ 4 ] ; in . read ( sizeGranularityInBytes , 0 , 4 ) ; final byte [ ] granularityBytes = new byte [ ByteBuffer . wrap ( sizeGranularityInBytes ) . getInt ( 0 ) ] ; in . read ( granularityBytes , 0 , granularityBytes . length ) ; granularity = Granularity . valueOf ( new String ( granularityBytes , Charset . forName ( "UTF-8" ) ) ) ; thriftEnvelope = deserializer . deserialize ( null ) ; }
Given an InputStream extract the eventDateTime granularity and thriftEnvelope to build the ThriftEnvelopeEvent . This method expects the stream to be open and won t close it for you .
200
43
11,563
public void add ( Collection < ApplicationInstance > applicationInstances ) { for ( ApplicationInstance applicationInstance : applicationInstances ) this . applicationInstances . put ( applicationInstance . getId ( ) , applicationInstance ) ; }
Adds the application instance list to the application instances for the account .
46
13
11,564
public Object get ( ) { synchronized ( this ) { if ( freePool . isEmpty ( ) || usedPool . size ( ) >= capacity ) { try { wait ( 1000 ) ; } catch ( InterruptedException e ) { } // The timeout value was reached if ( freePool . isEmpty ( ) ) add ( new SimpleDateFormat ( ) ) ; } Object o = freePool . get ( 0 ) ; freePool . remove ( o ) ; usedPool . add ( o ) ; return o ; } }
Retrieve a resource from the pool of free resources .
107
11
11,565
public SimpleDateFormat getFormat ( String format ) { SimpleDateFormat f = ( SimpleDateFormat ) get ( ) ; f . applyPattern ( format ) ; return f ; }
Retrieve a date format from the pool of free resources .
37
12
11,566
public void release ( Object o ) { synchronized ( this ) { usedPool . remove ( o ) ; freePool . add ( o ) ; notify ( ) ; } }
Release a resource and put it back in the pool of free resources .
35
14
11,567
public void execute ( ) throws MojoExecutionException { ClassLoader classloader ; try { classloader = createClassLoader ( ) ; } catch ( Exception e ) { throw new MojoExecutionException ( "could not create classloader from dependencies" , e ) ; } AbstractConfiguration [ ] configurations ; try { configurations = ConfigurationGenerator . execute ( generatedSourceDirectory , applicationDefinition , classloader , getSLF4JLogger ( ) ) ; } catch ( Exception e ) { throw new MojoExecutionException ( "could not generate the configurator" , e ) ; } getPluginContext ( ) . put ( GENERATED_CONFIGURATIONS_KEY , configurations ) ; project . addCompileSourceRoot ( generatedSourceDirectory . getPath ( ) ) ; }
Processes all dependencies first and then creates a new JVM to generate the configurator implementation with .
164
21
11,568
public String toShortString ( StringBuilder sb ) { sb . setLength ( 0 ) ; sb . append ( ' ' ) ; sb . append ( left ) ; sb . append ( ' ' ) ; sb . append ( top ) ; sb . append ( "][" ) ; sb . append ( right ) ; sb . append ( ' ' ) ; sb . append ( bottom ) ; sb . append ( ' ' ) ; return sb . toString ( ) ; }
Return a string representation of the rectangle in a compact form .
109
12
11,569
public String flattenToString ( ) { StringBuilder sb = new StringBuilder ( 32 ) ; // WARNING: Do not change the format of this string, it must be // preserved because Rects are saved in this flattened format. sb . append ( left ) ; sb . append ( ' ' ) ; sb . append ( top ) ; sb . append ( ' ' ) ; sb . append ( right ) ; sb . append ( ' ' ) ; sb . append ( bottom ) ; return sb . toString ( ) ; }
Return a string representation of the rectangle in a well - defined format .
117
14
11,570
public void set ( Rect src ) { this . left = src . left ; this . top = src . top ; this . right = src . right ; this . bottom = src . bottom ; }
Copy the coordinates from src into this rectangle .
41
9
11,571
public void offset ( int dx , int dy ) { left += dx ; top += dy ; right += dx ; bottom += dy ; }
Offset the rectangle by adding dx to its left and right coordinates and adding dy to its top and bottom coordinates .
28
22
11,572
public boolean contains ( int left , int top , int right , int bottom ) { // check for empty first return this . left < this . right && this . top < this . bottom // now check for containment && this . left <= left && this . top <= top && this . right >= right && this . bottom >= bottom ; }
Returns true iff the 4 specified sides of a rectangle are inside or equal to this rectangle . i . e . is this rectangle a superset of the specified rectangle . An empty rectangle never contains another rectangle .
69
42
11,573
public boolean contains ( Rect r ) { // check for empty first return this . left < this . right && this . top < this . bottom // now check for containment && left <= r . left && top <= r . top && right >= r . right && bottom >= r . bottom ; }
Returns true iff the specified rectangle r is inside or equal to this rectangle . An empty rectangle never contains another rectangle .
60
24
11,574
public void union ( Rect r ) { union ( r . left , r . top , r . right , r . bottom ) ; }
Update this Rect to enclose itself and the specified rectangle . If the specified rectangle is empty nothing is done . If this rectangle is empty it is set to the specified rectangle .
28
35
11,575
public void scale ( float scale ) { if ( scale != 1.0f ) { left = ( int ) ( left * scale + 0.5f ) ; top = ( int ) ( top * scale + 0.5f ) ; right = ( int ) ( right * scale + 0.5f ) ; bottom = ( int ) ( bottom * scale + 0.5f ) ; } }
Scales up the rect by the given scale .
84
10
11,576
public void add ( Collection < Plugin > plugins ) { for ( Plugin plugin : plugins ) this . plugins . put ( plugin . getId ( ) , plugin ) ; }
Adds the plugin list to the plugins for the account .
35
11
11,577
public PluginComponentCache components ( long pluginId ) { PluginComponentCache cache = components . get ( pluginId ) ; if ( cache == null ) components . put ( pluginId , cache = new PluginComponentCache ( pluginId ) ) ; return cache ; }
Returns the cache of plugin components for the given plugin creating one if it doesn t exist .
53
18
11,578
public TypeConverter getTypeConverter ( ) throws RpcException { if ( contract == null ) { throw new IllegalStateException ( "contract cannot be null" ) ; } if ( type == null ) { throw new IllegalStateException ( "field type cannot be null" ) ; } TypeConverter tc = null ; if ( type . equals ( "string" ) ) tc = new StringTypeConverter ( isOptional ) ; else if ( type . equals ( "int" ) ) tc = new IntTypeConverter ( isOptional ) ; else if ( type . equals ( "float" ) ) tc = new FloatTypeConverter ( isOptional ) ; else if ( type . equals ( "bool" ) ) tc = new BoolTypeConverter ( isOptional ) ; else { Struct s = contract . getStructs ( ) . get ( type ) ; if ( s != null ) { tc = new StructTypeConverter ( s , isOptional ) ; } Enum e = contract . getEnums ( ) . get ( type ) ; if ( e != null ) { tc = new EnumTypeConverter ( e , isOptional ) ; } } if ( tc == null ) { throw RpcException . Error . INTERNAL . exc ( "Unknown type: " + type ) ; } else if ( isArray ) { return new ArrayTypeConverter ( tc , isOptional ) ; } else { return tc ; } }
Returns a new TypeConverter appropriate for the Field s type .
312
14
11,579
public String getJavaType ( boolean wrapArray ) { String t = "" ; if ( type . equals ( "string" ) ) { t = "String" ; } else if ( type . equals ( "float" ) ) { t = "Double" ; } else if ( type . equals ( "int" ) ) { t = "Long" ; } else if ( type . equals ( "bool" ) ) { t = "Boolean" ; } else { t = type ; } if ( wrapArray && isArray ) { return t + "[]" ; } else { return t ; } }
Returns the Java type this type maps to . Used by Idl2Java code generator .
126
18
11,580
public static boolean isBlank ( final String source ) { if ( isEmpty ( source ) ) { return true ; } int strLen = source . length ( ) ; for ( int i = 0 ; i < strLen ; i ++ ) { if ( ! Character . isWhitespace ( source . charAt ( i ) ) ) { return false ; } } return true ; }
Returns true if the source string is null or all characters in this string is space ; false otherwise .
80
20
11,581
public static int indexOfIgnoreCase ( final String source , final String target ) { int targetIndex = source . indexOf ( target ) ; if ( targetIndex == INDEX_OF_NOT_FOUND ) { String sourceLowerCase = source . toLowerCase ( ) ; String targetLowerCase = target . toLowerCase ( ) ; targetIndex = sourceLowerCase . indexOf ( targetLowerCase ) ; return targetIndex ; } else { return targetIndex ; } }
Returns the index within given source string of the first occurrence of the specified target string with ignore case sensitive .
100
21
11,582
public static boolean containsWord ( final String text , final String word ) { if ( text == null || word == null ) { return false ; } if ( text . contains ( word ) ) { Matcher matcher = matchText ( text ) ; for ( ; matcher . find ( ) ; ) { String matchedWord = matcher . group ( 0 ) ; if ( matchedWord . equals ( word ) ) { return true ; } } } return false ; }
Returns true if given text contains given word ; false otherwise .
96
12
11,583
public static boolean containsWordIgnoreCase ( final String text , final String word ) { if ( text == null || word == null ) { return false ; } return containsWord ( text . toLowerCase ( ) , word . toLowerCase ( ) ) ; }
Returns true if given text contains given word ignore case ; false otherwise .
55
14
11,584
public static boolean startsWithIgnoreCase ( final String source , final String target ) { if ( source . startsWith ( target ) ) { return true ; } if ( source . length ( ) < target . length ( ) ) { return false ; } return source . substring ( 0 , target . length ( ) ) . equalsIgnoreCase ( target ) ; }
Returns true if given source string start with target string ignore case sensitive ; false otherwise .
76
17
11,585
public static boolean endsWithIgnoreCase ( final String source , final String target ) { if ( source . endsWith ( target ) ) { return true ; } if ( source . length ( ) < target . length ( ) ) { return false ; } return source . substring ( source . length ( ) - target . length ( ) ) . equalsIgnoreCase ( target ) ; }
Returns true if given source string end with target string ignore case sensitive ; false otherwise .
80
17
11,586
public static String getRandomString ( final int stringLength ) { StringBuilder stringBuilder = getStringBuild ( ) ; for ( int i = 0 ; i < stringLength ; i ++ ) { stringBuilder . append ( getRandomAlphabetic ( ) ) ; } return stringBuilder . toString ( ) ; }
Returns a random given length size alphabetic string .
65
11
11,587
public static String encoding ( final String source , final String sourceCharset , final String encodingCharset ) throws IllegalArgumentException { byte [ ] sourceBytes ; String encodeString = null ; try { sourceBytes = source . getBytes ( sourceCharset ) ; encodeString = new String ( sourceBytes , encodingCharset ) ; } catch ( UnsupportedEncodingException e ) { throw new IllegalArgumentException ( String . format ( "Unsupported encoding:%s or %s" , sourceCharset , encodingCharset ) ) ; } return encodeString ; }
Return encoded string by given charset .
124
8
11,588
public static double [ ] getBorders ( int numberOfBins , List < Double > counts ) { Collections . sort ( counts ) ; if ( ! counts . isEmpty ( ) ) { List < Integer > borderInds = findBordersNaive ( numberOfBins , counts ) ; if ( borderInds == null ) { borderInds = findBorderIndsByRepeatedDividing ( numberOfBins , counts ) ; } double [ ] result = new double [ borderInds . size ( ) ] ; for ( int i = 0 ; i < result . length ; i ++ ) { result [ i ] = counts . get ( borderInds . get ( i ) ) ; } return result ; } else return new double [ ] { 0.0 } ; }
Carefull this method sorts the counts list!
166
9
11,589
public Map < String , Set < String > > getDependencies ( ) { Map < String , Set < String > > new_deps = new HashMap < String , Set < String > > ( ) ; if ( explicitPackages == null ) return new_deps ; for ( Name pkg : explicitPackages ) { Set < Name > set = deps . get ( pkg ) ; if ( set != null ) { Set < String > new_set = new_deps . get ( pkg . toString ( ) ) ; if ( new_set == null ) { new_set = new HashSet < String > ( ) ; // Modules beware.... new_deps . put ( ":" + pkg . toString ( ) , new_set ) ; } for ( Name d : set ) { new_set . add ( ":" + d . toString ( ) ) ; } } } return new_deps ; }
Fetch the set of dependencies that are relevant to the compile that has just been performed . I . e . we are only interested in dependencies for classes that were explicitly compiled .
202
35
11,590
public void visitPubapi ( Element e ) { Name n = ( ( ClassSymbol ) e ) . fullname ; Name p = ( ( ClassSymbol ) e ) . packge ( ) . fullname ; StringBuffer sb = publicApiPerClass . get ( n ) ; assert ( sb == null ) ; sb = new StringBuffer ( ) ; PubapiVisitor v = new PubapiVisitor ( sb ) ; v . visit ( e ) ; if ( sb . length ( ) > 0 ) { publicApiPerClass . put ( n , sb ) ; } explicitPackages . add ( p ) ; }
Visit the api of a class and construct a pubapi string and store it into the pubapi_perclass map .
138
24
11,591
public void collect ( Name currPkg , Name depPkg ) { if ( ! currPkg . equals ( depPkg ) ) { Set < Name > theset = deps . get ( currPkg ) ; if ( theset == null ) { theset = new HashSet < Name > ( ) ; deps . put ( currPkg , theset ) ; } theset . add ( depPkg ) ; } }
Collect a dependency . curr_pkg is marked as depending on dep_pkg .
97
17
11,592
@ SuppressWarnings ( "unchecked" ) public void preload ( int quantity ) { Object [ ] objects = new Object [ quantity ] ; for ( int i = 0 ; i < quantity ; i ++ ) { objects [ i ] = this . instantiate ( ) ; } for ( int i = 0 ; i < quantity ; i ++ ) { this . release ( ( T ) objects [ i ] ) ; } }
Instantiate quantity numbers of elements from the Pool and set them in the pool right away
90
17
11,593
private void blockMe ( int cyclesToBlock ) { long unblock = cycles + cyclesToBlock ; BlockedEntry newEntry = new BlockedEntry ( unblock ) ; blockedCollection . add ( newEntry ) ; while ( unblock > cycles ) { try { newEntry . getSync ( ) . acquire ( ) ; // blocks } catch ( InterruptedException exc ) { log . error ( "[temporaryBlock] Spurious wakeup" , exc ) ; } } }
Blocks the calling thread until enough turns have elapsed
99
9
11,594
public void tick ( ) { log . trace ( "Tick {}" , cycles ) ; cycles ++ ; // check for robots up for unblocking for ( BlockedEntry entry : blockedCollection ) { if ( entry . getTimeout ( ) >= cycles ) { entry . getSync ( ) . release ( ) ; } } }
Signals one cycles has elapsed
67
6
11,595
public void waitFor ( Integer clientId , int turns , String reason ) { // for safety, check if we know the robot, otherwise fail if ( ! registered . contains ( clientId ) ) { throw new IllegalArgumentException ( "Unknown robot. All robots must first register with clock" ) ; } synchronized ( waitingList ) { if ( waitingList . contains ( clientId ) ) { throw new IllegalArgumentException ( "Client " + clientId + " is already waiting, no multithreading is allowed" ) ; } waitingList . add ( clientId ) ; } // we are in the robot's thread log . trace ( "[waitFor] Blocking {} for {} turns. Reason: {}" , clientId , turns , reason ) ; blockMe ( turns ) ; log . trace ( "[waitFor] Unblocked {} - {}" , clientId , reason ) ; synchronized ( waitingList ) { waitingList . remove ( clientId ) ; } }
Blocks the calling thread for the specified number of cycles
201
10
11,596
public String produce ( int size ) { byte bytes [ ] = new byte [ size ] ; _random . nextBytes ( bytes ) ; return Strings . toHexString ( bytes ) ; }
Produces a nonce of an arbitrary size in bytes which is not to be proved later .
41
19
11,597
public String produce ( String state , long time ) { Nonce nonce = new Nonce ( INSTANCE , time > 0 ? time : TTL , SIZE , _random ) ; _map . put ( state + ' ' + nonce . value , nonce ) ; return nonce . value ; }
Produces a nonce that is associated with the given state and is to be proved within a time limit .
64
22
11,598
public boolean renew ( String value , String state , long time ) { Nonce nonce = _map . get ( state + ' ' + value ) ; if ( nonce != null && ! nonce . hasExpired ( ) ) { nonce . renew ( time > 0 ? time : TTL ) ; return true ; } else { return false ; } }
Renews a nonce . The nonce must be valid and must have not expired .
75
18
11,599
public boolean prove ( String value , String state ) { Nonce nonce = _map . remove ( state + ' ' + value ) ; return nonce != null && ! nonce . hasExpired ( ) ; }
Proves a nonce and its associated state . A nonce can only be successfully proved once .
46
20