auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean append( RecordCursor<RECORD> cursor, RECORD[] array, long id, int index ) { RECORD record = array[index]; if ( !cursor.next( id, record, RecordLoad.CHECK ) || (filter != null && !filter.test( record )) ) { return false; } START return true; END } This can be simplified to return an expression. And the null-check could be avoided by initialising the `filter` field to `Predicates.alwaysTrue` if no filter is otherwise given in the constructor.

Target:
public boolean append( RecordCursor<RECORD> cursor, RECORD[] array, long id, int index ) { RECORD record = array[index]; return cursor.next( id, record, RecordLoad.CHECK ) && filter.test( record ); }
Source:
private void recalculatePercent() { START int percent = (int) (totalRead * 100 / size); END if ( percent > lastReportedPercent ) { lastReportedPercent = percent; listener.onProgress( percent ); } } i would add additional check to make sure we will never make it to more then 100 :)

Target:
private void recalculatePercent() { int percent = (int) (totalRead * 100 / size); if ( percent > 100 ) { percent = 100; } if ( percent < 0 ) { percent = 0; } if ( percent > lastReportedPercent ) { lastReportedPercent = percent; listener.onProgress( percent ); } }
Source:
public void addToArchive( Path archiveDestination, DiagnosticsReporterProgressCallback monitor ) throws IOException { long size = fs.getFileSize( source ); InputStream in = fs.openAsInputStream( source ); // Track progress of the file reading, source might be a very large file START ProgressAwareInputStream inStream = new ProgressAwareInputStream( in, size, monitor::percentChanged ); END Files.copy( inStream, archiveDestination ); } this stream needs to be closed

Target:
public void addToArchive( Path archiveDestination, DiagnosticsReporterProgressCallback monitor ) throws IOException { long size = fs.getFileSize( source ); InputStream in = fs.openAsInputStream( source ); // Track progress of the file reading, source might be a very large file try ( ProgressAwareInputStream inStream = new ProgressAwareInputStream( in, size, monitor::percentChanged ) ) { Files.copy( inStream, archiveDestination ); } }
Source:
public synchronized void stop() throws Throwable { stopped = true; if ( currentJob != null ) { currentJob.stop(); } if ( jobHandle != null ) { START jobHandle.cancel( false ); END try { jobHandle.waitTermination(); } catch ( CancellationException ignored ) { } } } The scheduler is designed to only run one task at the time so this should have no effect. Since it is either currently running or completed.

Target:
public synchronized void stop() throws Throwable { stopped = true; if ( currentJob != null ) { currentJob.stop(); } }
Source:
START protected void sharedOptimisticLock( ResourceType resource, long resourceId ) END { ktx.locks().optimistic().acquireShared( ktx.lockTracer(), resource, resourceId ); } Can be package private

Target:
void sharedOptimisticLock( ResourceType resource, long resourceId ) { ktx.locks().optimistic().acquireShared( ktx.lockTracer(), resource, resourceId ); }
Source:
void scan( Read read ) { if ( getId() != NO_ID ) { reset(); } if ( pageCursor == null ) { pageCursor = read.nodePage( 0 ); } this.next = 0; this.highMark = read.nodeHighMark(); this.read = read; START if ( labelCursor != null ) END { labelCursor = read.labelCursor(); } } I might be missing something here but shouldn't it be `labelCursor == null`

Target:
void scan( Read read ) { if ( getId() != NO_ID ) { reset(); } if ( pageCursor == null ) { pageCursor = read.nodePage( 0 ); } this.next = 0; this.highMark = read.nodeHighMark(); this.read = read; if ( labelCursor == null ) { labelCursor = read.labelCursor(); } }
Source:
START public void stop() throws Throwable END { if (currentJob != null) { currentJob.stop(); } } synchronize this also

Target:
public synchronized void stop() throws Throwable { if (currentJob != null) { currentJob.stop(); } }
Source:
private void writeConfigToFile( Config config, File file ) { try { Writer fileWriter = new BufferedWriter( new FileWriter( file ) ); for ( Map.Entry<String,String> entry : config.getRaw().entrySet() ) { fileWriter.write( String.format( "%s=%s\n", entry.getKey(), entry.getValue() ) ); } fileWriter.close(); } catch ( IOException e ) { START e.printStackTrace(); END } } Does not look like a good handling of exception? should we be able to continue if this fails?

Target:
private void writeConfigToFile( Config config, File file ) throws IOException { try ( Writer fileWriter = new BufferedWriter( new FileWriter( file ) ) ) { for ( Map.Entry<String,String> entry : config.getRaw().entrySet() ) { fileWriter.write( String.format( "%s=%s\n", entry.getKey(), entry.getValue() ) ); } } }
Source:
private String argAdditionalConf( File backupTarget ) { if ( additionalConfig == null ) { return ""; } START File configFile = neo4jHomeFromTarget( backupTarget ).resolve( "../additional_neo4j.conf" ).toFile(); END writeConfigToFile( additionalConfig, configFile ); return String.format( "--additional-config=%s", configFile ); } what is additional_neo4j.conf and why do we need it? how its correlate with other tools behavior?

Target:
private String argAdditionalConf( File backupTarget ) throws IOException { if ( additionalConfig == null ) { return ""; } File configFile = neo4jHomeFromTarget( backupTarget ).resolve( "../additional_neo4j.conf" ).toFile(); writeConfigToFile( additionalConfig, configFile ); return String.format( "--additional-config=%s", configFile ); }
Source:
public String getHARole() { START if (true) return roles.keySet().toString(); // TODO delete this END if ( roles.containsKey( HighAvailabilityModeSwitcher.MASTER ) ) { return HighAvailabilityModeSwitcher.MASTER; } if ( roles.containsKey( HighAvailabilityModeSwitcher.SLAVE ) ) { return HighAvailabilityModeSwitcher.SLAVE; } return HighAvailabilityModeSwitcher.UNKNOWN; } I think you should address this TODO.

Target:
public String getHARole() { if ( roles.containsKey( HighAvailabilityModeSwitcher.MASTER ) ) { return HighAvailabilityModeSwitcher.MASTER; } if ( roles.containsKey( HighAvailabilityModeSwitcher.SLAVE ) ) { return HighAvailabilityModeSwitcher.SLAVE; } return HighAvailabilityModeSwitcher.UNKNOWN; }
Source:
public void shutdown() { try ( ErrorHandler errorHandler = new ErrorHandler( "Error when trying to shutdown cluster" ) ) { START shutdownCoreMembers( errorHandler ); END shutdownReadReplicas( errorHandler ); } } You switched the order of cores and read replicas here.

Target:
public void shutdown() { try ( ErrorHandler errorHandler = new ErrorHandler( "Error when trying to shutdown cluster" ) ) { shutdownReadReplicas( errorHandler ); shutdownCoreMembers( errorHandler ); } }
Source:
public org.neo4j.internal.kernel.api.Session beginSession( SecurityContext securityContext ) { return new KernelSession( engine, kernel, securityContext ); START } END Java supports covariant return types, so you can make this method return `KernelSession` without breaking the type safety of the interface. Would be easier on the eye.

Target:
public KernelSession beginSession( SecurityContext securityContext ) { return new KernelSession( engine, kernel, securityContext ); }
Source:
public MapValue properties() { MapValue m = properties; if ( m == null ) { START synchronized ( propLock ) END { m = properties; if ( m == null ) { m = properties = ValueUtils.asMapValue( node.getAllProperties() ); } } } return m; } I remember us talking about decoupling synchronization on this class, but when I tried to completely remove synchronization it still didn't solve the regression according to the benchmarks I ran, way back i september or something. Back then I probably messed something up, but I would love to see some benchmark result to confirm this fix!

Target:
public MapValue properties() { MapValue m = properties; if ( m == null ) { synchronized ( this ) { m = properties; if ( m == null ) { m = properties = ValueUtils.asMapValue( node.getAllProperties() ); } } } return m; }
Source:
public static InFlightCache create( Config config, Monitors monitors ) { Type type = config.get( CausalClusteringSettings.in_flight_cache_type ); START switch ( type ) END { case NONE: return new VoidInFlightCache(); case CONSECUTIVE: return new ConsecutiveInFlightCache( config.get( in_flight_cache_max_entries ), config.get( in_flight_cache_max_bytes ), monitors.newMonitor( InFlightCacheMonitor.class ), false ); case UNBOUNDED: return new UnboundedInFlightCache(); default: throw new IllegalArgumentException( "Unrecognized type" ); } } This logic could be included in the enum as an overridden method

Target:
public static InFlightCache create( Config config, Monitors monitors ) { return config.get( CausalClusteringSettings.in_flight_cache_type ).create( config, monitors ); }
Source:
public boolean equals( Value value ) { START if ( value instanceof org.neo4j.values.storable.UTF8StringValue ) END { return Arrays.equals( bytes, ((org.neo4j.values.storable.UTF8StringValue) value).bytes ); } else { return super.equals( value ); } } It seems strange that we would need a fully qualified name here.

Target:
public boolean equals( Value value ) { if ( value instanceof UTF8StringValue ) { return Arrays.equals( bytes, ((org.neo4j.values.storable.UTF8StringValue) value).bytes ); } else { return super.equals( value ); } }
Source:
static GeometryHeader fromArrayHeaderBytes( byte[] header ) { int geometryType = Byte.toUnsignedInt( header[1] ); int dimension = Byte.toUnsignedInt( header[2] ); int crsTableId = Byte.toUnsignedInt( header[3] ); START int crsCode = Byte.toUnsignedInt( header[5] ) + (Byte.toUnsignedInt( header[4] ) << 8); END return new GeometryHeader( geometryType, dimension, crsTableId, crsCode ); } can we please update line to "(Byte.toUnsignedInt( header[4] ) << 8) + Byte.toUnsignedInt( header[5] ) "

Target:
static GeometryHeader fromArrayHeaderBytes( byte[] header ) { int geometryType = Byte.toUnsignedInt( header[1] ); int dimension = Byte.toUnsignedInt( header[2] ); int crsTableId = Byte.toUnsignedInt( header[3] ); int crsCode = (Byte.toUnsignedInt( header[4] ) << 8) + Byte.toUnsignedInt( header[5] ); return new GeometryHeader( geometryType, dimension, crsTableId, crsCode ); }
Source:
public static CoordinateReferenceSystem get( String href ) { if ( CoordinateReferenceSystem.WGS84.href.equals( href ) ) { return CoordinateReferenceSystem.WGS84; } else if ( CoordinateReferenceSystem.Cartesian.href.equals( href ) ) { return CoordinateReferenceSystem.Cartesian; } else { START throw new UnsupportedOperationException( "Unknown CRS: " + href ); END } } would say that its more illegal argument

Target:
public static CoordinateReferenceSystem get( String href ) { if ( CoordinateReferenceSystem.WGS84.href.equals( href ) ) { return CoordinateReferenceSystem.WGS84; } else if ( CoordinateReferenceSystem.Cartesian.href.equals( href ) ) { return CoordinateReferenceSystem.Cartesian; } else { throw new IllegalArgumentException( "Unknown CRS: " + href ); } }
Source:
public synchronized Group get( String name ) { boolean global = name == null; START if ( globalMode != null && global != globalMode.booleanValue() ) END { throw mixingOfGroupModesException(); } if ( name == null ) { return Group.GLOBAL; } Group group = byName.get( name ); if ( group == null ) { throw new HeaderException( "Group '" + name + "' not found. Available groups are: " + groupNames() ); } return group; } `.booleanValue()` is not needed

Target:
public synchronized Group get( String name ) { boolean global = name == null; if ( globalMode != null && global != globalMode ) { throw mixingOfGroupModesException(); } if ( name == null ) { return Group.GLOBAL; } Group group = byName.get( name ); if ( group == null ) { throw new HeaderException( "Group '" + name + "' not found. Available groups are: " + groupNames() ); } return group; }
Source:
public void shouldFailOnMixedGroupModeInGetOrCreate() throws Exception { // given Groups groups = new Groups(); groups.getOrCreate( null ); START try END { // when groups.getOrCreate( "Something" ); fail( "Should fail" ); } catch ( IllegalStateException e ) { // then OK } } Would prefer to have expected exceptions in the added tests since nothing is invoked after the throw.

Target:
public void shouldFailOnMixedGroupModeInGetOrCreate() throws Exception { // given Groups groups = new Groups(); groups.getOrCreate( null ); // when groups.getOrCreate( "Something" ); }
Source:
private void lockAllNodes( KernelStatement state, long[] nodeIds ) { for ( long nodeId : nodeIds ) { START state.locks().optimistic().acquireExclusive( state.lockTracer(), ResourceTypes.NODE, nodeId ); END } } You could use one call since the id argument is a vararg

Target:
private void lockAllNodes( KernelStatement state, long[] nodeIds ) { state.locks().optimistic().acquireExclusive( state.lockTracer(), ResourceTypes.NODE, nodeIds ); }
Source:
public void shouldCheckpointEvenIfNoChanges() throws Exception { // GIVEN CheckpointCounter checkpointCounter = new CheckpointCounter(); // WHEN try ( GBPTree<MutableLong,MutableLong> index = index().with( checkpointCounter ).build() ) { checkpointCounter.reset(); for ( int i = 0; i < 2; i++ ) { START } END index.checkpoint( unlimited() ); // THEN assertEquals( 1, checkpointCounter.count() ); } } Empty loop

Target:
public void shouldCheckpointEvenIfNoChanges() throws Exception { // GIVEN CheckpointCounter checkpointCounter = new CheckpointCounter(); // WHEN try ( GBPTree<MutableLong,MutableLong> index = index().with( checkpointCounter ).build() ) { checkpointCounter.reset(); index.checkpoint( unlimited() ); // THEN assertEquals( 1, checkpointCounter.count() ); } }
Source:
START static final File baseSchemaIndexFolder( File databaseStoreDir ) END { return path( databaseStoreDir, "schema", "index" ); } Does not need to be final.

Target:
static File baseSchemaIndexFolder( File databaseStoreDir ) { return path( databaseStoreDir, "schema", "index" ); }
Source:
START public RenewableBatchIdSequence( IdSequence source, int batchSize, LongConsumer excessIdConsumer ) END { this.source = source; this.batchSize = batchSize; this.excessIdConsumer = excessIdConsumer; } constructor can be package private

Target:
RenewableBatchIdSequence( IdSequence source, int batchSize, LongConsumer excessIdConsumer ) { this.source = source; this.batchSize = batchSize; this.excessIdConsumer = excessIdConsumer; }
Source:
public void release( T obj ) { // Return it locally if possible LocalSlot<T> localSlot = puddle.get(); START if ( localSlot.release( obj ) ) END { // It was released back into the slot } else { // Fall back to the delegate pool pool.release( obj ); } } ``` if ( !localSlot.release( obj ) ) { // Fall back to the delegate pool pool.release( obj ); } ```

Target:
public void release( T obj ) { // Return it locally if possible LocalSlot<T> localSlot = puddle.get(); if ( !localSlot.release( obj ) ) { // Fall back to the delegate pool pool.release( obj ); } // else it was released back into the slot }
Source:
public RecoveryApplier getRecoveryApplier( TransactionApplicationMode mode ) throws Exception { START transactionsToApply = new TransactionQueue( 100, ( first, last ) -> storageEngine.apply( first, mode ) ); END return new RecoveryVisitor( transactionsToApply ); } we don't need `transactionsToApply` as field anymore

Target:
public RecoveryApplier getRecoveryApplier( TransactionApplicationMode mode ) throws Exception { return new RecoveryVisitor( new TransactionQueue( 100, ( first, last ) -> storageEngine.apply( first, mode ) ) ); }
Source:
START public GivenTransactionCursor( CommittedTransactionRepresentation... transactions ) END { this.transactions = transactions; } can be `private`

Target:
private GivenTransactionCursor( CommittedTransactionRepresentation... transactions ) { this.transactions = transactions; }
Source:
START public TestGraphDatabaseFacadeFactory( TestGraphDatabaseFactoryState state, boolean impermanent ) END { this( state, impermanent, DatabaseInfo.COMMUNITY, CommunityEditionModule::new ); } `protected` is enough

Target:
protected TestGraphDatabaseFacadeFactory( TestGraphDatabaseFactoryState state, boolean impermanent ) { this( state, impermanent, DatabaseInfo.COMMUNITY, CommunityEditionModule::new ); }
Source:
public UpdateCapturingIndexProvider( SchemaIndexProvider actual, Map<Long,Collection<IndexEntryUpdate>> initialUpdates ) { START super( actual.getProviderDescriptor(), actual.priority() ); END this.actual = actual; this.initialUpdates = initialUpdates; } A copy constructor in `SchemaIndexProvider` might be more appropriate than having a public getter method

Target:
public UpdateCapturingIndexProvider( SchemaIndexProvider actual, Map<Long,Collection<IndexEntryUpdate>> initialUpdates ) { super( actual ); this.actual = actual; this.initialUpdates = initialUpdates; }
Source:
public Statement apply( Statement base, Description description ) { Repeat repeat = description.getAnnotation( Repeat.class ); if ( repeat != null || defaultTimes > 1 ) { START return new RepeatStatement( max( repeat != null ? repeat.times() : 1, defaultTimes ), base, description ); END } return base; } I would expect that the annotation would overrule the default, even if it is smaller.

Target:
public Statement apply( Statement base, Description description ) { Repeat repeat = description.getAnnotation( Repeat.class ); if ( repeat != null ) { return new RepeatStatement( repeat.times(), base, description ); } if ( defaultTimes > 1 ) { return new RepeatStatement( defaultTimes, base, description ); } return base; }
Source:
public Stream<BooleanResult> nodeManualIndexExists( @Name( "indexName" ) String legacyIndexName ) { BooleanResult result = new BooleanResult( graphDatabaseAPI.index().existsForNodes( legacyIndexName ) ); START ArrayList<BooleanResult> arrayResult = new ArrayList<>(); END arrayResult.add( result ); return arrayResult.stream(); } Better use `Stream#of()` everywhere to convert single element to stream.

Target:
public Stream<BooleanResult> nodeManualIndexExists( @Name( "indexName" ) String legacyIndexName ) { return Stream.of( new BooleanResult( graphDatabaseAPI.index().existsForNodes( legacyIndexName ) ) ); }
Source:
public Stream<BooleanResult> nodeManualIndexAdd( @Name( "indexName" ) String legacyIndexName, @Name( "node" ) Node node, @Name( "key" ) String key, @Name( "value" ) Object value ) { graphDatabaseAPI.index().forNodes( legacyIndexName ).add( node, key, value ); List<BooleanResult> results = new ArrayList<>( 1 ); results.add( new BooleanResult( true ) ); START return results.stream(); END } Stream.of

Target:
public Stream<BooleanResult> nodeManualIndexAdd( @Name( "indexName" ) String legacyIndexName, @Name( "node" ) Node node, @Name( "key" ) String key, @Name( "value" ) Object value ) { graphDatabaseAPI.index().forNodes( legacyIndexName ).add( node, key, value ); // Failures will be expressed as exceptions before the return return Stream.of( new BooleanResult( true ) ); }
Source:
private PrimitiveLongIterator partitionedOperation( Function<ReadOnlyFulltext,PrimitiveLongIterator> readerFunction ) { START return PrimitiveLongCollections.concat( indexReaders.parallelStream().map( readerFunction::apply ).collect( Collectors.toList() ) ); END } you can use readerFunction directly here, without apply

Target:
private PrimitiveLongIterator partitionedOperation( Function<ReadOnlyFulltext,PrimitiveLongIterator> readerFunction ) { return PrimitiveLongCollections.concat( indexReaders.parallelStream().map( readerFunction ).collect( Collectors.toList() ) ); }
Source:
public void dispatch( DummyRequest dummyRequest, long commandIndex, Consumer<Result> callback ) { if ( benchmarkMachine != null ) { benchmarkMachine.applyCommand( dummyRequest, commandIndex, callback ); START } END } If `benchmarkMachine` may be null, then perhaps it should be an `Optional<BenchmarkMachine>`

Target:
public void dispatch( DummyRequest dummyRequest, long commandIndex, Consumer<Result> callback ) { benchmarkMachine.applyCommand( dummyRequest, commandIndex, callback ); }
Source:
public void shouldRunRecurringJob() throws Throwable { // Given long period = 100; int count = 5; life.start(); // When scheduler.scheduleRecurring( indexPopulation, countInvocationsJob, period, MILLISECONDS ); START awaitFirstInvocation(); END // Alright it's running now. Let's await all the invocations to take place awaitInvocationCount( count ); scheduler.shutdown(); // Then assert that the recurring job was stopped (when the scheduler was shut down) int actualInvocations = invocations.get(); sleep( period * 2 ); assertThat( invocations.get(), equalTo( actualInvocations ) ); } Can remove this call because of `awaitInvocationCount( count )` below.

Target:
public void shouldRunRecurringJob() throws Throwable { // Given long period = 100; int count = 5; life.start(); // When scheduler.scheduleRecurring( indexPopulation, countInvocationsJob, period, MILLISECONDS ); awaitInvocationCount( count ); scheduler.shutdown(); // Then assert that the recurring job was stopped (when the scheduler was shut down) int actualInvocations = invocations.get(); sleep( period * 2 ); assertThat( invocations.get(), equalTo( actualInvocations ) ); }
Source:
public void failIfUnknownSetting() throws Exception { expect.expect( new NestedThrowableMatcher( IllegalArgumentException.class ) ); expect.expectMessage( "Unknown setting: unknown.setting.indeed" ); db.execute( "CALL dbms.setConfigValue('unknown.setting.indeed', 'foo')" ); START fail( "Should throw IllegalArgumentException" ); END } you do not need those fail in the end of the test since `ExpectedException` will throw an exception if expected error was not thrown and will fail the test (same for other tests)

Target:
public void failIfUnknownSetting() throws Exception { expect.expect( new NestedThrowableMatcher( IllegalArgumentException.class ) ); expect.expectMessage( "Unknown setting: unknown.setting.indeed" ); db.execute( "CALL dbms.setConfigValue('unknown.setting.indeed', 'foo')" ); }
Source:
private void flushAll() { START populations.forEach( population -> flush( population, population.takeCurrentBatch() ) ); END } there is no need to pass second param here since population is already passed as first one

Target:
private void flushAll() { populations.forEach( population -> flush( population ) ); }
Source:
public static <T> long count( Iterable<T> iterable, Predicate<T> filter ) { START try ( ResourceIterator<T> iterator = Iterators.asResourceIterator( iterable.iterator() ) ) END { return Iterators.count( iterator, filter ); } } Instead of wrapping in a resource iterator, which is potentially one unnecessary object instantiation, couldn't we just do the usual check of `Resource` in `finally`?

Target:
public static <T> long count( Iterable<T> iterable, Predicate<T> filter ) { Iterator<T> iterator = iterable.iterator(); try { return Iterators.count( iterator, filter ); } finally { if ( iterator instanceof ResourceIterator ) { ((ResourceIterator) iterator).close(); } } }
Source:
START ResultRowImpl( ) END { this( new HashMap<>() ); } Formatting?

Target:
public ResultRowImpl() { this( new HashMap<>() ); }
Source:
public static PathValue path( NodeValue[] nodes, EdgeValue[] edges ) { assert nodes != null; assert edges != null; START if ( nodes.length + edges.length % 2 == 0 ) END { throw new IllegalArgumentException( "Tried to construct a path that is not built like a path: even number of elements" ); } return new PathValue( nodes, edges ); } you want `if ( ( nodes.length + edges.length ) % 2 == 0 )` or maybe `nodes.length != edges.length + 1`?

Target:
public static PathValue path( NodeValue[] nodes, EdgeValue[] edges ) { assert nodes != null; assert edges != null; if ( (nodes.length + edges.length) % 2 == 0 ) { throw new IllegalArgumentException( "Tried to construct a path that is not built like a path: even number of elements" ); } return new PathValue( nodes, edges ); }
Source:
public LongArray newLongArray( long length, long defaultValue, long base ) { // Here we want to have the property of a dynamic array which makes some parts of the array // live on heap, some off. At the same time we want a fixed size array. Therefore first create // the array as a dynamic array and make it grow to the requested length. LongArray array = newDynamicLongArray( fractionOf( length ), defaultValue ); START array.at( length - 1 ); END return array; } rely on side effects of magic `at`?

Target:
public LongArray newLongArray( long length, long defaultValue, long base ) { // Here we want to have the property of a dynamic array so that some parts of the array // can live on heap, some off. return newDynamicLongArray( fractionOf( length ), defaultValue ); }
Source:
public PageCacheByteArray( PagedFile pagedFile, long length, byte[] defaultValue, long base ) throws IOException { // '0' default value means we skip filling it out in super START super( pagedFile, defaultValue.length, length, 0, base ); END this.defaultValue = defaultValue; setDefaultValue( -1 ); } and why not to pass -1 directly here as a default value?

Target:
PageCacheByteArray( PagedFile pagedFile, long length, byte[] defaultValue, long base ) throws IOException { // Default value is handled locally in this class, in contrast to its siblings, which lets the superclass // handle it. super( pagedFile, defaultValue.length, length, base ); this.defaultValue = defaultValue; setDefaultValue( -1 ); }
Source:
START public PageCachedNumberArrayFactory( PageCache pageCache, File storeDir ) END { this.pageCache = pageCache; this.storeDir = storeDir; } this can be package private

Target:
PageCachedNumberArrayFactory( PageCache pageCache, File storeDir ) { this.pageCache = pageCache; this.storeDir = storeDir; }
Source:
START public PageCacheLongArray( PagedFile pagedFile, long length, long defaultValue, long base ) throws IOException END { super( pagedFile, Long.BYTES, length, defaultValue, base ); } package private constructor here as well

Target:
PageCacheLongArray( PagedFile pagedFile, long length, long defaultValue, long base ) throws IOException { super( pagedFile, Long.BYTES, length, defaultValue, base ); }
Source:
protected int offset( long index ) { START return toIntExact( rebase( index ) % entriesPerPage ) * entrySize; END } whole expression should be wrapped into `toIntExact` not only `rebase( index ) % entriesPerPage`

Target:
protected int offset( long index ) { return toIntExact( rebase( index ) % entriesPerPage * entrySize ); }
Source:
public static Fixture prepareDirectoryAndPageCache( Class<?> testClass ) throws IOException { DefaultFileSystemAbstraction fileSystem = new DefaultFileSystemAbstraction(); TestDirectory testDirectory = TestDirectory.testDirectory( testClass, fileSystem ); File dir = testDirectory.prepareDirectoryForTest( "test" ); START fileSystem.mkdirs( dir ); END PageCache pageCache = StandalonePageCacheFactory.createPageCache( fileSystem ); return new Fixture( pageCache, fileSystem, dir ); } you don't need to do it, testDirectory does that for you already

Target:
public static Fixture prepareDirectoryAndPageCache( Class<?> testClass ) throws IOException { DefaultFileSystemAbstraction fileSystem = new DefaultFileSystemAbstraction(); TestDirectory testDirectory = TestDirectory.testDirectory( testClass, fileSystem ); File dir = testDirectory.prepareDirectoryForTest( "test" ); PageCache pageCache = StandalonePageCacheFactory.createPageCache( fileSystem ); return new Fixture( pageCache, fileSystem, dir ); }
Source:
public void moveMigratedFiles( File migrationDir, File storeDir, String versionToUpgradeFrom, String versionToMigrateTo ) throws IOException { if ( deleteObsoleteIndexes ) { deleteIndexes( schemaIndexDirectory ); } START deleteIndexes( LuceneLabelScanDirectory.getLuceneStoreDirectory( storeDir ) ); END } This will gonna delete old label scan store if that was used which is a nice thing. In the same time, we will not gonna create the new index as part of migration for those guys and people will be forced to wait during the startup, while they expecting everything is ready to fly. I know that proposed behaviour differs from how it was before at the same time that is something we had complaints in the recent past and as well it sounds like a correct thing to do. WDYT?

Target:
public void moveMigratedFiles( File migrationDir, File storeDir, String versionToUpgradeFrom, String versionToMigrateTo ) throws IOException { if ( deleteObsoleteIndexes ) { deleteIndexes( schemaIndexDirectory ); } deleteIndexes( getLuceneStoreDirectory( storeDir ) ); }
Source:
public final boolean equals( Object other ) { if ( other == null ) { return false; } // suppose that we will only ever call equals with Objects of AnyValue but just in case try { START if ( ((AnyValue) other).isSequenceValue() && this.isSequenceValue() ) END { return ((SequenceValue) this).equals( (SequenceValue) other ); } return other instanceof VirtualValue && equals( (VirtualValue) other ); } catch ( ClassCastException e ) { return false; } } doing ``` try { (AnyValue) other) } catch ( ClassCastException e ) { return false } ``` is much more slower and not that easy to read compared to using instanceOf operator, so would suggest here to use instanceOf AnyValue instead. This also applies to ArrayValue `equals`

Target:
public final boolean equals( Object other ) { if ( other == null ) { return false; } if ( other instanceof SequenceValue && this.isSequenceValue() ) { return ((SequenceValue) this).equals( (SequenceValue) other ); } return other instanceof VirtualValue && equals( (VirtualValue) other ); }
Source:
private File findFile( String targetFile, File directory ) { START File foundFile = null; END boolean didFindFile = false; for ( File file : directory.listFiles() ) { if ( file.getName().equals( targetFile ) ) { foundFile = file; didFindFile = true; break; } } if ( !didFindFile ) { fail( "Could not find file " + targetFile ); } return foundFile; } maybe something like this instead? ``` File file = new File( directory, targetFile ); if (!file.exists()) { fail( "Could not find file " + targetFile ); } return file; ```

Target:
private File findFile( String targetFile, File directory ) { File file = new File( directory, targetFile ); if ( !file.exists() ) { fail( "Could not find file " + targetFile ); } return file; }
Source:
public void reset() { START initCalled = rebuildingCalled = rebuiltCalled = noIndexCalled = corruptedIndex = false; END } please use separate lines

Target:
public void reset() { initCalled = false; rebuildingCalled = false; rebuiltCalled = false; noIndexCalled = false; corruptedIndex = false; }
Source:
public boolean equals( VirtualValue other ) { START if ( other == null || !(other instanceof PathValue) ) END { return false; } PathValue that = (PathValue) other; return size() == that.size() && Arrays.equals( nodes, that.nodes ) && Arrays.equals( edges, that.edges ); } same here, redundant?

Target:
public boolean equals( VirtualValue other ) { if ( other == null || other.getClass() != PathValue.class ) { return false; } PathValue that = (PathValue) other; return size() == that.size() && Arrays.equals( nodes, that.nodes ) && Arrays.equals( edges, that.edges ); }
Source:
START public NodeCountsProcessor( NodeStore nodeStore, NodeLabelsCache cache, int highLabelId, END CountsAccessor.Updater counts, MigrationProgressMonitor.Section progressMonitor ) { this.nodeStore = nodeStore; this.cache = cache; this.anyLabel = highLabelId; this.counts = counts; // Instantiate with high id + 1 since we need that extra slot for the ANY count this.labelCounts = new long[highLabelId + 1]; this.progressMonitor = progressMonitor; } This one can be package-private and the other constructor is not used by anyone and can be removed.

Target:
NodeCountsProcessor( NodeStore nodeStore, NodeLabelsCache cache, int highLabelId, CountsAccessor.Updater counts, MigrationProgressMonitor.Section progressMonitor ) { this.nodeStore = nodeStore; this.cache = cache; this.anyLabel = highLabelId; this.counts = counts; // Instantiate with high id + 1 since we need that extra slot for the ANY count this.labelCounts = new long[highLabelId + 1]; this.progressMonitor = progressMonitor; }
Source:
public void releaseShared( ResourceType resourceType, long... resourceIds ) { stateHolder.incrementActiveClients( this ); try { PrimitiveLongObjectMap<LockResource> localLocks = localShared( resourceType ); for ( long resourceId : resourceIds ) { LockResource resource = localLocks.get( resourceId ); if ( resource.releaseReference() != 0 ) { START return; END } localLocks.remove( resourceId ); manager.releaseReadLock( new LockResource( resourceType, resourceId ), lockTransaction ); } } finally { stateHolder.decrementActiveClients(); } } Do we not want to try releasing any remaining resources after the first failure? I don't know, maybe this will terminate the transaction and release everything anyway, just noting this observation.

Target:
public void releaseShared( ResourceType resourceType, long... resourceIds ) { stateHolder.incrementActiveClients( this ); try { PrimitiveLongObjectMap<LockResource> localLocks = localShared( resourceType ); for ( long resourceId : resourceIds ) { LockResource resource = localLocks.get( resourceId ); if ( resource.releaseReference() == 0 ) { localLocks.remove( resourceId ); manager.releaseReadLock( new LockResource( resourceType, resourceId ), lockTransaction ); } } } finally { stateHolder.decrementActiveClients(); } }
Source:
public void accept( PageCursor cursor ) { byte[] bytesToWrite = failureBytes; cursor.putByte( NativeSchemaNumberIndexPopulator.BYTE_FAILED ); int availableSpace = cursor.getCurrentPageSize() - cursor.getOffset(); if ( bytesToWrite.length + HEADER_LENGTH_FIELD_LENGTH > availableSpace ) { START bytesToWrite = Arrays.copyOf( bytesToWrite, availableSpace - 2 ); END } cursor.putShort( (short) bytesToWrite.length ); cursor.putBytes( bytesToWrite ); } you can't just fix all magic 2 :)

Target:
public void accept( PageCursor cursor ) { byte[] bytesToWrite = failureBytes; cursor.putByte( NativeSchemaNumberIndexPopulator.BYTE_FAILED ); int availableSpace = cursor.getCurrentPageSize() - cursor.getOffset(); if ( bytesToWrite.length + HEADER_LENGTH_FIELD_LENGTH > availableSpace ) { bytesToWrite = Arrays.copyOf( bytesToWrite, availableSpace - HEADER_LENGTH_FIELD_LENGTH ); } cursor.putShort( (short) bytesToWrite.length ); cursor.putBytes( bytesToWrite ); }
Source:
public void freeId( long id ) { if ( freeIdCondition.getAsBoolean() ) { idContainer.freeId( id ); START } END } Do we have a feel for the probability of ending up here, and the condition is false?

Target:
public synchronized void freeId( long id ) { idContainer.freeId( id ); }
Source:
public void freeId( long id ) { START idContainer.freeId( id ); END } `IdGeneratorImpl` protects its `IdContainer` by making its methods `synchronized`. This class does not do that, so does this not expose the `IdContainer` to concurrency that it is not prepared to handle?

Target:
public synchronized void freeId( long id ) { idContainer.freeId( id ); }
Source:
public boolean equals( Object other ) { START return false; END } replace with `return this == other;`

Target:
public boolean equals( Object other ) { return this == other; }
Source:
public boolean equals( Value other ) { START return false; END } replace with `return this == other;`

Target:
public boolean equals( Value other ) { return this == other; }
Source:
public static Lifecycle multiple( Lifecycle... lifecycles ) { START return new CombinedLifecycle( Arrays.asList( lifecycles ) ); END } We can reuse `multiple( Iterable lifecycles )` here.

Target:
public static Lifecycle multiple( Lifecycle... lifecycles ) { return multiple( Arrays.asList( lifecycles ) ); }
Source:
START public WrappingFileHandle( File file, File baseDirectory, FileSystemAbstraction fs ) END { this.file = file; this.baseDirectory = baseDirectory; this.fs = fs; } Checkstyle says this `public` modifier is redundant.

Target:
WrappingFileHandle( File file, File baseDirectory, FileSystemAbstraction fs ) { this.file = file; this.baseDirectory = baseDirectory; this.fs = fs; }
Source:
protected void process( Void batch, BatchSender sender ) throws Throwable { START System.out.println( Thread.currentThread().getName() + " process" ); END latch.await(); } Oops.

Target:
protected void process( Void batch, BatchSender sender ) throws Throwable { latch.await(); }
Source:
private static Long parseMaxMemory( String maxMemoryString ) { if ( maxMemoryString != null ) { START if ( maxMemoryString.endsWith( "%" ) ) END { int percent = Integer.parseInt( maxMemoryString.substring( 0, maxMemoryString.length() - 1 ) ); return calculateMaxMemoryFromPercent( percent ); } return Settings.parseLongWithUnit( maxMemoryString ); } return null; } we at least need to trim user provided string before trying to figure out what is inside of it

Target:
private static Long parseMaxMemory( String maxMemoryString ) { if ( maxMemoryString != null ) { maxMemoryString = maxMemoryString.trim(); if ( maxMemoryString.endsWith( "%" ) ) { int percent = Integer.parseInt( maxMemoryString.substring( 0, maxMemoryString.length() - 1 ) ); return calculateMaxMemoryFromPercent( percent ); } return Settings.parseLongWithUnit( maxMemoryString ); } return null; }
Source:
START public static long calculateMaxMemoryFromPercent( int percent ) END { if ( percent < 1 ) { throw new IllegalArgumentException( "Expected percentage to be > 0, was " + percent ); } if ( percent > 100 ) { throw new IllegalArgumentException( "Expected percentage to be < 100, was " + percent ); } long freePhysicalMemory = OsBeanUtil.getFreePhysicalMemory(); if ( freePhysicalMemory == OsBeanUtil.VALUE_UNAVAILABLE ) { throw new UnsupportedOperationException( "Unable to detect amount of free memory, so max memory has to be explicitly set" ); } double factor = percent / 100D; return round( (freePhysicalMemory - Runtime.getRuntime().maxMemory()) * factor ); } there is no need to declare it `public`

Target:
static long calculateMaxMemoryFromPercent( int percent ) { if ( percent < 1 ) { throw new IllegalArgumentException( "Expected percentage to be > 0, was " + percent ); } if ( percent > 100 ) { throw new IllegalArgumentException( "Expected percentage to be < 100, was " + percent ); } long freePhysicalMemory = OsBeanUtil.getFreePhysicalMemory(); if ( freePhysicalMemory == OsBeanUtil.VALUE_UNAVAILABLE ) { throw new UnsupportedOperationException( "Unable to detect amount of free memory, so max memory has to be explicitly set" ); } double factor = percent / 100D; return round( (freePhysicalMemory - Runtime.getRuntime().maxMemory()) * factor ); }
Source:
public static boolean tryWriteLock( long address ) { START long s, n; END for (; ; ) { s = getState( address ); boolean unwritablyLocked = (s & EXL_MASK) != 0; boolean writeCountOverflow = (s & CNT_MASK) == CNT_MASK; // bitwise-OR to reduce branching and allow more ILP if ( unwritablyLocked | writeCountOverflow ) { return failWriteLock( s, writeCountOverflow ); } n = s + CNT_UNIT | MOD_MASK; if ( compareAndSetState( address, s, n ) ) { UnsafeUtil.storeFence(); return true; } } } Just because the code resembles C doesn't mean that you have to adopt horrendous naming standards ;)

Target:
public static boolean tryWriteLock( long address ) { long s; long n; for ( ; ; ) { s = getState( address ); boolean unwritablyLocked = (s & EXL_MASK) != 0; boolean writeCountOverflow = (s & CNT_MASK) == CNT_MASK; // bitwise-OR to reduce branching and allow more ILP if ( unwritablyLocked | writeCountOverflow ) { return failWriteLock( s, writeCountOverflow ); } n = s + CNT_UNIT | MOD_MASK; if ( compareAndSetState( address, s, n ) ) { UnsafeUtil.storeFence(); return true; } } }
Source:
public void init() throws IOException { monitor.init(); boolean storeExists = hasStore(); boolean isDirty; try { needsRebuild = !storeExists; if ( !storeExists ) { monitor.noIndex(); } isDirty = instantiateTree(); } catch ( MetadataMismatchException e ) { // GBPTree is corrupt. Try to rebuild. isDirty = true; } if ( isDirty ) { monitor.notValidIndex(); dropStrict(); instantiateTree(); } if ( isDirty || !storeExists ) START { END needsRebuild = true; } } The `|| !storeExists` part is covered by the `needsRebuild = !storeExists;` further up, is it not?

Target:
public void init() throws IOException { monitor.init(); boolean storeExists = hasStore(); boolean isDirty; try { needsRebuild = !storeExists; if ( !storeExists ) { monitor.noIndex(); } isDirty = instantiateTree(); } catch ( MetadataMismatchException e ) { // GBPTree is corrupt. Try to rebuild. isDirty = true; } if ( isDirty ) { monitor.notValidIndex(); dropStrict(); instantiateTree(); needsRebuild = true; } }
Source:
public void close() throws IOException { writerCheckpointMutex.lock(); try { if ( closed ) { return; } START closed = true; END // Force close on writer to not risk deadlock on pagedFile.close() writer.close(); pagedFile.close(); } finally { writerCheckpointMutex.unlock(); } } isn't that unexpected thing to have a flag that say that index is closed to be raised before it's actually is?

Target:
public void close() throws IOException { writerCheckpointMutex.lock(); try { if ( closed ) { return; } // Force close on writer to not risk deadlock on pagedFile.close() writer.close(); pagedFile.close(); closed = true; } finally { writerCheckpointMutex.unlock(); } }
Source:
public IndexMap( START Map<Long, IndexProxy> indexesById ) END { this( indexesById, indexesByDescriptor( indexesById ), indexIdsByDescriptor( indexesById ) ); } this could fit on a single line...

Target:
IndexMap( Map<Long,IndexProxy> indexesById ) { this( indexesById, indexesByDescriptor( indexesById ), indexIdsByDescriptor( indexesById ) ); }
Source:
START public static <E extends Exception> void assertException( ThrowingAction<E> f, Class typeOfException ) throws END Exception { try { f.apply(); fail( "Expected exception of type " + typeOfException + ", but no exception was thrown" ); } catch ( Exception e ) { if ( !typeOfException.isInstance( e ) ) { fail( "Got unexpected exception " + e.getClass() + "\nExpected: " + typeOfException ); } } } isn't it copy paste mostly of another assertException method? why not reused that?

Target:
public static <E extends Exception> void assertException( ThrowingAction<E> f, Class typeOfException ) throws Exception { assertException( f, typeOfException, null ); }
Source:
protected ConstraintDescriptor readNonStandardConstraint( ConstraintRule rule, String errorMessage ) { if ( !rule.getConstraintDescriptor().type().enforcesPropertyExistence() ) { throw new IllegalStateException( "Unsupported constraint type: " + rule ); START } END return rule.getConstraintDescriptor(); } Do we really need to check anything here? Surely the enterprise edition supports all constraints?

Target:
protected ConstraintDescriptor readNonStandardConstraint( ConstraintRule rule, String errorMessage ) { if ( !rule.getConstraintDescriptor().enforcesPropertyExistence() ) { throw new IllegalStateException( "Unsupported constraint type: " + rule ); } return rule.getConstraintDescriptor(); }
Source:
private int[] propertyKeyIds() { return populations.keySet().stream().flatMapToInt( this::propertyKeyIds ).distinct().toArray(); START } END This method is actually pretty inefficient, it is only ever used together with `labelIds()`, it would be better to just have a single for-loop build both arrays at once, the streams just add overhead.

Target:
private int[] propertyKeyIds() { return populations.stream().flatMapToInt( this::propertyKeyIds ).distinct().toArray(); }
Source:
START public static boolean nodeHasSchemaProperties( END PrimitiveIntObjectMap<PropertyBlock> nodePropertyMap, int[] indexPropertyIds ) { for ( int indexPropertyId : indexPropertyIds ) { if ( !nodePropertyMap.containsKey( indexPropertyId ) ) { return false; } } return true; } this method can be private now right?

Target:
private static boolean nodeHasSchemaProperties( PrimitiveIntObjectMap<PropertyBlock> nodePropertyMap, int[] indexPropertyIds ) { for ( int indexPropertyId : indexPropertyIds ) { if ( !nodePropertyMap.containsKey( indexPropertyId ) ) { return false; } } return true; }
Source:
private NewIndexDescriptor getIndex( int labelId, int propertyKeyId, IndexSpecifier index ) throws ProcedureException { try { final int labelId1 = labelId; START final int[] propertyKeyIds = new int[]{propertyKeyId}; END return operations.indexGetForLabelAndPropertyKey( SchemaDescriptorFactory.forLabel( labelId1, propertyKeyIds ) ); } catch ( SchemaRuleNotFoundException e ) { throw new ProcedureException( Status.Schema.IndexNotFound, e, "No index on %s", index ); } } `getPropertyIds()` as above

Target:
private NewIndexDescriptor getIndex( int labelId, int propertyKeyId, IndexSpecifier index ) throws ProcedureException { try { return operations .indexGetForLabelAndPropertyKey( SchemaDescriptorFactory.forLabel( labelId, propertyKeyId ) ); } catch ( SchemaRuleNotFoundException e ) { throw new ProcedureException( Status.Schema.IndexNotFound, e, "No index on %s", index ); } }
Source:
public static String[] getPropertyKeys( ReadOperations readOperations, LabelSchemaDescriptor descriptor ) throws PropertyKeyIdNotFoundKernelException { int[] propertyKeyIds = START false ? descriptor.getPropertyIds() : new int[]{descriptor.getPropertyId()}; END String[] propertyKeys = new String[propertyKeyIds.length]; for ( int i = 0; i < propertyKeyIds.length; i++ ) { propertyKeys[i] = readOperations.propertyKeyGetName( propertyKeyIds[i] ); } return propertyKeys; } Whaat?

Target:
public static String[] getPropertyKeys( ReadOperations readOperations, LabelSchemaDescriptor descriptor ) throws PropertyKeyIdNotFoundKernelException { int[] propertyKeyIds = descriptor.getPropertyIds(); String[] propertyKeys = new String[propertyKeyIds.length]; for ( int i = 0; i < propertyKeyIds.length; i++ ) { propertyKeys[i] = readOperations.propertyKeyGetName( propertyKeyIds[i] ); } return propertyKeys; }
Source:
public static String[] getPropertyKeys( TokenNameLookup tokenNameLookup, LabelSchemaDescriptor descriptor ) { int[] propertyKeyIds = START false ? descriptor.getPropertyIds() : new int[]{descriptor.getPropertyId()}; END String[] propertyKeys = new String[propertyKeyIds.length]; for ( int i = 0; i < propertyKeyIds.length; i++ ) { propertyKeys[i] = tokenNameLookup.propertyKeyGetName( propertyKeyIds[i] ); } return propertyKeys; } Whaat 2

Target:
public static String[] getPropertyKeys( TokenNameLookup tokenNameLookup, LabelSchemaDescriptor descriptor ) { int[] propertyKeyIds = descriptor.getPropertyIds(); String[] propertyKeys = new String[propertyKeyIds.length]; for ( int i = 0; i < propertyKeyIds.length; i++ ) { propertyKeys[i] = tokenNameLookup.propertyKeyGetName( propertyKeyIds[i] ); } return propertyKeys; }
Source:
private NewIndexDescriptor findAnyIndexByLabelAndProperty( ReadOperations readOps, int propertyId, int labelId ) { try { final int labelId1 = labelId; START final int[] propertyKeyIds = new int[]{propertyId}; END NewIndexDescriptor descriptor = readOps.indexGetForLabelAndPropertyKey( SchemaDescriptorFactory.forLabel( labelId1, propertyKeyIds ) ); if ( readOps.indexGetState( descriptor ) == InternalIndexState.ONLINE ) { // Ha! We found an index - let's use it to find matching nodes return descriptor; } } catch ( SchemaRuleNotFoundException | IndexNotFoundKernelException e ) { // If we don't find a matching index rule, we'll scan all nodes and filter manually (below) } return null; } `getPropertyIds`

Target:
private NewIndexDescriptor findAnyIndexByLabelAndProperty( ReadOperations readOps, int propertyId, int labelId ) { try { NewIndexDescriptor descriptor = readOps.indexGetForLabelAndPropertyKey( SchemaDescriptorFactory.forLabel( labelId, propertyId ) ); if ( readOps.indexGetState( descriptor ) == InternalIndexState.ONLINE ) { // Ha! We found an index - let's use it to find matching nodes return descriptor; } } catch ( SchemaRuleNotFoundException | IndexNotFoundKernelException e ) { // If we don't find a matching index rule, we'll scan all nodes and filter manually (below) } return null; }