auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
START public RuntimeException translateException(Throwable throwable) { END RuntimeException runtimeException = throwable instanceof RuntimeException ? (RuntimeException) throwable : new RuntimeException(throwable.getMessage(), throwable); RuntimeException potentiallyTranslatedException = exceptionTranslator .translateExceptionIfPossible(runtimeException); return potentiallyTranslatedException != null ? potentiallyTranslatedException : runtimeException; } Nit: Let's have this method private unless someone asks for it.

Target:
private RuntimeException translateException(Throwable throwable) { RuntimeException runtimeException = throwable instanceof RuntimeException ? (RuntimeException) throwable : new RuntimeException(throwable.getMessage(), throwable); RuntimeException potentiallyTranslatedException = exceptionTranslator .translateExceptionIfPossible(runtimeException); return potentiallyTranslatedException != null ? potentiallyTranslatedException : runtimeException; }
Source:
START public <T> Optional<T> get(String id, Class<T> clazz, IndexCoordinates index) { END GetRequest request = requestFactory.getRequest(id, index); try { GetResponse response = client.get(request, RequestOptions.DEFAULT); return Optional.ofNullable(elasticsearchConverter.mapDocument(DocumentAdapters.from(response), clazz)); } catch (IOException e) { throw new ElasticsearchException("Error while getting for request: " + request.toString(), e); } } Let's stick with `T` instead of `Optional<T>`. A huge number of folks already asked us to roll back the `Optional` change at `findById` and `Optional` isn't being loved that much.

Target:
public <T> T get(String id, Class<T> clazz, IndexCoordinates index) { GetRequest request = requestFactory.getRequest(id, index); try { GetResponse response = client.get(request, RequestOptions.DEFAULT); return elasticsearchConverter.mapDocument(DocumentAdapters.from(response), clazz); } catch (IOException e) { throw new ElasticsearchException("Error while getting for request: " + request.toString(), e); } }
Source:
START float getScore() { END return score; } Nit: `public`

Target:
public float getScore() { return score; }
Source:
public static IndexCoordinates of(String... indexNames) { START Assert.notNull(indexNames,"indexNames must not be null"); END return new IndexCoordinates(indexNames); } Let's also ensure that `indexNames` contains at least one element so we can get rid of nullability in `getIndexName()`

Target:
public static IndexCoordinates of(String... indexNames) { Assert.notNull(indexNames, "indexNames must not be null"); return new IndexCoordinates(indexNames, null); }
Source:
public MappingElasticsearchConverter elasticsearchEntityMapper( SimpleElasticsearchMappingContext elasticsearchMappingContext) { START return new MappingElasticsearchConverter(elasticsearchMappingContext, new DefaultConversionService()); END } Let's use a constructor without a `conversionService` here to align with other modules.

