auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void fromBytes(ByteBuf buf) { int size = ByteBufUtils.readVarInt(buf, 5); data = new long[size][]; for (int i = 0; i < size; i++) { long[] array = new long[3]; for (int j = 0; j < 3; j++) { int val = ByteBufUtils.readVarInt(buf, 5); if (j == 2) { <START> array[j] = (long) val << 32 | ByteBufUtils.readVarInt(buf, 5) & 0xffffffffL; <END> } else { array[j] = val; } } data[i] = array; } }</code><technical_language>ByteBuf ByteBufUtils methods for longs? surprising</technical_language>

Target:
public void fromBytes(ByteBuf buf) { int size = ByteBufUtils.readVarInt(buf, 5); data = new EmcPKTInfo[size]; for (int i = 0; i < size; i++) { data[i] = new EmcPKTInfo(ByteBufUtils.readVarInt(buf, 5), ByteBufUtils.readVarInt(buf, 5), buf.readLong()); } }
Source:
<code>public boolean isCallerCalculationRequired() { final int callerCalculationState = this.callerCalculationState; if (callerCalculationState == 0) { return false; } else if (callerCalculationState == 1) { return true; } <START> return super.isCallerCalculationRequired(); <END> }</code><technical_language>Change this method to: return forceCallerCalculation || super.isCallerCalculationRequired();</technical_language>

Target:
public boolean isCallerCalculationRequired() { return callerCalculationRequired || super.isCallerCalculationRequired(); }
Source:
<code><START> @Override public String toString() { <END> return "StatsQueryRequest{" + "metrics=" + metrics + ", start=" + start + ", end=" + end + ", buckets=" + buckets + ", bucketDuration=" + bucketDuration + ", percentiles=" + percentiles + '}'; }</code><technical_language>Do mind MoreObjects.toStringHelper for toString method</technical_language>

Target:
@Override public String toString() { return MoreObjects.toStringHelper(this) .add("metrics", metrics) .add("tags", tags) .add("start", start) .add("end", end) .add("buckets", buckets) .add("bucketDuration", bucketDuration) .add("percentiles", percentiles) .add("types", types) .toString(); }
Source:
<code>public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { String platformName = config.getPlatformName(); View view = super.onCreateView(inflater, container, savedInstanceState); noFriendsLayout = (LinearLayout) view.findViewById(R.id.friends_course_no_friends_layout); TextView shareBtn = (TextView) view.findViewById(R.id.friends_course_no_btn_share_app); CharSequence shareText = ResourceUtil.getFormattedString(getResources(), R.string.btn_share_app, "platform_name", platformName); shareBtn.setText(shareText); shareBtn.setOnClickListener(this); CharSequence errorText = ResourceUtil.getFormattedString(getResources(), R.string.error_no_friends_connected, "platform_name", platformName); <START> TextView errorMessage = (TextView)view.findViewById(R.id.error_message); <END> errorMessage.setText(errorText); return view; }</code><technical_language>Again, this variable name change errorMessageView clear this is a widget</technical_language>

Target:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { String platformName = config.getPlatformName(); View view = super.onCreateView(inflater, container, savedInstanceState); noFriendsLayout = (LinearLayout) view.findViewById(R.id.friends_course_no_friends_layout); TextView shareBtn = (TextView) view.findViewById(R.id.friends_course_no_btn_share_app); CharSequence shareText = ResourceUtil.getFormattedString(getResources(), R.string.btn_share_app, "platform_name", platformName); shareBtn.setText(shareText); shareBtn.setOnClickListener(this); CharSequence errorText = ResourceUtil.getFormattedString(getResources(), R.string.error_no_friends_connected, "platform_name", platformName); TextView errorMessageView = (TextView)view.findViewById(R.id.error_message); errorMessageView.setText(errorText); return view; }
Source:
<code>public void doNotLeakOnFailedInitializationForChannels() throws Exception { setUp(Http2FrameCodecBuilder.forServer(), new Http2Settings().maxConcurrentStreams(2)); Http2FrameStream stream1 = frameCodec.newStream(); Http2FrameStream stream2 = frameCodec.newStream(); ChannelPromise stream1HeaderPromise = channel.newPromise(); ChannelPromise stream2HeaderPromise = channel.newPromise(); channel.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers()).stream(stream1), stream1HeaderPromise); channel.runPendingTasks(); frameInboundWriter.writeInboundGoAway(stream1.id(), 0L, Unpooled.EMPTY_BUFFER); channel.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers()).stream(stream2), stream2HeaderPromise); channel.runPendingTasks(); assertTrue(stream1HeaderPromise.syncUninterruptibly().isSuccess()); assertTrue(stream2HeaderPromise.isDone()); assertEquals(0, frameCodec.numInitializingStreams()); <START> channel.finishAndReleaseAll(); <END> }</code><technical_language>add assert</technical_language>

Target:
public void doNotLeakOnFailedInitializationForChannels() throws Exception { setUp(Http2FrameCodecBuilder.forServer(), new Http2Settings().maxConcurrentStreams(2)); Http2FrameStream stream1 = frameCodec.newStream(); Http2FrameStream stream2 = frameCodec.newStream(); ChannelPromise stream1HeaderPromise = channel.newPromise(); ChannelPromise stream2HeaderPromise = channel.newPromise(); channel.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers()).stream(stream1), stream1HeaderPromise); channel.runPendingTasks(); frameInboundWriter.writeInboundGoAway(stream1.id(), 0L, Unpooled.EMPTY_BUFFER); channel.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers()).stream(stream2), stream2HeaderPromise); channel.runPendingTasks(); assertTrue(stream1HeaderPromise.syncUninterruptibly().isSuccess()); assertTrue(stream2HeaderPromise.isDone()); assertEquals(0, frameCodec.numInitializingStreams()); assertFalse(channel.finishAndReleaseAll()); }
Source:
<code>public void testBadReplicationLocations() throws Exception { <START> processor = new ReplicationProcessor(repository, badReplicationLocations, maxRetries, retryDelay); <END> try { processor.process(exchange); } finally { verify(processor).equals(ReplicationDestinationUnavailableException.class); } }</code><technical_language>This method ends this line. clearer remove rest of method</technical_language>

