auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public MetacardType getMetacardType(SolrDocument doc) throws MetacardCreationException { String mTypeFieldName = doc.getFirstValue(SchemaFields.METACARD_TYPE_FIELD_NAME).toString(); MetacardType cachedMetacardType = metacardTypesCache.getIfPresent(mTypeFieldName); if (cachedMetacardType != null) { return cachedMetacardType; } byte[] bytes = (byte[]) doc.getFirstValue(SchemaFields.METACARD_TYPE_OBJECT_FIELD_NAME); try { cachedMetacardType = OBJECT_MAPPER.readValue(bytes, MetacardType.class); } catch (IOException e) { <START> LOGGER.info("IO exception loading cached metacard type", e); <END> throw new MetacardCreationException(COULD_NOT_READ_METACARD_TYPE_MESSAGE); } metacardTypeNameToSerialCache.put(mTypeFieldName, bytes); metacardTypesCache.put(mTypeFieldName, cachedMetacardType); addToFieldsCache(cachedMetacardType.getAttributeDescriptors()); return cachedMetacardType; }</code><technical_language>problems databases created prior this version info serialized Java Json? detect if is a Java serialized blob (i.e. starts 0xCAFEBABE) a Json string? consider adding a signature beginning of byte buffer Json serialization detect data serialized Json</technical_language>

Target:
public MetacardType getMetacardType(SolrDocument doc) throws MetacardCreationException { String mTypeFieldName = doc.getFirstValue(SchemaFields.METACARD_TYPE_FIELD_NAME).toString(); MetacardType cachedMetacardType = metacardTypesCache.getIfPresent(mTypeFieldName); if (cachedMetacardType != null) { return cachedMetacardType; } byte[] bytes = (byte[]) doc.getFirstValue(SchemaFields.METACARD_TYPE_OBJECT_FIELD_NAME); try { cachedMetacardType = METACARD_TYPE_MAPPER.readValue(bytes, MetacardType.class); } catch (IOException e) { LOGGER.info("IO exception loading cached metacard type", e); throw new MetacardCreationException(COULD_NOT_READ_METACARD_TYPE_MESSAGE); } metacardTypeNameToSerialCache.put(mTypeFieldName, bytes); metacardTypesCache.put(mTypeFieldName, cachedMetacardType); addToFieldsCache(cachedMetacardType.getAttributeDescriptors()); return cachedMetacardType; }
Source:
<code>public synchronized void remove(int n) throws IOException { if (isEmpty()) throw new NoSuchElementException(); if (n == 1) { remove(); <START> } else if (n >= elementCount) { <END> clear(); } else { final int eraseStartPosition = first.position; int eraseTotalLength = 0; int newFirstPosition = first.position; int newFirstLength = first.length; for (int i = 0; i < n; i++) { eraseTotalLength += Element.HEADER_LENGTH + newFirstLength; newFirstPosition = wrapPosition(newFirstPosition + Element.HEADER_LENGTH + newFirstLength); ringRead(newFirstPosition, buffer, 0, Element.HEADER_LENGTH); newFirstLength = readInt(buffer, 0); } writeHeader(fileLength, elementCount - n, newFirstPosition, last.position); elementCount -= n; first = new Element(newFirstPosition, newFirstLength); ringErase(eraseStartPosition, eraseTotalLength); } }</code><technical_language>Including greater is interesting behavior. This means a loop of 10 remove(1) vs. remove(10) behavior. I throw in greater case</technical_language>

Target:
public synchronized void remove(int n) throws IOException { if (isEmpty()) throw new NoSuchElementException(); if (n > elementCount) { throw new IllegalArgumentException( "Cannot remove more elements (" + n + ") than present in queue (" + elementCount + ")."); } if (n == elementCount) { clear(); return; } final int eraseStartPosition = first.position; int eraseTotalLength = 0; int newFirstPosition = first.position; int newFirstLength = first.length; for (int i = 0; i < n; i++) { eraseTotalLength += Element.HEADER_LENGTH + newFirstLength; newFirstPosition = wrapPosition(newFirstPosition + Element.HEADER_LENGTH + newFirstLength); ringRead(newFirstPosition, buffer, 0, Element.HEADER_LENGTH); newFirstLength = readInt(buffer, 0); } writeHeader(fileLength, elementCount - n, newFirstPosition, last.position); elementCount -= n; first = new Element(newFirstPosition, newFirstLength); ringErase(eraseStartPosition, eraseTotalLength); }
Source:
<code>public void testNext() throws Exception { <START> try (FeatureWriter writer = <END> dataStore.getFeatureWriter(tname("ft1"), Transaction.AUTO_COMMIT)) { assertTrue(writer.hasNext()); final SimpleFeature feature = (SimpleFeature) writer.next(); assertTrue(feature.getAttribute(0).toString().equals("POINT (0 0)")); assertTrue((Integer) feature.getAttribute(1) == 0); assertTrue((Double) feature.getAttribute(2) == 0.0); assertTrue(((String) feature.getAttribute(3)).equals("zero")); } try (FeatureWriter writer = dataStore.getFeatureWriter(tname("ft1"), Transaction.AUTO_COMMIT)) { assertTrue(writer.hasNext()); final SimpleFeature feature = (SimpleFeature) writer.next(); assertTrue(feature.getAttribute(0).toString().equals("POINT (0 0)")); assertTrue((Integer) feature.getAttribute(1) == 0); assertTrue((Double) feature.getAttribute(2) == 0.0); assertTrue(((String) feature.getAttribute(3)).equals("zero")); } }</code><technical_language>description states "The test shows attributes of features returned JDBC-FeatureWriters ok if retrieved {{feature.getAttribute(index)}} {{null}} if retrieved {{feature.getAttributes()}}." I call getAttributes() here? Is test failing if change backed out</technical_language>

Target:
public void testNext() throws Exception { try (FeatureWriter writer = dataStore.getFeatureWriter(tname("ft1"), Transaction.AUTO_COMMIT)) { assertTrue(writer.hasNext()); final SimpleFeature feature = (SimpleFeature) writer.next(); assertTrue(feature.getAttribute(0).toString().equals("POINT (0 0)")); assertTrue((Integer) feature.getAttribute(1) == 0); assertTrue((Double) feature.getAttribute(2) == 0.0); assertTrue(((String) feature.getAttribute(3)).equals("zero")); } try (FeatureWriter writer = dataStore.getFeatureWriter(tname("ft1"), Transaction.AUTO_COMMIT)) { assertTrue(writer.hasNext()); final SimpleFeature feature = (SimpleFeature) writer.next(); final List<Object> attributes = feature.getAttributes(); for (int k = 0; k < attributes.size(); k++) { assertTrue(attributes.get(k) != null); } } }
Source:
<code>public void filter(final MethodNode methodNode, final IFilterContext context, final IFilterOutput output) { if ((methodNode.access & Opcodes.ACC_SYNTHETIC) == 0) { return; } if (!KotlinGeneratedFilter.isKotlinClass(context)) { return; } <START> if (isDefaultArgumentsMethodName(methodNode.name)) { <END> new Matcher().match(methodNode, output, false); } else if (isDefaultArgumentsConstructor(methodNode)) { new Matcher().match(methodNode, output, true); } }</code><technical_language>For consistency new isDefaultArgumentsConstructor() method I rename this method isDefaultArgumentsMethod(). passing a MethodNode callers do methodNode.name anyways</technical_language>