Target:
public MappingElasticsearchConverter elasticsearchEntityMapper( SimpleElasticsearchMappingContext elasticsearchMappingContext) { return new MappingElasticsearchConverter(elasticsearchMappingContext); }
Source:
public void shouldSupportSortOnStandardFieldWithCriteria() { final List<String> sortedIds = repository.findAllByNameOrderByText("Salt").stream() // .map(it -> it.id).collect(Collectors.toList()); START assertThat(sortedIds).containsExactly("4", "5"); END } Nit: No need for `final` keyword in local variables.

Target:
public void shouldSupportSortOnStandardFieldWithCriteria() { List<String> sortedIds = repository.findAllByNameOrderByText("Salt").stream() // .map(it -> it.id).collect(Collectors.toList()); assertThat(sortedIds).containsExactly("4", "5"); }
Source:
public String getFieldName() { START return isAnnotatedFieldName ? annotatedFieldName : getProperty().getName(); END } ```java return annotatedFieldName == null ? getProperty().getName() : annotatedFieldName ```

Target:
public String getFieldName() { return annotatedFieldName == null ? getProperty().getName() : annotatedFieldName; }
Source:
protected CompositeJsonFormatter<ILoggingEvent> createFormatter() { LogstashFormatter formatter = new LogstashFormatter(this); START formatter.setLineSeparator(getLineSeparator()); END return formatter; } Hmm. The Encoder's lineSeparator property is the string to output between events. Coupling the separator to output between events with the regex to use to split the message string does not seem ideal. I think the regex to use to split the message string should be separate from the separator string to use between events.

Target:
protected CompositeJsonFormatter<ILoggingEvent> createFormatter() { return new LogstashFormatter(this); }
Source:
protected void prepareViewing() { START drawRegistration.remove(); END clickRegistration.remove(); if(markerRegisration != null) { markerRegisration.remove(); } } Don't have the project open ATM, should there be a null check? Can the field go for "view mode" directly if a populated readonly property is set (I don't actually know if this is possible currently with V8)?

Target:
protected void prepareViewing() { if (drawRegistration != null) { drawRegistration.remove(); drawRegistration = null; } if (clickRegistration != null) { clickRegistration.remove(); clickRegistration = null; } if (markerRegisration != null) { markerRegisration.remove(); markerRegisration = null; } }
Source:
protected void createFile(FileVersion reconstructedFileVersion) throws IOException { File reconstructedFileInCache; try { START reconstructedFileInCache = assembleFileToCache(reconstructedFileVersion); END } catch (NoSuchAlgorithmException | ChecksumMismatchException e) { throw new IOException(e); } moveFileToFinalLocation(reconstructedFileInCache, reconstructedFileVersion); } I generally dislike this pattern: ``` X var; try { X = ...; } catch (..) { } ``` Couldn't we just move the `moveFileToFinalLocation` inside the `try`?

Target:
protected void createFile(FileVersion reconstructedFileVersion) throws IOException { try { File reconstructedFileInCache = assembleFileToCache(reconstructedFileVersion); moveFileToFinalLocation(reconstructedFileInCache, reconstructedFileVersion); } catch (NoSuchAlgorithmException | ChecksumMismatchException e) { throw new IOException(e); } }
Source:
public SortedMap<Long, String> getPurgeFileVersionSettings() { START END if (purgeFileVersionSettings == null) { purgeFileVersionSettings = new TreeMap<Long, String>(); purgeFileVersionSettings.put(30L * 24L * 3600L, "DD"); purgeFileVersionSettings.put(3L * 24L * 3600L, "HH"); purgeFileVersionSettings.put(3600L, "MI"); } return purgeFileVersionSettings; } Shouldn't we use [`TimeUnit`](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/TimeUnit.html) instead of plain strings for interval definitions?

Target:
public SortedMap<Long, TimeUnit> getPurgeFileVersionSettings() { return purgeFileVersionSettings; }
Source:
public void afterPropertiesSet() throws Exception { ThymeleafViewResolver viewResolver = applicationContext.getBean(ThymeleafViewResolver.class); if (viewResolver == null) { LOG.warn( "Cannot adjust ThymeleafViewResolver: " + "bean of this type wasn't found in application context" ); return; } boolean productionEnv = environment.acceptsProfiles("prod"); START Boolean useCdn = environment.getProperty("app.use-cdn", Boolean.class, Boolean.TRUE); END viewResolver.setStaticVariables(resourcesAsMap(productionEnv, useCdn)); } If you want, you can try to use `boolean useCdn = ...` here. It should work.

Target:
public void afterPropertiesSet() throws Exception { ThymeleafViewResolver viewResolver = applicationContext.getBean(ThymeleafViewResolver.class); if (viewResolver == null) { LOG.warn( "Cannot adjust ThymeleafViewResolver: " + "bean of this type wasn't found in application context" ); return; } boolean productionEnv = environment.acceptsProfiles("prod"); boolean useCdn = environment.getProperty("app.use-cdn", Boolean.class, Boolean.TRUE); viewResolver.setStaticVariables(resourcesAsMap(productionEnv, useCdn)); }
Source:
public void changeStatus(Integer requestId, String oldStatus, String newStatus) { Validate.isTrue(requestId != null, "Request id must be non null"); Validate.isTrue(StringUtils.isNotBlank(oldStatus), "Old status must be non-blank"); Validate.isTrue(StringUtils.isNotBlank(newStatus), "New status must be non-blank"); Validate.isTrue(!oldStatus.equals(newStatus), "Statuses must be different"); Date now = new Date(); START seriesImportDao.changeStatus(new UpdateImportRequestStatusDbDto(requestId, now, oldStatus, newStatus)); END } Please, extract a local variable: ```java Date now = new Date(); UpdateImportRequestStatusDbDto status = new UpdateImportRequestStatusDbDto( requestId, now, oldStatus, newStatus ); seriesImportDao.changeStatus(status); ```

Target:
public void changeStatus(Integer requestId, String oldStatus, String newStatus) { Validate.isTrue(requestId != null, "Request id must be non null"); Validate.isTrue(StringUtils.isNotBlank(oldStatus), "Old status must be non-blank"); Validate.isTrue(StringUtils.isNotBlank(newStatus), "New status must be non-blank"); Validate.isTrue(!oldStatus.equals(newStatus), "Statuses must be different"); Date now = new Date(); UpdateImportRequestStatusDbDto status = new UpdateImportRequestStatusDbDto(requestId, now, oldStatus, newStatus); seriesImportDao.changeStatus(status); }
Source:
public List<SeriesInfoDto> findByMichelNumber(String michelNumberCode, String lang) { Validate.isTrue(michelNumberCode != null, "Michel number code must be non null"); Validate.isTrue(!michelNumberCode.trim().isEmpty(), "Michel number code must be non empty"); List<Integer> seriesIds = seriesDao.findSeriesIdsByMichelNumberCode(michelNumberCode); return seriesIds.isEmpty() ? Collections.emptyList() START : seriesDao.findByIdsAsSeriesInfo(seriesIds, lang); END } Ah, and CheckStyle allows it? Rewrite to the long but more readable form: ``` java if (result.IsEmpty) { return emptyList; } return callDao(); ```

Target:
public List<SeriesInfoDto> findByMichelNumber(String michelNumberCode, String lang) { Validate.isTrue(michelNumberCode != null, "Michel number code must be non null"); Validate.isTrue(!michelNumberCode.trim().isEmpty(), "Michel number code must be non empty"); List<Integer> seriesIds = seriesDao.findSeriesIdsByMichelNumberCode(michelNumberCode); if (seriesIds.isEmpty()) { return Collections.emptyList(); } return seriesDao.findByIdsAsSeriesInfo(seriesIds, lang); }
Source:
public boolean isValid(AddSeriesDto dto, ConstraintValidatorContext context) { if (dto == null) { return true; } START LocalDate today = LocalDate.now(); END if (yearInFuture(today, dto)) { rejectField(context, "year"); return false; } if (yearAndMonthInFuture(today, dto)) { rejectField(context, "month"); return false; } if (dateInFuture(today, dto)) { rejectField(context, "day"); return false; } return true; } Ok, let's move this back to the methods, because we don't have any benefits of extracting here. Sorry :)

Target:
public boolean isValid(AddSeriesDto dto, ConstraintValidatorContext context) { if (dto == null) { return true; } if (yearInFuture(dto)) { rejectField(context, "year"); return false; } if (yearAndMonthInFuture(dto)) { rejectField(context, "month"); return false; } if (dateInFuture(dto)) { rejectField(context, "day"); return false; } return true; }
Source:
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context) { AccessControlled _context = (context instanceof AccessControlled ? (AccessControlled) context : Jenkins.getInstance()); START if (_context != null && !_context.hasPermission(Computer.CONFIGURE)) { END return new ListBoxModel(); } return new StandardUsernameListBoxModel().withMatching(SSHAuthenticator.matcher(Connection.class), CredentialsProvider.lookupCredentials(StandardUsernameCredentials.class, context, ACL.SYSTEM, SSHLauncher.SSH_SCHEME)); } :bug: this would open a security hole: a direct call to `/descriptorById/hudson.plugins.sshslaves.SSHConnector/fillCredentialsIdItems` from a user with only `Jenkins.READ` permission (perhaps anonymous) could enumerate credentials. I think you meant ``` java if (_context == null || !_context.hasPermission(Computer.CONFIGURE)) { ```