Target:
public void testBadReplicationLocations() throws Exception { processor = new ReplicationProcessor(repository, badReplicationLocations, maxRetries, retryDelay); }
Source:
<code>public static boolean isUNC(String path) { if (path.length() < 2) { return false; } char c0 = path.charAt(0); char c1 = path.charAt(1); if (c0 != c1) { return false; } <START> return (c0 == BSLASH || c0 == SLASH); <END> }</code><technical_language>wrong treat backslash a path separator non-Windows systems</technical_language>

Target:
public static boolean isUNC(String path) { if (path.length() >= 2) { char c= path.charAt(0); if (c == IPath.SEPARATOR || c == File.separatorChar) { c= path.charAt(1); return c == IPath.SEPARATOR || c == File.separatorChar; } } return false; }
Source:
<code>public AuditLogType getAuditLogTypeValue() { switch (getActionState()) { case END_FAILURE: return <START> getSucceeded() <END> ? AuditLogType.UNASSIGNED: AuditLogType.USER_DEACTIVATE_STORAGE_DOMAIN_FAILED; default: return AuditLogType.UNASSIGNED; } }</code><technical_language>Hoe getSucceeded() true if command ended failure</technical_language>

Target:
public AuditLogType getAuditLogTypeValue() { return AuditLogType.UNASSIGNED; }
Source:
<code>private boolean hasTenantSpecificTables(HRegion region, byte[] tableName) throws IOException { Scan scan = new Scan(); <START> scan.setStartRow(new byte[]{1}); END> SingleColumnValueFilter filter = new SingleColumnValueFilter(TABLE_FAMILY_BYTES, DATA_TABLE_NAME_BYTES, EQUAL, tableName); filter.setFilterIfMissing(true); scan.setFilter(filter); RegionScanner scanner = region.getScanner(scan); try { List<KeyValue> results = newArrayList(); scanner.next(results); return results.size() > 0; } finally { scanner.close(); } }</code><technical_language>This is correct, do this instead: scan.setStartRow(KeyRange.IS_NOT_NULL_RANGE.getLowerRange());</technical_language>

Target:
private boolean hasTenantSpecificTables(HRegion region, byte[] tableName) throws IOException { Scan scan = new Scan(); scan.setStartRow(KeyRange.IS_NOT_NULL_RANGE.getLowerRange()); SingleColumnValueFilter filter = new SingleColumnValueFilter(TABLE_FAMILY_BYTES, DATA_TABLE_NAME_BYTES, EQUAL, tableName); filter.setFilterIfMissing(true); scan.setFilter(filter); RegionScanner scanner = region.getScanner(scan); try { List<KeyValue> results = newArrayList(); scanner.next(results); return results.size() > 0; } finally { scanner.close(); } }
Source:
<code>private void addMatchingProposals(SortedSet<BranchContentProposal> branches, String searchText) { <START> if (proposals.size() > 0) { <END> for (String branchProposal : proposals) { if (branchProposal.toLowerCase().contains(searchText)) { branches.add(new BranchContentProposal(branchProposal)); } } } }</code><technical_language>need this check</technical_language>

Target:
private void addMatchingProposals(SortedSet<BranchContentProposal> branches, String searchText) { for (String branchProposal : proposals) { if (branchProposal.toLowerCase().contains(searchText)) { branches.add(new BranchContentProposal(branchProposal)); } } }
Source:
<code>public static boolean looksLikeSql(String sql) { final String local = left(stripStart(sql), 7).toLowerCase(); return local.startsWith("insert ") || local.startsWith("update ") || local.startsWith("select ") || local.startsWith("call ") || local.startsWith("delete ") || local.startsWith("create ") || local.startsWith("alter ") || local.startsWith("merge ") <START> || local.startsWith("replace ") <END> || local.startsWith("drop "); }</code><technical_language>is change? Is part of fix some spurious sneaked in? If latter, I prefer separate commits (one fix bug, for a feature change)</technical_language>

Target:
public static boolean looksLikeSql(String sql) { final String local = left(stripStart(sql), 8).toLowerCase(); return local.startsWith("insert ") || local.startsWith("update ") || local.startsWith("select ") || local.startsWith("call ") || local.startsWith("delete ") || local.startsWith("create ") || local.startsWith("alter ") || local.startsWith("merge ") || local.startsWith("replace ") || local.startsWith("drop "); }
Source:
<code>HttpSolrServer getMaCore() { <START> return new HttpSolrServer("http://localhost:8090/solr" + "/ma"); <END> }</code><technical_language>This changed solrBaseUrl</technical_language>

Target:
HttpSolrServer getMaCore() { return new HttpSolrServer(solrBaseUrl + "/ma"); }
Source:
<code>AzureFileStore(AzureFileSystem parentFileSystem, String containerName) throws IOException { if (Objects.isNull(parentFileSystem)) { throw new IllegalStateException("AzureFileStore cannot be instantiated without a parent FileSystem"); } this.parentFileSystem = parentFileSystem; this.containerClient = this.parentFileSystem.getBlobServiceClient().getBlobContainerClient(containerName); try { <START> if (!this.containerClient.exists()) { this.containerClient.create(); <END> } } catch (Exception e) { throw new IOException("There was an error in establishing the existence of container: " + containerName, e); } }</code><technical_language>kill birds stone create passing ETag equals * catch exception ignore if returned error is ContainerAlreadyExists. This result in existing container making call in case exist cut network calls in one</technical_language>

Target:
AzureFileStore(AzureFileSystem parentFileSystem, String containerName) throws IOException { if (Objects.isNull(parentFileSystem)) { throw Utility.logError(logger, new IllegalStateException("AzureFileStore cannot be instantiated without " + "a parent FileSystem")); } this.parentFileSystem = parentFileSystem; this.containerClient = this.parentFileSystem.getBlobServiceClient().getBlobContainerClient(containerName); try { if (!this.containerClient.exists()) { this.containerClient.create(); } } catch (Exception e) { throw Utility.logError(logger, new IOException("There was an error in establishing the existence of " + "container: " + containerName, e)); } }
Source:
<code>private double settlementPrice(ResolvedDsfTrade trade, RatesProvider ratesProvider) { StandardId standardId = trade.getProduct().getSecurityId().getStandardId(); QuoteId id = QuoteId.of(standardId, FieldName.SETTLEMENT_PRICE); double price = ratesProvider.data(id); <START> ArgChecker.isTrue(price < 10, "Price must be in decimal form, such as 1.007 for a 0.7% rate, but was: {}", price); <END> return price; }</code><technical_language>typo: 'for a 0.7% present value'</technical_language>