Target:
public void filter(final MethodNode methodNode, final IFilterContext context, final IFilterOutput output) { if ((methodNode.access & Opcodes.ACC_SYNTHETIC) == 0) { return; } if (!KotlinGeneratedFilter.isKotlinClass(context)) { return; } if (isDefaultArgumentsMethod(methodNode)) { new Matcher().match(methodNode, output, false); } else if (isDefaultArgumentsConstructor(methodNode)) { new Matcher().match(methodNode, output, true); } }
Source:
<code>private void createMasterFile(boolean isActive) throws IOException { String fileName = masterName.replaceAll(":", "_"); Path path = null; if (isActive) { path = new Path(activePath, fileName); } else { path = new Path(backupPath, fileName); } StringBuilder sb = new StringBuilder(); InetSocketAddress address = getHostAddress(HAConstants.MASTER_CLIENT_RPC_ADDRESS); sb.append(address.getAddress().getHostAddress()).append(":").append(address.getPort()).append("_"); address = getHostAddress(HAConstants.RESOURCE_TRACKER_RPC_ADDRESS); sb.append(address.getAddress().getHostAddress()).append(":").append(address.getPort()).append("_"); address = getHostAddress(HAConstants.CATALOG_ADDRESS); sb.append(address.getAddress().getHostAddress()).append(":").append(address.getPort()).append("_"); address = getHostAddress(HAConstants.MASTER_INFO_ADDRESS); sb.append(address.getAddress().getHostAddress()).append(":").append(address.getPort()); FSDataOutputStream out = fs.create(path); try { out.writeUTF(sb.toString()); out.hsync(); out.close(); } catch (FileAlreadyExistsException e) { createMasterFile(false); } if (isActive) { isActiveStatus = true; Path backupFile = new Path(backupPath, fileName); if (fs.exists(backupFile)) { fs.delete(backupFile, true); } } else { isActiveStatus = false; <START> Path activeFile = new Path(activePath, fileName); <END> if (fs.exists(activeFile)) { fs.delete(activeFile, true); } } startPingChecker(); }</code><technical_language>refactor duplicate codes</technical_language>

Target:
private void createMasterFile(boolean isActive) throws IOException { String fileName = masterName.replaceAll(":", "_"); Path path = null; if (isActive) { path = new Path(activePath, fileName); } else { path = new Path(backupPath, fileName); } StringBuilder sb = new StringBuilder(); InetSocketAddress address = getHostAddress(HAConstants.MASTER_CLIENT_RPC_ADDRESS); sb.append(address.getAddress().getHostAddress()).append(":").append(address.getPort()).append("_"); address = getHostAddress(HAConstants.RESOURCE_TRACKER_RPC_ADDRESS); sb.append(address.getAddress().getHostAddress()).append(":").append(address.getPort()).append("_"); address = getHostAddress(HAConstants.CATALOG_ADDRESS); sb.append(address.getAddress().getHostAddress()).append(":").append(address.getPort()).append("_"); address = getHostAddress(HAConstants.MASTER_INFO_ADDRESS); sb.append(address.getAddress().getHostAddress()).append(":").append(address.getPort()); FSDataOutputStream out = fs.create(path); try { out.writeUTF(sb.toString()); out.hsync(); out.close(); } catch (FileAlreadyExistsException e) { createMasterFile(false); } Path file = null; if (isActive) { isActiveStatus = true; file = new Path(backupPath, fileName); } else { isActiveStatus = false; file = new Path(activePath, fileName); } if (fs.exists(file)) { fs.delete(file, true); } startPingChecker(); }
Source:
<code>void validateSanityForUndelete(StoreKey key, List<IndexValue> values, short lifeVersion) throws StoreException { if (values == null || values.isEmpty()) { throw new StoreException("Id " + key + " not present in index " + dataDir, StoreErrorCodes.ID_Not_Found); } if (!IndexValue.hasLifeVersion(lifeVersion)) { validateSanityForUndeleteWithoutLifeVersion(key, values); return; } IndexValue firstValue = values.get(values.size() - 1); <START> IndexValue lastValue = values.get(0); <END> if (!firstValue.isPut()) { throw new StoreException("Id " + key + " requires first value to be a put in index " + dataDir, StoreErrorCodes.ID_Deleted_Permanently); } if (lastValue.getLifeVersion() >= lifeVersion) { throw new StoreException( "LifeVersion conflict in index. Id " + key + " LifeVersion: " + lastValue.getLifeVersion() + " Undelete LifeVersion: " + lifeVersion, StoreErrorCodes.Life_Version_Conflict); } }</code><technical_language>I get point I suggest reverse values hand logic easier understand more consistent java docs of this method</technical_language>