Target:
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context) { AccessControlled _context = (context instanceof AccessControlled ? (AccessControlled) context : Jenkins.getInstance()); if (_context == null || !_context.hasPermission(Computer.CONFIGURE)) { return new ListBoxModel(); } return new StandardUsernameListBoxModel().withMatching(SSHAuthenticator.matcher(Connection.class), CredentialsProvider.lookupCredentials(StandardUsernameCredentials.class, context, ACL.SYSTEM, SSHLauncher.SSH_SCHEME)); }
Source:
public ExportWiki(String url, String user, String password) throws AuthenticationException { BasicEndpoint basicEndpoint = new BasicEndpoint(); basicEndpoint.setUrl(url); basicEndpoint.setForceTrustSSLCertificate(true); START basicEndpoint.setUser(user); END basicEndpoint.setPassword(password); basicEndpoint.login(user, password); wikiService = new WikiService(); setEndpoint(basicEndpoint); } You don't need setUser and setPassword anymore if you call login(user, password)

Target:
public ExportWiki(String url, String user, String password) throws AuthenticationException { BasicEndpoint basicEndpoint = new BasicEndpoint(); basicEndpoint.setUrl(url); basicEndpoint.setForceTrustSSLCertificate(true); basicEndpoint.login(user, password); wikiService = new WikiService(); setEndpoint(basicEndpoint); }
Source:
public String getBlogUuid() { START return super.getUid(); END } Could you please remove all the unnecessary super. and this. ? Thanks!

Target:
public String getBlogUuid() { return getUid(); }
Source:
public void remove() throws BlogServiceException{ if(StringUtil.isNotEmpty(getBlogHandle())){ getService().removeBlogPost(getPostUuid(), getBlogHandle()); } else{ START getService().removeBlogPost(getPostUuid(), getAsString(BlogXPath.handle)); END } } Should this logic be part of getBlogHandle function itself ?

Target:
public void remove() throws BlogServiceException{ getService().removeBlogPost(getPostUuid(), getBlogHandle()); }
Source:
public void testUnRecommendPost() { JavaScriptPreviewPage previewPage = executeSnippet(SNIPPET_ID); JsonJavaObject json = previewPage.getJson(); START System.out.println("aaaaaaaaaaaa "+json.getString("status")); END Assert.assertTrue(json.getString("status").equals("204.0")); } Should not have any sysout