Target:
private double settlementPrice(ResolvedDsfTrade trade, RatesProvider ratesProvider) { StandardId standardId = trade.getProduct().getSecurityId().getStandardId(); QuoteId id = QuoteId.of(standardId, FieldName.SETTLEMENT_PRICE); double price = ratesProvider.data(id); ArgChecker.isTrue( price < 10, "Price must be in decimal form, such as 1.007 for a 0.7% present value, but was: {}", price); return price; }
Source:
<code>private boolean readNextRow() { while (!stop) { String row = getLineWrapped(); if (row == null || row.startsWith("{\"last_seq\":")) { terminate(); return false; } else if (row.isEmpty()) { continue; } setNextRow(gson.fromJson(row, ChangesResult.Row.class)); return true; } <START> return false; <END> }</code><technical_language>do need call terminate(); too</technical_language>

Target:
private boolean readNextRow() { while (!stop) { String row = getLineWrapped(); if (row == null || row.startsWith("{\"last_seq\":")) { terminate(); return false; } else if (row.isEmpty()) { continue; } setNextRow(gson.fromJson(row, ChangesResult.Row.class)); return true; } terminate(); return false; }
Source:
<code>public Result loginUser() { DynamicForm bindedForm = new DynamicForm().bindFromRequest(); String username = bindedForm.get("loginUsername"); String password = bindedForm.get("loginPassword"); FrontEndDBInterface f = new FrontEndDBInterface(); String passCheck = f.authenticateUser(username, password); <START> if (passCheck.equals("errorCheck")) { <END> String error = "Some error"; LoginViewModel viewModel = new LoginViewModel(); viewModel.errorMessage = error; viewModel.loginUsername = username; viewModel.teamNames = getTeamNames(); return ok(login.render(viewModel)); } session().clear(); session("username", username); return redirect("/"); }</code><technical_language>This changed return a boolean instead of a string</technical_language>

Target:
public Result loginUser() { DynamicForm bindedForm = new DynamicForm().bindFromRequest(); String username = bindedForm.get("loginUsername"); String password = bindedForm.get("loginPassword"); FrontEndDBInterface f = new FrontEndDBInterface(); boolean passCheck = f.authenticateUser(username, password); if (!passCheck) { String error = "Some error"; LoginViewModel viewModel = new LoginViewModel(); viewModel.errorMessage = error; viewModel.loginUsername = username; viewModel.teamNames = getTeamNames(); return ok(login.render(viewModel)); } session().clear(); session("username", username); return redirect("/"); }
Source:
<code>public static void waitForKieServerMessage(final KieServicesClient client, final String containerId, final String expectedMessage) throws Exception { waitForCondition(() -> { ServiceResponse<KieContainerResource> containerResponse = client.getContainerInfo(containerId); if (!containerResponse.getType().equals(ServiceResponse.ResponseType.SUCCESS)) { return false; } List<Message> messagesList = containerResponse.getResult().getMessages(); if (messagesList.size() == 1) { <START> for (String message : messagesList.get(0).getMessages()) { <END> if (message.equals(expectedMessage)) { return true; } } } return false; }); }</code><technical_language>idea, this cycle replaced "return messagesList.get(0).getMessages().stream().anyMatch(n -> n.equals(expectedMessage));"</technical_language>

