auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static void cleanCredentialStore() { File dir = new File(BASE_STORE_DIRECTORY); START dir.mkdirs(); END File file = new File(BASE_STORE_DIRECTORY + "/mycredstore.cs"); file.delete(); } Just minor but no need to call `dir.mkdirs()` here. This clean up method just needs to check if the file exists and if so, delete it.

Target:
private static void cleanCredentialStore() { File file = new File(BASE_STORE_DIRECTORY + "/mycredstore.cs"); file.delete(); }
Source:
public void testObtainCertificateChain() throws Exception { START server = setupTestObtainCertificate(false); END AcmeAccount account = populateAccount(ACCOUNT_3_V2); String domainName = "fjsljghasldfjgkv2.com"; // randomly generated domain name obtainCertificateChain(null, -1, account, domainName); } Same here, a new `setupTestObtainCertificate()` method could be added that calls `setupTestObtainCertificate(false)` by default.

Target:
public void testObtainCertificateChain() throws Exception { server = setupTestObtainCertificate(); AcmeAccount account = populateAccount(ACCOUNT_3_V2); String domainName = "fjsljghasldfjgkv2.com"; // randomly generated domain name obtainCertificateChain(null, -1, account, domainName); }
Source:
public Set<String> getSupportedExtensions() { START return supportedExts; END } maybe we can simply return 'null' here as `supportedExts` is not set anywhere, so it will be null anyway... as a result that variable does not have to be declared at all?

Target:
public Set<String> getSupportedExtensions() { return null; }
Source:
public Builder setMaxReconnectAttempts(int maxReconnectAttempts) throws IllegalArgumentException { START checkNotNullParam("reconnectAttempts", maxReconnectAttempts); END if (maxReconnectAttempts < -1) { throw audit.badReconnectAttemptsNumber(maxReconnectAttempts); } this.maxReconnectAttempts = maxReconnectAttempts; return this; } This null check can be removed since ```maxReconnectAttempts``` is an ```int```

Target:
public Builder setMaxReconnectAttempts(int maxReconnectAttempts) throws IllegalArgumentException { if (maxReconnectAttempts < -1) { throw audit.badReconnectAttemptsNumber(maxReconnectAttempts); } this.maxReconnectAttempts = maxReconnectAttempts; return this; }
Source:
public static void cleanUpLdapFiles() throws Exception { File workingDirLDIF = new File(LDAP_DIRECTORY_LOCATION); if (workingDirLDIF.exists() == false) { START workingDirLDIF.mkdirs(); END } Files.copy(Paths.get(workingDirLDIF + LDIF_LOCATION + ".bak"), Paths.get(workingDirLDIF + LDIF_LOCATION), StandardCopyOption.REPLACE_EXISTING); } If the directory doesn't exist, the .bak file won't exist so this if statement can be removed and replaced with a check to make sure the directory does exist.

Target:
public void cleanUpLdapFiles() throws Exception { File workingDirLDIF = new File(LDAP_DIRECTORY_LOCATION); if (workingDirLDIF.exists()) { Files.copy(Paths.get(workingDirLDIF + LDIF_LOCATION + ".bak"), Paths.get(workingDirLDIF + LDIF_LOCATION), StandardCopyOption.REPLACE_EXISTING); } }
Source:
public PublicKey getPublicKey(String kid, URL url) { if (!checkRemote(url)) { return null; } START Map<String, RSAPublicKey> urlKeys = keys.get(url); END if (urlKeys == null) { return null; } PublicKey pk = urlKeys.get(kid); if (pk == null) { log.warn("Unknown kid: " + kid); return null; } return pk; } Looks like this should be in a synchronized block. Perhaps the ```checkRemote``` method could be refactored slightly so it returns the key if found directly and null otherwise.

Target:
public PublicKey getPublicKey(String kid, URL url) { Map<String, RSAPublicKey> urlKeys = checkRemote(url); if (urlKeys == null) { return null; } PublicKey pk = urlKeys.get(kid); if (pk == null) { log.warn("Unknown kid: " + kid); return null; } return pk; }
Source:
public MappedRoleMapper() { this.reverseRoleMap = new LinkedHashMap<>(); START this.removeMapped = true; //not keeping any delegate roles as there is no way to avoid configuration conflicts END this.removeNonMapped = true; //this functionality is possible to recreate by manually combining role mappers this.keyRoles = Roles.NONE; } This should not be on fields as this is custom-role-mapper specific - not related when used as mapped-role-mapper in subsystem.

Target:
public MappedRoleMapper()
Source:
public boolean equals(Object other) { if (! (other instanceof MaskedPasswordAlgorithmSpec)) return false; MaskedPasswordAlgorithmSpec otherSpec = (MaskedPasswordAlgorithmSpec) other; return otherSpec == this || Arrays.equals(initialKeyMaterial, otherSpec.initialKeyMaterial) && iterationCount == otherSpec.iterationCount && Arrays.equals(salt, otherSpec.salt) START && initializationVector == otherSpec.initializationVector; END } This should use Arrays.equals()

Target:
public boolean equals(Object other) { if (! (other instanceof MaskedPasswordAlgorithmSpec)) return false; MaskedPasswordAlgorithmSpec otherSpec = (MaskedPasswordAlgorithmSpec) other; return otherSpec == this || Arrays.equals(initialKeyMaterial, otherSpec.initialKeyMaterial) && iterationCount == otherSpec.iterationCount && Arrays.equals(salt, otherSpec.salt) && Arrays.equals(initializationVector, otherSpec.initializationVector); }
Source:
public TimberClientHandler(TimberClient client, ClientBootstrap bootstrap) { // Do we need to call super()? Since we extend SimpleChannelUpstreamHandler // it is likely the answer is yes. START super(); END this.client = client; this.bootstrap = bootstrap; timer = new HashedWheelTimer(); } Redundant - super() is always called anyway.

Target:
public TimberClientHandler(TimberClient client, ClientBootstrap bootstrap) { this.client = client; this.bootstrap = bootstrap; timer = new HashedWheelTimer(); }
Source:
public void testEquals() throws Exception { START assertTrue( END new Coordinate(1,"foo", "bar", "baz").equals(new Coordinate(1, "foo", "bar", "baz")) ); } There exists an assertEquals().

Target:
public void testEquals() throws Exception { assertEquals( new Coordinate(1,"foo", "bar", "baz"), new Coordinate(1, "foo", "bar", "baz") ); }
Source:
private Properties loadStringProperties(String body) { Properties properties = new Properties(); try { properties.load(new StringReader(body)); } catch (IOException e) { e.printStackTrace(); } START return properties; END } Is this intended to return an empty Properties object even if an exception occurs?

Target:
private Properties loadStringProperties(String body) { Properties properties = new Properties(); try { properties.load(new StringReader(body)); } catch (IOException e) { // IOException will never occur here because we're loading directly from a String } return properties; }
Source:
public static String getGroupId(GroupApi groupApi) { for ( GroupState state : groupApi.listGroupStates() ) { Group g = groupApi.get(state.getId()); for ( ScalingPolicyResponse policy : g.getScalingPolicies() ) { if (policy.getName().equals(NAME)) return g.getId(); } } START throw new RuntimeException("Group not found"); END } [minor] IllegalArgException?

Target:
public static String getGroupId(GroupApi groupApi) { for ( GroupState state : groupApi.listGroupStates() ) { Group g = groupApi.get(state.getId()); for ( ScalingPolicyResponse policy : g.getScalingPolicies() ) { if (policy.getName().equals(NAME)) return g.getId(); } } throw new IllegalArgumentException("Group not found"); }
Source:
public static String getPolicyId(PolicyApi policyApi) { for ( ScalingPolicyResponse policy : policyApi.list() ) { if (policy.getName().equals(NAME)) return policy.getId(); } START throw new RuntimeException("Policy not found"); END } [minor] IllegalArgException?

Target:
public static String getPolicyId(PolicyApi policyApi) { for ( ScalingPolicyResponse policy : policyApi.list() ) { if (policy.getName().equals(NAME)) return policy.getId(); } throw new IllegalArgumentException("Policy not found"); }
Source:
public static void main(String[] args) { UploadDirectoryToCDN uploadDirToCDN = new UploadDirectoryToCDN(); try { START uploadDirToCDN.init(args); END uploadDirToCDN.uploadDirectory(args[2], args[3]); uploadDirToCDN.enableCdnContainer(args[3]); } catch (Exception e) { e.printStackTrace(); } finally { uploadDirToCDN.close(); } } Move this to the `UploadDirectoryToCDN` constructor and make the `storage` and `rackspace` variables `final`?

Target:
public static void main(String[] args) { UploadDirectoryToCDN uploadDirToCDN = new UploadDirectoryToCDN(args[0], args[1]); try { uploadDirToCDN.uploadDirectory(args[2], args[3]); uploadDirToCDN.enableCdnContainer(args[3]); } catch (Exception e) { e.printStackTrace(); } finally { uploadDirToCDN.close(); } }
Source:
public BlobDetail call() throws Exception { Blob blob = storage.blobBuilder(toBeUploadedBlobDetail.getRemoteBlobName()) .payload(toBeUploadedBlobDetail.getLocalFile()) START .contentType("") END .build(); String eTag = storage.putBlob(container, blob); BlobDetail uploadedBlobDetail = new BlobDetail( toBeUploadedBlobDetail.getRemoteBlobName(), toBeUploadedBlobDetail.getLocalFile(), eTag); return uploadedBlobDetail; } Hmm...will this allow all the files to render correctly? Don't we need to preserve content types?

Target:
public BlobDetail call() throws Exception { Blob blob = storage.blobBuilder(toBeUploadedBlobDetail.getRemoteBlobName()) .payload(toBeUploadedBlobDetail.getLocalFile()) .build(); String eTag = storage.putBlob(container, blob); BlobDetail uploadedBlobDetail = new BlobDetail( toBeUploadedBlobDetail.getRemoteBlobName(), toBeUploadedBlobDetail.getLocalFile(), eTag); return uploadedBlobDetail; }
Source:
private void generateFileList(File localDir, String remotePath, List<BlobDetail> blobDetails) { for (File localFile: localDir.listFiles()) { if (localFile.isFile()) { START String remoteBlobName = remotePath + localFile.getName(); END blobDetails.add(new BlobDetail(remoteBlobName, localFile)); } else { generateFileList(localFile, remotePath + localFile.getName() + "/", blobDetails); } } } Bit of a nit, but since you end up using this expression in both branches, pull it up before the `if`?

Target:
private void generateFileList(File localDir, String remotePath, List<BlobDetail> blobDetails) { for (File localFile: localDir.listFiles()) { String remoteBlobName = remotePath + localFile.getName(); if (localFile.isFile()) { blobDetails.add(new BlobDetail(remoteBlobName, localFile)); } else { generateFileList(localFile, remoteBlobName + "/", blobDetails); } } }
Source:
public static void main(String[] args) { CreateDatabase createDatabase = new CreateDatabase(); try { createDatabase.init(args); Instance instance = createDatabase.getInstance(); createDatabase.createDatabase(instance); START } END catch (Exception e) { e.printStackTrace(); } finally { createDatabase.close(); } } [style] `} catch {`? And same for `} finally {`? But not a big deal - leave this way if you prefer

Target:
public static void main(String[] args) throws IOException { CreateDatabase createDatabase = new CreateDatabase(); try { createDatabase.init(args); Instance instance = createDatabase.getInstance(); createDatabase.createDatabase(instance); } catch (Exception e) { e.printStackTrace(); } finally { createDatabase.close(); } }
Source:
public void setSize(int width, int height) { super.setSize(width, height); validate(); if (isDisplayable()) { scrollView(); START loadBackgroundImage(); END } } Loading background image every time map size changes e.g. on every unfold operation does not look like sensible, does it?

Target:
public void setSize(int width, int height) { super.setSize(width, height); validate(); if (isDisplayable()) { scrollView(); } }
Source:
public void actionPerformed(final ActionEvent e) { final Controller controller = Controller.getCurrentController(); final MapStyle mapStyle = controller.getModeController().getExtension(MapStyle.class); final MapModel model = controller.getMap(); START mapStyle.setProperty(model, MapStyle.RESOURCES_BACKGROUND_IMAGE, MapStyle.CLEAR_BACKGROUND_IMAGE); END } I like that you use an identifier here. However I would expect its value to be equal to null.

Target:
public void actionPerformed(final ActionEvent e) { final Controller controller = Controller.getCurrentController(); final MapStyle mapStyle = controller.getModeController().getExtension(MapStyle.class); final MapModel model = controller.getMap(); mapStyle.setProperty(model, MapStyle.RESOURCES_BACKGROUND_IMAGE, null); }
Source:
public static String toString(Values vals) { if(vals != null){ String output ="["; for(int i = 0 ; i < vals.size() ; i++){ Object actObj = vals.get(i); output += actObj.toString(); START if(i+1 != vals.size()) END output += ", "; else output +="]"; } return output; } else return "null"; } In this case, put the default in the else part. So you do not need negation.

Target:
public static String toString(Values vals) { if(vals != null){ String output ="["; for(int i = 0 ; i < vals.size() ; i++){ Object actObj = vals.get(i); output += actObj.toString(); if(i+1 == vals.size()) output += "]"; else output +=", "; } return output; } else return "null"; }
Source:
private ILaserTarget getTarget() { if (targetPos != null) { START return (ILaserTarget) world.getTileEntity(targetPos); END } return null; } Don't blindly cast -- check if the returned tile entity actually is an ILaserTarget (it might change before you get updated)

Target:
private ILaserTarget getTarget() { if (targetPos != null) { if (world.getTileEntity(targetPos) instanceof ILaserTarget) { return (ILaserTarget) world.getTileEntity(targetPos); } } return null; }
Source:
public void update() { smoothedTank.tick(getWorld()); if (tank.getFluidAmount() != fluidAmountPrev) { fluidAmountPrev = tank.getFluidAmount(); comparatorLevel = MathUtil.scaledClamp(tank.getFluidAmount(), tank.getCapacity(), 15); markDirty(); START } END } Perhaps compare with the previous comparator level rather than the previous amount of fluid?

Target:
public void update() { smoothedTank.tick(getWorld()); if (tank.getFluidAmount() != fluidAmountPrev) { fluidAmountPrev = tank.getFluidAmount(); markDirty(); } }
Source:
protected boolean canReplaceBiome(int biomeId) { Biome biome = Biome.getBiomeForId(biomeId); if (biome == null) { if (BCLib.DEV) //don't spam outside of dev, it's way to noisy START BCLog.logger.warn("Couldn't find a biome with an ID of " + biomeId); END return false; } return BiomeDictionary.getTypes(biome).containsAll(REQUIRED_TYPES); } Just removing the log would be fine actually, we don't have any use for it in dev

Target:
protected boolean canReplaceBiome(int biomeId) { Biome biome = Biome.getBiomeForId(biomeId); if (biome == null) { return false; } return BiomeDictionary.getTypes(biome).containsAll(REQUIRED_TYPES); }
Source:
protected void drawItemStackAt(ItemStack stack, int x, int y) { RenderHelper.enableGUIStandardItemLighting(); START RenderHelper.disableStandardItemLighting(); END itemRender.renderItemAndEffectIntoGUI(mc.thePlayer, stack, x, y); itemRender.renderItemOverlayIntoGUI(mc.fontRendererObj, stack, x, y, null); } Why do you need to enable and then disable? In theory you can just call disable and then it should work (provided you have no direct GL11 calls anywhere)

Target:
protected void drawItemStackAt(ItemStack stack, int x, int y) { RenderHelper.enableGUIStandardItemLighting(); itemRender.renderItemAndEffectIntoGUI(mc.thePlayer, stack, x, y); itemRender.renderItemOverlayIntoGUI(mc.fontRendererObj, stack, x, y, null); RenderHelper.disableStandardItemLighting(); }
Source:
public AxisAlignedBB getRenderBoundingBox() { START return box == null ? super.getRenderBoundingBox() : BoundingBoxUtil.makeFrom(getPos(), box); END } BoundingBoxUtil checks to see if box is null, and if it is it just uses "pos". So you don't need the null check, and can replace this with ``` java public AxisAlignedBB getRenderBoundingBox() { return BoundingBoxUtil.makeFrom(getPos(), box); } ``` and it won't ever throw an NPE.

Target:
public AxisAlignedBB getRenderBoundingBox() { return BoundingBoxUtil.makeFrom(getPos(), box); }
Source:
protected final void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { drawForegroundLayer(); GlStateManager.translate(-guiLeft, -guiTop, 0); mouse.setMousePosition(mouseX, mouseY); START END for (IGuiElement element : guiElements) { element.drawForeground(); } tooltips.drawForeground(); GlStateManager.translate(guiLeft, guiTop, 0); } Swapping these around breaks all other GUI's.

Target:
protected final void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { GlStateManager.translate(-guiLeft, -guiTop, 0); mouse.setMousePosition(mouseX, mouseY); drawForegroundLayer(); for (IGuiElement element : guiElements) { element.drawForeground(); } tooltips.drawForeground(); GlStateManager.translate(guiLeft, guiTop, 0); }
Source:
public void clear() { for (DimensionProperty p : properties) { START if(p!=null) END p.clear(); } properties.clear(); } Need

Target:
public void clear() { for (DimensionProperty p : properties) { if (p != null) { p.clear(); } } properties.clear(); }
Source:
private boolean isQuarriableBlock(int bx, int by, int bz) { Block block = worldObj.getBlock(bx, by, bz); START return !BlockUtil.canChangeBlock(block, worldObj, bx, by, bz) || END BuildCraftAPI.isSoftBlock(block, worldObj, bx, by, bz) || (block.getBlockHardness(worldObj, bx, by, bz) > MAX_BREAK_HARDNESS); } Only I seen in this lines a logical rubbish?

Target:
private boolean isQuarriableBlock(int bx, int by, int bz) { Block block = worldObj.getBlock(bx, by, bz); return BlockUtil.canChangeBlock(block, worldObj, bx, by, bz) && !BuildCraftAPI.isSoftBlock(block, worldObj, bx, by, bz) && (block.getBlockHardness(worldObj, bx, by, bz) < MAX_BREAK_HARDNESS); }
Source:
private void setTarget(int x, int y, int z) { this.targetX = x; this.targetY = y; this.targetZ = z; Block b = worldObj.getBlock(x, y - 1, z); this.nextDigRequiredEnergy = DIG_BASE_REQUIRED_ENERGY + START (b.getBlockHardness(null, 0, 0, 0) * DIG_HARDNESS_ENERGY_MULTIPLIER); END } Terrible idea. Pass in the proper parameters, since you have them.

Target:
private void setTarget(int x, int y, int z) { this.targetX = x; this.targetY = y; this.targetZ = z; Block b = worldObj.getBlock(x, y - 1, z); this.nextDigRequiredEnergy = DIG_BASE_REQUIRED_ENERGY + (b.getBlockHardness(worldObj, x, y - 1, z) * DIG_HARDNESS_ENERGY_MULTIPLIER); }
Source:
public Supplier<ValueType> getPipelined(final Object key, final Pipeline pipeline) { final String redisKey = generateRedisKey(turnObjectIntoKeyType(key)); START final Response<String> valAsString; valAsString = pipeline.get(redisKey); END pipeline.expire(redisKey, valueTtl); return new ValueSupplier(valAsString); } Is there a reason this can't be one line? Genuinely asking

Target:
public Supplier<ValueType> getPipelined(final Object key, final Pipeline pipeline) { final String redisKey = generateRedisKey(turnObjectIntoKeyType(key)); final Response<String> valAsString = pipeline.get(redisKey); pipeline.expire(redisKey, valueTtl); return new ValueSupplier(valAsString); }
Source:
public List getLoggerNameList() { List<String> copy = new ArrayList<String>(); START synchronized (loggers) { END copy.addAll(loggers.keySet()); } return copy; } Same as above. I think something like ``` java return new ArrayList<String>(loggers.keySet()); ``` is enough

Target:
public List getLoggerNameList() { return new ArrayList<String>(loggers.keySet()); }
Source:
public Iterable<SubstitutableLogger> getLoggers() { START return loggers.values(); END } Maybe return a copy? ``` java return new ArrayList<SubstitutableLogger>(loggers.values()); ```

Target:
public List<SubstitutableLogger> getLoggers() { return new ArrayList<SubstitutableLogger>(loggers.values()); }
Source:
public MapExpressionMethods() { START context = new StandardEvaluationContext(); END context.addMethodResolver(new PartitionKeyMethodResolver()); context.addPropertyAccessor(new MapPartitionKeyPropertyAccessor()); } I think we need to get reference to an evaluation context that already has even other functions/methods registered with it - at least in the XD context as #jsonPath is registered in SI by default now. I could see one wanting to base a directory name based on the value returned by jsonPath. Perhaps there needs to be an overloaded ctor so that in an XD context, we can contribute to the 'standard/shared' evaluation context.

Target:
public MapExpressionMethods() { this(null); }
Source:
private void tearDown() { try { processDestroyer.clean(); tmpDir.dispose(); } catch (IOException e) { START throw new UncheckedIOException(e); END } catch (InterruptedException e) { e.printStackTrace(System.err); } } Test methods can more simply just `throws Exception`.

Target:
private void tearDown() throws IOException { try { processDestroyer.clean(); } catch (InterruptedException e) { e.printStackTrace(System.err); } }
Source:
public static String formatStopDistance(float distance) { int distanceSmoots = (int) (distance * TourUtils.METERS_TO_SMOOTS); float distanceMiles = distance * TourUtils.METERS_TO_MILES; String milesString = String.valueOf(distanceMiles).substring(0, 3); START return distanceSmoots + " miles (" + milesString + " smoots) "; END } I think you have these variables mixed up, should be switched

Target:
public static String formatStopDistance(float distance) { int distanceSmoots = (int) (distance * TourUtils.METERS_TO_SMOOTS); float distanceMiles = distance * TourUtils.METERS_TO_MILES; String milesString = String.valueOf(distanceMiles).substring(0, 3); return milesString + " miles (" + distanceSmoots + " smoots) "; }
Source:
public void setMainLoopActionBarTitle(int mainLoopStopNum, int mainLoopStopsSize) { START setTitle(getResources().getString(R.string.stop_nav_main_loop) + " " + mainLoopStopNum + " of " + mainLoopStopsSize); END } You can pass values into a string resource to avoid this. See the "Formatting strings" section of http://developer.android.com/guide/topics/resources/string-resource.html

Target:
public void setMainLoopActionBarTitle(int mainLoopStopNum, int mainLoopStopsSize) { setTitle(String.format(getResources().getString(R.string.stop_nav_main_loop, mainLoopStopNum, mainLoopStopsSize))); }
Source:
public void onLoadFinished(Loader<Cursor> loader, Cursor data) { data.moveToFirst(); route.buildFromCursor(data, DBAdapter.getInstance()); START data.close(); END stops = route.getStops(); int currentStop = predictionViewPager.getCurrentItem(); stopViewPagerAdapter.updatePredictions(currentStop, stops.get(currentStop).getPredictions()); updateMapItems((ArrayList) route.getVehicles(), false); } Don't need to call here either

Target:
public void onLoadFinished(Loader<Cursor> loader, Cursor data) { data.moveToFirst(); route.buildFromCursor(data, DBAdapter.getInstance()); stops = route.getStops(); int currentStop = predictionViewPager.getCurrentItem(); stopViewPagerAdapter.updatePredictions(currentStop, stops.get(currentStop).getPredictions()); updateMapItems((ArrayList) route.getVehicles(), false); }
Source:
START public Contact(String start_first_name, String start_last_name, String start_phone_number, String start_second_phone) { END if (start_first_name == null){ start_first_name = ""; } if (start_last_name == null){ start_last_name = ""; } if (start_phone_number == null){ start_phone_number = ""; } if (start_second_phone == null){ start_second_phone = ""; } first_name = start_first_name; last_name = start_last_name; phone_number = start_phone_number; second_phone = start_second_phone; } I thought we were only going to allow null args for lastName and secondPhone? We shouldn't be able to construct a firstName or phoneNumber with null -- I think we should be throwing a RuntimeException() in those if statements instead of changing it to "".

Target:
public Contact(String start_first_name, String start_last_name, String start_phone_number, String start_second_phone) { if (start_first_name == null || start_first_name.equals("")){ throw new IllegalArgumentException(); } if (start_last_name == null){ start_last_name = ""; } if (start_phone_number == null || start_phone_number.length() < 3){ throw new IllegalArgumentException(); } if (start_second_phone == null){ start_second_phone = ""; } first_name = start_first_name; last_name = start_last_name; phone_number = start_phone_number; second_phone = start_second_phone; }
Source:
START public static void reLogin() throws UnknownHostException, ClassNotFoundException, SQLException{ END Login login = new Login(); login.setVisible(true); System.out.println("Got HEre"); } Why do you make this method chain throw exceptions up the stack when you just bury them in the end? If you never intend to do any handling of these exceptions, can you just handle them inside of the reLogin() method so the calls are cleaner?

Target:
public static void reLogin(){ Login login = new Login(); login.setVisible(true); }
Source:
public double get(int i, int j) { START ensureIndexesAreInBounds(i, j); END return getOrElse(i, j, 0.0); } Yeah. I missed the double check in sparse vector. Please, remove that too. This is a performance penalty doing this check two times.

Target:
public double get(int i, int j) { return getOrElse(i, j, 0.0); }
Source:
public double max() { double max = Double.NEGATIVE_INFINITY; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { START if (get(i, j) > max) { END max = get(i, j); } } } return max; } How about do not call get twice. It might be expensive for sparse entries. Like this: ``` java double value = get(i, j); if (value > max) { max = value; } ```

Target:
public double max() { double max = Double.NEGATIVE_INFINITY; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { double value = get(i, j); if (value > max) { max = value; } } } return max; }
Source:
public void eachNonZeroInColumn(int j, MatrixProcedure procedure) { START int k = columnPointers[j], i = k; END while (i < columnPointers[j + 1]) { procedure.apply(rowIndices[i], j, values[i]); i++; } } So, now it looks correct, but I still don't see the reason of having this `k` variable. For what it is? And I would prefer having a `for` loop like (equivalent to your `while` loop but much clear): ``` java for (int i = columnPointers[j]; i < columnPointers[j + 1]; i++) { procedure.apply(rowIndices[i], j, values[i]); } ```

Target:
public void eachNonZeroInColumn(int j, MatrixProcedure procedure) { for (int i = columnPointers[j]; i < columnPointers[j + 1]; i++) { procedure.apply(rowIndices[i], j, values[i]); } }
Source:
START public void eachNonZero(VectorProcedure procedure) { END for (int i = 0; i < cardinality; i++) { if (Math.abs(values[i])>Vectors.EPS) procedure.apply(indices[i], values[i]); } } It is not necessary to check value in compressed vector on zero. It is guaranteed that only non-zero values are store. Which means, that we only need to rename `each` to `eachNonZero` in `CompressedVector` class. Please also make sure that `MatrixMarketStream` uses the proper iteration method. TIP: It should be `eachNonZero`.

Target:
public void eachNonZero(VectorProcedure procedure) { for (int i = 0; i < cardinality; i++) { procedure.apply(indices[i], values[i]); } }
Source:
START public Vector shuffle(){ END return self.shuffle(); } Missed space before `{`.

Target:
public Vector shuffle() { return self.shuffle(factory); }
Source:
public void undoQuote() { PostgreSQLDbSupport dbSupport = new PostgreSQLDbSupport(null); assertEquals("abc", dbSupport.unQuote("\"abc\"")); START assertEquals("abc", dbSupport.unQuote("abc\"")); END assertEquals("abc", dbSupport.unQuote("\"abc")); assertEquals("a\"b\"c", dbSupport.unQuote("a\"b\"c")); assertEquals("a\"b\"c", dbSupport.unQuote("\"a\"b\"c")); } Why is this and all other cases from line 34 to 37 necessary?

Target:
public void undoQuote() { PostgreSQLDbSupport dbSupport = new PostgreSQLDbSupport(null); assertEquals("abc", dbSupport.unQuote("\"abc\"")); assertEquals("abc", dbSupport.unQuote("abc")); }
Source:
START public String unQuote(final String quoted) { END if (quoted == null || quoted.length() <= 2) { return quoted; } String result = quoted.startsWith("\"") ? quoted.substring(1) : quoted; return result.endsWith("\"") ? result.substring(0, result.length() - 1) : result; } Can you make this package-private and add JavaDoc?

Target:
String unQuote(final String quoted) { if (quoted == null || quoted.length() <= 2) { return quoted; } String result = quoted.startsWith("\"") ? quoted.substring(1) : quoted; return result.endsWith("\"") ? result.substring(0, result.length() - 1) : result; }
Source:
private static <ViewModelType extends ViewModel> Method getInitializeMethod(ViewModelType viewModel) { for (Method method : viewModel.getClass().getDeclaredMethods()) { if(method.isAnnotationPresent(Initialize.class)) { START method.setAccessible(true); END return method; } } return null; } The refactoring looks good.

Target:
private static <ViewModelType extends ViewModel> Method getInitializeMethod(ViewModelType viewModel) { for (Method method : viewModel.getClass().getDeclaredMethods()) { if(method.isAnnotationPresent(Initialize.class)) { return method; } } return null; }
Source:
private static GoAssignmentStatement getValidAssignmentParent(@Nullable PsiElement element) { return ObjectUtils.nullizeByCondition(PsiTreeUtil.getNonStrictParentOfType(element, GoAssignmentStatement.class), START assignment -> assignment == null || END !assignment.isValid() || !isAssignmentEqualsSized(assignment)); } I think it's better: ``` GoAssignmentStatement assignment = PsiTreeUtil.getNonStrictParentOfType(element, GoAssignmentStatement.class); return assignment != null && assignment.isValid() && isAssignmentEqualsSized(assignment) ? assignment : null; ``` Please, use lambdas if it give some gain in readability

Target:
private static GoAssignmentStatement getValidAssignmentParent(@Nullable PsiElement element) { GoAssignmentStatement assignment = PsiTreeUtil.getNonStrictParentOfType(element, GoAssignmentStatement.class); return assignment != null && assignment.isValid() && isAssignmentEqualsSized(assignment) ? assignment : null; }
Source:
protected void checkFile(@NotNull GoFile file, @NotNull ProblemsHolder problemsHolder) { super.checkFile(file, problemsHolder); START ProgressManager.checkCanceled(); END if (!GoTestFinder.isTestFile(file)) return; for (GoImportSpec importSpec : file.getImports()) { if (importSpec.isCImport()) { problemsHolder.registerProblem(importSpec, "Usage of cgo in tests is not supported.", new GoDeleteImportQuickFix()); } } } checkCancelled is called for every element via `com.intellij.psi.PsiElementVisitor#visitElement`, so it doesn't make sense to invoke it just after `super.visit*`.

Target:
protected void checkFile(@NotNull GoFile file, @NotNull ProblemsHolder problemsHolder) { if (!GoTestFinder.isTestFile(file)) return; for (GoImportSpec importSpec : file.getImports()) { if (importSpec.isCImport()) { problemsHolder.registerProblem(importSpec, "Usage of cgo in tests is not supported.", new GoDeleteImportQuickFix()); } } }
Source:
public void check(@Nullable GoSignature o, @NotNull ProblemsHolder holder) { START super.check(o, holder); END if (o == null) return; Set<String> names = getParamNames(o); GoResult result = o.getResult(); if (result == null) return; GoParameters parameters = result.getParameters(); if (parameters == null) return; checkParameters(holder, parameters, names); } are you sure? looks like o.getParamters will be checked twice and also they will be checked even if `GoDuplicateArgumentInspection` is disabled.

Target:
public void check(@Nullable GoSignature o, @NotNull ProblemsHolder holder) { if (o == null) return; Set<String> names = getParamNames(o); GoResult result = o.getResult(); if (result == null) return; GoParameters parameters = result.getParameters(); if (parameters == null) return; checkParameters(holder, parameters, names); }
Source:
protected void checkFile(@NotNull GoFile file, @NotNull ProblemsHolder problemsHolder) { START super.checkFile(file, problemsHolder); END if (!GoTestFinder.isTestFile(file)) return; for (GoImportSpec importSpec : file.getImports()) { if (importSpec.isCImport()) { problemsHolder.registerProblem(importSpec, "Usage of cgo in tests is not supported.", new GoDeleteImportQuickFix()); } } } `super.checkFile` does nothing

Target:
protected void checkFile(@NotNull GoFile file, @NotNull ProblemsHolder problemsHolder) { if (!GoTestFinder.isTestFile(file)) return; for (GoImportSpec importSpec : file.getImports()) { if (importSpec.isCImport()) { problemsHolder.registerProblem(importSpec, "Usage of cgo in tests is not supported.", new GoDeleteImportQuickFix()); } } }
Source:
public static GoFunctionDeclaration createFunctionDeclarationFromText(@NotNull Project project, @NotNull String name, @NotNull String text, @Nullable String expectedType) { START if (expectedType == null) { END expectedType = ""; } else { expectedType += " "; } GoFile file = createFileFromText(project, "package a; func " + name + "(" + text + ") " + expectedType + "{\n}"); return ContainerUtil.getFirstItem(file.getFunctions()); } use ternary operator

Target:
public static GoFunctionDeclaration createFunctionDeclarationFromText(@NotNull Project project, @NotNull String name, @NotNull String text, @Nullable String expectedType) { expectedType = expectedType == null ? "" : expectedType + " "; GoFile file = createFileFromText(project, "package a; func " + name + "(" + text + ") " + expectedType + "{\n}"); return ContainerUtil.getFirstItem(file.getFunctions()); }
Source:
protected GoVisitor buildGoVisitor(@NotNull final ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitDeferStatement(@NotNull GoDeferStatement o) { PsiElement parent = PsiTreeUtil .getParentOfType(o, GoForStatement.class, START GoFunctionLit.class, GoFunctionDeclaration.class, GoMethodDeclaration.class, GoFile.class); END if (parent instanceof GoForStatement) { holder.registerProblem(o, "Possible resource leak, \"defer\" is called in a for loop.", ProblemHighlightType.WEAK_WARNING); } } }; } Why do you need (GoFunctionDeclaration.class, GoMethodDeclaration.class, GoFile.class)? Is this some optimization? If so then I think it isn't needed.

Target:
protected GoVisitor buildGoVisitor(@NotNull final ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitDeferStatement(@NotNull GoDeferStatement o) { PsiElement parent = PsiTreeUtil .getParentOfType(o, GoForStatement.class, GoFunctionLit.class); if (parent instanceof GoForStatement) { holder.registerProblem(o, "Possible resource leak, \"defer\" is called in a for loop.", ProblemHighlightType.WEAK_WARNING); } } }; }
Source:
public String getQuickNavigateInfo(PsiElement element, PsiElement originalElement) { if (element instanceof GoNamedElement) { String result = getSignature(element); START if (result != "") { END return result; } } return super.getQuickNavigateInfo(element, originalElement); } 1. do not use != for comparing 2. StringUtil#nullize

Target:
public String getQuickNavigateInfo(PsiElement element, PsiElement originalElement) { if (element instanceof GoNamedElement) { String result = getSignature(element); if (!result.isEmpty()) { return result; } } return super.getQuickNavigateInfo(element, originalElement); }
Source:
public static boolean isTestPackageName(@Nullable String packageName) { START return packageName != null && packageName.length() > GoConstants.TEST_SUFFIX.length() && packageName.endsWith(GoConstants.TEST_SUFFIX); END } length checking looks redundant

Target:
public static boolean isTestPackageName(@Nullable String packageName) { return packageName != null && packageName.endsWith(GoConstants.TEST_SUFFIX); }
Source:
public FormattingModel createModel(@NotNull PsiElement element, @NotNull CodeStyleSettings settings) { // TODO decide if this is a good thing to do or not. // Given the go docs and the community enforce the rules for tabs // The plugin should try and emulate the gofmt behavior, which replaces spaces with tabs for idents // For more detail see: http://golang.org/doc/effective_go.html#formatting START if (settings.getIndentOptions() != null) { END settings.getIndentOptions().USE_TAB_CHARACTER = true; settings.getIndentOptions().SMART_TABS = false; } Block block = new GoFormattingBlock(element.getNode(), null, Indent.getNoneIndent(), null, settings, createSpacingBuilder(settings)); return FormattingModelProvider.createFormattingModelForPsiFile(element.getContainingFile(), block, settings); } GoLanguageCodeStyleSettingsProvider should be used for setting default values

Target:
public FormattingModel createModel(@NotNull PsiElement element, @NotNull CodeStyleSettings settings) { Block block = new GoFormattingBlock(element.getNode(), null, Indent.getNoneIndent(), null, settings, createSpacingBuilder(settings)); return FormattingModelProvider.createFormattingModelForPsiFile(element.getContainingFile(), block, settings); }
Source:
public static void broadcast(Set<Team> teams, String msg) { START Iterator<Team> it = teams.iterator(); END while(it.hasNext()) { sendMsg(it.next(), msg); } } einfacher: for(Team t : teams){...

Target:
public static void broadcast(Set<Team> teams, String msg) { for(Team x : teams) { sendMsg(x, msg); } }
Source:
public void testValidIsNotHonoredValidateValue() { Validator validator = TestUtil.getValidatorUnderTest(); Customer customer = new Customer(); Order order = new Order(); START customer.addOrder( order ); END Set<ConstraintViolation<Customer>> constraintViolations = validator.validateValue( Customer.class, "orders", Collections.singleton(order) ); assertNumberOfViolations( constraintViolations, 0 ); } Given this is testing `validateValue()`, the `customer` instance could be removed altogether.

Target:
public void testValidIsNotHonoredValidateValue() { Validator validator = TestUtil.getValidatorUnderTest(); Order order = new Order(); Set<ConstraintViolation<Customer>> constraintViolations = validator.validateValue( Customer.class, "orders", Collections.singleton(order) ); assertNumberOfViolations( constraintViolations, 0 ); }
Source:
public void parallelValueExtractorDefinitionsCausesException() { Validator validator = Validation.byDefaultProvider() .configure() START .addValueExtractor( new IWrapper21ValueExtractor0() ) END .addValueExtractor( new IWrapper211ValueExtractor0() ) .addValueExtractor( new IWrapper212ValueExtractor0() ) .addValueExtractor( new IWrapper22ValueExtractor0() ) .addValueExtractor( new IWrapper221ValueExtractor0() ) .addValueExtractor( new Wrapper2ValueExtractor1() ) .buildValidatorFactory() .getValidator(); validator.validate( new CascadingEntity2( null ) ); } Are all of them needed? Seems like two extractors would be enough to cause this situation?

Target:
public void parallelValueExtractorDefinitionsCausesException() { Validator validator = Validation.byDefaultProvider() .configure() .addValueExtractor( new IWrapper211ValueExtractor0() ) .addValueExtractor( new IWrapper212ValueExtractor0() ) .addValueExtractor( new Wrapper2ValueExtractor1() ) .buildValidatorFactory() .getValidator(); validator.validate( new CascadingEntity2( null ) ); }
Source:
START public Optional<@NotNull @NotBlank String> returnStringOptional() { END return stringOptional; } An optional of not null is a bit painful. Use another constraint perhaps? Do we have one test on the payload business btw. (applying it to the wrapper)?

Target:
public Optional<@NotBlank String> returnStringOptional() { return stringOptional; }
Source:
START public void testAllComposingConstraintsMustBeApplicableToAnnotatedType() { END validator.validate( new Shoe( 41 ) ); fail( "Shoe defines @NotEmpty on an int. Validation should have failed." ); } For the record, there is actually one benefit of the try/catch approach compared to _expectedExceptions_ . Using _expectedExceptions_ makes the test shorter, but also harder to debug for a developer, since I can for example not set a breakpoint in the catch clause to inspect the exception. It is also less explicit. Also the explicit fail() gives additional information.

Target:
public void testAllComposingConstraintsMustBeApplicableToAnnotatedType() { validator.validate( new Shoe( 41 ) ); }
Source:
public void testOverriddenAttributesMustMatchInType() { validator.validate( new DummyEntityWithZipCode( "foobar" ) ); START fail( "Wrong attribute override in composite constraint. An Exception should have been thrown." ); END } I find the fail w/o the try/catch misleading. IMO it is either try/catch or just _ expectedExceptions _

Target:
public void testOverriddenAttributesMustMatchInType() { validator.validate( new DummyEntityWithZipCode( "foobar" ) ); }
Source:
protected PopupPresenter() { START this(null); END } Please don't use null here. Just pass "" and make stateKey always concatenate.

Target:
protected PopupPresenter() { this(""); }
Source:
public boolean isType(TileEntity tile, EnumFacing dir) { if (tile instanceof IGridHost && tile.hasCapability(LPStorageMonitorableAccessor.STORAGE_MONITORABLE_ACCESSOR_CAPABILITY, dir)) { START IGridNode tempNode = ((IGridHost) tile).getGridNode(AEPartLocation.fromFacing(dir)); //for some reason when AE loads (5 ticks) this is null END if (tempNode == null) //should not be a problem because interfaces are still treated like IInvertoryHandler return false; return true; } return false; } replace with `return ((IGridHost) tile).getGridNode(AEPartLocation.fromFacing(dir)) != null;`

Target:
public boolean isType(TileEntity tile, EnumFacing dir) { if (tile instanceof IGridHost && tile.hasCapability(LPStorageMonitorableAccessor.STORAGE_MONITORABLE_ACCESSOR_CAPABILITY, dir)) { return ((IGridHost) tile).getGridNode(AEPartLocation.fromFacing(dir)) != null; } return false; }
Source:
public int getSizeInventory() { if (cached == null) { initCache(); } START if(cached.size() == 0) END return 1; return cached.size(); } spacing, code style

Target:
public int getSizeInventory() { if (cached == null) { initCache(); } if(cached.size() == 0) { return 1; } return cached.size(); }
Source:
public boolean isType(TileEntity tile, EnumFacing dir) { START if(tile instanceof IGridHost && tile.hasCapability(LPStorageMonitorableAccessor.STORAGE_MONITORABLE_ACCESSOR_CAPABILITY, dir)) { END return true; } return false; } Formatting

Target:
public boolean isType(TileEntity tile, EnumFacing dir) { return tile instanceof IGridHost && tile.hasCapability(LPStorageMonitorableAccessor.STORAGE_MONITORABLE_ACCESSOR_CAPABILITY, dir); }
Source:
public boolean hasCapability(Capability<?> capability, @Nullable EnumFacing facing) { if (capability == CapabilityEnergy.ENERGY) { return true; } START if (capability != null && (capability == MJ_CONN || capability == MJ_RECV)) { END return true; } return super.hasCapability(capability, facing); } you don't need the check for null here

Target:
public boolean hasCapability(Capability<?> capability, @Nullable EnumFacing facing) { if (capability == CapabilityEnergy.ENERGY) { return true; } if (capability == MJ_CONN || capability == MJ_RECV) { return true; } return super.hasCapability(capability, facing); }
Source:
public <T> T getCapability(Capability<T> capability, @Nullable EnumFacing facing) { START if (capability == CapabilityEnergy.ENERGY) { END return (T) energyInterface; } if (capability != null && (capability == MJ_CONN || capability == MJ_RECV)) { return (T) mjReceiver; } return super.getCapability(capability, facing); } Why is it bad to check if null equals to any of these fields?

Target:
public <T> T getCapability(Capability<T> capability, @Nullable EnumFacing facing) { if (capability == CapabilityEnergy.ENERGY) { return (T) energyInterface; } if (capability == MJ_CONN || capability == MJ_RECV) { return (T) mjReceiver; } return super.getCapability(capability, facing); }
Source:
private char getChar() { int rndNum = baseProducer.randomBetween(0, 35); START if (rndNum < 10) END return (char)(49 + rndNum); else return (char)(65 + rndNum - 10); } Plase add `{}` to improve readability.

Target:
private char getChar() { int rndNum = baseProducer.randomBetween(0, 35); if (rndNum < 10) { return (char) (49 + rndNum); } else { return (char) (65 + rndNum - 10); } }
Source:
public static CSPDirective fromValue(String value) { if (Strings.isEmpty(value)) START return null; END for (int i = 0; i < values().length; i++) { if (value.equals(values()[i].getValue())) return values()[i]; } return null; } missing curly braces? (also in some other places)

Target:
public static CSPDirective fromValue(String value) { if (Strings.isEmpty(value)) { return null; } for (int i = 0; i < values().length; i++) { if (value.equals(values()[i].getValue())) { return values()[i]; } } return null; }
Source:
public static void writeOpenTag(final Response response, IValueMap attributes) { response.write(INLINE_OPEN_TAG_START); if (attributes != null) { START response.write(" "+attributes.toString()); END } response.write(">\n"); } `toString()` call is redundant here, missing white-spaces

Target:
public static void writeOpenTag(final Response response, IValueMap attributes) { response.write(INLINE_OPEN_TAG_START); if (attributes != null) { response.write(" " + attributes); } response.write(">\n"); }
Source:
public OnLoadHeaderItem setNonce(String nonce) { START Args.notNull(nonce, "nonce"); END this.nonce = nonce; return this; } nonEmpty

Target:
public OnLoadHeaderItem setNonce(String nonce) { this.nonce = nonce; return this; }
Source:
public void executeBehavior(final Class<?> testClass, final AbstractAjaxBehavior behavior, final String filename) throws Exception { START assert(behavior != null); END log.info("=== " + testClass.getName() + " : " + behavior.toString() + " ==="); executeBehavior(behavior); assertResultPage(testClass, filename); } This looks wrong.

Target:
public void executeBehavior(final Class<?> testClass, final AbstractAjaxBehavior behavior, final String filename) throws Exception { assertNotNull(behavior); log.info("=== " + testClass.getName() + " : " + behavior.toString() + " ==="); executeBehavior(behavior); assertResultPage(testClass, filename); }
Source:
public void deferred() throws Exception { START tester.getApplication().setHeaderResponseDecorator(new IHeaderResponseDecorator() END { @Override public IHeaderResponse decorate(IHeaderResponse response) { return new ResourceAggregator(new JavaScriptDeferHeaderResponse(response)); } }); executeTest(DeferredPage.class, "DeferredPageExpected.html"); } this can be simplified to be ``` tester.getApplication().setHeaderResponseDecorator(response -> new ResourceAggregator(new JavaScriptDeferHeaderResponse(response))); ```

Target:
public void deferred() throws Exception { tester.getApplication().setHeaderResponseDecorator(response -> new ResourceAggregator(new JavaScriptDeferHeaderResponse(response))); executeTest(DeferredPage.class, "DeferredPageExpected.html"); }
Source:
public void setXValues(String... values) { if (xValues == null) { xValues = new ArrayList<>(); } START xValues.clear(); END xValues.addAll(Arrays.asList(values)); } `.clear()` could be in an `else` clause

Target:
public void setXValues(String... values) { if (xValues == null) { xValues = new ArrayList<>(); } else { xValues.clear(); } xValues.addAll(Arrays.asList(values)); }
Source:
public void setSizes(String... sizes) { if (this.sizes == null) { this.sizes = new ArrayList<>(); } START this.sizes.clear(); END this.sizes.addAll(Arrays.asList(sizes)); } could be in `else`

Target:
public void setSizes(String... sizes) { if (this.sizes == null) { this.sizes = new ArrayList<>(); } else { this.sizes.clear(); } this.sizes.addAll(Arrays.asList(sizes)); }
Source:
protected void buildSrcAttribute(final ComponentTag tag, IModel<?> srcModel) { START if (srcModel != null) END { tag.put("src", srcModel.getObject().toString()); } } The first statement remains valid :) `srcModel.getObject()` is still not tested for nullity...

Target:
protected void buildSrcAttribute(final ComponentTag tag, IModel<?> srcModel) { tag.put("src", String.valueOf(srcModel.getObject())); }
Source:
public FileSystemResourceReference(String name, Path path) { START super(Args.notNull(name, "name")); END Args.notNull(path, "path"); this.path = path; } org.apache.wicket.request.resource.ResourceReference#ResourceReference(java.lang.Class<?>, java.lang.String, java.util.Locale, java.lang.String, java.lang.String) cares about the non-null name. No need to check it here too.

Target:
public FileSystemResourceReference(String name, Path path) { super(name); Args.notNull(path, "path"); this.path = path; }