Target:
public void testUnRecommendPost() { JavaScriptPreviewPage previewPage = executeSnippet(SNIPPET_ID); JsonJavaObject json = previewPage.getJson(); Assert.assertTrue(json.getString("status").equals("204.0")); }
Source:
public void testCreateDeleteFolder() throws Exception { FileService fileService = new FileService(); authenticateEndpoint(fileService.getEndpoint(), USERNAME, PASSWORD); String name = "testCreateFolder" + System.currentTimeMillis(); START String description = "Vimal's testCreateFolder"; END File folder = fileService.createFolder(name, description, ""); assertEquals(folder.getTitle(), name); //now delete the folder created fileService.deleteFolder(folder.getFileId()); } Can we replace description to something else ?

Target:
public void testCreateDeleteFolder() throws Exception { FileService fileService = new FileService(); authenticateEndpoint(fileService.getEndpoint(), USERNAME, PASSWORD); String name = "testCreateFolder" + System.currentTimeMillis(); String description = "testCreateFolder"; File folder = fileService.createFolder(name, description, ""); assertEquals(folder.getTitle(), name); //now delete the folder created fileService.deleteFolder(folder.getFileId()); }
Source:
START public static void fireChunkWatch(boolean wasLoaded, boolean load, ServerPlayerEntity entity, ChunkPos chunkpos, ServerWorld world) END { if (!wasLoaded && load) MinecraftForge.EVENT_BUS.post(new ChunkWatchEvent.Watch(entity, chunkpos, world)); else if (wasLoaded && !load) MinecraftForge.EVENT_BUS.post(new ChunkWatchEvent.UnWatch(entity, chunkpos, world)); } Yes it falls under binary compatibility

Target:
public static void fireChunkWatch(boolean wasLoaded, boolean load, ServerPlayerEntity entity, ChunkPos chunkpos, ServerWorld world) { if (wasLoaded != load) fireChunkWatch(load, entity, chunkpos, world); }
Source:
public void setContent(String contents) { START this.nameplateContent = Strings.nullToEmpty(contents); END } Again, why nullToEmpty?

Target:
public void setContent(String contents) { this.nameplateContent = contents; }
Source:
public static double getLivingVisibility(LivingEntity living, @Nullable Entity lookingEntity, double visibility) { LivingVisibilityEvent event = new LivingVisibilityEvent(living, lookingEntity, visibility); MinecraftForge.EVENT_BUS.post(event); double value = event.getVisibility(); if(living instanceof PlayerEntity) { START value = getPlayerVisibilityDistance((PlayerEntity)living, value, visibility); END } return value; } I think the legacy event should be fired first, so the new event can overwrite the legacy result

Target:
public static double getLivingVisibility(LivingEntity living, @Nullable Entity lookingEntity, double visibility) { double value = visibility; if(living instanceof PlayerEntity) { value = getPlayerVisibilityDistance((PlayerEntity)living, visibility, visibility); } LivingVisibilityEvent event = new LivingVisibilityEvent(living, lookingEntity, value); MinecraftForge.EVENT_BUS.post(event); return event.getVisibility(); }
Source:
public void setSwingHand(boolean value) { START if(isPickBlock()) throw new UnsupportedOperationException("The hand swing can't be disabled if this is a pick block input."); END handSwing = value; } I would argue there is no point punishing modders for this. Just put in the method doc that changing this value has no affect for pick blocks.

Target:
public void setSwingHand(boolean value) { handSwing = value; }
Source:
public static int getItemBurnTime(ItemStack stack) { if (stack.isEmpty()) { return 0; } else { Item item = stack.getItem(); int base = stack.getBurnTime(); //I changed the original logic here. Previously every time ForgeEventFactory#getItemBurnTime was called, now the result is cahced aswell. START return getBurnTimes().computeIfAbsent(item, i -> net.minecraftforge.event.ForgeEventFactory.getItemBurnTime(stack, base == -1 ? getVanillaBurnTimes().getOrDefault(i, 0) : base)); END } } the event should still be fired every time because you could e.g. have mods that dynamically adjust other mods' items' burn times

Target:
public static int getItemBurnTime(ItemStack stack) { if (stack.isEmpty()) { return 0; } else { Item item = stack.getItem(); int base = stack.getBurnTime(); return net.minecraftforge.event.ForgeEventFactory.getItemBurnTime(stack, base == -1 ? getBurnTimes().getOrDefault(item, 0) : base); } }
Source:
public static void invalidate() START { END burnTimes = null; vanillaBurnTimes = null; } not called anywhere?

Target:
public static void invalidate() { burnTimes = null; }
Source:
public static Map<DataFixer, Pair<Integer, Integer>> getFixVersionsNoVanilla(NBTTagCompound nbttagcompound, boolean useLatestOtherwiseN1) { START return getFixVersionsNoVanilla(nbttagcompound, (useLatestOtherwiseN1 ? -2492 : -1)); END } What is -2492?

Target:
public static Map<DataFixer, Pair<Integer, Integer>> getFixVersionsNoVanilla(NBTTagCompound nbttagcompound, boolean useLatestOtherwiseN1) { return getFixVersionsNoVanilla(nbttagcompound, -1, useLatestOtherwiseN1); }
Source:
public Class<T> getBaseClass() { return baseClass; START } END Is there a method for modders to share recipe types? An enum system with our extender or some form of get(ResourceLocation) would be good.

Target:
public Class<? extends T> getBaseClass() { return baseClass; }
Source:
public <T> T get() { if (FMLEnvironment.dist == Dist.CLIENT) { return (T)this.clientSide.apply(client); } else if (FMLEnvironment.dist == Dist.DEDICATED_SERVER) { return (T)this.serverSide.apply(server); } else if (FMLEnvironment.dist == null) { return (T)this.testSide.get(); } else { START throw new IllegalArgumentException("THREE SIDES? WUT?"); END } } This should update and say that custom sides are not supported

Target:
public <T> T get() { if (FMLEnvironment.dist == Dist.CLIENT) { return (T)this.clientSide.apply(client); } else if (FMLEnvironment.dist == Dist.DEDICATED_SERVER) { return (T)this.serverSide.apply(server); } else { return (T)this.testSide.get(); } }
Source:
public static <T> Comparator<IForgeRegistryEntry<T>> registryNameComparator() { START return Comparator.comparing(IForgeRegistryEntry::getRegistryName, Comparator.naturalOrder()); END } `Comparator.comparing(IForgeRegistryEntry::getRegistryName)` should be sufficient.

Target:
public static <T> Comparator<IForgeRegistryEntry<T>> registryNameComparator() { return Comparator.comparing(IForgeRegistryEntry::getRegistryName); }
Source:
public void write(PacketBuffer buffer) { this.getBlocks().write(buffer); this.getItems().write(buffer); START this.getFluids().write(buffer); END //we might wind up sending more data than vanilla needs (and therefore produce excessive Network traffic...) //TODO Check if connected to vanilla client and if so don't write ForgeTag Data writeForgeTags(buffer); } Welcome to the world of limited packet sizes. This will explode and explode fast. Do not hijack the vanilla packet.

Target:
public void write(PacketBuffer buffer) { this.getBlocks().write(buffer); this.getItems().write(buffer); this.getFluids().write(buffer); //we might wind up sending more data than vanilla needs (and therefore produce excessive Network traffic...) //writeForgeTags(buffer); }
Source:
public Predicate<IResourceType> get() { START if (this.currentPredicate == null) // TODO configs || !ForgeMod.selectiveResourceReloadEnabled) END { return ReloadRequirements.all(); } return this.currentPredicate; } Default to off until config is back

Target:
public Predicate<IResourceType> get() { if (this.currentPredicate == null && false) // TODO configs || !ForgeMod.selectiveResourceReloadEnabled) { return ReloadRequirements.all(); } return this.currentPredicate; }
Source:
START private String[] setPropertyAndGetStringList(String name, String category, String[] defaultValue, String comment, String[] validValues, String[] validValuesDisplay, String langKey) END { Property prop = this.get(category, name, defaultValue); prop.setValidValues(validValues); if (validValuesDisplay != null) prop.setValidValuesDisplay(validValuesDisplay); prop.setLanguageKey(langKey); prop.setComment(comment + " [default: " + defaultValue + "]"); return prop.getStringList(); } ```suggestion private String[] setPropertyAndGetStringList(String name, String category, String[] defaultValue, String comment, String[] validValues, @Nullable String[] validValuesDisplay, String langKey) ```

Target:
private String[] setPropertyAndGetStringList(String name, String category, String[] defaultValue, String comment, String[] validValues, String[] validValuesDisplay, String langKey) { Property prop = this.get(category, name, defaultValue); prop.setValidValues(validValues); prop.setValidValuesDisplay(validValuesDisplay); prop.setLanguageKey(langKey); prop.setComment(comment + " [default: " + defaultValue + "]"); return prop.getStringList(); }
Source:
public float getBlockLiquidHeight(World world, BlockPos pos, IBlockState state, Material material) { float filled = getFilledPercentage(world, pos); START return filled > 0 ? filled : 0; END } Use `Math.max`

Target:
public float getBlockLiquidHeight(World world, BlockPos pos, IBlockState state, Material material) { float filled = getFilledPercentage(world, pos); return Math.max(filled, 0); }
Source:
public CommandTreeTest() { addSubcommand(new CommandPing()); addSubcommand(new CommandValue()); START addSubcommand(new CommandTreeHelp(this)); END } Use 4 spaces instead of tabs

Target:
public CommandTreeTest() { addSubcommand(new CommandPing(this)); addSubcommand(new CommandValue(this)); addSubcommand(new CommandTreeHelp(this)); }
Source:
START public static String remapFieldName(Class<?> clazz, String fieldName) END { String internalClassName = FMLDeobfuscatingRemapper.INSTANCE.unmap(Type.getInternalName(clazz)); return FMLDeobfuscatingRemapper.INSTANCE.mapFieldName(internalClassName, fieldName, null); } Maybe make it more clear that this is supposed to be srg name by naming it "fieldSrgName"? (and same for methods)

Target:
private static String remapFieldName(Class<?> clazz, String fieldName) { String internalClassName = FMLDeobfuscatingRemapper.INSTANCE.unmap(Type.getInternalName(clazz)); return FMLDeobfuscatingRemapper.INSTANCE.mapFieldName(internalClassName, fieldName, null); }
Source:
START public PotionRemoveEvent(EntityLivingBase living, Potion potion) END { super(living, living.getActivePotionMap().get(potion)); toRemove = potion; } there are two spaces in `Potion potion`

Target:
public PotionRemoveEvent(EntityLivingBase living, Potion potion) { super(living, living.getActivePotionMap().get(potion)); this.potion = potion; }
Source:
START public @Nullable MobSpawnerBaseLogic getSpawner() { return spawner; } END `@Nullable` should go on the line before, except in patches where size is being minimized.

Target:
public MobSpawnerBaseLogic getSpawner() { return spawner; }
Source:
private String getTileEntityName(TileEntity tileEntity) { START String className = tileEntity.getClass().getSimpleName(); END ResourceLocation registryId = TileEntity.getKey(tileEntity.getClass()); if (registryId == null) return className; else { return registryId.toString(); } } Calculate this only if the registry id is null, or it is a waste or time and memory

Target:
private String getTileEntityName(TileEntity tileEntity) { ResourceLocation registryId = TileEntity.getKey(tileEntity.getClass()); if (registryId == null) return tileEntity.getClass().getSimpleName(); else { return registryId.toString(); } }
Source:
public static boolean onLivingKnockBack(EntityLivingBase target, Entity attacker, float strength, double ratioX, double ratioZ) { START return !MinecraftForge.EVENT_BUS.post(new LivingKnockBackEvent(target, attacker, strength, ratioX, ratioZ)); END } As you are negating the result when using this function, it'd be better to avoid the double-negation by just returning the result here directly.

Target:
public static LivingKnockBackEvent onLivingKnockBack(EntityLivingBase target, Entity attacker, float strength, double ratioX, double ratioZ) { LivingKnockBackEvent event = new LivingKnockBackEvent(target, attacker, strength, ratioX, ratioZ); MinecraftForge.EVENT_BUS.post(event); return event; }
Source:
START public static boolean hasElytraFlightAbility(EntityLivingBase player, ItemStack itemstack) { END if(!(player instanceof EntityPlayer)) return false; boolean vanillaElytra = itemstack.getItem() == Items.ELYTRA && ItemElytra.isUsable(itemstack); double attributeValue = player.getEntityAttribute(SharedMonsterAttributes.ELYTRA_FLIGHT).getAttributeValue(); return attributeValue>1.0D || (vanillaElytra && attributeValue >=1.0D); } Please follow the formatting used elsewhere in the project. Braces go on a new line, spaces after `if` before the parenthesis, spaces around comparison operators, etc.

Target:
public static boolean hasElytraFlightAbility(EntityLivingBase player, ItemStack itemstack) { boolean vanillaElytra = itemstack.getItem() == Items.ELYTRA && ItemElytra.isUsable(itemstack); if (!(player instanceof EntityPlayer)) { return vanillaElytra; } double attributeValue = player.getEntityAttribute(EntityPlayer.ELYTRA_FLIGHT).getAttributeValue(); return attributeValue > 1.0D || (vanillaElytra && attributeValue >= 1.0D); }
Source:
START public boolean containsAll(Collection<?> tileEntities) END { for (Iterator<?> iterator = tileEntities.iterator(); iterator.hasNext();) { if(!contains(iterator.next())) return false; } return true; } Missing @ Override

Target:
public boolean containsAll(Collection<?> tileEntities) { for (Object object : tileEntities) { if (!contains(object)) return false; } return true; }
Source:
START @Nonnull public Explosion getExplosion() { return explosion; } END Formatting. Don't sqeeze it in one line, follow forge code style. Use this formatter: https://github.com/ForgeEssentials/ForgeEssentials/blob/develop/misc/eclipseformatter.xml

Target:
public Explosion getExplosion() { return explosion; }
Source:
public IPropertyWrapper getProperty(String name) { buildPropertyMap(); START return null; END } Ahem.

Target:
public IPropertyWrapper getProperty(String name) { buildPropertyMap(); return properties.get(name); }
Source:
public EntityEquipmentInvWrapper(final EntityLivingBase entity, final EntityEquipmentSlot.Type slotType) { this.entity = entity; final List<EntityEquipmentSlot> slots = new ArrayList<EntityEquipmentSlot>(); for (final EntityEquipmentSlot slot : EntityEquipmentSlot.values()) { if (slot.getSlotType() == slotType) { slots.add(slot.getIndex(), slot); } START } END this.slots = ImmutableList.copyOf(slots); } Not a fan of this, it would seem to add non-congruent slots. So the inventory would appear to have 'holes' A better way may be using add instead of a indexed add.

Target:
public EntityEquipmentInvWrapper(final EntityLivingBase entity, final EntityEquipmentSlot.Type slotType) { this.entity = entity; final List<EntityEquipmentSlot> slots = new ArrayList<EntityEquipmentSlot>(); for (final EntityEquipmentSlot slot : EntityEquipmentSlot.values()) { if (slot.getSlotType() == slotType) { slots.add(slot); } } this.slots = ImmutableList.copyOf(slots); }
Source:
public int fill(FluidStack resource, boolean doFill) { // NOTE: "Filling" means placement in this context! if (resource.amount < Fluid.BUCKET_VOLUME) { return 0; } if (doFill) { Material material = blockLiquid.getDefaultState().getMaterial(); START BlockDynamicLiquid block = BlockLiquid.getFlowingBlock(material); END world.setBlockState(blockPos, block.getDefaultState().withProperty(BlockLiquid.LEVEL, 0), 11); } return Fluid.BUCKET_VOLUME; } You don't need to change the type here.

Target:
public int fill(FluidStack resource, boolean doFill) { // NOTE: "Filling" means placement in this context! if (resource.amount < Fluid.BUCKET_VOLUME) { return 0; } if (doFill) { Material material = blockLiquid.getDefaultState().getMaterial(); BlockLiquid block = BlockLiquid.getFlowingBlock(material); world.setBlockState(blockPos, block.getDefaultState().withProperty(BlockLiquid.LEVEL, 0), 11); } return Fluid.BUCKET_VOLUME; }
Source:
START public boolean isFluid(@Nonnull IBlockState blockstate) END { return blockstate.getMaterial().isLiquid() || blockstate.getBlock() instanceof IFluidBlock; } I think this should be private since it shouldn't be overridden.

Target:
private boolean isFluid(@Nonnull IBlockState blockstate) { return blockstate.getMaterial().isLiquid() || blockstate.getBlock() instanceof IFluidBlock; }
Source:
START public IMerchant getMerchant(){ END return merchant; } formatting

Target:
public IMerchant getMerchant() { return this.merchant; }
Source:
public GuiTab(String name, ResourceLocation icon, Class<? extends GuiContainer> clazz) { this.name = name; this.iconResLoc = icon; // Make sure the vanilla tab doesnt get duplicated START if (GuiTab.tabRegistry.get(clazz).contains(VANILLA_INVENTORY_TAB) == false) END { GuiTab.VANILLA_INVENTORY_TAB.addTo(clazz); } } ```java if (!GuiTab.tabRegistry.get(clazz).contains(VANILLA_INVENTORY_TAB)) ```

Target:
public GuiTab(String name, ResourceLocation icon, Class<? extends GuiContainer> clazz) { this.name = name; this.iconResLoc = icon; // Make sure the vanilla tab doesnt get duplicated if (!GuiTab.tabRegistry.get(clazz).contains(VANILLA_INVENTORY_TAB)) { // GuiTab.VANILLA_INVENTORY_TAB.addTo(clazz); } }
Source:
public boolean has_finished( int sample_idx ) { if( loop_length <= 1 && sample_idx > loop_start ) { return true; } else { START return false; END } } This shows you don't know about optimization at all.

Target:
public boolean has_finished( int sample_idx ) { return loop_length <= 1 && sample_idx > loop_start; }
Source:
public void onItemLoad(AttachCapabilitiesEvent.Item event) { START if (!event.getItemStack().func_190926_b() && event.getItemStack().getItem() == Items.STICK) END event.addCapability(new ResourceLocation("forge.testcapmod:dummy_cap"), new Provider(event.getItemStack())); } Only `event.getItemStack().getItem() == Items.STICK` is enough.

Target:
public void onItemLoad(AttachCapabilitiesEvent.Item event) { if (event.getItemStack().getItem() == Items.STICK) event.addCapability(new ResourceLocation("forge.testcapmod:dummy_cap"), new Provider(event.getItemStack())); }
Source:
private static long bytesToMb(long bytes) { START return bytes / 1024L / 1024L; END } ```java return bytes >> 20; ```

Target:
private static int bytesToMb(long bytes) { return (int) (bytes / 1024L / 1024L); }
Source:
public static NonNullList<ItemStack> defaultRecipeGetRemainingItems(InventoryCrafting inv) { NonNullList<ItemStack> ret = NonNullList.func_191197_a(inv.getSizeInventory(), ItemStack.field_190927_a); for (int i = 0; i < ret.size(); i++) { ItemStack container = getContainerItem(inv.getStackInSlot(i)); if (container != null) { ret.set(i, container); } START } END return ret; } The PROPER solution would be to make getContainerItem NOT return null, as Null ItemStacks are not valid anymore in 1.11

Target:
public static NonNullList<ItemStack> defaultRecipeGetRemainingItems(InventoryCrafting inv) { NonNullList<ItemStack> ret = NonNullList.func_191197_a(inv.getSizeInventory(), ItemStack.field_190927_a); for (int i = 0; i < ret.size(); i++) { ret.set(i, getContainerItem(inv.getStackInSlot(i))); } return ret; }
Source:
public static int getLootingLevel(Entity target, Entity killer, DamageSource cause) { int looting = 0; if (killer instanceof EntityLivingBase) { looting = EnchantmentHelper.getLootingModifier((EntityLivingBase)killer); } if (target instanceof EntityLivingBase) { START looting = net.minecraftforge.common.ForgeHooks.getLootingLevel((EntityLivingBase)target, cause, looting); END } return looting; } ``` java looting = getLootingLevel((EntityLivingBase)target, cause, looting); ``` This code is already in `ForgeHooks` class.

Target:
public static int getLootingLevel(Entity target, Entity killer, DamageSource cause) { int looting = 0; if (killer instanceof EntityLivingBase) { looting = EnchantmentHelper.getLootingModifier((EntityLivingBase)killer); } if (target instanceof EntityLivingBase) { looting = getLootingLevel((EntityLivingBase)target, cause, looting); } return looting; }
Source:
public static MultiPlaceEvent onPlayerMultiBlockPlace(EntityPlayer player, List<BlockSnapshot> blockSnapshots, EnumFacing direction) START { END BlockSnapshot snap = blockSnapshots.get(0); IBlockState placedAgainst = snap.getWorld().getBlockState(snap.getPos().offset(direction.getOpposite())); MultiPlaceEvent event = new MultiPlaceEvent(blockSnapshots, placedAgainst, player); MinecraftForge.EVENT_BUS.post(event); return event; } Dont duplicate code, bounce to the new one with the argument null, this makes it more obvious what to remove when deleting deprecated functions. And illustrates the parameter CAN be null.

Target:
public static MultiPlaceEvent onPlayerMultiBlockPlace(EntityPlayer player, List<BlockSnapshot> blockSnapshots, EnumFacing direction) { return onPlayerMultiBlockPlace(player, blockSnapshots, direction, null); }
Source:
public ActionResult<ItemStack> onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn, EnumHand hand) { START if (itemStackIn.hasCapability(CapabilityGuiProvider.GUI_PROVIDER_CAPABILITY, EnumFacing.UP)) END { IGuiProvider provider = itemStackIn.getCapability(CapabilityGuiProvider.GUI_PROVIDER_CAPABILITY, hand == EnumHand.MAIN_HAND ? EnumFacing.UP : EnumFacing.DOWN); playerIn.openGui(provider); return ActionResult.newResult(EnumActionResult.SUCCESS, itemStackIn); } return ActionResult.newResult(EnumActionResult.PASS, itemStackIn); } I still think using `UP` or the hand for the `EnumFacing` is fishy here. Nobody else is going to know how to open your gui. I think `null` should be used, unless it's a block and you know which side of the block is being clicked.

Target:
public ActionResult<ItemStack> onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn, EnumHand hand) { if (itemStackIn.hasCapability(CapabilityGuiProvider.GUI_PROVIDER_CAPABILITY, EnumFacing.UP)) { IGuiProvider provider = itemStackIn.getCapability(CapabilityGuiProvider.GUI_PROVIDER_CAPABILITY, null); playerIn.openGui(provider, hand); return ActionResult.newResult(EnumActionResult.SUCCESS, itemStackIn); } return ActionResult.newResult(EnumActionResult.PASS, itemStackIn); }
Source:
public void writeToNBT(NBTTagCompound nbt) { START nbt.setInteger("dimension", this.dimension); END nbt.setTag("ForgeCaps", serializable.serializeNBT()); } I'm not very versed in WorldSavedData, but is this required? I thought WorldSavedData is already per-world making this redundant

Target:
public void writeToNBT(NBTTagCompound nbt) { nbt.setTag("ForgeCaps", serializable.serializeNBT()); }
Source:
private void register(VillagerCareer career) { Validate.isTrue(!careers.contains(career), "Attempted to register career that is already registered."); Validate.isTrue(career.profession == this, "Attempted to register career for the wrong profession."); career.id = careers.size(); careers.add(career); START TRADES.put(career, new ArrayList<List<ITradeList>>()); END } Having second lists associated with careers we control is just dumb. That's what the trade list is in the career object.

Target:
private void register(VillagerCareer career) { Validate.isTrue(!careers.contains(career), "Attempted to register career that is already registered."); Validate.isTrue(career.profession == this, "Attempted to register career for the wrong profession."); career.id = careers.size(); careers.add(career); }
Source:
public VillagerCareer getCareer(String name) { for (VillagerCareer car : this.careers) { START if (car.getName() == name) END return car; } return null; } Always use `equals` when comparing Strings in Java

Target:
public VillagerCareer getCareer(String name) { for (VillagerCareer car : this.careers) { if (car.getName().equals(name)) return car; } return null; }
Source:
public static boolean canHarvestBlock(Block block, EntityPlayer player, IBlockAccess world, BlockPos pos) { IBlockState state = world.getBlockState(pos); state = state.getBlock().getActualState(state, world, pos); START return canHarvestBlock(block, player, state); END } Shouldn't this be ``` canHarvestBlock(player, state): ``` ?

Target:
public static boolean canHarvestBlock(Block block, EntityPlayer player, IBlockAccess world, BlockPos pos) { IBlockState state = world.getBlockState(pos); state = state.getBlock().getActualState(state, world, pos); return canHarvestBlock(player, state); }
Source:
public void onPostServerTick() { START this.onPreServerTick(this.getMinecraftServerInstance()); END } ``` java this.onPostServerTick(this.getMinecraftServerInstance()); ```

Target:
public void onPostServerTick() { this.onPostServerTick(this.getMinecraftServerInstance()); }
Source:
public void setStackInSlot(int slot, ItemStack stack) { START ItemStack[] stacks = this.stacks; END validateSlotIndex(slot, stacks); if (ItemStack.areItemStacksEqual(stacks[slot], stack)) return; stacks[slot] = stack; onContentsChanged(slot); } Very minor, but a bit redundant?

Target:
public void setStackInSlot(int slot, ItemStack stack) { validateSlotIndex(slot); if (ItemStack.areItemStacksEqual(this.stacks[slot], stack)) return; this.stacks[slot] = stack; onContentsChanged(slot); }
Source:
public ItemStack getStackInSlot(int slot) { START ItemStack[] stacks = this.stacks; END validateSlotIndex(slot, stacks); return stacks[slot]; } Very minor, but a bit redundant?

Target:
public ItemStack getStackInSlot(int slot) { validateSlotIndex(slot); return this.stacks[slot]; }
Source:
private void registerVillagerSkin(int villagerId, ResourceLocation villagerSkin) START { END if (newVillagers == null) { newVillagers = Maps.newHashMap(); } newVillagers.put(villagerId, villagerSkin); } This is deprecated to be removed in 1.8.8 but still exists because we dont want to fire MissingMethodExceptions.

Target:
private void registerVillagerSkin(int villagerId, ResourceLocation villagerSkin) { }
Source:
START public static <P extends IProperty, V>IUnlistedProperty toUnlisted(P property) END { return new PropertyAdapter(property); } Why is this needed? And all the other places with added/removed casts/generics?

Target:
public static <P extends IProperty, V>IUnlistedProperty<V> toUnlisted(P property) { return new PropertyAdapter(property); }
Source:
START public Class getType() END { return B3DState.class; } Raw type here, generic in the base

Target:
public Class<B3DState> getType() { return B3DState.class; }
Source:
public static Set<String> getDimensionTypes(WorldProvider provider) { if (provider instanceof Handler) return ((Handler) provider).getDimensionTypes(); Set<String> types = dimensionTypes.get(provider.dimensionId); START return types != null ? SET_UNCATEGORIZED : Collections.<String>emptySet(); END } If types != null returns SET_UNCATEGORIZED if types == null, returns Collections.<String>emptySet(); Neither case actually returns types. :P

Target:
public static Set<String> getDimensionTypes(WorldProvider provider) { if (provider instanceof Handler) return ((Handler) provider).getDimensionTypes(); Set<String> types = dimensionTypes.get(provider.dimensionId); return types != null ? types : SET_UNCATEGORIZED; }
Source:
public FillBucketEvent(EntityPlayer player, ItemStack current, World world, MovingObjectPosition target) { super(player, current, world, target); START } END Moving these fields breaks all current mods that use this event.

Target:
public FillBucketEvent(EntityPlayer player, ItemStack current, World world, MovingObjectPosition target) { super(player, current, world, target); this.current = current; this.world = world; this.target = target; }
Source:
public static boolean checkPerm(EntityPlayer player, String node, Map<String, IContext> contextInfo) { if (player instanceof FakePlayer) START throw new IllegalArgumentException("You cannot check permissions with a fake player. Use PermManager.getPerm(username, node)"); END return FACTORY.checkPerm(player, node, contextInfo); } Obnoxious and buggy. Let FACTORY determine what permissions fake players should have.

Target:
public static boolean checkPerm(EntityPlayer player, String node, Map<String, IContext> contextInfo) { return FACTORY.checkPerm(player, node, contextInfo); }
Source:
public int size() START { END return properties.size(); } Seriously dude, don't reformat code for no reason.

Target:
@Override public int size(){ return properties.size(); }
Source:
private boolean isCountFunction(FunctionCallTree tree) { START return FUNCTION_PREDICATE.test(TreeValues.of(tree, context().symbolTable())) && tree.arguments().size() == 1; END } What about cases where [`count`](https://www.php.net/manual/en/function.count.php) has 2 arguments? I guess that we don't want to exclude such cases.

Target:
private boolean isCountFunction(FunctionCallTree tree) { return FUNCTION_PREDICATE.test(TreeValues.of(tree, context().symbolTable())) && !tree.arguments().isEmpty(); }
Source:
public void visitVariableIdentifier(VariableIdentifierTree varIdentifier) { START if (inStaticContext && !isWithinNonStaticFunctionExpression(varIdentifier) && "$this".equals(varIdentifier.variableExpression().text())) { END context().newIssue(this, varIdentifier.variableExpression(), MESSAGE); } super.visitVariableIdentifier(varIdentifier); } Nitpicking: I suppose that this new condition is slightly more costly than the next one. I would have put the new condition last.

Target:
public void visitVariableIdentifier(VariableIdentifierTree varIdentifier) { if (inStaticContext && "$this".equals(varIdentifier.variableExpression().text()) && !isWithinNonStaticFunctionExpression(varIdentifier)) { context().newIssue(this, varIdentifier.variableExpression(), MESSAGE); } super.visitVariableIdentifier(varIdentifier); }
Source:
private boolean hasEnoughNumberOfSpecialChars(String value) { int numberOfSpecialChars = 0; for (char c : value.toCharArray()) { if (SPECIAL_CHARS.contains(c)) { numberOfSpecialChars++; } } START return numberOfSpecialChars >= 2; END } we should return from the loop once this var is greater than 2. One way to do also get rid of the set could be to use a switch here : ``` for () { switch(c) { case '+': case '*': case '{': nb++; break; } if(nb == 2) return true; } return false; ```

Target:
private boolean hasEnoughNumberOfSpecialChars(String value) { int numberOfSpecialChars = 0; for (char c : value.toCharArray()) { if (SPECIAL_CHARS.contains(c)) { numberOfSpecialChars++; } if (numberOfSpecialChars == 2) { return true; } } return false; }
Source:
private int getPatternArgumentIndex(FunctionCallTree tree) { int index = 0; if (tree.callee().toString().equalsIgnoreCase(MB_EREG_SEARCH_INIT)) { index = 1; } START return index; END } personal preference (so up to you to take the suggestion into account) but I would go for : ``` if(cond) { return 1; } return 0;

Target:
private int getPatternArgumentIndex(FunctionCallTree tree) { if (tree.callee().toString().equalsIgnoreCase(MB_EREG_SEARCH_INIT)) { return 1; } return 0; }
Source:
START public static EchoTagStatementTree newEchoTagStatement(SeparatedList<ExpressionTree> expressions, InternalSyntaxToken eosToken) { END return new EchoTagStatementTreeImpl(expressions, eosToken); } Can we make this method private?

Target:
private static EchoTagStatementTree newEchoTagStatement(SeparatedList<ExpressionTree> expressions, InternalSyntaxToken eosToken) { return new EchoTagStatementTreeImpl(expressions, eosToken); }
Source:
public void test() { assertThat(PHPLexicalGrammar.FUNCTION_CALL_PARAMETER_LIST) .matches("()") .matches("($p)") .matches("(& $p)") .matches("(...$p)") .matches("(yield $a)") .matches("($p1, & $p2, ...$p3, yield $p4)") START .notMatches("('title', 'body','comments',)") END .notMatches("(,)") .notMatches("('function','bar',,)") .notMatches("(,'function','bar')"); } According to this [rfc](https://wiki.php.net/rfc/trailing-comma-function-calls) this code should "matches" and not the opposite!!!

Target:
public void test() { assertThat(PHPLexicalGrammar.FUNCTION_CALL_PARAMETER_LIST) .matches("()") .matches("($p)") .matches("(& $p)") .matches("(...$p)") .matches("(yield $a)") .matches("($p1, & $p2, ...$p3, yield $p4)") .matches("('title', 'body','comments',)") .notMatches("(,)") .notMatches("('function','bar',,)") .notMatches("(,'function','bar')"); }
Source:
START PhpCfgBlock(Set<PhpCfgBlock> successors, @Nullable PhpCfgBlock syntacticSuccessor) { END this.successors = ImmutableSet.copyOf(successors); this.syntacticSuccessor = syntacticSuccessor; } should it be `private`?

Target:
private PhpCfgBlock(Set<PhpCfgBlock> successors, @Nullable PhpCfgBlock syntacticSuccessor) { this.successors = ImmutableSet.copyOf(successors); this.syntacticSuccessor = syntacticSuccessor; }
Source:
public static Tree findAncestorWithKind(Tree tree, Collection<Tree.Kind> kinds) { Tree parent = tree; while (parent != null && !kinds.contains(parent.getKind())) { parent = parent.getParent(); } START if (parent != null) { END return parent; } return null; } can't we just return `parent`?

Target:
public static Tree findAncestorWithKind(Tree tree, Collection<Tree.Kind> kinds) { Tree parent = tree; while (parent != null && !kinds.contains(parent.getKind())) { parent = parent.getParent(); } return parent; }
Source:
public void test_isDescendant() { Tree tree = PHPParserBuilder.createParser().parse("<?= for(;;) ?>"); StatementTree statementTree = ((CompilationUnitTree) tree).script().statements().get(0); assertThat(isDescendant(statementTree, tree)).isTrue(); START assertThat(isDescendant(tree, statementTree)).isFalse(); END } add `assertThat(isDescendant(tree, tree)).isTrue();` and `assertThat(isDescendant(statementTree, statementTree)).isTrue();`?

Target:
public void test_isDescendant() { Tree tree = PHPParserBuilder.createParser().parse("<?= for(;;) ?>"); StatementTree statementTree = ((CompilationUnitTree) tree).script().statements().get(0); assertThat(isDescendant(statementTree, tree)).isTrue(); assertThat(isDescendant(tree, statementTree)).isFalse(); assertThat(isDescendant(tree, tree)).isTrue(); assertThat(isDescendant(statementTree, statementTree)).isTrue(); }