Target:
public static void waitForKieServerMessage(final KieServicesClient client, final String containerId, final String expectedMessage) throws Exception { waitForCondition(() -> { ServiceResponse<KieContainerResource> containerResponse = client.getContainerInfo(containerId); if (!containerResponse.getType().equals(ServiceResponse.ResponseType.SUCCESS)) { return false; } List<Message> messagesList = containerResponse.getResult().getMessages(); if (messagesList.size() == 1) { return messagesList.get(0).getMessages().stream().anyMatch(n -> n.equals(expectedMessage)); } return false; }); }
Source:
<code>public MessageBundlesHelper( String dashboardFolderPath, IReadAccess dashboardAccess, IRWAccess pluginAccess, Locale locale, String pluginStaticBaseContentUrl ) throws CpfException { if ( dashboardAccess == null ) { throw new CpfException( "dashboardAccess is null" ); <START> <END> } else if ( pluginAccess == null ) { throw new CpfException( "pluginAccess is null" ); } else if ( locale == null || StringUtils.isEmpty( locale.getLanguage() ) ) { throw new CpfException( "locale language is null" ); } else if ( StringUtils.isEmpty( pluginStaticBaseContentUrl ) ) { throw new CpfException( "pluginStaticBaseContentUrl is null" ); } setDashboardFolderPath( StringUtils.isEmpty( dashboardFolderPath ) ? Util.SEPARATOR : dashboardFolderPath ); setDashboardAccess( dashboardAccess ); setPluginAccess( pluginAccess ); setPluginStaticBaseContentUrl( pluginStaticBaseContentUrl ); setLocale( locale ); init(); }</code><technical_language>IllegalArgumentException instead of a custom CpfException provide additional information (it's informative IllegalArgument) ? means drop CpfException class well</technical_language>

Target:
public MessageBundlesHelper( String dashboardFolderPath, IReadAccess dashboardAccess, IRWAccess pluginAccess, Locale locale, String pluginStaticBaseContentUrl ) throws IllegalArgumentException, IOException { if ( dashboardAccess == null ) { throw new IllegalArgumentException( "dashboardAccess is null" ); } else if ( pluginAccess == null ) { throw new IllegalArgumentException( "pluginAccess is null" ); } else if ( locale == null || StringUtils.isEmpty( locale.getLanguage() ) ) { throw new IllegalArgumentException( "locale language is null" ); } else if ( StringUtils.isEmpty( pluginStaticBaseContentUrl ) ) { throw new IllegalArgumentException( "pluginStaticBaseContentUrl is null" ); } setDashboardFolderPath( StringUtils.isEmpty( dashboardFolderPath ) ? Util.SEPARATOR : dashboardFolderPath ); setDashboardAccess( dashboardAccess ); setPluginAccess( pluginAccess ); setPluginStaticBaseContentUrl( pluginStaticBaseContentUrl ); setLocale( locale ); init(); }
Source:
<code>public TestTpchDistributedStats() throws Exception { <START> runner = createQueryRunnerWithoutCatalogs(emptyMap(), emptyMap(), 4); <END> runner.createCatalog("tpch", "tpch", ImmutableMap.of( "tpch.column-naming", ColumnNaming.STANDARD.name() )); }</code><technical_language>add another overloaded method a worker count (similar already)</technical_language>

Target:
public TestTpchDistributedStats() throws Exception { runner = createQueryRunnerWithoutCatalogs(emptyMap(), emptyMap()); runner.createCatalog("tpch", "tpch", ImmutableMap.of( "tpch.column-naming", ColumnNaming.STANDARD.name() )); }
Source:
<code>public Xid[] doRecover(Xid xid, String parentNodeName) throws XAException { Xid[] indoubt = null; try { RecoveryStore recoveryStore = StoreManager.getRecoveryStore(); InputObjectState states = new InputObjectState(); if (recoveryStore.allObjUids(ServerTransaction.getType(), states) && (states.notempty())) { Stack<Transaction> values = new Stack<Transaction>(); boolean finished = false; do { Uid uid = null; try { uid = UidHelper.unpackFrom(states); } catch (IOException ex) { jtsLogger.i18NLogger.info_fail_to_read_subordinate_uid(recoveryStore, states, ex); finished = true; } if (uid.notEquals(Uid.nullUid())) { if (parentNodeName != null) { throw new IllegalArgumentException("JTS doRecover method does not handle parentNodeName, see JBTM-2124"); } else if (xid == null) { Transaction tx = SubordinationManager.getTransactionImporter().recoverTransaction(uid); if (tx != null) values.push(tx); } else { SubordinateAtomicTransaction sat = new SubordinateAtomicTransaction(uid); XidImple loadedXid = (XidImple) sat.getXid(); if ((loadedXid != null && loadedXid.getFormatId() == Arjuna.XID()) && (Arrays.equals(loadedXid.getGlobalTransactionId(), xid.getGlobalTransactionId()))) { TransactionImple tx = (TransactionImple) SubordinationManager.getTransactionImporter().recoverTransaction(uid); <START> if (tx != null) <END> values.push(tx); } } } else finished = true; } while (!finished); if (values.size() > 0) { int index = 0; indoubt = new Xid[values.size()]; while (!values.empty()) { TransactionImple id = (TransactionImple) values.pop(); indoubt[index] = id.baseXid(); index++; } } } } catch (Exception ex) { jtsLogger.i18NLogger.info_fail_to_dorecover(xid, parentNodeName, ex); } return indoubt; }</code><technical_language>I xid != null is error it</technical_language>

Target:
public Xid[] doRecover(Xid xid, String parentNodeName) throws XAException, NotSupportedException { if(xid != null || parentNodeName != null) throw new NotSupportedException("doRecover method works only with null arguments"); Xid[] indoubt = null; try { RecoveryStore recoveryStore = StoreManager.getRecoveryStore(); InputObjectState states = new InputObjectState(); if (recoveryStore.allObjUids(ServerTransaction.getType(), states) && (states.notempty())) { Stack<Transaction> values = new Stack<Transaction>(); boolean finished = false; do { Uid uid = null; try { uid = UidHelper.unpackFrom(states); } catch (IOException ex) { jtsLogger.i18NLogger.info_fail_to_read_subordinate_uid(recoveryStore, states, ex); finished = true; } if (uid.notEquals(Uid.nullUid())) { Transaction tx = SubordinationManager.getTransactionImporter().recoverTransaction(uid); if (tx != null) values.push(tx); } else finished = true; } while (!finished); if (values.size() > 0) { int index = 0; indoubt = new Xid[values.size()]; while (!values.empty()) { TransactionImple id = (TransactionImple) values.pop(); indoubt[index] = id.baseXid(); index++; } } } } catch (Exception ex) { jtsLogger.i18NLogger.info_fail_to_dorecover(xid, parentNodeName, ex); } return indoubt; }
Source:
<code>public void failover_newTimestampRequested() throws Exception { while (!oserver.isConnected()) Thread.sleep(100); int port2 = PortUtils.getRandomFreePort(); int port3 = PortUtils.getRandomFreePort(); OracleServer oserver2 = createExtraOracle(port2); OracleServer oserver3 = createExtraOracle(port3); oserver2.start(); while (!oserver2.isConnected()) Thread.sleep(100); oserver3.start(); while (!oserver3.isConnected()) Thread.sleep(100); OracleClient client = OracleClient.getInstance(config); long timestamp; for (long i = 2; i <= 7; i++) { timestamp = client.getTimestamp(); assertEquals(i, timestamp); } assertTrue(client.getOracle().endsWith(Integer.toString(config.getOraclePort()))); <START> Thread.sleep(1000); <END> oserver.stop(); Thread.sleep(1000); assertEquals(1002, client.getTimestamp()); assertTrue(client.getOracle().endsWith(Integer.toString(port2))); oserver2.stop(); Thread.sleep(1000); assertEquals(2002, client.getTimestamp()); assertTrue(client.getOracle().endsWith(Integer.toString(port3))); oserver3.stop(); }</code><technical_language>hard judge sleep is necessary. amount of sleep work machine fail periodically machines. sleep check a status status changed Keith proposed I implemented for TransactorIT. do similar in OracleIT</technical_language>

Target:
public void failover_newTimestampRequested() throws Exception { while (!oserver.isConnected()) Thread.sleep(100); int port2 = PortUtils.getRandomFreePort(); int port3 = PortUtils.getRandomFreePort(); OracleServer oserver2 = createExtraOracle(port2); OracleServer oserver3 = createExtraOracle(port3); oserver2.start(); while (!oserver2.isConnected()) Thread.sleep(100); oserver3.start(); while (!oserver3.isConnected()) Thread.sleep(100); OracleClient client = OracleClient.getInstance(config); long timestamp; for (long i = 2; i <= 7; i++) { timestamp = client.getTimestamp(); assertEquals(i, timestamp); } assertTrue(client.getOracle().endsWith(Integer.toString(config.getOraclePort()))); oserver.stop(); Thread.sleep(1000); assertEquals(1002, client.getTimestamp()); assertTrue(client.getOracle().endsWith(Integer.toString(port2))); oserver2.stop(); Thread.sleep(1000); assertEquals(2002, client.getTimestamp()); assertTrue(client.getOracle().endsWith(Integer.toString(port3))); oserver3.stop(); }
Source:
<code>private <T extends Identifiable<?>> boolean isComplete(T prototype, UID targetUID, Function<T, URI> configDescriptionURIFunction, Configuration configuration) { if (prototype == null) { logger.debug("Prototype for '{}' is not known, assuming it is initializable", targetUID); return true; } ConfigDescription description = resolve(configDescriptionURIFunction.apply(prototype), null); if (description == null) { logger.debug("Config description for '{}' is not resolvable, assuming '{}' is initializable", prototype.getUID(), targetUID); return true; } List<String> requiredParameters = getRequiredParameters(description); Map<String, Object> properties = configuration.getProperties(); if (logger.isDebugEnabled()) { logger.debug("Configuration of '{}' needs {}, has {}.", targetUID, requiredParameters, <START> configuration.getProperties().keySet()); <END> } return properties.keySet().containsAll(requiredParameters); }</code><technical_language>store configuration.getProperties() properties, need call getProperties() again</technical_language>

Target:
private <T extends Identifiable<?>> boolean isComplete(T prototype, UID targetUID, Function<T, URI> configDescriptionURIFunction, Configuration configuration) { if (prototype == null) { logger.debug("Prototype for '{}' is not known, assuming it is initializable", targetUID); return true; } ConfigDescription description = resolve(configDescriptionURIFunction.apply(prototype), null); if (description == null) { logger.debug("Config description for '{}' is not resolvable, assuming '{}' is initializable", prototype.getUID(), targetUID); return true; } List<String> requiredParameters = getRequiredParameters(description); Set<String> propertyKeys = configuration.getProperties().keySet(); if (logger.isDebugEnabled()) { logger.debug("Configuration of '{}' needs {}, has {}.", targetUID, requiredParameters, propertyKeys); } return propertyKeys.containsAll(requiredParameters); }
Source:
<code>public void added(Provider<E> provider, E element) { Collection<E> elements = elementMap.get(provider); if (elements != null) { try { K uid = element.getUID(); if (uid != null && get(uid) != null) { <START> logger.warn(String.format( <END> "%s with Key \"%s\" already exists! Failed to add a second with the same UID!", element.getClass().getName(), uid)); return; } onAddElement(element); elements.add(element); notifyListenersAboutAddedElement(element); } catch (Exception ex) { logger.warn("Could not add element: " + ex.getMessage(), ex); } } }</code><technical_language>Is a special reason String.format simply parameterized logging</technical_language>

Target:
public void added(Provider<E> provider, E element) { Collection<E> elements = elementMap.get(provider); if (elements != null) { try { K uid = element.getUID(); if (uid != null && get(uid) != null) { logger.warn("{} with key '{}' already exists! Failed to add a second with the same UID!", element.getClass().getName(), uid); return; } onAddElement(element); elements.add(element); notifyListenersAboutAddedElement(element); } catch (Exception ex) { logger.warn("Could not add element: {}", ex.getMessage(), ex); } } }
Source:
<code>private List<String> buildFileNameList(String... fileNames) { List<String> fileNameList = new ArrayList<String>(); for (String fileName : fileNames) { <START> fileNameList.add(fileName); <END> } return fileNameList; }</code><technical_language>greatly simplify this code Arrays.asList() instead</technical_language>

Target:
private List<String> buildFileNameList(String... fileNames) { List<String> fileNameList = Arrays.asList(fileNames); return fileNameList; }
Source:
<code>public List<ElementRecord> getModelChildren() { List<ElementRecord> filtered = new ArrayList<ElementRecord>(); <START> for (ElementRecord el : getElementRecord().getVisibleChildElements()) { <END> String tag = el.getName(); if (tag.equals(SVGConstants.SVG_RECT_TAG) || tag.equals(SVGConstants.SVG_POLYLINE_TAG) || tag.equals(SVGConstants.SVG_ELLIPSE_TAG) || tag.equals(SVGConstants.SVG_TEXT_TAG) || tag.equals(SVGConstants.SVG_SVG_TAG)) { filtered.add(el); } } return filtered; }</code><technical_language>record r e1</technical_language>

Target:
public List<ElementRecord> getModelChildren() { List<ElementRecord> filtered = new ArrayList<ElementRecord>(); for (ElementRecord r : getElementRecord().getVisibleChildElements()) { String tag = r.getName(); if (tag.equals(SVGConstants.SVG_RECT_TAG) || tag.equals(SVGConstants.SVG_POLYLINE_TAG) || tag.equals(SVGConstants.SVG_ELLIPSE_TAG) || tag.equals(SVGConstants.SVG_TEXT_TAG) || tag.equals(SVGConstants.SVG_SVG_TAG)) { filtered.add(r); } } return filtered; }
Source:
<code>private ProjectState newProjectState() { final Map<Project.NameKey, ProjectState> all = new HashMap<Project.NameKey, ProjectState>(); final ProjectCache projectCache = new ProjectCache() { @Override public ProjectState get(Project.NameKey projectName) { return all.get(projectName); } @Override public void evict(Project p) { } @Override public Iterable<Project.NameKey> all() { <START> return null; <END> } @Override public Iterable<Project.NameKey> byName(String prefix) { return Collections.emptySet(); } @Override public void onCreateProject(Project.NameKey newProjectName) { } }; GitRepositoryManager mgr = null; ProjectControl.AssistedFactory projectControlFactory = null; all.put(local.getProject().getNameKey(), new ProjectState(anonymousUser, projectCache, wildProject, projectControlFactory, mgr, local)); all.put(parent.getProject().getNameKey(), new ProjectState(anonymousUser, projectCache, wildProject, projectControlFactory, mgr, parent)); all.put(wild.getProject().getNameKey(), new ProjectState(anonymousUser, projectCache, wildProject, projectControlFactory, mgr, wild)); return all.get(local.getProject().getNameKey()); }</code><technical_language>need change this emptySet() null</technical_language>

Target:
private ProjectState newProjectState() { final Map<Project.NameKey, ProjectState> all = new HashMap<Project.NameKey, ProjectState>(); final ProjectCache projectCache = new ProjectCache() { @Override public ProjectState get(Project.NameKey projectName) { return all.get(projectName); } @Override public void evict(Project p) { } @Override public Iterable<Project.NameKey> all() { return Collections.emptySet(); } @Override public Iterable<Project.NameKey> byName(String prefix) { return Collections.emptySet(); } @Override public void onCreateProject(Project.NameKey newProjectName) { } }; GitRepositoryManager mgr = null; ProjectControl.AssistedFactory projectControlFactory = null; all.put(local.getProject().getNameKey(), new ProjectState(anonymousUser, projectCache, wildProject, projectControlFactory, mgr, local)); all.put(parent.getProject().getNameKey(), new ProjectState(anonymousUser, projectCache, wildProject, projectControlFactory, mgr, parent)); all.put(wild.getProject().getNameKey(), new ProjectState(anonymousUser, projectCache, wildProject, projectControlFactory, mgr, wild)); return all.get(local.getProject().getNameKey()); }
Source:
<code>void initialize() { <START> fgKeys= new HashMap<String, Integer>(); <END> Integer k= new Integer(KEY); for (String word : fgKeywords) fgKeys.put(word, k); }</code><technical_language>need for type here</technical_language>

Target:
void initialize() { fgKeys= new HashMap<>(); Integer k= new Integer(KEY); for (String word : fgKeywords) fgKeys.put(word, k); }
Source:
<code>private GoPluginApiResponse handleGetPluginSettingsConfiguration() { Map<String, Object> response = new HashMap<String, Object>(); response.put(PLUGIN_SETTINGS_SERVER_BASE_URL, createField("Server Base URL", null, true, false, "0")); response.put(PLUGIN_SETTINGS_END_POINT, createField("End Point", null, true, false, "1")); response.put(PLUGIN_SETTINGS_USERNAME, createField("Username", null, true, false, "2")); response.put(PLUGIN_SETTINGS_PASSWORD, createField("Password", null, true, true, "3")); response.put(PLUGIN_SETTINGS_OAUTH_TOKEN, createField("OAuth Token", null, true, true, "4")); <START> if (provider.pluginId().equals(GerritProvider.PLUGIN_ID)) { <END> response.put(PLUGIN_SETTINGS_REVIEW_LABEL, createField("Gerrit Review Label", "Verified", true, false, "5")); } return renderJSON(SUCCESS_RESPONSE_CODE, response); }</code><technical_language>GerritProvider class other plugins, causing a CNFE here. Do feel push this behaviour Provider interface, provider passed response object add more fields it, determine correct index needs start from, based size of existing fields</technical_language>

Target:
private GoPluginApiResponse handleGetPluginSettingsConfiguration() { return renderJSON(SUCCESS_RESPONSE_CODE, provider.configurationView().fields()); }
Source:
<code>private String replaceHonoringProtectedGroups(final String input) { Matcher matcher = PATTERN_ENCLOSED_IN_CURLY_BRACES.matcher(input); List<String> replaced = new ArrayList<>(); while (matcher.find()) { replaced.add(matcher.group(1)); } String workingString = matcher.replaceAll(PLACEHOLDER_FOR_PROTECTED_GROUP); try { workingString = workingString.replaceAll(regex, replacement); } catch (PatternSyntaxException e) { <START> LOGGER.warn("There is a syntax error in the regular expression, " + regex + ", used by the regex modifier", e); <END> return input; } for (String r : replaced) { workingString = workingString.replaceFirst(PLACEHOLDER_FOR_PROTECTED_GROUP, r); } return workingString; }</code><technical_language>suggestion LOGGER.warn("There is a syntax error in regular expression \"{}\" regex modifier", regex, e);</technical_language>

Target:
private String replaceHonoringProtectedGroups(final String input) { Matcher matcher = ENCLOSED_IN_CURLY_BRACES.matcher(input); List<String> replaced = new ArrayList<>(); while (matcher.find()) { replaced.add(matcher.group()); } String workingString = matcher.replaceAll(PLACEHOLDER_FOR_PROTECTED_GROUP); try { workingString = workingString.replaceAll(regex, replacement); } catch (PatternSyntaxException e) { LOGGER.warn("There is a syntax error in the regular expression \"{}\" used by the regex modifier", regex, e); return input; } for (String r : replaced) { workingString = workingString.replaceFirst(PLACEHOLDER_FOR_PROTECTED_GROUP, r); } return workingString; }
Source:
<code>public static ValidationResult setAndValidateCpuProfileForUser(VmBase vmBase, Version version, Guid userId) { if (!FeatureSupported.cpuQoS(version)) { return ValidationResult.VALID; } if (vmBase.getCpuProfileId() == null) { Optional<CpuProfile> cpuProfileWithPermissions = getCpuProfileDao().getAllForCluster(vmBase.getVdsGroupId()).stream() <START> .findAny(); <END> if (!cpuProfileWithPermissions.isPresent()) { return new ValidationResult(EngineMessage.ACTION_TYPE_NO_PERMISSION_TO_ASSIGN_CPU_PROFILE, "$cpuProfileId <CPU Profile empty>", "$cpuProfileName <CPU Profile empty>"); } else { vmBase.setCpuProfileId(cpuProfileWithPermissions.get().getId()); return ValidationResult.VALID; } } else { Optional<CpuProfile> choseCpuProfile = getCpuProfileDao().getAllForCluster(vmBase.getVdsGroupId(), userId, true).stream() .filter( cp -> cp.getId().equals(vmBase.getCpuProfileId()) ).findAny(); if (choseCpuProfile.isPresent()) { vmBase.setCpuProfileId(choseCpuProfile.get().getId()); return ValidationResult.VALID; } } Optional<CpuProfile> choseCpuProfile = getCpuProfileDao().getAllForCluster(vmBase.getVdsGroupId()).stream() .filter( cp -> cp.getId().equals(vmBase.getCpuProfileId()) ).findAny(); Guid chosenCpuProfileId = vmBase.getCpuProfileId(); String chosenCpuProfileName = "<N/A>"; if (choseCpuProfile.isPresent()) { chosenCpuProfileName = choseCpuProfile.get().getName(); } return new ValidationResult(EngineMessage.ACTION_TYPE_NO_PERMISSION_TO_ASSIGN_CPU_PROFILE, String.format("$cpuProfileId %s", chosenCpuProfileId), String.format("$cpuProfileName %s", chosenCpuProfileName)); }</code><technical_language>Is this currently select a default policy unit? This necessarily return element multiple executions, theoretically end selected cpu profiles fallback [1]. [1] <LINK_0></technical_language>

Target:
public static ValidationResult setAndValidateCpuProfileForUser(VmBase vmBase, Version version, Guid userId) { if (!FeatureSupported.cpuQoS(version)) { return ValidationResult.VALID; } if (vmBase.getCpuProfileId() == null) { return assignAnyCpuProfile(vmBase); } Optional<CpuProfile> chosenCpuProfileWithPermissions = getCpuProfileDao().getAllForCluster(vmBase.getVdsGroupId(), userId, true).stream() .filter( cp -> cp.getId().equals(vmBase.getCpuProfileId()) ).findFirst(); if (chosenCpuProfileWithPermissions.isPresent()) { vmBase.setCpuProfileId(chosenCpuProfileWithPermissions.get().getId()); return ValidationResult.VALID; } CpuProfile chosenCpuProfile = getCpuProfileDao().get(vmBase.getCpuProfileId()); if(chosenCpuProfile == null) { return new ValidationResult(EngineMessage.ACTION_TYPE_NO_CPU_PROFILE_WITH_THAT_ID, String.format("$cpuProfileId %s", vmBase.getCpuProfileId())); } return new ValidationResult(EngineMessage.ACTION_TYPE_NO_PERMISSION_TO_ASSIGN_CPU_PROFILE, String.format("$cpuProfileId %s", vmBase.getCpuProfileId()), String.format("$cpuProfileName %s", chosenCpuProfile.getName())); }
Source:
<code>private List<MacraMeasureEntity> getAllMeasuresWhereValueIsNotNull() { Query query = entityManager .createQuery("FROM MacraMeasureEntity mme " <START> + "WHERE mme.value IS NOT NULL", MacraMeasureEntity.class); <END> return query.getResultList(); }</code><technical_language>deleted macra measures? this check deleted flag is set "false"</technical_language>

Target:
private List<MacraMeasureEntity> getAllMeasuresWhereValueIsNotNull() { Query query = entityManager .createQuery("FROM MacraMeasureEntity mme " + "WHERE mme.value IS NOT NULL " + "AND mme.deleted = FALSE", MacraMeasureEntity.class); return query.getResultList(); }
Source:
<code>public Object execute() throws Exception { <START> AccessController.doPrivileged( <END> (PrivilegedExceptionAction<Void>) () -> { if (increaseLogLevel) { logService.setLevel("org.codice.ddf.sync.installer.impl", "TRACE"); } syncInstaller.waitForBootFinish(); return null; }); return null; }</code><technical_language>catch PrivilegedActionException unwrap contained exception</technical_language>

Target:
public Object execute() throws Exception { try { AccessController.doPrivileged( (PrivilegedExceptionAction<Void>) () -> { if (increaseLogLevel) { logService.setLevel("org.codice.ddf.sync.installer.impl", "TRACE"); } syncInstaller.waitForBootFinish(); return null; }); } catch (PrivilegedActionException e) { throw e.getException(); } return null; }
Source:
<code>public MeterFrame(UUID uuid) { super(Bundle.getMessage("TrackVoltageMeterTitle")); this.uuid = uuid; MeterManager mm = InstanceManager.getNullableDefault(MeterManager.class); if (mm == null) throw new RuntimeException("No meter manager exists"); <START> for (Meter m : mm.getNamedBeanSet()) { if ((m != null) && (m instanceof VoltageMeter)) voltageMeters.add(m); if ((m != null) && (m instanceof CurrentMeter)) currentMeters.add(m); } <END> if (!voltageMeters.isEmpty()) { setMeter(voltageMeters.get(0)); } else if (!currentMeters.isEmpty()) { setMeter(currentMeters.get(0)); } else { setTitle(Bundle.getMessage("TrackVoltageMeterTitle")); } MeterFrameManager.getInstance().register(this); }</code><technical_language>I assume a concrete, system-specific MeterManager implementation register VoltageMeter CurrentMeter objects, registered objects of types for display in MeterFrame GUI. I assume this loop construct registered Meter objects for selection for display MeterFrame. Question: a concrete MeterManager implementation register more VoltageMeter and/or more CurrentMeter object? For example, "track current booster 1" "track current booster 2" "track current booster N"? If so, multiple current meters differentiatable he/she select Meter object display in MeterFrame</technical_language>

Target:
public MeterFrame(UUID uuid) { super(Bundle.getMessage("VoltageMeterTitle")); this.uuid = uuid; MeterManager mm = InstanceManager.getNullableDefault(MeterManager.class); if (mm == null) throw new RuntimeException("No meter manager exists"); for (Meter m : mm.getNamedBeanSet()) { if ((m != null) && (m instanceof VoltageMeter)) voltageMeters.add(m); if ((m != null) && (m instanceof CurrentMeter)) currentMeters.add(m); } if (!voltageMeters.isEmpty()) { setMeter(voltageMeters.get(0)); } else if (!currentMeters.isEmpty()) { setMeter(currentMeters.get(0)); } else { setTitle(Bundle.getMessage("VoltageMeterTitle")); } MeterFrameManager.getInstance().register(this); }
Source:
<code><START> public static void setOtherSchemes(List<String> otherSchemes) { <END> OAS2Parser.otherSchemes = otherSchemes; }</code><technical_language>here. setOtherSchemes is class, so, private</technical_language>

Target:
private void setOtherSchemes(List<String> otherSchemes) { this.otherSchemes = otherSchemes; }
Source:
<code>public CommandResult<RuleViolation> execute(final GraphCommandExecutionContext context) { final CommandResult<RuleViolation> results = super.execute(context); <START> if (!results.getType().equals(CommandResult.Type.ERROR)) { <END> final Node<?, Edge> candidate = getCandidate(); if (candidate.getContent() instanceof View) { final DMNModelInstrumentedBase dmnModel = (DMNModelInstrumentedBase) ((View) candidate.getContent()).getDefinition(); if (dmnModel instanceof BusinessKnowledgeModel) { final FunctionDefinition function = ((BusinessKnowledgeModel) dmnModel).getEncapsulatedLogic(); KindUtilities.setKind(function, FunctionDefinition.Kind.FEEL); final LiteralExpression le = new LiteralExpression(); function.setExpression(le); le.setParent(function); } } } return results; }</code><technical_language>Please !CommandUtils.isError(commandResult) Other classes do this change by: grep -r -i "getType().equals(CommandResult.Type.ERROR)"</technical_language>

Target:
public CommandResult<RuleViolation> execute(final GraphCommandExecutionContext context) { final CommandResult<RuleViolation> results = super.execute(context); if (!CommandUtils.isError(results)) { final Node<?, Edge> candidate = getCandidate(); if (candidate.getContent() instanceof View) { final DMNModelInstrumentedBase dmnModel = (DMNModelInstrumentedBase) ((View) candidate.getContent()).getDefinition(); if (dmnModel instanceof BusinessKnowledgeModel) { final FunctionDefinition function = ((BusinessKnowledgeModel) dmnModel).getEncapsulatedLogic(); KindUtilities.setKind(function, FunctionDefinition.Kind.FEEL); final LiteralExpression le = new LiteralExpression(); function.setExpression(le); le.setParent(function); } } } return results; }
Source:
<code>public void create() { super.create(); Job job = new Job(UIText.CreateTagDialog_GetTagJobName) { @Override protected IStatus run(IProgressMonitor monitor) { final RevTag[] tags = getRevTags(); <START> Display.getDefault().syncExec(new Runnable() { <END> public void run() { if (!tagViewer.getTable().isDisposed()) { tagViewer.setInput(tags); tagViewer.getTable().setEnabled(true); } } }); return Status.OK_STATUS; } }; job.setSystem(true); job.schedule(); }</code><technical_language>is generally asyncExec(Runnable) instead of syncExec(Runnable). work is done asynchronously a separate thread I hard requirement for this table population done immediately. Please do change code Display.getDefault() (you swap getShell().getDisplay()) though</technical_language>

Target:
public void create() { super.create(); Job job = new Job(UIText.CreateTagDialog_GetTagJobName) { @Override protected IStatus run(IProgressMonitor monitor) { final List<RevTag> tags = getRevTags(); getShell().getDisplay().asyncExec(new Runnable() { public void run() { if (!tagViewer.getTable().isDisposed()) { tagViewer.setInput(tags); tagViewer.getTable().setEnabled(true); } } }); return Status.OK_STATUS; } }; job.setSystem(true); job.schedule(); }
Source:
<code>public void putAll(List<Entry<K, V>> entries) { List<Entry<K, V>> toPut = new LinkedList<>(); List<K> toDelete = new LinkedList<>(); entries.forEach(e -> { if (e.getValue() != null) { toPut.add(e); } else { toDelete.add(e.getKey()); } }); <START> instrument(writeMetrics.numPutAlls, writeMetrics.putAllNs, () -> kvStore.putAll(toPut)); <END> if (!toDelete.isEmpty()) { deleteAll(toDelete); } }</code><technical_language>need check if toPut is empty well</technical_language>

Target:
public void putAll(List<Entry<K, V>> entries) { List<Entry<K, V>> toPut = new LinkedList<>(); List<K> toDelete = new LinkedList<>(); entries.forEach(e -> { if (e.getValue() != null) { toPut.add(e); } else { toDelete.add(e.getKey()); } }); if (!toPut.isEmpty()) { instrument(writeMetrics.numPutAlls, writeMetrics.putAllNs, () -> kvStore.putAll(toPut)); } if (!toDelete.isEmpty()) { deleteAll(toDelete); } }
Source:
<code>public static int getIndexForValue(int bucketCount, double min, double max, double value) { checkArgument( value >= min && value <= max, <START> "value must be within range [%s, %s]", min, max); <END> return Math.min( (int) (bucketCount * (value - min) / (max - min)), bucketCount - 1); }</code><technical_language>reasoning inclusive range ends? handling a more complicated conventional (very limited) experience. love learn it</technical_language>

Target:
public static int getIndexForValue(int bucketCount, double min, double max, double value) { checkArgument( value >= min && value < max, "value must be within range [%s, %s]", min, max); return Math.min( (int) (bucketCount * (value - min) / (max - min)), bucketCount - 1); }
Source:
<code>public int hashCode() { <START> return (int) (time / 1000L) + event.getValue(); <END> }</code><technical_language>Please Guava's hashcode helpers <LINK_0></technical_language>

Target:
public int hashCode() { return Objects.hashCode(time, event.getValue()); }
Source:
<code>public WinRmToolResponse executeCommand(String command) { WinRmClient.Builder builder = WinRmClient.builder(address, authenticationScheme); if (username != null && password != null) { builder.credentials(username, password); } if (disableCertificatesChecks) { <START> LOG.info("Disabled check for https connections " + this); <END> builder.setDisableCertificatesChecks(disableCertificatesChecks); } WinRmClient client = builder.build(); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); try { int code = client.command(command, out, err); return new WinRmToolResponse(out.toString(), err.toString(), code); } finally { client.disconnect(); } }</code><technical_language>clear for certificates, i.e. Disabled certificate check for https connections</technical_language>

Target:
public WinRmToolResponse executeCommand(String command) { WinRmClient.Builder builder = WinRmClient.builder(address, authenticationScheme); if (username != null && password != null) { builder.credentials(username, password); } if (disableCertificateChecks) { LOG.info("Disabled check for https connections " + this); builder.disableCertificateChecks(disableCertificateChecks); } WinRmClient client = builder.build(); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); try { int code = client.command(command, out, err); return new WinRmToolResponse(out.toString(), err.toString(), code); } finally { client.disconnect(); } }