auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testCreate() throws StripeException { Map<String, Object> params = new HashMap<String, Object>(); params.put("amount", 100); params.put("currency", "usd"); params.put("destination", "acct_123"); START Transfer transfer = Transfer.create(params); END assertNotNull(transfer); verifyRequest( APIResource.RequestMethod.POST, "/v1/transfers", params ); } should be named `resource`

Target:
public void testCreate() throws StripeException { final Map<String, Object> params = new HashMap<String, Object>(); params.put("amount", 100); params.put("currency", "usd"); params.put("destination", "acct_123"); final Transfer transfer = Transfer.create(params); assertNotNull(transfer); verifyRequest( APIResource.RequestMethod.POST, "/v1/transfers", params ); }
Source:
START private boolean isGlobalFailure(ITestResult result) { END ITestNGMethod m = result.getMethod(); return m.isBeforeTestConfiguration() || m.isBeforeSuiteConfiguration(); } static here and later

Target:
private static boolean isGlobalFailure(ITestResult result) { ITestNGMethod m = result.getMethod(); return m.isBeforeTestConfiguration() || m.isBeforeSuiteConfiguration(); }
Source:
private static void validateEmail(String value) throws WSSecurityException { START final EmailValidator validator = EmailValidator.getInstance(); END if (!validator.isValid(value)) { throw new WSSecurityException(ErrorCode.FAILURE, "Not a valid email address."); } } no need to create a variable here. Use EmailValidator.getInstance().isvalid()

Target:
private static void validateEmail(String value) throws WSSecurityException { if (!EmailValidator.getInstance().isValid(value)) { throw new WSSecurityException(ErrorCode.FAILURE, "Not a valid email address."); } }
Source:
private void addAll(Object array) throws JSONException { if (array.getClass().isArray()) { int length = Array.getLength(array); START this.myArrayList.ensureCapacity(length); END for (int i = 0; i < length; i += 1) { this.put(JSONObject.wrap(Array.get(array, i))); } } else { throw new JSONException( "JSONArray initial value should be a string or collection or array."); } } change to ```java this.myArrayList.ensureCapacity(this.myArrayList.size() + length); ```

Target:
private void addAll(Object array) throws JSONException { if (array.getClass().isArray()) { int length = Array.getLength(array); this.myArrayList.ensureCapacity(this.myArrayList.size() + length); for (int i = 0; i < length; i += 1) { this.put(JSONObject.wrap(Array.get(array, i))); } } else { throw new JSONException( "JSONArray initial value should be a string or collection or array."); } }
Source:
START public static END synchronized IBinder makeConnector(Context context) { if (sConnector == null) { sConnector = new TetheringConnector(context); } return sConnector; } I don't think this should be public (NetworkStack version is still public for legacy reasons)

Target:
private static synchronized IBinder makeConnector(Context context) { if (sConnector == null) { sConnector = new TetheringConnector(context); } return sConnector; }
Source:
protected void setSplitterPosition(int leftWidth, int rightWidth) { try { if (lockSplitter.acquire()) { START double total = leftWidth + rightWidth; END if (total > 0) { double d = leftWidth / total; getSwingContainer().setDividerLocation(d); getSwingContainer().setResizeWeight(d); } } } finally { lockSplitter.release(); } } Can leftWidth ever be negative?

Target:
protected void setSplitterPosition(int leftWidth, int rightWidth) { if (leftWidth < 0 || rightWidth < 0) { return; } try { if (lockSplitter.acquire()) { double total = leftWidth + rightWidth; if (total > 0) { double d = leftWidth / total; getSwingContainer().setDividerLocation(d); getSwingContainer().setResizeWeight(d); } } } finally { lockSplitter.release(); } }
Source:
public void process(CtElement element) { START if(element instanceof CtPackage && element != getFactory().Package().getRootPackage()){ END ((CtPackage) element).setSimpleName("newtest"); } } there is a confusion, the goal is that client code indeed never has to write this. so the implementation RootPackage.setSimpleName would simply be ... empty. do you see what I mean?

Target:
public void process(CtElement element) { if(element instanceof CtPackage){ ((CtPackage) element).setSimpleName("newtest"); } }
Source:
public CommandContext withoutCompensationContext() { START return withCompensationContext(new DefaultCompensationContext()); END } shouldn't it be return withCompensationContext(new *NoOpCompensationContext*()) or even return withCompensationContext(NoOpCompensationContext.getInstance())

Target:
public CommandContext withoutCompensationContext() { return withCompensationContext(null); }
Source:
START public <T> Model<T> getOrNull(Class<T> type, @CheckForNull Class<?> propertyOwner, @Nullable String property) throws NotExportableException { END Model m = models.get(type); if(m==null && type.getAnnotation(ExportedBean.class) != null) { m = new Model<T>(this, type, propertyOwner, property); } return m; } `@CheckForNull` return. And why is this declared to throw `NotExportableException`?

Target:
public <T> Model<T> getOrNull(Class<T> type, @CheckForNull Class<?> propertyOwner, @Nullable String property) { Model<T> m = models.get(type); if(m==null && type.getAnnotation(ExportedBean.class) != null) { m = new Model<T>(this, type, propertyOwner, property); } return m; }
Source:
START public void beforeParamAndAfterParamAreRun() { END fLog = ""; final Result result = JUnitCore.runClasses(BeforeParamAndAfterParam.class); assertEquals(0, result.getFailureCount()); assertEquals("beforeClass before(A) first(A) second(A) afterParam " + "before(B) first(B) second(B) afterParam afterClass ", fLog); } It would be great to have tests for 1. Multiple `@BeforeParam` methods 1. Multiple `@AfterParam` methods 1. `@AfterParam` methods with parameters 1. `@BeforeParam` methods without parameters 1. Parameterized tests with more than one parameter

