idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
41,800
private static int subAndCheck ( final int x , final int y ) { final long s = ( long ) x - ( long ) y ; if ( s < Integer . MIN_VALUE || s > Integer . MAX_VALUE ) { throw new ArithmeticException ( "overflow: add" ) ; } return ( int ) s ; }
Subtract two integers checking for overflow .
71
9
41,801
public int binarySearch ( final int fromIndex , final int toIndex , final int key ) { checkFromToIndex ( fromIndex , toIndex ) ; return N . binarySearch ( elementData , fromIndex , toIndex , key ) ; }
This List should be sorted first .
51
7
41,802
public static < K , V > boolean remove ( final Map < K , V > map , Map . Entry < ? , ? > entry ) { return remove ( map , entry . getKey ( ) , entry . getValue ( ) ) ; }
Removes the specified entry .
51
6
41,803
public static double asinh ( double a ) { boolean negative = false ; if ( a < 0 ) { negative = true ; a = - a ; } double absAsinh ; if ( a > 0.167 ) { absAsinh = Math . log ( Math . sqrt ( a * a + 1 ) + a ) ; } else { final double a2 = a * a ; if ( a > 0.097 ) { absAsinh = a * ( 1 - a2 * ( F_1_3 - a2 * ( F_1_5 - a2 * (...
Compute the inverse hyperbolic sine of a number .
513
13
41,804
public static double atanh ( double a ) { boolean negative = false ; if ( a < 0 ) { negative = true ; a = - a ; } double absAtanh ; if ( a > 0.15 ) { absAtanh = 0.5 * Math . log ( ( 1 + a ) / ( 1 - a ) ) ; } else { final double a2 = a * a ; if ( a > 0.087 ) { absAtanh = a * ( 1 + a2 * ( F_1_3 + a2 * ( F_1_5 + a2 * ( F_...
Compute the inverse hyperbolic tangent of a number .
394
13
41,805
@ Override public Statement createStatement ( int resultSetType , int resultSetConcurrency ) throws SQLException { // return new // NativeStatement(internalConn.createStatement(resultSetType, // resultSetConcurrency), this); return internalConn . createStatement ( resultSetType , resultSetConcurrency ) ; }
Method createStatement .
68
4
41,806
@ Override public boolean isClosed ( ) throws SQLException { if ( ! isClosed ) { try { if ( internalConn . isClosed ( ) ) { destroy ( ) ; } } catch ( SQLException e ) { // ignore destroy ( ) ; if ( logger . isWarnEnabled ( ) ) { logger . warn ( AbacusException . getErrorMsg ( e ) ) ; } } } return isClosed ; }
Method isClosed .
96
5
41,807
@ Override public void setTypeMap ( Map < String , Class < ? > > arg0 ) throws SQLException { internalConn . setTypeMap ( arg0 ) ; }
Method setTypeMap .
39
5
41,808
@ Override public void setClientInfo ( String name , String value ) throws SQLClientInfoException { internalConn . setClientInfo ( name , value ) ; }
Method setClientInfo .
34
5
41,809
public AnyDelete addFamilyVersion ( String family , final long timestamp ) { delete . addFamilyVersion ( toFamilyQualifierBytes ( family ) , timestamp ) ; return this ; }
Delete all columns of the specified family with a timestamp equal to the specified timestamp .
37
16
41,810
public AnyDelete addColumn ( String family , String qualifier ) { delete . addColumn ( toFamilyQualifierBytes ( family ) , toFamilyQualifierBytes ( qualifier ) ) ; return this ; }
Delete the latest version of the specified column . This is an expensive call in that on the server - side it first does a get to find the latest versions timestamp . Then it adds a delete using the fetched cells timestamp .
41
45
41,811
public AnyDelete addColumns ( String family , String qualifier ) { delete . addColumns ( toFamilyQualifierBytes ( family ) , toFamilyQualifierBytes ( qualifier ) ) ; return this ; }
Delete all versions of the specified column .
43
8
41,812
@ Beta public Triple < R , M , L > reversed ( ) { return new Triple <> ( this . right , this . middle , this . left ) ; }
Returns a new instance of Triple&lt ; R M L&gt ; .
35
16
41,813
long freeSpaceWindows ( String path , final long timeout ) throws IOException { path = FilenameUtil . normalize ( path , false ) ; if ( path . length ( ) > 0 && path . charAt ( 0 ) != ' ' ) { path = "\"" + path + "\"" ; } // build and run the 'dir' command final String [ ] cmdAttribs = new String [ ] { "cmd.exe" , "/C"...
Find free space on the Windows platform using the dir command .
302
12
41,814
long parseDir ( final String line , final String path ) throws IOException { // read from the end of the line to find the last numeric // character on the line, then continue until we find the first // non-numeric character, and everything between that and the last // numeric character inclusive is our free space bytes...
Parses the Windows dir response last line
387
9
41,815
long parseBytes ( final String freeSpace , final String path ) throws IOException { try { final long bytes = Long . parseLong ( freeSpace ) ; if ( bytes < 0 ) { throw new IOException ( "Command line '" + DF + "' did not find free space in response " + "for path '" + path + "'- check path is valid" ) ; } return bytes ; ...
Parses the bytes from a string .
137
9
41,816
List < String > performCommand ( final String [ ] cmdAttribs , final int max , final long timeout ) throws IOException { // this method does what it can to avoid the 'Too many open files' error // based on trial and error and these links: // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4784692 // http://bugs.sun....
Performs the os command .
620
6
41,817
@ Override public Set < Map . Entry < K , V > > entrySet ( ) { return new AbstractSet < Map . Entry < K , V > > ( ) { @ Override public Iterator < Map . Entry < K , V > > iterator ( ) { return new ObjIterator < Map . Entry < K , V > > ( ) { private final Iterator < Map . Entry < K , V > > keyValueEntryIter = keyMap . e...
Returns an immutable Set of Immutable entry .
365
9
41,818
public BiMap < V , K > inversed ( ) { return ( inverse == null ) ? inverse = new BiMap <> ( valueMap , keyMap ) : inverse ; }
Returns the inverse view of this BiMap which maps each of this bimap s values to its associated key . The two BiMaps are backed by the same data ; any changes to one will appear in the other .
39
44
41,819
protected void evict ( ) { for ( int i = 0 , len = _segments . length ; i < len ; i ++ ) { if ( _segments [ i ] . blockBitSet . isEmpty ( ) ) { final Deque < Segment > queue = _segmentQueueMap . get ( i ) ; if ( queue != null ) { synchronized ( queue ) { if ( _segments [ i ] . blockBitSet . isEmpty ( ) ) { synchronized...
recycle the empty Segment .
149
7
41,820
private void log ( String callerFQCN , Level level , String msg , Throwable t ) { // millis and thread are filled by the constructor LogRecord record = new LogRecord ( level , msg ) ; record . setLoggerName ( getName ( ) ) ; record . setThrown ( t ) ; // Note: parameters in record are not set because SLF4J only // supp...
Log the message at the specified level with the specified throwable if any . This method creates a LogRecord and fills in caller date before calling this instance s JDK14 logger .
109
36
41,821
final private void fillCallerData ( String callerFQCN , LogRecord record ) { StackTraceElement [ ] steArray = new Throwable ( ) . getStackTrace ( ) ; int selfIndex = - 1 ; for ( int i = 0 ; i < steArray . length ; i ++ ) { final String className = steArray [ i ] . getClassName ( ) ; if ( className . equals ( callerFQCN...
Fill in caller data if possible .
268
7
41,822
public boolean removeAll ( final Collection < ? > c , final long occurrences ) { checkOccurrences ( occurrences ) ; if ( N . isNullOrEmpty ( c ) || occurrences == 0 ) { return false ; } boolean result = false ; for ( Object e : c ) { if ( result == false ) { result = remove ( e , occurrences ) ; } else { remove ( e , o...
Remove the specified occurrences from the specified elements . The elements will be removed from this set if the occurrences equals to or less than 0 after the operation .
91
30
41,823
public static < T > T newInstance ( final Class < T > cls ) { if ( Modifier . isAbstract ( cls . getModifiers ( ) ) ) { if ( cls . equals ( Map . class ) ) { return ( T ) new HashMap <> ( ) ; } else if ( cls . equals ( List . class ) ) { return ( T ) new ArrayList <> ( ) ; } else if ( cls . equals ( Set . class ) ) { r...
Method newInstance .
626
4
41,824
@ SuppressWarnings ( "unchecked" ) public static < T > T newArray ( final Class < ? > componentType , final int length ) { // if (length == 0) { // final Object result = CLASS_EMPTY_ARRAY.get(componentType); // // if (result != null) { // return (T) result; // } // } return ( T ) Array . newInstance ( componentType , l...
Method newArray .
96
4
41,825
public static < E > Set < E > newSetFromMap ( final Map < E , Boolean > map ) { return Collections . newSetFromMap ( map ) ; }
Returns a set backed by the specified map .
36
9
41,826
@ SuppressWarnings ( "unchecked" ) public static Object [ ] toArray ( final Collection < ? > c ) { if ( N . isNullOrEmpty ( c ) ) { return N . EMPTY_OBJECT_ARRAY ; } return c . toArray ( new Object [ c . size ( ) ] ) ; }
Returns an empty array if the specified collection is null or empty .
72
13
41,827
public static int deepHashCode ( final Object obj ) { if ( obj == null ) { return 0 ; } if ( obj . getClass ( ) . isArray ( ) ) { return typeOf ( obj . getClass ( ) ) . deepHashCode ( obj ) ; } return obj . hashCode ( ) ; }
Method deepHashCode .
67
5
41,828
public static String deepToString ( final Object obj ) { if ( obj == null ) { return NULL_STRING ; } if ( obj . getClass ( ) . isArray ( ) ) { return typeOf ( obj . getClass ( ) ) . deepToString ( obj ) ; } return obj . toString ( ) ; }
Method deepToString .
70
5
41,829
public static < T > List < T > repeatEach ( final Collection < T > c , final int n ) { N . checkArgNotNegative ( n , "n" ) ; if ( n == 0 || isNullOrEmpty ( c ) ) { return new ArrayList < T > ( ) ; } final List < T > result = new ArrayList <> ( c . size ( ) * n ) ; for ( T e : c ) { for ( int i = 0 ; i < n ; i ++ ) { re...
Repeats the elements in the specified Collection one by one .
123
12
41,830
public static < T > List < T > repeatEachToSize ( final Collection < T > c , final int size ) { N . checkArgNotNegative ( size , "size" ) ; checkArgument ( size == 0 || notNullOrEmpty ( c ) , "Collection can not be empty or null when size > 0" ) ; if ( size == 0 || isNullOrEmpty ( c ) ) { return new ArrayList < T > ( )...
Repeats the elements in the specified Collection one by one till reach the specified size .
200
17
41,831
public static < T > T max ( final Collection < ? extends T > c , final int from , final int to , Comparator < ? super T > cmp ) { checkFromToIndex ( from , to , size ( c ) ) ; if ( N . isNullOrEmpty ( c ) || to - from < 1 || from >= c . size ( ) ) { throw new IllegalArgumentException ( "The size of collection can not b...
Returns the maximum element in the collection .
362
8
41,832
private synchronized PoolableConnection newConnection ( ) { synchronized ( xpool ) { if ( xpool . size ( ) >= maxActive ) { return null ; } try { PoolableConnection conn = null ; if ( xpool . size ( ) < minIdle ) { conn = new PoolableConnection ( this , ds . getConnection ( ) , liveTime , Integer . MAX_VALUE , maxOpenP...
Method newConnection .
335
4
41,833
private void initPool ( ) { if ( logger . isWarnEnabled ( ) ) { logger . warn ( "Start to initialize connection pool with url: " + url + " ..." ) ; } for ( int i = 0 ; ( i < initialSize ) && ( xpool . size ( ) < initialSize ) ; i ++ ) { pool . lock ( ) ; try { if ( pool . isClosed ( ) ) { break ; } if ( ( i < initialSi...
Method initPool .
197
4
41,834
public static void registerXMLBindingClassForPropGetSetMethod ( final Class < ? > cls ) { if ( registeredXMLBindingClassList . containsKey ( cls ) ) { return ; } synchronized ( entityDeclaredPropGetMethodPool ) { registeredXMLBindingClassList . put ( cls , false ) ; if ( entityDeclaredPropGetMethodPool . containsKey ( ...
The property maybe only has get method if its type is collection or map by xml binding specificatio Otherwise it will be ignored if not registered by calling this method .
143
32
41,835
public static Set < Class < ? > > getAllInterfaces ( final Class < ? > cls ) { final Set < Class < ? > > interfacesFound = new LinkedHashSet <> ( ) ; getAllInterfaces ( cls , interfacesFound ) ; return interfacesFound ; }
Copied from Apache Commons Lang under Apache License v2 .
61
12
41,836
public static List < String > getPropNameList ( final Class < ? > cls ) { List < String > propNameList = entityDeclaredPropNameListPool . get ( cls ) ; if ( propNameList == null ) { loadPropGetSetMethodList ( cls ) ; propNameList = entityDeclaredPropNameListPool . get ( cls ) ; } return propNameList ; }
Returns an immutable entity property name List by the specified class .
87
12
41,837
public int totalCountOfValues ( ) { int count = 0 ; for ( V v : valueMap . values ( ) ) { count += v . size ( ) ; } return count ; }
Returns the total count of all the elements in all values .
40
12
41,838
public static long skip ( final InputStream input , final long toSkip ) throws UncheckedIOException { if ( toSkip < 0 ) { throw new IllegalArgumentException ( "Skip count must be non-negative, actual: " + toSkip ) ; } else if ( toSkip == 0 ) { return 0 ; } final byte [ ] buf = Objectory . createByteArrayBuffer ( ) ; lo...
Return the count of skipped bytes .
179
7
41,839
private static long estimateLineCount ( final File file , final int byReadingLineNum ) throws UncheckedIOException { final Holder < ZipFile > outputZipFile = new Holder <> ( ) ; InputStream is = null ; BufferedReader br = null ; try { is = openFile ( outputZipFile , file ) ; br = Objectory . createBufferedReader ( is )...
Estimate the total line count of the file by reading the specified line count ahead .
222
17
41,840
public static long merge ( final Collection < File > sourceFiles , final File destFile ) throws UncheckedIOException { final byte [ ] buf = Objectory . createByteArrayBuffer ( ) ; long totalCount = 0 ; OutputStream output = null ; try { output = new FileOutputStream ( destFile ) ; InputStream input = null ; for ( File ...
Merge the specified source files into the destination file .
193
11
41,841
private static String decodeUrl ( final String url ) { String decoded = url ; if ( url != null && url . indexOf ( ' ' ) >= 0 ) { final int n = url . length ( ) ; final StringBuffer buffer = new StringBuffer ( ) ; final ByteBuffer bytes = ByteBuffer . allocate ( n ) ; for ( int i = 0 ; i < n ; ) { if ( url . charAt ( i ...
unavoidable until Java 7
272
6
41,842
public static < R > Stream < R > zip ( final ShortStream a , final ShortStream b , final ShortBiFunction < R > zipFunction ) { return zip ( a . iteratorEx ( ) , b . iteratorEx ( ) , zipFunction ) . onClose ( newCloseHandler ( N . asList ( a , b ) ) ) ; }
Zip together the a and b streams until one of them runs out of values . Each pair of values is combined into a single value using the supplied zipFunction function .
73
33
41,843
static URLSpec getReleaseDownloadUrl ( String path , MavenSettings settings ) throws IOException { String url = settings . mCentralUrl ; if ( settings . mMirrorUrl != null ) url = settings . mMirrorUrl ; return new URLSpec ( url + path , settings . mProxyHost , settings . mProxyPort ) ; }
get release download URL
72
4
41,844
static URLSpec getSnapshotDownloadUrl ( String path , MavenSettings settings ) throws IOException { String url = settings . mSnapshotUrl ; return new URLSpec ( url + path , settings . mProxyHost , settings . mProxyPort ) ; }
get snapshot download URL
54
4
41,845
static MavenSettings getMavenSettings ( ) { try { String homeDir = System . getProperty ( "user.home" ) ; return parseMavenSettings ( new File ( homeDir , ".m2/settings.xml" ) ) ; } catch ( Exception e ) { log ( e ) ; } return new MavenSettings ( ) ; }
get maven settings
74
4
41,846
static MavenSettings parseMavenSettings ( File settingsFile ) throws IOException { MavenSettings settings = new MavenSettings ( ) ; try { DocumentBuilder xmlBuilder = DocumentBuilderFactory . newInstance ( ) . newDocumentBuilder ( ) ; Document xmlDoc = xmlBuilder . parse ( settingsFile ) ; NodeList mirrorList = xmlDoc ...
parse maven settings . xml
459
6
41,847
static String parseSnapshotExeName ( File mdFile ) throws IOException { String exeName = null ; try { String clsStr = Protoc . getPlatformClassifier ( ) ; DocumentBuilder xmlBuilder = DocumentBuilderFactory . newInstance ( ) . newDocumentBuilder ( ) ; Document xmlDoc = xmlBuilder . parse ( mdFile ) ; NodeList versions ...
parse snapshot exe name from maven - metadata . xml
307
12
41,848
public static void assertSelectCount ( long expectedSelectCount ) { QueryCount queryCount = QueryCountHolder . getGrandTotal ( ) ; long recordedSelectCount = queryCount . getSelect ( ) ; if ( expectedSelectCount != recordedSelectCount ) { throw new SQLSelectCountMismatchException ( expectedSelectCount , recordedSelectC...
Assert select statement count
74
5
41,849
public static void assertInsertCount ( long expectedInsertCount ) { QueryCount queryCount = QueryCountHolder . getGrandTotal ( ) ; long recordedInsertCount = queryCount . getInsert ( ) ; if ( expectedInsertCount != recordedInsertCount ) { throw new SQLInsertCountMismatchException ( expectedInsertCount , recordedInsertC...
Assert insert statement count
74
5
41,850
public static void assertUpdateCount ( long expectedUpdateCount ) { QueryCount queryCount = QueryCountHolder . getGrandTotal ( ) ; long recordedUpdateCount = queryCount . getUpdate ( ) ; if ( expectedUpdateCount != recordedUpdateCount ) { throw new SQLUpdateCountMismatchException ( expectedUpdateCount , recordedUpdateC...
Assert update statement count
74
5
41,851
public static void assertDeleteCount ( long expectedDeleteCount ) { QueryCount queryCount = QueryCountHolder . getGrandTotal ( ) ; long recordedDeleteCount = queryCount . getDelete ( ) ; if ( expectedDeleteCount != recordedDeleteCount ) { throw new SQLDeleteCountMismatchException ( expectedDeleteCount , recordedDeleteC...
Assert delete statement count
74
5
41,852
public void login ( String username , String passwd , String domain ) { this . login = getPerformedAction ( new PostLogin ( username , passwd , domain ) ) . getLoginData ( ) ; loginChangeUserInfo = true ; if ( getVersion ( ) == Version . UNKNOWN ) { loginChangeVersion = true ; } }
Performs a Login .
71
5
41,853
public void delete ( String title , String reason ) { getPerformedAction ( new PostDelete ( getUserinfo ( ) , title , reason ) ) ; }
deletes an article with a reason
33
7
41,854
private EditType getEditType ( String typeName ) { for ( EditType type : EditType . values ( ) ) { if ( type . toString ( ) . equals ( typeName ) ) { return type ; } } return null ; }
Create a EditType from the name type used by MW
51
11
41,855
@ Override protected ImmutableList < String > parseElements ( String s ) { ImmutableList . Builder < String > titles = ImmutableList . builder ( ) ; Optional < XmlElement > child = XmlConverter . getChildOpt ( s , "query" , "allpages" ) ; if ( child . isPresent ( ) ) { for ( XmlElement pageElement : child . get ( ) . g...
Picks the article name from a MediaWiki api response .
149
12
41,856
static Optional < XmlElement > getErrorElement ( XmlElement rootXmlElement ) { Optional < XmlElement > elem = rootXmlElement . getChildOpt ( "error" ) ; if ( elem . isPresent ( ) ) { ApiException error = elem . transform ( toApiException ( ) ) . get ( ) ; log . error ( error . getCode ( ) + ": " + error . getValue ( ) ...
Determines if the given XML Document contains an error message which then would printed by the logger .
105
20
41,857
@ Deprecated protected Optional < String > parseXmlHasMore ( String xml , String elementName , String attributeKey , String newContinueKey ) { XmlElement rootElement = XmlConverter . getRootElement ( xml ) ; Optional < XmlElement > aContinue = rootElement . getChildOpt ( "continue" ) ; if ( aContinue . isPresent ( ) ) ...
XML related methods will be removed .
154
8
41,858
public synchronized @ Nullable < Z > Z map ( Function < T , Z > f ) { if ( ref == null ) { return f . apply ( null ) ; } else { return f . apply ( ref . get ( ) ) ; } }
Call some function f on the reference we are storing . Saving the value of T after this call returns is COMPLETELY UNSAFE . Don t do it .
52
33
41,859
public @ Nullable < Z > Z mapWithCopy ( Function < T , Z > f ) throws IOException { final @ Nullable SharedReference < T > localRef = getCopy ( ) ; try { if ( localRef == null ) { return f . apply ( null ) ; } else { return f . apply ( localRef . get ( ) ) ; } } finally { if ( localRef != null ) localRef . close ( ) ; ...
Call some function f on a threadsafe copy of the reference we are storing . Should be used if you expect the function to take a while to run . Saving the value of T after this call returns is COMPLETELY UNSAFE . Don t do it .
95
53
41,860
@ Nonnull private static File writeDataToTempFileOrDie ( @ Nonnull final OutputStreamCallback callback , @ Nonnull final File targetFile , @ Nonnull final Logger log ) throws IOException { Preconditions . checkNotNull ( callback , "callback argument is required!" ) ; Preconditions . checkNotNull ( log , "log argument i...
return a reference to a temp file that contains the written + flushed + fsynced + closed data
325
20
41,861
@ Deprecated public static boolean writeObjectToFile ( Object obj , String file ) { try { writeObjectToFileOrDie ( obj , file , LOGGER ) ; return true ; } catch ( Exception e ) { LOGGER . error ( e . getClass ( ) + ": writeObjectToFile(" + file + ") encountered exception: " + e . getMessage ( ) , e ) ; return false ; }...
Writes an object to a file .
89
8
41,862
private static boolean arrayCompare ( byte [ ] a , int offset1 , byte [ ] a2 , int offset2 , int length ) { for ( int i = 0 ; i < length ; i ++ ) { if ( a [ offset1 ++ ] != a2 [ offset2 ++ ] ) return false ; } return true ; }
Returns true if the array chunks are equal false otherwise .
69
11
41,863
public static long parseTimestampFromUIDString ( String s , final int start , final int end ) { long ret = 0 ; for ( int i = start ; i < end && i < start + 9 ; i ++ ) { ret <<= 5 ; char c = s . charAt ( i ) ; if ( c >= ' ' && c <= ' ' ) { ret |= c - ' ' ; } else if ( c >= ' ' && c <= ' ' ) { ret |= c - ' ' + 10 ; } els...
Parses out the timestamp portion of the uid Strings used in the logrepo
170
19
41,864
public void advise ( long position , long length ) throws IOException { final long ap = address + position ; final long a = ( ap ) / PAGE_SIZE * PAGE_SIZE ; final long l = Math . min ( length + ( ap - a ) , address + memory . length ( ) - ap ) ; final int err = madvise ( a , l ) ; if ( err != 0 ) { throw new IOExceptio...
this is not particularly useful the syscall takes forever
106
11
41,865
@ Deprecated public static void madviseDontNeedTrackedBuffers ( ) { if ( openBuffersTracker == null ) { return ; } openBuffersTracker . forEachOpenTrackedBuffer ( new Function < MMapBuffer , Void > ( ) { @ Override public Void apply ( final MMapBuffer b ) { //noinspection deprecation madviseDontNeed ( b . memory . getA...
If open buffers tracking is enabled calls madvise with MADV_DONTNEED for all tracked buffers . If open buffers tracking is disabled does nothing .
110
32
41,866
public boolean isLoadedDataSuccessfullyRecently ( ) { final Integer timeSinceLastError = getSecondsSinceLastFailedLoad ( ) ; final Integer timeSinceLastSuccess = getSecondsSinceLastLoad ( ) ; if ( timeSinceLastSuccess == null ) { return false ; // never loaded data, so must be FAIL } if ( timeSinceLastError == null ) {...
useful for artifact - based healthchecks
102
8
41,867
public static Quicksortable getQuicksortableIntArray ( final int [ ] array ) { return new Quicksortable ( ) { public void swap ( int i , int j ) { int t = array [ i ] ; array [ i ] = array [ j ] ; array [ j ] = t ; } public int compare ( int a , int b ) { int x = array [ a ] ; int y = array [ b ] ; if ( x < y ) return ...
the sorting code contained in this class was copied from Arrays . java and then modified
120
17
41,868
private static void sort1 ( Quicksortable q , int off , int k , int len ) { // we don't care about anything >= to k if ( off >= k ) return ; // Insertion sort on smallest arrays if ( len < 7 ) { for ( int i = off ; i < len + off ; i ++ ) for ( int j = i ; j > off && q . compare ( j , j - 1 ) < 0 ; j -- ) q . swap ( j ,...
Sorts the specified sub - array of integers into ascending order .
581
13
41,869
public static void heapSort ( Quicksortable q , int size ) { q = reverseQuicksortable ( q ) ; makeHeap ( q , size ) ; sortheap ( q , size ) ; }
sorts the elements in q using the heapsort method
46
12
41,870
private static void sortheap ( Quicksortable q , int size ) { for ( int i = size - 1 ; i >= 1 ; i -- ) { q . swap ( 0 , i ) ; heapifyDown ( q , 0 , i ) ; } }
sorts the heap stored in q
56
7
41,871
public static void partialSortUsingHeap ( Quicksortable q , int k , int size ) { Quicksortable revq = reverseQuicksortable ( q ) ; makeHeap ( revq , k ) ; for ( int i = k ; i < size ; i ++ ) { if ( q . compare ( 0 , i ) > 0 ) { q . swap ( 0 , i ) ; heapifyDown ( revq , 0 , k ) ; } } sortheap ( revq , k ) ; }
finds the lowest k elements of q and stores them in sorted order at the beginning of q by using a heap of size k
111
26
41,872
public static void partialHeapSort ( Quicksortable q , int k , int size ) { makeHeap ( q , size ) ; for ( int i = 0 ; i < k ; i ++ ) { q . swap ( 0 , size - i - 1 ) ; heapifyDown ( q , 0 , size - i - 1 ) ; } vecswap ( q , 0 , size - k , k ) ; reverse ( q , k ) ; }
finds the lowest k elements of q and stores them in sorted order at the beginning of q by turning q into a heap .
97
26
41,873
public static void makeHeap ( Quicksortable q , int size ) { for ( int i = ( size - 1 ) / 2 ; i >= 0 ; i -- ) { heapifyDown ( q , i , size ) ; } }
Makes a heap with the elements [ 0 size ) of q
51
13
41,874
public static void popHeap ( Quicksortable q , int size ) { q . swap ( 0 , size - 1 ) ; heapifyDown ( q , 0 , size - 1 ) ; }
Pops the lowest element off the heap and stores it in the last element
42
15
41,875
public static void topK ( Quicksortable qs , int totalSize , int k ) { if ( k > totalSize ) k = totalSize ; makeHeap ( qs , k ) ; for ( int i = k ; i < totalSize ; i ++ ) { // compare each element to the root of the heap if ( qs . compare ( i , 0 ) > 0 ) { // if it's greater, swap it out and push it down qs . swap ( 0 ...
in an unspecified order
138
4
41,876
public static int binarySearch ( Quicksortable qs , int size ) { int low = 0 ; int high = size - 1 ; while ( low <= high ) { int mid = ( low + high ) >> 1 ; int cmp = qs . compare ( mid , - 1 ) ; if ( cmp < 0 ) low = mid + 1 ; else if ( cmp > 0 ) high = mid - 1 ; else return mid ; // key found } return - ( low + 1 ) ; ...
the compare function on Quicksortable will always pass - 1 as the second index swap function is never called
111
22
41,877
public final long plus ( final long value , @ Nonnull final TimeUnit timeUnit ) { return this . millis . addAndGet ( timeUnit . toMillis ( value ) ) ; }
Add the specified amount of time to the current clock .
41
11
41,878
private static long findMaxTime ( Node n ) { long max = Long . MIN_VALUE ; for ( Map . Entry < String , Node > entry : n . children . entrySet ( ) ) { max = Math . max ( max , entry . getValue ( ) . time ) ; } return max ; }
used for aligning output for prettier printing
65
9
41,879
public final void and ( ThreadSafeBitSet other ) { if ( other . size != size ) throw new IllegalArgumentException ( "BitSets must be of equal size" ) ; for ( int i = 0 ; i < bits . length ; i ++ ) { bits [ i ] &= other . bits [ i ] ; } }
basically same as java s BitSet . and
71
10
41,880
public final void or ( ThreadSafeBitSet other ) { if ( other . size != size ) throw new IllegalArgumentException ( "BitSets must be of equal size" ) ; for ( int i = 0 ; i < bits . length ; i ++ ) { bits [ i ] |= other . bits [ i ] ; } }
this = this | other bitwise
71
7
41,881
public final void xor ( ThreadSafeBitSet other ) { if ( other . size != size ) throw new IllegalArgumentException ( "BitSets must be of equal size" ) ; for ( int i = 0 ; i < bits . length ; i ++ ) { bits [ i ] ^= other . bits [ i ] ; } }
this = this ^ other bitwise
72
7
41,882
@ Nonnegative public static int count ( @ Nonnull final Path dir ) throws IOException { try ( final DirectoryStream < Path > stream = Files . newDirectoryStream ( dir ) ) { return Iterables . size ( stream ) ; } catch ( DirectoryIteratorException ex ) { // I/O error encounted during the iteration, the cause is an IOExc...
Count the number of entries in a directory .
84
9
41,883
public static void rename ( final Path oldName , final Path newName ) throws IOException { checkNotNull ( oldName ) ; checkNotNull ( newName ) ; final boolean sameDir = Files . isSameFile ( oldName . getParent ( ) , newName . getParent ( ) ) ; // rename the file Files . move ( oldName , newName , StandardCopyOption . A...
Perform an atomic rename of oldName - &gt ; newName and fsync the containing directory . This is only truly fsync - safe if both files are in the same directory but it will at least try to do the right thing if the files are in different directories .
128
56
41,884
public static void ensureDirectoryExists ( final Path path ) throws IOException { if ( Files . exists ( path ) ) { if ( ! Files . isDirectory ( path ) ) { throw new IOException ( "path is not a directory: " + path ) ; } // probably should fsync parent here just to be sure, but that might slow stuff down } else { Files ...
Create a directory if it does not already exist . Fails if the path exists and is NOT a directory . Will fsync the parent directory inode .
101
31
41,885
@ Nonnegative public static int fsyncRecursive ( final Path root ) throws IOException { final FsyncingSimpleFileVisitor visitor = new FsyncingSimpleFileVisitor ( ) ; Files . walkFileTree ( root , visitor ) ; return visitor . getFileCount ( ) ; }
Walk a directory tree and Fsync both Directory and File inodes . This does NOT follow symlinks and does not attempt to fsync anything other than Directory or NormalFiles .
61
35
41,886
public static void fsync ( final Path path ) throws IOException { if ( ! Files . isDirectory ( path ) && ! Files . isRegularFile ( path ) ) { throw new IllegalArgumentException ( "fsync is only supported for regular files and directories: " + path ) ; } try ( final FileChannel channel = FileChannel . open ( path , Stan...
Fsync a single path . Please only call this on things that are Directories or NormalFiles .
92
20
41,887
private static void fsyncLineage ( final Path path ) throws IOException { Path cursor = path . toRealPath ( ) ; while ( cursor != null ) { fsync ( cursor ) ; cursor = cursor . getParent ( ) ; } }
Fsync a path and all parents all the way up to the fs root .
51
16
41,888
public static void writeUTF8 ( final String value , final Path path ) throws IOException { write ( value . getBytes ( Charsets . UTF_8 ) , path ) ; }
Write the string to a temporary file fsync the file then atomically rename to the target path . On error it will make a best - effort to erase the temporary file .
39
35
41,889
public static void write ( final byte [ ] data , final Path path ) throws IOException { try ( final SafeOutputStream out = createAtomicFile ( path ) ) { out . write ( ByteBuffer . wrap ( data ) ) ; out . commit ( ) ; } }
Write the bytes to a temporary file fsync the file then atomically rename to the target path . On error it will make a best - effort to erase the temporary file .
57
35
41,890
@ Nonnull public static String determineHostName ( ) throws UnknownHostException { if ( ! OPT_HOSTNAME . isPresent ( ) ) { final String hostName = InetAddress . getLocalHost ( ) . getHostName ( ) ; if ( Strings . isNullOrEmpty ( hostName ) ) { throw new UnknownHostException ( "Unable to lookup localhost, got back empty...
Determine the hostname of the machine that we are on . Do not allow blank or 0 . 0 . 0 . 0 as valid hostnames . The host name will be save into the OPT_HOSTNAME static variable .
179
47
41,891
@ Nonnull public static String determineHostName ( @ Nonnull final String defaultValue ) { checkNotNull ( defaultValue , "Unable to use default value of null for hostname" ) ; if ( ! OPT_HOSTNAME . isPresent ( ) ) { try { return determineHostName ( ) ; // this will get and save it. } catch ( final UnknownHostException ...
Same as determineHostName but will use default value instead of throwing UnknownHostException
130
16
41,892
@ Nullable public static String determineIpAddress ( ) throws SocketException { SocketException caughtException = null ; for ( final Enumeration < NetworkInterface > networkInterfaces = NetworkInterface . getNetworkInterfaces ( ) ; networkInterfaces . hasMoreElements ( ) ; ) { try { final NetworkInterface nextInterface...
Make a best effort to determine the IP address of this machine .
326
13
41,893
public static synchronized VarExporter forNamespace ( @ Nonnull final Class < ? > clazz , final boolean declaredFieldsOnly ) { return getInstance ( clazz . getSimpleName ( ) , clazz , declaredFieldsOnly ) ; }
Load an exporter with a specified class .
52
9
41,894
@ SuppressWarnings ( "unchecked" ) public < T > T getValue ( final String variableName ) { final Variable variable = getVariable ( variableName ) ; return ( variable == null ) ? null : ( T ) variable . getValue ( ) ; }
Load the current value of a given variable .
57
9
41,895
@ Override @ SuppressWarnings ( "unchecked" ) public < T > Variable < T > getVariable ( final String variableName ) { final String [ ] subTokens = getSubVariableTokens ( variableName ) ; if ( subTokens != null ) { final Variable < T > sub = getSubVariable ( subTokens [ 0 ] , subTokens [ 1 ] ) ; if ( sub != null ) { ret...
Load the dynamic variable object .
119
6
41,896
@ Override public void visitVariables ( VariableVisitor visitor ) { // build a collection of live variables in a synchronized block final List < Variable > variablesCopy ; synchronized ( variables ) { variablesCopy = Lists . newArrayListWithExpectedSize ( variables . size ( ) ) ; final Iterator < Variable > iterator = ...
Visit all the values exported by this exporter .
354
10
41,897
public void dumpJson ( final PrintWriter out ) { out . append ( "{" ) ; visitVariables ( new Visitor ( ) { int count = 0 ; public void visit ( Variable var ) { if ( count ++ > 0 ) { out . append ( ", " ) ; } out . append ( var . getName ( ) ) . append ( "='" ) . append ( String . valueOf ( var . getValue ( ) ) ) . appe...
Write all variables as a JSON object . Will not escape names or values . All values are written as Strings .
114
23
41,898
@ Override public void merge ( final Object from , final Object target , final NullHandlingPolicy nullPolicy ) { if ( from == null || target == null ) { return ; } final BeanWrapper fromWrapper = beanWrapper ( from ) ; final BeanWrapper targetWrapper = beanWrapper ( target ) ; final DomainTypeAdministrationConfiguratio...
Merges the given target object into the source one .
647
11
41,899
public List getOptions ( int code ) { if ( options == null ) return Collections . EMPTY_LIST ; List list = Collections . EMPTY_LIST ; for ( Iterator it = options . iterator ( ) ; it . hasNext ( ) ; ) { EDNSOption opt = ( EDNSOption ) it . next ( ) ; if ( opt . getCode ( ) == code ) { if ( list == Collections . EMPTY_LI...
Gets all options in the OPTRecord with a specific code . This returns a list of EDNSOptions .
114
24