Target:
void validateSanityForUndelete(StoreKey key, List<IndexValue> values, short lifeVersion) throws StoreException { if (values == null || values.isEmpty()) { throw new StoreException("Id " + key + " not present in index " + dataDir, StoreErrorCodes.ID_Not_Found); } if (!IndexValue.hasLifeVersion(lifeVersion)) { validateSanityForUndeleteWithoutLifeVersion(key, values); return; } IndexValue firstValue = values.get(0); IndexValue lastValue = values.get(values.size() - 1); if (!lastValue.isPut()) { throw new StoreException("Id " + key + " requires first value to be a put in index " + dataDir, StoreErrorCodes.ID_Deleted_Permanently); } if (firstValue.getLifeVersion() >= lifeVersion) { throw new StoreException( "LifeVersion conflict in index. Id " + key + " LifeVersion: " + firstValue.getLifeVersion() + " Undelete LifeVersion: " + lifeVersion, StoreErrorCodes.Life_Version_Conflict); } maybeChangeExpirationDate(lastValue, values); if (isExpired(lastValue)) { throw new StoreException("Id " + key + " already expired in index " + dataDir, StoreErrorCodes.TTL_Expired); } }
Source:
<code>public boolean onOptionsItemSelected(@NonNull MenuItem item) { if (item.getItemId() == R.id.export_logcat) { AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this); alertBuilder.setTitle("Warning!").setMessage("Logs may contain sensitive information"); <START> alertBuilder.setPositiveButton("Continue", (dialog, which) -> { <END> try { File filename = new File(UserPreferences.getDataFolder(null), "full-logs.txt"); filename.createNewFile(); String cmd = "logcat -d -f " + filename.getAbsolutePath(); Runtime.getRuntime().exec(cmd); try { Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/*"); String authString = getString(de.danoeh.antennapod.core.R.string.provider_authority); Uri fileUri = FileProvider.getUriForFile(this, authString, filename); i.putExtra(Intent.EXTRA_STREAM, fileUri); i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) { PackageManager pm = getPackageManager(); List<ResolveInfo> resInfos = pm.queryIntentActivities(i, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo resolveInfo : resInfos) { String packageName = resolveInfo.activityInfo.packageName; grantUriPermission(packageName, fileUri, Intent.FLAG_GRANT_READ_URI_PERMISSION); } } String chooserTitle = getString(de.danoeh.antennapod.core.R.string.share_file_label); startActivity(Intent.createChooser(i, chooserTitle)); } catch (Exception e) { e.printStackTrace(); int strResId = R.string.log_file_share_exception; Snackbar.make(findViewById(android.R.id.content), strResId, Snackbar.LENGTH_LONG) .show(); } } catch (IOException e) { e.printStackTrace(); Snackbar.make(findViewById(android.R.id.content), e.getMessage(), Snackbar.LENGTH_LONG).show(); } dialog.dismiss(); }); alertBuilder.setNegativeButton("Cancel", (dialog, which) -> dialog.cancel()); alertBuilder.create(); alertBuilder.show(); return true; } return super.onOptionsItemSelected(item); }</code><technical_language>Please string resources, text translated</technical_language>

Target:
public boolean onOptionsItemSelected(@NonNull MenuItem item) { if (item.getItemId() == R.id.export_logcat) { AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this); alertBuilder.setMessage(R.string.confirm_export_log_dialog_message); alertBuilder.setPositiveButton(R.string.confirm_label, (dialog, which) -> { exportLog(); dialog.dismiss(); }); alertBuilder.setNegativeButton(R.string.cancel_label, null); alertBuilder.show(); return true; } return super.onOptionsItemSelected(item); }
Source:
<code>public GenericEdge(GenericEdge copyMe) { <START> this(new GenericVertex(copyMe.source), new GenericVertex(copyMe.target), new HashMap<>(copyMe.getProperties())); <END> }</code><technical_language>access properties name method, mix</technical_language>

Target:
public GenericEdge(GenericEdge copyMe) { this(new GenericVertex(copyMe.source), new GenericVertex(copyMe.target), new HashMap<>(copyMe.properties)); }
Source:
<code>public boolean shouldBackup() { return true; <START> } <END></code><technical_language>This improved checking backup count: @Override public boolean shouldBackup() { return mapContainer.getTotalBackupCount() > 0; }</technical_language>

Target:
public boolean shouldBackup() { return mapContainer.getTotalBackupCount() > 0; }
Source:
<code>private boolean executeSshSoftFencingCommand(String version) { boolean ret = false; try ( final EngineSSHClient sshClient = new EngineSSHClient(); final ByteArrayOutputStream cmdOut = new ByteArrayOutputStream(); final ByteArrayOutputStream cmdErr = new ByteArrayOutputStream(); ) { try { log.info("Opening SSH Soft Fencing session on host '{}'", getVds().getHostName()); sshClient.setVds(getVds()); sshClient.useDefaultKeyPair(); sshClient.connect(); sshClient.authenticate(); log.info("Executing SSH Soft Fencing command on host '{}'", getVds().getHostName()); sshClient.executeCommand( Config.<String> getValue(ConfigValues.SshSoftFencingCommand, version), null, cmdOut, cmdErr ); ret = true; } catch (Exception ex) { log.error("SSH Soft Fencing command failed on host '{}': {}\nStdout: {}\nStderr: {}", getVds().getHostName(), ex.getMessage(), cmdOut.toString(), <START> cmdErr.toString()); <END> log.debug("Exception", ex); } } catch(IOException e) { log.error("IOException", e); } return ret; }</code><technical_language>toString</technical_language>

Target:
private boolean executeSshSoftFencingCommand(String version) { boolean ret = false; try ( final EngineSSHClient sshClient = new EngineSSHClient(); final ByteArrayOutputStream cmdOut = new ByteArrayOutputStream(); final ByteArrayOutputStream cmdErr = new ByteArrayOutputStream(); ) { try { log.info("Opening SSH Soft Fencing session on host '{}'", getVds().getHostName()); sshClient.setVds(getVds()); sshClient.useDefaultKeyPair(); sshClient.connect(); sshClient.authenticate(); log.info("Executing SSH Soft Fencing command on host '{}'", getVds().getHostName()); sshClient.executeCommand( Config.<String> getValue(ConfigValues.SshSoftFencingCommand, version), null, cmdOut, cmdErr ); ret = true; } catch (Exception ex) { log.error("SSH Soft Fencing command failed on host '{}': {}\nStdout: {}\nStderr: {}", getVds().getHostName(), ex.getMessage(), cmdOut, cmdErr); log.debug("Exception", ex); } } catch(IOException e) { log.error("IOException", e); } return ret; }
Source:
<code>public void startBackgroundTasks() { <START> scheduler.schedule(paCompletePeopleUpdater().withName("PA Complete People Updater"), PEOPLE_COMPLETE_INGEST); <END> scheduler.schedule(paDailyPeopleUpdater().withName("PA People Updater"), PEOPLE_INGEST); scheduler.schedule(paFeaturesUpdater().withName("PA Features Updater"), FEATURES_INGEST); scheduler.schedule(paFileUpdater().withName("PA File Updater"), RECENT_FILE_DOWNLOAD); scheduler.schedule(paCompleteUpdater().withName("PA Complete Updater"), COMPLETE_INGEST); scheduler.schedule(paRecentUpdater().withName("PA Recent Updater"), RECENT_FILE_INGEST); log.record(new AdapterLogEntry(Severity.INFO).withDescription("PA update scheduled task installed").withSource(PaCompleteUpdater.class)); }</code><technical_language>add another property enable/disable this ingest independently other PA ingests</technical_language>

Target:
public void startBackgroundTasks() { if (peopleEnabled) { scheduler.schedule(paCompletePeopleUpdater().withName("PA Complete People Updater"), PEOPLE_COMPLETE_INGEST); scheduler.schedule(paDailyPeopleUpdater().withName("PA People Updater"), PEOPLE_INGEST); } scheduler.schedule(paChannelsUpdater().withName("PA Channels Updater"), CHANNELS_INGEST); scheduler.schedule(paFeaturesUpdater().withName("PA Features Updater"), FEATURES_INGEST); scheduler.schedule(paFileUpdater().withName("PA File Updater"), RECENT_FILE_DOWNLOAD); scheduler.schedule(paCompleteUpdater().withName("PA Complete Updater"), COMPLETE_INGEST); scheduler.schedule(paRecentUpdater().withName("PA Recent Updater"), RECENT_FILE_INGEST); log.record(new AdapterLogEntry(Severity.INFO).withDescription("PA update scheduled task installed").withSource(PaCompleteUpdater.class)); }
Source:
<code>public ValidationResult diskImagesNotExist() { <START> List<String> disksNotExistInDbIds = new ArrayList<>(); for (Guid diskGuid : diskGuids) { if (!isDiskExists(diskGuid)) { disksNotExistInDbIds.add(diskGuid.toString()); } } <END> if (!disksNotExistInDbIds.isEmpty()) { return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_DISKS_NOT_EXIST, String.format("$diskIds %s", StringUtils.join(disksNotExistInDbIds, ", "))); } return ValidationResult.VALID; }</code><technical_language>I understand this code moved DiskValidator want this patch small possible, a followup patch convert this boiler-plate a more elegant stream: String disksNotExistInDbIds = diskGuids.stream() .filter(d -> !isDiskExists(d)) .map(Object::toString) .collect(Collectors.joining(", "));</technical_language>

Target:
public ValidationResult diskImagesNotExist() { List<String> disksNotExistInDbIds = diskGuids.stream() .filter(guid -> !isDiskExists(guid)) .map(Guid::toString) .collect(Collectors.toList()); if (!disksNotExistInDbIds.isEmpty()) { return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_DISKS_NOT_EXIST, String.format("$diskIds %s", StringUtils.join(disksNotExistInDbIds, ", "))); } return ValidationResult.VALID; }
Source:
<code>public void addUserMetaData(Map<String, String> userMetaDataMap) { StringBuilder userMetadata = new StringBuilder("?SDK=Android&Version=" + SDK_VERSION); int baseLength = userMetadata.length(); if (userMetaDataMap != null) { LOGGER.warn("Keynames 'SDK' and 'Version' are reserved and will be skipped"); for (Map.Entry<String, String> metaData : userMetaDataMap.entrySet()) { if (!(metaData.getKey().equals("SDK") || metaData.getKey().equals("Version"))) { userMetadata.append("&" + metaData.getKey() + "=" + metaData.getValue()); <START> } <END> } } if(userMetadata.length() > 255) { LOGGER.warn("Too many characters. User metadata was truncated.", new IllegalArgumentException("Total number of characters in user metadata" + " cannot exceed " + (255 - baseLength))); this.userMetaData = userMetadata.substring(0, 255); } else { this.userMetaData = userMetadata.toString(); } }</code><technical_language>move warn log message else log key names used</technical_language>

Target:
public void addUserMetaData(Map<String, String> userMetaDataMap) { StringBuilder userMetadata = new StringBuilder("?SDK=Android&Version=" + SDK_VERSION); int baseLength = userMetadata.length(); if (userMetaDataMap != null) { for (Map.Entry<String, String> metaData : userMetaDataMap.entrySet()) { if (!(metaData.getKey().equals("SDK") || metaData.getKey().equals("Version"))) { userMetadata.append("&" + metaData.getKey() + "=" + metaData.getValue()); } else { LOGGER.warn("Keynames 'SDK' and 'Version' are reserved and will be skipped"); } } } if(userMetadata.length() > 255) { LOGGER.warn("Too many characters. User metadata was truncated.", new IllegalArgumentException("Total number of characters in user metadata" + " cannot exceed " + (255 - baseLength))); this.userMetaData = userMetadata.substring(0, 255); } else { this.userMetaData = userMetadata.toString(); } }
Source:
<code>protected AttributesImpl cloneWithGmlId(AttributesImpl atts, String gmlId) { if (gmlId == null) { return atts; } AttributesImpl result; if (atts == null) { result = new AttributesImpl(); } else { result = new AttributesImpl(atts); } <START> if (encodeGmlId) addGmlId(result, gmlId); <END> return result; }</code><technical_language>beginning, if gmlId == null || !encodeGMlId</technical_language>

Target:
protected AttributesImpl cloneWithGmlId(AttributesImpl atts, String gmlId) { if (gmlId == null || !encodeGmlId) { return atts; } AttributesImpl result; if (atts == null) { result = new AttributesImpl(); } else { result = new AttributesImpl(atts); } addGmlId(result, gmlId); return result; }
Source:
<code>public void clickRemoveInstructorFromCourse(String courseId) { List<WebElement> instructorRows = instructorTable.findElement(By.tagName("tbody")).findElements(By.tagName("tr")); WebElement deleteButton = null; for (WebElement instructorRow : instructorRows) { List<WebElement> cells = instructorRow.findElements(By.tagName("td")); if (cells.get(0).getText().startsWith("[" + courseId + "]")) { deleteButton = cells.get(1).findElement(By.className("btn-danger")); } } if (deleteButton == null) { fail("Instructor to be deleted is not found"); } click(deleteButton); waitForPageToLoad(true); <START> verifyStatusMessage("Instructor is successfully deleted from course \"" + courseId + "\""); <END> }</code><technical_language>verifyStatusMessage in AdminAccountsPageE2ETest instead feel belongs action related methods</technical_language>

Target:
public void clickRemoveInstructorFromCourse(String courseId) { List<WebElement> instructorRows = instructorTable.findElement(By.tagName("tbody")).findElements(By.tagName("tr")); WebElement deleteButton = null; for (WebElement instructorRow : instructorRows) { List<WebElement> cells = instructorRow.findElements(By.tagName("td")); if (cells.get(0).getText().startsWith("[" + courseId + "]")) { deleteButton = cells.get(1).findElement(By.className("btn-danger")); } } if (deleteButton == null) { fail("Instructor to be deleted is not found"); } click(deleteButton); waitForPageToLoad(true); }
Source:
<code>public HttpRequests(HttpParams params, String username, String password, Map<String, String> customHeaders){ this.jsonHelper = new JSONHelper(); this.context = new BasicHttpContext(); HttpProtocolParams.setUserAgent(params, this.getUserAgent()); ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRoute() { @Override public int getMaxForRoute(HttpRoute route) { return CONN_PER_ROUT; } }); ClientConnectionManager manager = getClientConnectionManager(params); DefaultHttpClient httpClient = new DefaultHttpClient(manager,params); addDebuggingInterceptor(httpClient); this.httpClient = httpClient; String authHeaderValue = null; if (!Strings.isNullOrEmpty(username) && !Strings.isNullOrEmpty(password)) { String authString = username + ":" + password; Base64 base64 = new Base64(); authHeaderValue = "Basic " + new String(base64.encode(authString.getBytes())); } if (customHeaders != null) { this.requestHeaders = customHeaders; if (customHeaders.containsKey("authorization")) { if (authHeaderValue != null) { logger.warning("custom header \"authorization\" and username/password are both set; will use the value from custom header"); } } else { if (authHeaderValue != null) { this.requestHeaders = new HashMap<String, String>(); customHeaders.putAll(customHeaders); customHeaders.put("authorization", authHeaderValue); } } <START> } <END> }</code><technical_language>Authorization header set if already-existing custom headers (customHeaders != null)</technical_language>

Target:
public HttpRequests(HttpParams params, String username, String password, Map<String, String> customHeaders){ this.jsonHelper = new JSONHelper(); this.context = new BasicHttpContext(); HttpProtocolParams.setUserAgent(params, this.getUserAgent()); ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRoute() { @Override public int getMaxForRoute(HttpRoute route) { return CONN_PER_ROUT; } }); ClientConnectionManager manager = getClientConnectionManager(params); DefaultHttpClient httpClient = new DefaultHttpClient(manager,params); addDebuggingInterceptor(httpClient); this.httpClient = httpClient; String authHeaderValue = null; if (!Strings.isNullOrEmpty(username) && !Strings.isNullOrEmpty(password)) { String authString = username + ":" + password; Base64 base64 = new Base64(); authHeaderValue = "Basic " + new String(base64.encode(authString.getBytes())); } this.requestHeaders = new HashMap<String, String>(); if (customHeaders != null) { for (Map.Entry<String, String> header : customHeaders.entrySet()) { this.requestHeaders.put(header.getKey().toLowerCase(), header.getValue()); } } if (authHeaderValue != null) { if (this.requestHeaders.containsKey("authorization")) { logger.warning( "custom header \"authorization\" and username/password are both set; will use the value from custom header" ); } else { this.requestHeaders.put("authorization", authHeaderValue); } } }
Source:
<code>public void configure(RuntimeHarness harness, File workingDir) throws IOException, URISyntaxException { File dest = new File(workingDir, "web/root.war/WEB-INF/"); dest.mkdirs(); <START> dest = new File(workingDir + "/web/root.war/WEB-INF/", "web.xml"); <END> try (InputStream in = getResource("test-web.xml").openStream()) { FileUtils.copyInputStreamToFile(in, dest); } try (InputStream in = getResource("test-oauth2Grant.jsp").openStream()) { FileUtils.copyInputStreamToFile(in, new File(workingDir, "web/root.war/oauth2Grant.jsp")); } }</code><technical_language>Files.copy</technical_language>

Target:
public void configure(RuntimeHarness harness, File workingDir) throws IOException, URISyntaxException { File webInf = new File(workingDir, "web/root.war/WEB-INF/"); if (!webInf.mkdirs()) { throw new IOException(String.format("Unable to create %s directory", webInf.getAbsolutePath())); } Files.copy(Paths.get(getResource("test-web.xml").toURI()), webInf.toPath().resolve("web.xml")); Files.copy(Paths.get(getResource("test-oauth2Grant.jsp").toURI()), workingDir.toPath().resolve("web/root.war/oauth2Grant.jsp")); }
Source:
<code>public synchronized void executeDiagnoserIncr(String diagnoser) { <START> executeDiagnoserCount.scope(diagnoser); <END> }</code><technical_language>missing incr()</technical_language>

Target:
public synchronized void executeDiagnoserIncr(String diagnoser) { executeDiagnoserCount.scope(diagnoser).incr(); }
Source:
<code>final void writeRawValue(Object value) { ByteString byteString = (ByteString) value; <START> Binary binary = Binary.fromUnmodifiedByteArray(byteString.toByteArray()); <END> recordConsumer.addBinary(binary); }</code><technical_language>Is ByteString immutable? If isn't, I this fromReusedByteArray</technical_language>

Target:
final void writeRawValue(Object value) { ByteString byteString = (ByteString) value; Binary binary = Binary.fromConstantByteArray(byteString.toByteArray()); recordConsumer.addBinary(binary); }
Source:
<code>public void setup(){ broker = new EmbeddedActiveMQBroker(); broker.start(); <START> flowTestRule.withFlow((Flow) moduleUnderTest.getFlow("Jms Flow")); <END> }</code><technical_language>previous, defined Module<Flow> need cast</technical_language>

Target:
public void setup() { flowTestRule.withFlow(moduleUnderTest.getFlow("Jms Flow")); }
Source:
<code>private void revertPreviousHandlers() { getParameters().decrementExecutionIndex(); if (canRevertTasks()) { logRollbackedTask(); getParameters().setExecutionReason(CommandExecutionReason.ROLLBACK_FLOW); getCurrentTaskHandler().compensate(); if (!hasRevertTask()) { revertPreviousHandlers(); } } else { <START> setSucceeded(true); <END> } }</code><technical_language>consider flipping if else blocks, a dangling on-liner</technical_language>

Target:
private void revertPreviousHandlers() { getParameters().decrementExecutionIndex(); if (hasStepsToRevert()) { logRollbackedTask(); getParameters().setExecutionReason(CommandExecutionReason.ROLLBACK_FLOW); getCurrentTaskHandler().compensate(); if (!hasRevertTask()) { revertPreviousHandlers(); } } else { setSucceeded(true); } }
Source:
<code>public void registerLayers(MapActivity activity) { if(parkingLayer != null) { activity.getMapView().removeLayer(parkingLayer); } <START> parkingLayer = new ParkingPositionLayer(activity, this); <END> registerWidget(activity); }</code><technical_language>ParkingPositionLayer - delete</technical_language>

Target:
public void registerLayers(MapActivity activity) { registerWidget(activity); }
Source:
<code>void load(File file) throws IOException { long start = Time.monotonicNow(); <START> FSImageFormatProtobuf.Loader.DigestThread dt = <END> new FSImageFormatProtobuf.Loader.DigestThread(file); dt.start(); RandomAccessFile raFile = new RandomAccessFile(file, "r"); FileInputStream fin = new FileInputStream(file); try { loadInternal(raFile, fin); try { dt.join(); imgDigest = dt.getDigest(); if (dt.getException() != null) { throw dt.getException(); } } catch (InterruptedException ie) { throw new IOException(ie); } long end = Time.monotonicNow(); LOG.info("Loaded FSImage in seconds.", (end - start) / 1000); } finally { fin.close(); raFile.close(); } }</code><technical_language>DigestThread? Instead of full declaration</technical_language>

Target:
void load(File file) throws IOException { long start = Time.monotonicNow(); DigestThread dt = new DigestThread(file); dt.start(); RandomAccessFile raFile = new RandomAccessFile(file, "r"); FileInputStream fin = new FileInputStream(file); try { loadInternal(raFile, fin); try { dt.join(); imgDigest = dt.getDigest(); } catch (InterruptedException ie) { throw new IOException(ie); } long end = Time.monotonicNow(); LOG.info("Loaded FSImage in seconds.", (end - start) / 1000); } finally { fin.close(); raFile.close(); } }
Source:
<code>protected String getDescriptivePayeeTypesAsString(Collection<String> payeeTypeCodes) { List<String> payeeTypeDescriptions = new ArrayList<>(); for (String payeeTypeCode : payeeTypeCodes) { String description = disbursementVoucherPayeeService.getPayeeTypeDescription(payeeTypeCode); if (payeeTypeDescriptions.indexOf(description) == -1) { payeeTypeDescriptions.add(description); } } <START> return this.convertListToString(payeeTypeDescriptions); <END> }</code><technical_language>Is "this" needed here</technical_language>

Target:
protected String getDescriptivePayeeTypesAsString(Collection<String> payeeTypeCodes) { List<String> payeeTypeDescriptions = new ArrayList<>(); for (String payeeTypeCode : payeeTypeCodes) { String description = disbursementVoucherPayeeService.getPayeeTypeDescription(payeeTypeCode); if (payeeTypeDescriptions.indexOf(description) == -1) { payeeTypeDescriptions.add(description); } } return convertListToString(payeeTypeDescriptions); }
Source:
<code>public String getViewSql(String tableName, String schemaName) { return "SELECT DISTINCT COLUMN_FAMILY, TENANT_ID FROM " + "SYSTEM.CHILD_LINK " + "WHERE TABLE_NAME = \'" + tableName + "\' " <START> + (!StringUtil.EMPTY_STRING.equals(schemaName) ? "AND TABLE_SCHEM = \'" <END> + schemaName + "\' " : "") + "AND LINK_TYPE = " + PTable.LinkType.CHILD_TABLE.getSerializedValue(); }</code><technical_language>a long check emptiness of a string. add isEmpty() fn in StringUtil class, if schemaName.isEmpty() is sufficient for reason</technical_language>

Target:
public String getViewSql(String tableName, String schemaName) { return "SELECT DISTINCT COLUMN_FAMILY, TENANT_ID FROM " + "SYSTEM.CHILD_LINK " + "WHERE TABLE_NAME = \'" + tableName + "\'" + (!Strings.isNullOrEmpty(schemaName) ? " AND TABLE_SCHEM = \'" + schemaName + "\'" : "") + " AND LINK_TYPE = " + PTable.LinkType.CHILD_TABLE.getSerializedValue(); }
Source:
<code>public Result<K, T> execute(Query<K, T> query) throws GoraException { String[] avFields = getFieldsToQuery(query.getFields()); List<String> dbFields = new ArrayList<>(); for (String af : avFields) { dbFields.add(kuduMapping.getFields().get(af).getName()); } try { ColumnSchema column = table.getSchema().getColumn(kuduMapping.getPrimaryKey().get(0).getName()); dbFields.add(kuduMapping.getPrimaryKey().get(0).getName()); KuduScanner.KuduScannerBuilder scannerBuilder = client.newScannerBuilder(table); if (query.getLimit() != -1) { scannerBuilder.limit(query.getLimit()); } scannerBuilder.setProjectedColumnNames(dbFields); List<KuduPredicate> rangePredicates = KuduClientUtils.createRangePredicate(column, query.getStartKey(), query.getEndKey()); for (KuduPredicate predicate : rangePredicates) { scannerBuilder.addPredicate(predicate); } scannerBuilder.addPredicate(KuduPredicate.newIsNotNullPredicate(column)); KuduScanner build = scannerBuilder.build(); <START> KuduResult<K, T> kuduResult = new KuduResult<>(this, query, build); <END> return kuduResult; } catch (Exception e) { throw new GoraException(e); } }</code><technical_language>Immediately return this expression instead of assigning temporary variable "kuduResult"</technical_language>

Target:
public Result<K, T> execute(Query<K, T> query) throws GoraException { String[] avFields = getFieldsToQuery(query.getFields()); List<String> dbFields = new ArrayList<>(); for (String af : avFields) { dbFields.add(kuduMapping.getFields().get(af).getName()); } try { ColumnSchema column = table.getSchema().getColumn(kuduMapping.getPrimaryKey().get(0).getName()); dbFields.add(kuduMapping.getPrimaryKey().get(0).getName()); List<KuduPredicate> rangePredicates = KuduClientUtils.createRangePredicate(column, query.getStartKey(), query.getEndKey()); rangePredicates.add(KuduPredicate.newIsNotNullPredicate(column)); KuduScanner build = createScanner(rangePredicates, dbFields, query.getLimit()); return new KuduResult<>(this, query, build); } catch (Exception e) { throw new GoraException(e); } }
Source:
<code>private static String getContent(String location) throws IOException { <START> return IOUtils.toString(ClassPathBasedPatentServiceFacade.class.getResourceAsStream(location), "utf8"); <END> }</code><technical_language>IDE says: StandardCharsets.UTF_8 instead</technical_language>

Target:
private static String getContent(String location) throws IOException { return IOUtils.toString(ClassPathBasedPatentServiceFacade.class.getResourceAsStream(location), StandardCharsets.UTF_8); }
Source:
<code>private IllegalStateException methodInvocationReturnedNull(Object[] args) { return new IllegalStateException( <START> "method invocation returned null: " + getName() + Tuple.copyOf(Arrays.asList(args))); <END> }</code><technical_language>Tuple.of(args) (or fail spread args of Java's Obj/Obj[] ambiguity?)</technical_language>

Target:
private NullPointerException methodInvocationReturnedNull(Object[] args) { return new NullPointerException( "method invocation returned null: " + getName() + Tuple.of(args)); }
Source:
<code>public static void main(String[] args) { if (args.length != 1) { System.err .println("usage: java edu.illinois.cs.cogcomp.lbj.pos.POSTagPlain <text file>"); System.exit(1); } String testingFile = args[0]; POSTagger tagger = new POSTagger(); Parser parser = new PlainToTokenParser(new WordSplitter(new SentenceSplitter(testingFile))); String sentence = ""; for (Token word = (Token) parser.next(); word != null; word = (Token) parser.next()) { String tag = tagger.discreteValue(word); <START> sentence += " (" + tag + " " + word.form + ")"; <END> if (word.next == null) { logger.info(sentence.substring(1)); sentence = ""; } } }</code><technical_language>main(), STDOUT</technical_language>

Target:
public static void main(String[] args) { if (args.length != 1) { System.err .println("usage: java edu.illinois.cs.cogcomp.lbj.pos.POSTagPlain <text file>"); System.exit(1); } String testingFile = args[0]; POSTagger tagger = new POSTagger(); Parser parser = new PlainToTokenParser(new WordSplitter(new SentenceSplitter(testingFile))); String sentence = ""; for (Token word = (Token) parser.next(); word != null; word = (Token) parser.next()) { String tag = tagger.discreteValue(word); sentence += " (" + tag + " " + word.form + ")"; if (word.next == null) { System.out.println(sentence.substring(1)); sentence = ""; } } }
Source:
<code>public void aFirmware(final Map<String, String> settings) { DeviceModel deviceModel = this.deviceModelRepo .findByModelCode(getString(settings, PlatformKeys.DEVICEMODEL_MODELCODE)); if (deviceModel == null) { deviceModel = this.deviceModelSteps.aDeviceModel(settings); } <START> String comm = getString(settings, PlatformKeys.FIRMWARE_MODULE_VERSION_COMM, <END> PlatformDefaults.FIRMWARE_MODULE_VERSION_COMM); comm = (comm.equals("")) ? null : comm; String func = getString(settings, PlatformKeys.FIRMWARE_MODULE_VERSION_FUNC, PlatformDefaults.FIRMWARE_MODULE_VERSION_FUNC); func = (func.equals("")) ? null : func; String ma = getString(settings, PlatformKeys.FIRMWARE_MODULE_VERSION_MA, PlatformDefaults.FIRMWARE_MODULE_VERSION_MA); ma = (ma.equals("")) ? null : ma; String mbus = getString(settings, PlatformKeys.FIRMWARE_MODULE_VERSION_MBUS, PlatformDefaults.FIRMWARE_MODULE_VERSION_MBUS); mbus = (mbus.equals("")) ? null : mbus; String sec = getString(settings, PlatformKeys.FIRMWARE_MODULE_VERSION_SEC, PlatformDefaults.FIRMWARE_MODULE_VERSION_SEC); sec = (sec.equals("")) ? null : sec; final FirmwareModuleData firmwareModuleData = new FirmwareModuleData(comm, func, ma, mbus, sec); final Firmware entity = new Firmware(deviceModel, getString(settings, PlatformKeys.FIRMWARE_FILENAME, ""), getString(settings, PlatformKeys.FIRMWARE_DESCRIPTION, PlatformDefaults.FIRMWARE_DESCRIPTION), getBoolean(settings, PlatformKeys.FIRMWARE_PUSH_TO_NEW_DEVICES, PlatformDefaults.FIRMWARE_PUSH_TO_NEW_DEVICE), firmwareModuleData); this.firmwareRepo.save(entity); }</code><technical_language>reduce code duplication, create a function string replaces empty values</technical_language>

Target:
public void aFirmware(final Map<String, String> settings) { DeviceModel deviceModel = this.deviceModelRepo .findByModelCode(getString(settings, PlatformKeys.DEVICEMODEL_MODELCODE)); if (deviceModel == null) { deviceModel = this.deviceModelSteps.aDeviceModel(settings); } final String comm = getNullOrNonEmptyString(settings, PlatformKeys.FIRMWARE_MODULE_VERSION_COMM, PlatformDefaults.FIRMWARE_MODULE_VERSION_COMM); final String func = getNullOrNonEmptyString(settings, PlatformKeys.FIRMWARE_MODULE_VERSION_FUNC, PlatformDefaults.FIRMWARE_MODULE_VERSION_FUNC); final String ma = getNullOrNonEmptyString(settings, PlatformKeys.FIRMWARE_MODULE_VERSION_MA, PlatformDefaults.FIRMWARE_MODULE_VERSION_MA); final String mbus = getNullOrNonEmptyString(settings, PlatformKeys.FIRMWARE_MODULE_VERSION_MBUS, PlatformDefaults.FIRMWARE_MODULE_VERSION_MBUS); final String sec = getNullOrNonEmptyString(settings, PlatformKeys.FIRMWARE_MODULE_VERSION_SEC, PlatformDefaults.FIRMWARE_MODULE_VERSION_SEC); final FirmwareModuleData firmwareModuleData = new FirmwareModuleData(comm, func, ma, mbus, sec); final Firmware entity = new Firmware(deviceModel, getString(settings, PlatformKeys.FIRMWARE_FILENAME, ""), getString(settings, PlatformKeys.FIRMWARE_DESCRIPTION, PlatformDefaults.FIRMWARE_DESCRIPTION), getBoolean(settings, PlatformKeys.FIRMWARE_PUSH_TO_NEW_DEVICES, PlatformDefaults.FIRMWARE_PUSH_TO_NEW_DEVICE), firmwareModuleData); this.firmwareRepo.save(entity); }
Source:
<code>protected abstract void serializeOperatorState(OperatorState operatorState, DataOutputStream dos) throws IOException; protected abstract OperatorState deserializeOperatorState(DataInputStream dis) throws IOException; protected void serializeSubtaskState(OperatorSubtaskState subtaskState, DataOutputStream dos) throws IOException { serializeSingleton(subtaskState.getManagedOperatorState(), dos, MetadataV2V3SerializerBase::serializeOperatorStateHandle); serializeSingleton(subtaskState.getRawOperatorState(), dos, MetadataV2V3SerializerBase::serializeOperatorStateHandle); serializeKeyedStateCol(subtaskState.getManagedKeyedState(), dos); serializeKeyedStateCol(subtaskState.getRawKeyedState(), dos); <START> serializeCollection(subtaskState.getInputChannelState(), dos, this::serializeInputChannelStateHandle); serializeCollection(subtaskState.getResultSubpartitionState(), dos, this::serializeResultSubpartitionStateHandle); <END> }</code><technical_language>I noticed weird here. MetadataV2Serializer serialize checkpoint this version, however, changed serialized format of MetadataV2Serializer, serialize 0 stream here. other hand, MetadataV2Serializer#deserializeSubtaskState ignore written part return a StateObjectCollection.empty(). In other words, this PR changed logic of serialize deserialize of MetadataV2Serializer. meet this error in real environment MetadataV3Serializer serialize</technical_language>

Target:
protected abstract void serializeOperatorState(OperatorState operatorState, DataOutputStream dos) throws IOException; protected abstract OperatorState deserializeOperatorState(DataInputStream dis) throws IOException; protected void serializeSubtaskState(OperatorSubtaskState subtaskState, DataOutputStream dos) throws IOException { serializeSingleton(subtaskState.getManagedOperatorState(), dos, MetadataV2V3SerializerBase::serializeOperatorStateHandle); serializeSingleton(subtaskState.getRawOperatorState(), dos, MetadataV2V3SerializerBase::serializeOperatorStateHandle); serializeKeyedStateCol(subtaskState.getManagedKeyedState(), dos); serializeKeyedStateCol(subtaskState.getRawKeyedState(), dos); }
Source:
<code>public ApacheClient(HttpClient client) { this.client = client; ProxyRedirectHandler proxyRedirectHandler = null; <START> if (client instanceof DefaultHttpClient) { <END> DefaultHttpClient defaultHttpClient = (DefaultHttpClient) client; proxyRedirectHandler = new ProxyRedirectHandler(defaultHttpClient.getRedirectHandler()); defaultHttpClient.setRedirectHandler(proxyRedirectHandler); } redirectHandler = proxyRedirectHandler; }</code><technical_language>I want AbstractHttpClient support HttpClient implementations (even AndroidApacheClient), right</technical_language>

Target:
public ApacheClient(HttpClient client) { this.client = client; ProxyRedirectHandler proxyRedirectHandler = null; if (client instanceof AbstractHttpClient) { AbstractHttpClient defaultHttpClient = (AbstractHttpClient) client; proxyRedirectHandler = new ProxyRedirectHandler(defaultHttpClient.getRedirectHandler()); defaultHttpClient.setRedirectHandler(proxyRedirectHandler); } redirectHandler = proxyRedirectHandler; }
Source:
<code>private static Map<String, TumorType> getUnmodifiableTumorTypesByVersion(Map<String, TumorType> tumorTypeMap) { Map<String, TumorType> unmodifiableTumorTypeMap = new HashMap<String, TumorType>(tumorTypeMap.size()); for (Map.Entry<String, TumorType> entry : tumorTypeMap.entrySet()) { <START> unmodifiableTumorTypeMap.put(entry.getKey(), new TumorType(entry.getValue())); <END> } return Collections.unmodifiableMap(unmodifiableTumorTypeMap); }</code><technical_language>Ok, I .. clone function is for returned values CacheUtil. duplication cache (which more primitive constructors)</technical_language>

Target:
private static Map<String, TumorType> getUnmodifiableTumorTypesByVersion(Map<String, TumorType> tumorTypeMap) { Map<String, TumorType> unmodifiableTumorTypeMap = new HashMap<String, TumorType>(tumorTypeMap.size()); for (Map.Entry<String, TumorType> entry : tumorTypeMap.entrySet()) { unmodifiableTumorTypeMap.put(entry.getKey(), entry.getValue().deepCopy()); } return Collections.unmodifiableMap(unmodifiableTumorTypeMap); }
Source:
<code>public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException, DataAccessException { UserDetails userDetails = userDetailsService.loadUserByUsername(userId); <START> return (SocialUserDetails) userDetails; <END> }</code><technical_language>lines 21-22 combined</technical_language>

Target:
public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException, DataAccessException { return (SocialUserDetails) userDetailsService.loadUserByUsername(userId); }
Source:
<code>private static boolean parentUseValue(Tree child) { Tree parent = child.getParent(); if (parent == null) { <START> return false; <END> } if (parent.is(Tree.Kind.PARENTHESISED_EXPRESSION, Tree.Kind.ERROR_CONTROL)) { return parentUseValue(parent); } else if (parent.is(Tree.Kind.EXPRESSION_STATEMENT)) { return false; } else if (parent.is(Tree.Kind.FOR_STATEMENT)) { SeparatedList<ExpressionTree> conditions = ((ForStatementTree) parent).condition(); ExpressionTree lastCondition = conditions.isEmpty() ? null : conditions.get(conditions.size() - 1); return child.equals(lastCondition); } return true; }</code><technical_language>hard cover unit tests</technical_language>

Target:
private static boolean parentUseValue(Tree child) { Tree parent = child.getParent(); Preconditions.checkNotNull(parent); if (parent.is(Tree.Kind.PARENTHESISED_EXPRESSION, Tree.Kind.ERROR_CONTROL)) { return parentUseValue(parent); } else if (parent.is(Tree.Kind.EXPRESSION_STATEMENT)) { return false; } else if (parent.is(Tree.Kind.FOR_STATEMENT)) { SeparatedList<ExpressionTree> conditions = ((ForStatementTree) parent).condition(); ExpressionTree lastCondition = conditions.isEmpty() ? null : conditions.get(conditions.size() - 1); return child.equals(lastCondition); } return true; }
Source:
<code>protected final void layoutChildren() { double width = rectangle.getWidth(); double height = rectangle.getHeight(); double fontWidth = text.getLayoutBounds().getWidth(); text.setFont(Font.font(FONTNAME, (HORIZONTALSCALE) * width / fontWidth)); text.setLayoutX(width / 2 - text.getLayoutBounds().getWidth() / 2); text.setLayoutY(height / 2); <START> if ((HORIZONTALSCALE * width / fontWidth) < MINTEXTSIZE) { <END> text.setVisible(false); } else { text.setVisible(true); } clip.setWidth(width); clip.setHeight(height); clip.setLayoutX(0); clip.setLayoutY(-height / 2); }</code><technical_language>refactored a one-liner: text.setVisible(HORIZONTALSCALE * width / fontWidth >= MINTEXTSIZE)</technical_language>

Target:
protected final void layoutChildren() { double width = rectangle.getWidth(); double height = rectangle.getHeight(); double fontWidth = text.getLayoutBounds().getWidth(); text.setFont(Font.font(FONTNAME, (HORIZONTALSCALE) * width / fontWidth)); text.setLayoutX(width / 2 - text.getLayoutBounds().getWidth() / 2); text.setLayoutY(height / 2); text.setVisible(HORIZONTALSCALE * width / fontWidth >= MINTEXTSIZE); clip.setWidth(width); clip.setHeight(height); clip.setLayoutX(0); clip.setLayoutY(-height / 2); }