Target:
public void beforeParamAndAfterParamAreRun() { fLog = ""; Result result = JUnitCore.runClasses(BeforeParamAndAfterParam.class); assertEquals(0, result.getFailureCount()); assertEquals("beforeClass before(A) first(A) second(A) afterParam " + "before(B) first(B) second(B) afterParam afterClass ", fLog); }
Source:
public void setup() { START Section section = new Section(new Shell(), SWT.NONE); END event = new ExpansionEvent(section, true); expansionEventConsumer = new ExpansionEventConsumer(); } shell should be disposed in teardown

Target:
public void setup() { event = new ExpansionEvent(section, true); expansionEventConsumer = new ExpansionEventConsumer(); }
Source:
public void testGenerateGroupId() { String user = System.getProperty("user.name"); String vcloudGroupId = JcloudsLocation.generateGroupId("vcloud"); assertTrue(vcloudGroupId.startsWith("br-")); String fooGroupId = JcloudsLocation.generateGroupId("foo"); START if (!"brooklyn".equals(user)) END assertTrue(fooGroupId.startsWith("brooklyn-"+user)); } What happens if the user is "brooklyn"? Is it sensible behaviour? Can/should we add an else block with an assertion for that?

Target:
public void testGenerateGroupId() { String user = System.getProperty("user.name"); String vcloudGroupId = JcloudsLocation.generateGroupId("vcloud"); assertTrue(vcloudGroupId.startsWith("br-")); String fooGroupId = JcloudsLocation.generateGroupId("foo"); if ("brooklyn".equals(user)) { // skip check -- we don't write brooklyn-brooklyn- because that looks funny // (and running as user brooklyn is common) } else { assertTrue(fooGroupId.startsWith("brooklyn-"+user)); } }
Source:
START private void checkPasswordValidity(DocumentModel userModel) throws InvalidPasswordException { END String schema = dirService.getDirectorySchema(userDirectoryName); String passwordField = dirService.getDirectory(userDirectoryName).getPasswordField(); Property passwordProperty = userModel.getProperty(String.format("%s:%s", schema, passwordField)); if (passwordProperty.isDirty()) { String clearPassword = passwordProperty.getValue(String.class); if (StringUtils.isNotBlank(clearPassword) && !validatePassword(clearPassword)) { throw new InvalidPasswordException(); } } } `protected`, to allow easy subclassing.

Target:
protected void checkPasswordValidity(DocumentModel userModel) throws InvalidPasswordException { String schema = dirService.getDirectorySchema(userDirectoryName); String passwordField = dirService.getDirectory(userDirectoryName).getPasswordField(); Property passwordProperty = userModel.getProperty(String.format("%s:%s", schema, passwordField)); if (passwordProperty.isDirty()) { String clearPassword = passwordProperty.getValue(String.class); if (StringUtils.isNotBlank(clearPassword) && !validatePassword(clearPassword)) { throw new InvalidPasswordException(); } } }
Source:
protected void cancel() { setWindow(null); START setConfirmWindow(null); END } There is no harm in setting the confirmWindow to null, but since you are not actually setting it, there is no need to set it to null.

Target:
protected void cancel() { setWindow(null); }
Source:
public RemoveUnregisteredVmCommand(T parameters, CommandContext cmdContext) { super(parameters, cmdContext); START setStorageDomainId(parameters.getStorageDomainId()); END } already done in the super?

Target:
public RemoveUnregisteredVmCommand(T parameters, CommandContext cmdContext) { super(parameters, cmdContext); }
Source:
public String skipString() throws IOException { START return tokenizer.readString(); END } tokenizer.skipString() I guess. No need to convert Utf8 to String here, just use the stream.skip().

Target:
public void skipString() throws IOException { readString(); }
Source:
START public AbstractCursorWrappingIndexHits( int size, float score ) END { this.size = size; this.score = score; } Why public?

Target:
AbstractCursorWrappingIndexHits( int size, float score ) { this.size = size; this.score = score; }
Source:
START public ReportDocument(String targetDir, String testName, int testsSize, boolean separateClusterCharts) { END super(targetDir, String.format("test_%s.html", testName), "Test " + testName); this.testSize = testsSize; this.testName = testName; this.separateClusterCharts = separateClusterCharts; } 'testsSize' is not very descriptive name, please use something like 'maxConfigurations' (is it really number of configurations that have executed this test?)

Target:
public ReportDocument(String targetDir, String testName, int testsSize, boolean separateClusterCharts) { super(targetDir, String.format("test_%s.html", testName), "Test " + testName); this.testName = testName; this.testSize = testsSize; this.separateClusterCharts = separateClusterCharts; }
Source:
public void populateExpressionProperty(FactModelTree factModelTree) { if (factModelTree.getSimpleProperties().containsValue(ConstantsHolder.EXPRESSION_CLASSNAME)) { return; } final String expressionName = factModelTree.getFactName() + ConstantsHolder.EXPRESSION_SUFFIX; long count = factModelTree.getSimpleProperties().keySet().stream().filter(key -> key.startsWith(expressionName)).count(); START factModelTree.addSimpleProperty(count > 0 ? expressionName + "_" + count : expressionName, ConstantsHolder.EXPRESSION_CLASSNAME); END } @yesamer Please, do not do that, and follow what we agreed upon: a fixed static part (ScesimExpression) followed by "-" and a randomly generated two digit number. Beside that, for each "Object" there can be only one "expression" property, so that count has no meaning; if you need to take this in account, there is something wrong in the code

Target:
public void populateExpressionProperty(FactModelTree factModelTree) { factModelTree.addSimpleProperty(factModelTree.getFactName() + ConstantsHolder.EXPRESSION_SUFFIX, ConstantsHolder.EXPRESSION_CLASSNAME); }
Source:
public VmCommand(T parameters) { super(parameters); setVmId(parameters.getVmId()); START setReason(parameters.getReason()); END } why this is in vmCommand? should be in stopBase command

Target:
public VmCommand(T parameters) { super(parameters); setVmId(parameters.getVmId()); }
Source:
public String retrieve(VeluxBridgeProvider bridge) { logger.trace("retrieve() called."); logger.trace("retrieve() About to query device status."); BCgetDeviceStatus.Response response = bridge.bridgeCommunicate(new BCgetDeviceStatus()); if ((response == null) || (!response.getResult())) { logger.trace("retrieve() finished with failure."); return null; START } else { END logger.trace("retrieve() finished successfully with result {}.", response.getDeviceStatus()); return response.getDeviceStatus(); } } "else" is redundant here. Consider dropping it.

Target:
public String retrieve(VeluxBridgeProvider bridge) { logger.trace("retrieve() called."); logger.trace("retrieve() About to query device status."); BCgetDeviceStatus.Response response = bridge.bridgeCommunicate(new BCgetDeviceStatus()); if ((response == null) || (!response.getResult())) { logger.trace("retrieve() finished with failure."); return null; } logger.trace("retrieve() finished successfully with result {}.", response.getDeviceStatus()); return response.getDeviceStatus(); }
Source:
private static int getNeededNumberOfUsbControllers(int numberOfSlots) { int numOfcontrollers = numberOfSlots / SLOTS_PER_CONTROLLER; if (numOfcontrollers == 0) { numOfcontrollers = 1; } START return numOfcontrollers; END } whole function can be return math.max(numberOfSlots / SLOTS_PER_CONTROLLER, 1);

Target:
private static int getNeededNumberOfUsbControllers(int numberOfSlots) { int numOfcontrollers = numberOfSlots / SLOTS_PER_CONTROLLER; if (numberOfSlots > 0 && numOfcontrollers == 0) { numOfcontrollers = 1; } return numOfcontrollers; }
Source:
START public synchronized Long size() END { final File file = path.toFile(); Long size = (file.exists() && !file.isDirectory()) ? file.length() : 0l; if (childSize < 0l || childModCount > lastSizeCheck) { Long childSize = 0l; lastSizeCheck = childModCount; for (FileCopyResult child : children) { childSize += child.size(); } this.childSize = childSize; } size += childSize; return size; } can this be primitive long to avoid the unnecessary wrapping?

Target:
public long size() { return size; }
Source:
public RngDeviceParameters(VmRngDevice rngDevice, boolean vm) { START if (rngDevice == null) { END throw new IllegalArgumentException("RNG Device must be specified."); } this.rngDevice = rngDevice; isVm = vm; } please no exceptions in the constructor

Target:
public RngDeviceParameters(VmRngDevice rngDevice, boolean vm) { this.rngDevice = rngDevice; isVm = vm; }
Source:
private static boolean isInContext(Pair<IErrorParserNamed, Integer> pair, int context) { START return (pair.second & context) == context; END } Simpler: (pair.second & context) != 0

Target:
private static boolean isInContext(Pair<IErrorParserNamed, Integer> pair, int context) { return (pair.second & context) != 0; }
Source:
START private void removeAlwaysOn(IActionSetDescriptor descriptor) { END if (descriptor == null) { return; } if (!alwaysOnActionSets.contains(descriptor)) { return; } alwaysOnActionSets.remove(descriptor); if (page != null) { page.perspectiveActionSetChanged(this, descriptor, ActionSetManager.CHANGE_HIDE); } } Hard to say in Gerrit (I still have to pull in the change into Eclipse) but the checks are already done in the protected addAlwaysOff method. Is this method called in places where these checks are not already done?

Target:
private void removeAlwaysOn(IActionSetDescriptor descriptor) { if (!alwaysOnActionSets.contains(descriptor)) { return; } alwaysOnActionSets.remove(descriptor); page.perspectiveActionSetChanged(this, descriptor, ActionSetManager.CHANGE_HIDE); }
Source:
public void createGroupUnionForIndirectRelationship() throws Exception { System.out.println(CLASS_NAME + "createGroupUnionForIndirectRelationship"); Vo vo = setUpVo(); groupsManagerBl.createGroup(sess, vo, group2); groupsManagerBl.createGroup(sess, group2, group3); groupsManagerBl.createGroup(sess, group3, group4); START groupsManagerBl.createGroupUnion(sess, group4, group2, false); END } I think there is an invalid order of the groups. The way it is implemented now, this test creates this relation: 2 | 3 | 4 And calling `createGroupUnion(sess, group4, group2, false)` tries to import members from group2 to group4. This causes a cycle, and I am not sure if we can detect this in the current implementation. Also, the test passes because of the error which I have pointed out above. ```suggestion groupsManagerBl.createGroupUnion(sess, group2, group4, false); ```

Target:
public void createGroupUnionForIndirectRelationship() throws Exception { System.out.println(CLASS_NAME + "createGroupUnionForIndirectRelationship"); Vo vo = setUpVo(); groupsManagerBl.createGroup(sess, vo, group2); groupsManagerBl.createGroup(sess, group2, group3); groupsManagerBl.createGroup(sess, group3, group4); groupsManagerBl.createGroupUnion(sess, group2, group4, false); }
Source:
private SelectionListener createListener() { final SelectionListener listener = new SelectionListener() { @Override public void START widgetSelected(SelectionEvent e) { END resetProperties(); } @Override public void widgetDefaultSelected(SelectionEvent e) { // nothing to do } }; return listener; } final missing

Target:
private SelectionListener createListener() { final SelectionListener listener = new SelectionListener() { @Override public void widgetSelected(final SelectionEvent e) { resetProperties(); } @Override public void widgetDefaultSelected(final SelectionEvent e) { // nothing to do } }; return listener; }
Source:
public void testOur404Handler(String wiki, String inputPath, String expectedPath) { String wikiBase = urlBuilder.getUrlForWiki(wiki); String inputUrl = wikiBase + inputPath; String expectedUrl = expectedPath; START if (!expectedUrl.startsWith("http://")) { END expectedUrl = wikiBase + expectedUrl; } driver.get(inputUrl); String actualUrl = driver.getCurrentUrl(); Assertion.assertEquals(actualUrl, expectedUrl); } I would flip the condition since the special case is when we have protocol, not otherwise: ``` java if (expectedUrl.startsWith("http://")) { expectedUrl = expectedPath } ```

Target:
public void testOur404Handler(String wiki, String inputPath, String expectedPath) { String wikiBase = urlBuilder.getUrlForWiki(wiki); String inputUrl = wikiBase + inputPath; String expectedUrl = wikiBase + expectedPath; // Special case for favicon: if (expectedPath.startsWith("http://")) { expectedUrl = expectedPath; } driver.get(inputUrl); String actualUrl = driver.getCurrentUrl(); Assertion.assertEquals(actualUrl, expectedUrl); }
Source:
public void closeDirty() { try { close(false); } catch (final RuntimeException e) { START log.warn(String.format("Ignoring uncaught error in unclean close of standby task %s", id), e); END } log.info("Closed dirty"); } What exception is possibly thrown from this close(false) call?

Target:
public void closeDirty() { close(false); log.info("Closed dirty"); }
Source:
public boolean renderClouds(int cloudTicks, float partialTicks) { START net.minecraftforge.client.IRenderHandler renderer = this.client.world.provider.getCloudRenderer(); END if (renderer != null) { renderer.render(partialTicks, this.client.world, this.client); return true; } return cloudRenderer.render(cloudTicks, partialTicks); } Just `IRenderHandler` (use an import)

Target:
public boolean renderClouds(int cloudTicks, float partialTicks) { IRenderHandler renderer = this.client.world.provider.getCloudRenderer(); if (renderer != null) { renderer.render(partialTicks, this.client.world, this.client); return true; } return cloudRenderer.render(cloudTicks, partialTicks); }
Source:
private ValueType getResultILType(GenContext ctx) { Arrow a = (Arrow) this.type; START if( END isGeneric() && a.getResult() instanceof UnresolvedType && ((UnresolvedType) a.getResult()).getName().equals(this.genTypeName) ) { return new NominalType(new Variable(GENERIC_PREFACE), GENERIC_MEMBER); } return ((Arrow)type).getResult().getILType(ctx); } Don't need this if statement either

Target:
private ValueType getResultILType(GenContext ctx) { Arrow a = (Arrow) this.type; return a.getResult().getILType(ctx); }
Source:
public Entity getControllingPassenger() { List<Entity> _passengers = getPassengers(); if(_passengers.isEmpty()) { setDriverState(false); return null; } else { START setDriverState(true); END return _passengers.get(0); } } that seems like a hack to me. Shouldn't the boolean `driver` indicate if the seat is the driver seat? Which doesn't change based on the presence of a actual driver entity. I did not take a deeper look at this, but my assumption is that the boolean is not correctly set after reloading the entity from a save file

Target:
public Entity getControllingPassenger() { return getPassengers().isEmpty() ? null : getPassengers().get(0); }
Source:
public Limit(@Nonnull final Long limit, final Operator child) { super(child); this.limit = Objects.requireNonNull(limit, "limit"); Preconditions.checkArgument(limit >= 0L, "limit must be non-negative"); toEmit = this.limit; START done = false; END } I don't think you need this new flag. You should immediately return `null` from `fetchNextReady()` if the child has already been closed, which you can test with `child.isOpen()` or `child.eos()`. @jingjingwang do you agree?

Target:
public Limit(@Nonnull final Long limit, final Operator child) { super(child); this.limit = Objects.requireNonNull(limit, "limit"); Preconditions.checkArgument(limit >= 0L, "limit must be non-negative"); toEmit = this.limit; }
Source:
public void add(Key k, Value v) { if (key == null) { key = k; timeStamps.add(k.getTimestamp()); values.add(v); size++; } else if (key.compareRow(k.getRow()) == 0 START && key.compareColumnFamily(k.getColumnFamily()) == 0) { END timeStamps.add(k.getTimestamp()); values.add(v); } else { //TODO: what happens here } } Not quite (did not check column qualifier or visibility), you can use `key.equals(k, PartialKey.ROW_COLFAM_COLQUAL_COLVIS)` and it checks row and all three column fields.

Target:
public void add(Key k, Value v) throws IllegalArgumentException { add(k, v.get()); }
Source:
public STGroup getTemplates() { if (templates == null) { templates = loadTemplates(); START String version = getVersion(); END if (version == null || !version.equals(Tool.VERSION)) { gen.tool.errMgr.toolError(ErrorType.INCOMPATIBLE_TOOL_AND_TEMPLATES, version, Tool.VERSION, language); } } return templates; } The version check should come before the call to `loadTemplates()`.

Target:
public STGroup getTemplates() { if (templates == null) { String version = getVersion(); if (version == null || !version.equals(Tool.VERSION)) { gen.tool.errMgr.toolError(ErrorType.INCOMPATIBLE_TOOL_AND_TEMPLATES, version, Tool.VERSION, language); } templates = loadTemplates(); } return templates; }
Source:
private boolean isException(String value) { START return value.length() == 4 || Integer.parseInt(value) < 8; END } This line triggers a `java.lang.NumberFormatException` for the following code: ``` $a = 012_345; ```

Target:
private static boolean isException(String value) { return value.length() == 4 || Integer.parseInt(value) < 8; }
Source:
public LatLng getGoogleMapsLocation() { START ParseGeoPoint pGP = (ParseGeoPoint) getClient().get("location"); END return new LatLng(pGP.getLatitude(), pGP.getLongitude()); } Same here...one thing I've noticed is that if location == null NPE exceptions get thrown. We should probably check on null here.

Target:
public LatLng getGoogleMapsLocation() { return getClient().getGoogleMapsLocation(); }
Source:
public void saveSMA(IAtsChangeSet changes) { super.saveSMA(changes); try { ActionArtifact parentAction = getParentActionArtifact(); if (parentAction != null) { ActionArtifactRollup rollup = new ActionArtifactRollup(parentAction); rollup.resetAttributesOffChildren(); changes.add(parentAction); START } END } catch (Exception ex) { OseeLog.log(Activator.class, OseeLevel.SEVERE_POPUP, "Can't reset Action parent of children", ex); } } If the parent is null, this does nothing and the caller/log gets no indication that there was a problem. Is this desired?

Target:
public void saveSMA(IAtsChangeSet changes) { super.saveSMA(changes); try { ActionArtifact parentAction = getParentActionArtifact(); ActionArtifactRollup rollup = new ActionArtifactRollup(parentAction); rollup.resetAttributesOffChildren(); changes.add(parentAction); } catch (Exception ex) { OseeLog.log(Activator.class, OseeLevel.SEVERE_POPUP, "Can't reset Action parent of children", ex); } }
Source:
START public List getArquivosOriginais() END { return arquivosIniciais; } usar generics no tipo de retorno

Target:
public List<File> getArquivosOriginais() { return arquivosIniciais; }
Source:
private static long combineFilters(long[] filters) { if (filters == null) { return 0; } int combined = 0; START for (int i = 0; i < filters.length; i++) { END combined |= filters[i]; } return combined; } nit ```java for (long filter : filters) { combined |= filter; }

Target:
private static long combineFilters(long[] filters) { if (filters == null) { return 0; } int combined = 0; for (long filter : filters) { combined |= filter; } return combined; }
Source:
private boolean matchExpressionAndColumnRef(AbstractExpression statementExpr, ColumnRef indexColRef, START StmtTableScan tableScan) { END if (statementExpr instanceof TupleValueExpression) { TupleValueExpression tve = (TupleValueExpression)statementExpr; if (tve.getTableAlias().equals(tableScan.getTableAlias()) && tve.getColumnName().equals(indexColRef.getColumn().getTypeName())) { // NB: m_emptyBindings is a null list. That means // we matched, but with no bindings. return true; } } return false; } Extra whitespace forming neat little columns makes the code arguably HARDER to read and inarguably harder to write and maintain -- turning future single-line changes into multi-line mostly whitespace changes , so PLEASE DESIST.

Target:
private static boolean matchExpressionAndColumnRef(AbstractExpression statementExpr, ColumnRef indexColRef, StmtTableScan tableScan) { if (statementExpr instanceof TupleValueExpression) { TupleValueExpression tve = (TupleValueExpression)statementExpr; if (tve.getTableAlias().equals(tableScan.getTableAlias()) && tve.getColumnName().equals(indexColRef.getColumn().getTypeName())) { return true; } } return false; }
Source:
public static void log(Throwable e) { START log(new Status(IStatus.ERROR, PLUGIN_ID, IStatus.OK, e.getLocalizedMessage(), e)); END } Why localized? We usually don't localize log message, if somebody gets a translated IOException in the log would be hard to understand later when they submit the bug

Target:
public static void log(Throwable e) { log(new Status(IStatus.ERROR, PLUGIN_ID, IStatus.OK, e.getMessage(), e)); }
Source:
private boolean isNotTimeshiftedOrHd(Channel channel) { START boolean timeshifted = MoreObjects.firstNonNull(channel.getTimeshifted(), false); END boolean hd = MoreObjects.firstNonNull(channel.getHighDefinition(), false); return !(timeshifted || hd); } You can use Boolean.TRUE.equals(obj) if you want, though it's less explicit, so I don't mind :-)

Target:
boolean isNotTimeshiftedOrHd(Channel channel) { boolean timeshifted = MoreObjects.firstNonNull(channel.getTimeshifted(), false); boolean hd = MoreObjects.firstNonNull(channel.getHighDefinition(), false); return !(timeshifted || hd); }
Source:
default CacheContainerAdmin administration() { START throw new UnsupportedOperationException(); END } So we lose the typing on `CacheContainerAdmin`, should we define that on this method or as a generic on `CacheContainer` at least?

Target:
default CacheContainerAdmin<?> administration() { throw new UnsupportedOperationException(); }
Source:
public RegistrationData findByToken(Context context, String token) throws SQLException { CriteriaBuilder criteriaBuilder = getCriteriaBuilder(context); CriteriaQuery criteriaQuery = getCriteriaQuery(criteriaBuilder, RegistrationData.class); Root<RegistrationData> registrationDataRoot = criteriaQuery.from(RegistrationData.class); criteriaQuery.select(registrationDataRoot); criteriaQuery.where(criteriaBuilder.equal(registrationDataRoot.get(RegistrationData_.token), token)); START return uniqueResult(context, criteriaQuery, true, RegistrationData.class, -1, -1); END } Original query was not cacheable. This one is. I think the third param should be false.

Target:
public RegistrationData findByToken(Context context, String token) throws SQLException { CriteriaBuilder criteriaBuilder = getCriteriaBuilder(context); CriteriaQuery criteriaQuery = getCriteriaQuery(criteriaBuilder, RegistrationData.class); Root<RegistrationData> registrationDataRoot = criteriaQuery.from(RegistrationData.class); criteriaQuery.select(registrationDataRoot); criteriaQuery.where(criteriaBuilder.equal(registrationDataRoot.get(RegistrationData_.token), token)); return uniqueResult(context, criteriaQuery, false, RegistrationData.class, -1, -1); }
Source:
public static void setReindexOnConfigChange(IProject project, boolean shouldReindexOnConfigChange) { if (shouldReindexOnConfigChange != getReindexOnConfigChange(project)) { getProjectPreferences(project).putBoolean(KEY_REINDEX_ON_CONFIG_CHANGE, shouldReindexOnConfigChange); START CCoreInternals.savePreferences(project, true); END } } Saving preferences inside a setter is not appropriate. Please follow the pattern used for other preferences.

Target:
public static void setReindexOnConfigChange(IProject project, boolean shouldReindexOnConfigChange) { if (shouldReindexOnConfigChange != getReindexOnConfigChange(project)) { getProjectPreferences(project).putBoolean(KEY_REINDEX_ON_CONFIG_CHANGE, shouldReindexOnConfigChange); } }
Source:
public void beforeBlockElement(ProgramState currentState, Tree element) { T tree = getTree(element); if (tree != null) { boolean isProblem = isProblem(tree, currentState); if (!isProblem) { problemMap.put(tree, true); START } else if (!problemMap.containsKey(tree)) { END problemMap.put(tree, false); } } } @vilchik-elena It looks like problemMap is actually a noProblemMap. Suggestion: invert the meaning of the Boolean: true for problem, false for no problem.

Target:
public void beforeBlockElement(ProgramState currentState, Tree element) { T tree = getTree(element); if (tree != null) { boolean isProblem = isProblem(tree, currentState); if (!isProblem) { problemMap.put(tree, false); } else if (!problemMap.containsKey(tree)) { problemMap.put(tree, true); } } }
Source:
public String toString() { return toStringHelper(this) .omitNullValues() START .add("outputSymbolAliases", this.outputSymbolAliases) END .add("expectedOutputSymbolCount", expectedOutputSymbolCount) .add("expectedRows", expectedRows) .toString(); } extra `this.`

Target:
public String toString() { return toStringHelper(this) .omitNullValues() .add("outputSymbolAliases", outputSymbolAliases) .add("expectedOutputSymbolCount", expectedOutputSymbolCount) .add("expectedRows", expectedRows) .toString(); }
Source:
public void testSinglePartUnknownEncoding_throwsUnsupportedEncodingException() throws Exception { MimeMessage msg = parseWithoutRecurse(toStream( "From: <adam@example.org>\r\n" + "To: <eva@example.org>\r\n" + "Subject: Testmail\r\n" + "MIME-Version: 1.0\r\n" + "Content-type: text/plain\r\n" + "Content-Transfer-Encoding: utf-8\r\n" + "\r\n" + "dGhpcyBpcyBzb21lIG1vcmUgdGVzdCB0ZXh0Lg==\r\n")); checkAddresses(msg.getFrom(), "adam@example.org"); START checkAddresses(msg.getRecipients(RecipientType.TO), "eva@example.org"); END streamToString(MimeUtility.decodeBody(msg.getBody())); } These two checks seem unrelated to the actual check you want to perform.

Target:
public void testSinglePartUnknownEncoding_throwsUnsupportedEncodingException() throws Exception { MimeMessage msg = parseWithoutRecurse(toStream( "From: <adam@example.org>\r\n" + "To: <eva@example.org>\r\n" + "Subject: Testmail\r\n" + "MIME-Version: 1.0\r\n" + "Content-type: text/plain\r\n" + "Content-Transfer-Encoding: utf-8\r\n" + "\r\n" + "dGhpcyBpcyBzb21lIG1vcmUgdGVzdCB0ZXh0Lg==\r\n")); MimeUtility.decodeBody(msg.getBody()); }
Source:
START public UpdateSite createDefaultUpdateSite() { END return new UpdateSite(PREDEFINED_UPDATE_SITE_ID, config.getUpdateCenterUrl() + "update-center.json"); } I'd make this `protected`.

Target:
protected UpdateSite createDefaultUpdateSite() { return new UpdateSite(PREDEFINED_UPDATE_SITE_ID, config.getUpdateCenterUrl() + "update-center.json"); }
Source:
START private void assertCorrectGetManagedInterfaceForVdsResult(VdsNetworkInterface result) { END assertNotNull(result); assertTrue(result.getIsManagement()); } You can make this method private

Target:
static private void assertCorrectGetManagedInterfaceForVdsResult(VdsNetworkInterface result) { assertNotNull(result); assertTrue(result.getIsManagement()); }
Source:
public static RequestControlAdminRequest readFrom(DataInputStream stream, AdminRequest adminRequest) throws IOException { Short versionId = stream.readShort(); if (!versionId.equals(VERSION_V1)) { throw new IllegalStateException("Unrecognized version for RequestControlAdminRequest: " + VERSION_V1); } RequestOrResponseType requestType = RequestOrResponseType.values()[stream.readShort()]; START boolean enable = stream.readByte() == 1; END return new RequestControlAdminRequest(requestType, enable, adminRequest); } Define a constant for `1`?

Target:
public static RequestControlAdminRequest readFrom(DataInputStream stream, AdminRequest adminRequest) throws IOException { Short versionId = stream.readShort(); if (!versionId.equals(VERSION_V1)) { throw new IllegalStateException("Unrecognized version for RequestControlAdminRequest: " + versionId); } RequestOrResponseType requestType = RequestOrResponseType.values()[stream.readShort()]; boolean enable = stream.readByte() == 1; return new RequestControlAdminRequest(requestType, enable, adminRequest); }
Source:
public void buildDependencyGraph(AbstractProject owner, DependencyGraph graph) { // Can only add dependencies in Hudson 1.341 or higher if (!canDeclare(owner)) return; for (BuildTriggerConfig config : configs) { START List<AbstractProject> projectList = Util.filter(config.getProjectList(owner.getParent(), null), AbstractProject.class); END for (AbstractProject project : projectList) ParameterizedDependency.add(owner, project, config, graph); } } Are you expecting to get Workflow jobs here? If so, I think it will not work.

Target:
public void buildDependencyGraph(AbstractProject owner, DependencyGraph graph) { // Can only add dependencies in Hudson 1.341 or higher if (!canDeclare(owner)) return; for (BuildTriggerConfig config : configs) { List<AbstractProject> projectList = config.getProjectList(owner.getParent(), null); for (AbstractProject project : projectList) { ParameterizedDependency.add(owner, project, config, graph); } } }
Source:
public DAnalysis getDAnalysis() { DAnalysis dAnalysis = null; DRepresentation representation = START getRepresentation().get(); END DRepresentationDescriptor representationDescriptor = new DRepresentationQuery(representation).getRepresentationDescriptor(); EObject rootContainer = EcoreUtil.getRootContainer(representationDescriptor, false); if (rootContainer instanceof DAnalysis) { dAnalysis = (DAnalysis) rootContainer; } return dAnalysis; } This method returns an Option<DRepresentation>, so the API clearly says it can be null. You must check 'if getRepresentation().some()" before.

Target:
public DAnalysis getDAnalysis() { DAnalysis dAnalysis = null; DRepresentation representation = getRepresentation().get(); if (representation != null) { DRepresentationDescriptor representationDescriptor = new DRepresentationQuery(representation).getRepresentationDescriptor(); EObject rootContainer = EcoreUtil.getRootContainer(representationDescriptor, false); if (rootContainer instanceof DAnalysis) { dAnalysis = (DAnalysis) rootContainer; } } return dAnalysis; }
Source:
public ASTNode(HasLocation hasLocation) { this(hasLocation.getLocation()); START metadataSet = new HashSet<>(); END } Unnecessary; the call to this(...) does it

Target:
public ASTNode(HasLocation hasLocation) { this(hasLocation.getLocation()); }
Source:
public synchronized void dispose() { for (Entry<String, IObservableValue> entry : expressionMap.entrySet()) { entry.getValue().dispose(); } START super.dispose(); END } You should also clear the map. The EMF observable value holds the EObject after even after disposal which may prevent the GC to collect the model if this observable is retained. For similar reasons, please set 'match' to null here.

Target:
public synchronized void dispose() { for (Entry<String, IObservableValue> entry : expressionMap.entrySet()) { entry.getValue().dispose(); } expressionMap.clear(); super.dispose(); }
Source:
private void visitParameterDef(DetailAST parameterDef) { final DetailAST grandParentAST = parameterDef.getParent().getParent(); if (grandParentAST.getType() == TokenTypes.METHOD_DEF && isCheckedMethod(grandParentAST) && isVerifiable(grandParentAST) START && !AnnotationUtil.containsAnnotation(grandParentAST, "Override")) { END checkClassName(parameterDef); } } As discussed in main issue, this should be in the check for the entire method. Maybe this should be moved to the `isCheckedMethod` method?

Target:
private void visitParameterDef(DetailAST parameterDef) { final DetailAST grandParentAST = parameterDef.getParent().getParent(); if (grandParentAST.getType() == TokenTypes.METHOD_DEF && isCheckedMethod(grandParentAST)) { checkClassName(parameterDef); } }
Source:
public static boolean hasPushStatusBug(int[] version) { START int cmp = compare(version, v1_7_8_6); END if (cmp < 0) return true; // Everything before 1.7.8.6 is known broken. else if (cmp == 0) return false; // 1.7.8.6 contained the bug fix. if (compare(version, v1_7_9) <= 0) return true; // 1.7.9 shipped before 1.7.8.6 and has the bug. return false; // 1.7.9.1 and later are fixed. } The implementation can just "return false".

Target:
public static boolean hasPushStatusBug(int[] version) { return false; }
Source:
protected void addListeners() { this.resourceSetListener = new UpdateTableContentListener(getTableManager(), this); START getTableEditingDomain().addResourceSetListener(this.resourceSetListener); END } Why removing the NPE check?

Target:
protected void addListeners() { this.resourceSetListener = new UpdateTableContentListener(getTableManager(), this); if (getTableEditingDomain() != null) { getTableEditingDomain().addResourceSetListener(this.resourceSetListener); } }
Source:
public static ExpectedCondition<WebDriverElement> visible(final Hook hook) { return new ExpectedCondition<WebDriverElement>() { @Override public WebDriverElement apply(WebDriver driver) { try { WebElement element = findElement(hook, driver); return element.isDisplayed()? createWebDriverElement(hook, element, driver) : null; START } catch (CandybeanException e) { END return null; } catch (StaleElementReferenceException e) { return null; } } @Override public String toString() { return "visibility of " + hook; } }; } Let's use multi-catch here.

Target:
public static ExpectedCondition<WebDriverElement> visible(final Hook hook) { return new ExpectedCondition<WebDriverElement>() { @Override public WebDriverElement apply(WebDriver driver) { try { WebElement element = findElement(hook, driver); return element.isDisplayed()? createWebDriverElement(hook, element, driver) : null; } catch (CandybeanException | StaleElementReferenceException e) { return null; } } @Override public String toString() { return "visibility of " + hook; } }; }
Source:
public ApplicationListener<?> xdInitializer(ApplicationContext context) { XdConfigLoggingInitializer delegate = new XdConfigLoggingInitializer(true); delegate.setEnvironment(context.getEnvironment()); START if (zooKeeperConnection != null) { END delegate.setZkConnectString(zooKeeperConnection.getClient().getZookeeperClient().getCurrentConnectionString()); } return new SourceFilteringListener(context, delegate); } Not really the fault of this PR, but it feels really weird to have everything in the Environment **except** the zk connection string

Target:
public ApplicationListener<?> xdInitializer(ApplicationContext context) { XdConfigLoggingInitializer delegate = new XdConfigLoggingInitializer(true); delegate.setEnvironment(context.getEnvironment()); return new SourceFilteringListener(context, delegate); }
Source:
public String[] getCodecs() { START return this.codecs.toArray(new String[]{}); END } specify array length (based on codecs.size) to optimize. http://stackoverflow.com/a/5982478/4142153

Target:
public String[] getCodecs() { return this.codecs.toArray(new String[codecs.size()]); }
Source:
public static Long getTimeFromDateString(String dateString) { try { SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); Date date = dateFormatter.parse(dateString); START return date.getTime(); END } catch (ParseException e) { logger.warn("Could not parse milliseconds from an HTTP date header (" + dateString + ")."); return null; } } minor `return dateFormatter.parse(dateString).getTime()`

Target:
public static Long getTimeFromDateString(String dateString) { try { SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); return dateFormatter.parse(dateString).getTime(); } catch (ParseException e) { logger.warn("Could not parse milliseconds from an HTTP date header (" + dateString + ")."); return null; } }
Source:
START public OpaqueTokenConfigurer(ApplicationContext context) { END this.context = context; } Please remove the `public` modifier

Target:
OpaqueTokenConfigurer(ApplicationContext context) { this.context = context; }
Source:
public void onDateInputBlur(final BlurEvent blurEvent) { final Object target = getEventTarget(blurEvent); START if (this.onValueInputBlur != null && !Objects.isNull(target)) { END onValueInputBlur.accept(blurEvent); } } For consistency, could we use `!Objects.isNull(this.onValueInputBlur) && !Objects.isNull(target)` please?

Target:
public void onDateInputBlur(final BlurEvent blurEvent) { final Object target = getEventTarget(blurEvent); if (!Objects.isNull(onValueInputBlur) && !Objects.isNull(target)) { onValueInputBlur.accept(blurEvent); } }
Source:
START public void registerAt(Class<? extends Filter> filter, END Class<? extends Filter> atFilter) { Integer position = getOrder(atFilter); if (position == null) { throw new IllegalArgumentException( "Cannot register after unregistered Filter " + atFilter); } put(filter, position + 1); } The new registerAt method has the same implementation as the existing registerAfter method. Possible case for reuse.

Target:
public void registerAt(Class<? extends Filter> filter, Class<? extends Filter> atFilter) { Integer position = getOrder(atFilter); if (position == null) { throw new IllegalArgumentException( "Cannot register after unregistered Filter " + atFilter); } put(filter, position); }
Source:
public boolean matches(String packageName) { if (packageName == null || packageName.isEmpty()) { return false; } boolean result = false; for (Pattern pattern : patterns) { START result |= pattern.matcher(packageName).matches(); END } return result; } Just a little otimization: if one pattern matches, you don't need to check the others. To do this, write if (pattern.matcher(packageName).matches()) return true;

Target:
public boolean matches(String packageName) { if (StringUtils.isEmpty(packageName)) { return false; } for (Pattern pattern : patterns) { if (pattern.matcher(packageName).matches()) { return true; } } return false; }
Source:
public Mapping<String, V> build() { START return new ImmutableDomainWildcardMapping<V>(defaultValue, new LinkedHashMap<String, V>(map)); END } you can pass directly `map` to the `ImmutableDomainWildcardMapping` constructor (it will make the copy internally)

Target:
public Mapping<String, V> build() { return new ImmutableDomainWildcardMapping<V>(defaultValue, map); }
Source:
START static boolean isFixedWidth(ValueVector vv) { return (vv instanceof FixedWidthVector); } END ```suggestion private static boolean isFixedWidth(ValueVector vv) { return (vv instanceof FixedWidthVector); } ```

Target:
private static boolean isFixedWidth(ValueVector vv) { return (vv instanceof FixedWidthVector); }
Source:
public static Mono<byte[]> downloadFileAsync(String url, HttpPipeline httpPipeline) { FileService service = RestProxy.create(FileService.class, httpPipeline); try { return service.download(getHost(url), getPathAndQuery(url)) .flatMap(response -> FluxUtil.collectBytesInByteBufferStream(response.getValue())); } catch (MalformedURLException ex) { START return Mono.empty(); END } } Maybe a `Mono.error` would be more proper? Generally we would like an error early than late.

Target:
public static Mono<byte[]> downloadFileAsync(String url, HttpPipeline httpPipeline) { FileService service = RestProxy.create(FileService.class, httpPipeline); try { return service.download(getHost(url), getPathAndQuery(url)) .flatMap(response -> FluxUtil.collectBytesInByteBufferStream(response.getValue())); } catch (MalformedURLException ex) { return Mono.error(() -> ex); } }
Source:
public long getOldestWriteTimstamp() { // When there is no data in the buffer return the max possible timestamp // so that no query's timestamp is less than this timestamp if(writes.size() == 0) { return Long.MAX_VALUE; } START Write oldestWrite = writes.get(0); END return oldestWrite.getVersion(); } Can you add an explicit else block ``` if (condition) { } else { } ```

Target:
public long getOldestWriteTimstamp() { // When there is no data in the buffer return the max possible timestamp // so that no query's timestamp is less than this timestamp if(writes.size() == 0) { return Long.MAX_VALUE; } else { Write oldestWrite = writes.get(0); return oldestWrite.getVersion(); } }
Source:
private static String getAddonDirectory(List<String> arguments) START { END int addDirectoryIndex = arguments.indexOf("--immutableAddonDir") + 1; return arguments.get(addDirectoryIndex); } We are asuming we will allways have that argument. Is that the case ?

Target:
private static String getAddonDirectory(List<String> arguments) { int index = arguments.indexOf("--immutableAddonDir"); if (index == -1) { return ""; } return arguments.get(++index); }
Source:
private void updateWatchdogModels() { START updateWatchdogModels(getOSType().getSelectedItem()); END } Are these changes relevant to this patch?

Target:
private void updateWatchdogModels() { updateWatchdogModels((Integer) getOSType().getSelectedItem()); }
Source:
public ScanningMode enter(CtElement element) { START CtElement ele = element; END if (ele.hasParent(ignoredParent)) { if (element.hasParent(ignoredParent)) { return ScanningMode.SKIP_ALL; } } if (element instanceof CtType) { nrOfNestedLocalClasses++; } return ScanningMode.NORMAL; } I don't understand the purpose of local variable ele here: IMHO you can just remove this variable and the first if.

Target:
public ScanningMode enter(CtElement element) { if (element.hasParent(ignoredParent)) { return ScanningMode.SKIP_ALL; } if (element instanceof CtType) { nrOfNestedLocalClasses++; } return ScanningMode.NORMAL; }
Source:
protected boolean isInterestingFolder(IFolder folder) { START return !findProductFiles(folder, false).isEmpty(); END } Is this correct? When deleting a product, I would assume that this reports the parent as not interesting and we never see the file delta.

Target:
protected boolean isInterestingFolder(IFolder folder) { return true; }
Source:
protected Short getNetworkAccessPointTypeCode(String hostAddress) { if (InetAddressValidator.getInstance().isValid(hostAddress)) { return AuditTransformConstants.NETWORK_ACCESSOR_PT_TYPE_CODE_IP; START } else { END return AuditTransformConstants.NETWORK_ACCESSOR_PT_TYPE_CODE_NAME; } } This is the only place you put an "else" after the "if" returns -- for consistency, change this to not use an else statement.

Target:
protected Short getNetworkAccessPointTypeCode(String hostAddress) { if (InetAddressValidator.getInstance().isValid(hostAddress)) { return AuditTransformConstants.NETWORK_ACCESSOR_PT_TYPE_CODE_IP; } return AuditTransformConstants.NETWORK_ACCESSOR_PT_TYPE_CODE_NAME; }