auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void update() throws BankException, LoginException, BankChoiceException, IOException { super.update(); if (username == null || password == null || username.length() == 0 || password.length() == 0) { throw new LoginException(res.getText(R.string.invalid_username_password).toString()); } urlopen = login(); try { response = urlopen.open("<LINK_0>"); Matcher matcher = reAccounts.matcher(response); while (matcher.find()) { accounts.add(new Account(Html.fromHtml(matcher.group(2)).toString().trim(), Helpers.parseBalance(matcher.group(3)), matcher.group(1).trim())); balance = balance.add(Helpers.parseBalance(matcher.group(3))); } if (accounts.isEmpty()) { throw new BankException(res.getText(R.string.no_accounts_found).toString()); } <START> } finally { <END> super.updateComplete(); } }</code><technical_language>need a finally block here. If Exceptions thrown updateComplete() either</technical_language>

Target:
public void update() throws BankException, LoginException, BankChoiceException, IOException { super.update(); if (username == null || password == null || username.length() == 0 || password.length() == 0) { throw new LoginException(res.getText(R.string.invalid_username_password).toString()); } urlopen = login(); response = urlopen.open("<LINK_0>"); Matcher matcher = reAccounts.matcher(response); while (matcher.find()) { accounts.add(new Account(Html.fromHtml(matcher.group(2)).toString().trim(), Helpers.parseBalance(matcher.group(3)), matcher.group(1).trim())); balance = balance.add(Helpers.parseBalance(matcher.group(3))); } if (accounts.isEmpty()) { throw new BankException(res.getText(R.string.no_accounts_found).toString()); } super.updateComplete(); }
Source:
<code>public void testLongTableNameLengthFailsCassandra() throws IOException { Schema schema = new Schema("Table", TEST_PACKAGE, Namespace.EMPTY_NAMESPACE); int longLengthCassandra = AtlasDbConstants.CASSANDRA_TABLE_NAME_CHAR_LIMIT + 1; String longTableName = String.join("", Collections.nCopies(longLengthCassandra, "x")); TableReference tableRef = TableReference.createWithEmptyNamespace(longTableName); assertThatThrownBy(() -> schema.addTableDefinition(longTableName, getSimpleTableDefinition(tableRef))) .isInstanceOf(IllegalArgumentException.class) <START> .hasMessage("Internal table name %s is too long, exceeds Cassandra limit (%s). " + <END> "If using a table prefix, please ensure that the concatenation " + "of the prefix with the internal table name is below the KVS limit. " + "If running using a different KVS, set the ignoreTableNameLength flag.", longTableName, AtlasDbConstants.CASSANDRA_TABLE_NAME_CHAR_LIMIT); }</code><technical_language>nit: refactor message part, a method getExceededName(String tableName, Enum dbType), similarly in impl code too</technical_language>

Target:
public void testLongTableNameLengthFailsCassandra() throws IOException { Schema schema = new Schema("Table", TEST_PACKAGE, Namespace.EMPTY_NAMESPACE); int longLengthCassandra = AtlasDbConstants.CASSANDRA_TABLE_NAME_CHAR_LIMIT + 1; String longTableName = String.join("", Collections.nCopies(longLengthCassandra, "x")); TableReference tableRef = TableReference.createWithEmptyNamespace(longTableName); List<CharacterLimitType> kvsList = new ArrayList<CharacterLimitType>(); kvsList.add(CharacterLimitType.CASSANDRA); assertThatThrownBy(() -> schema.addTableDefinition(longTableName, getSimpleTableDefinition(tableRef))) .isInstanceOf(IllegalArgumentException.class) .hasMessage(getErrorMessage(longTableName, kvsList)); }
Source:
<code>public Session startSession() throws ConnectionException, TransportException { checkConnected(); checkAuthenticated(); <START> final SessionChannel sess = (remoteCharset != null)? new SessionChannel(conn, remoteCharset) : new SessionChannel(conn); <END> sess.open(); return sess; }</code><technical_language>need do if in case default UTF_8 already</technical_language>

Target:
public Session startSession() throws ConnectionException, TransportException { checkConnected(); checkAuthenticated(); final SessionChannel sess = new SessionChannel(conn, remoteCharset); sess.open(); return sess; }
Source:
<code>public List<OnmsResource> getResourcesForParent(OnmsResource parent) { if (!NodeResourceType.isNode(parent)) { return Collections.emptyList(); } final OnmsNode node = ResourceTypeUtils.getNodeFromResource(parent); final List<OnmsResource> resources = Lists.newLinkedList(); final Collection<LocationIpInterface> statuses = m_locationSpecificStatusDao.findStatusChangesForNodeForUniqueMonitorAndInterface(node.getId()); <START> for (LocationIpInterface status : statuses) { <END> String definitionName = status.getLocation().getLocationName(); String id = status.getLocation().getLocationName(); final OnmsIpInterface ipInterface = status.getIpInterface(); String ipAddr = InetAddressUtils.str(ipInterface.getIpAddress()); if (m_resourceStorageDao.exists(getRelativeInterfacePath(id, ipAddr), 0)) { resources.add(createResource(definitionName, id, ipAddr)); } } return OnmsResource.sortIntoResourceList(resources); }</code><technical_language>Get rid of definitionName. createResource is adopted easily</technical_language>

Target:
public List<OnmsResource> getResourcesForParent(OnmsResource parent) { if (!NodeResourceType.isNode(parent)) { return Collections.emptyList(); } final OnmsNode node = ResourceTypeUtils.getNodeFromResource(parent); final List<OnmsResource> resources = Lists.newLinkedList(); final Collection<LocationIpInterface> statuses = m_locationSpecificStatusDao.findStatusChangesForNodeForUniqueMonitorAndInterface(node.getId()); for (LocationIpInterface status : statuses) { String location = status.getLocation().getLocationName(); final OnmsIpInterface ipInterface = status.getIpInterface(); String ipAddr = InetAddressUtils.str(ipInterface.getIpAddress()); if (m_resourceStorageDao.exists(getRelativeInterfacePath(location, ipAddr), 0)) { resources.add(createResource(location, ipAddr)); } } return OnmsResource.sortIntoResourceList(resources); }
Source:
<code>public Builder setLength(int length) { if (length > 0) { this.length = length; return this; } else { <START> throw new IllegalArgumentException("Length shoud be positive. Incase of live streaming, length is expected to be null"); <END> } }</code><technical_language>typo "should", "In case"</technical_language>

Target:
public Builder setLength(int length) { return setLength(UInt16.from(length)); }
Source:
<code>public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { if (!isInit) return invoker.invoke(invocation); TraceContext invocationContext = currentTraceContext.get(); RpcContext rpcContext = RpcContext.getContext(); Kind kind = rpcContext.isProviderSide() ? Kind.SERVER : Kind.CLIENT; Span span; DubboRequest request; if (kind.equals(Kind.CLIENT)) { Map<String, String> attachments = RpcContext.getContext().getAttachments(); DubboClientRequest clientRequest = new DubboClientRequest(invoker, invocation, attachments); request = clientRequest; span = clientHandler.handleSendWithParent(clientRequest, invocationContext); } else { DubboServerRequest serverRequest = new DubboServerRequest(invoker, invocation); request = serverRequest; span = serverHandler.handleReceive(serverRequest); } boolean deferFinish = false; Scope scope = currentTraceContext.newScope(span.context()); Result result = null; Throwable error = null; try { result = invoker.invoke(invocation); error = result.getException(); Future<Object> future = rpcContext.getFuture(); if (future instanceof CompletableFuture) { deferFinish = true; ((CompletableFuture<?>) future) .whenComplete(FinishSpan.create(this, request, result, span)); } return result; } catch (Throwable e) { propagateIfFatal(e); error = e; throw e; } finally { <START> if (!deferFinish) FinishSpan.finish(this, request, result, error, span); <END> scope.close(); } }</code><technical_language>for this PR, wondering, this timestamp of span bogus</technical_language>

Target:
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { if (!isInit) return invoker.invoke(invocation); TraceContext invocationContext = currentTraceContext.get(); RpcContext rpcContext = RpcContext.getContext(); Kind kind = rpcContext.isProviderSide() ? Kind.SERVER : Kind.CLIENT; Span span; DubboRequest request; if (kind.equals(Kind.CLIENT)) { Map<String, String> attachments = RpcContext.getContext().getAttachments(); DubboClientRequest clientRequest = new DubboClientRequest(invoker, invocation, attachments); request = clientRequest; span = clientHandler.handleSendWithParent(clientRequest, invocationContext); } else { DubboServerRequest serverRequest = new DubboServerRequest(invoker, invocation); request = serverRequest; span = serverHandler.handleReceive(serverRequest); } boolean isSynchronous = true; Scope scope = currentTraceContext.newScope(span.context()); Result result = null; Throwable error = null; try { result = invoker.invoke(invocation); error = result.getException(); CompletableFuture<Object> future = rpcContext.getCompletableFuture(); if (future != null) { isSynchronous = false; future.whenComplete(FinishSpan.create(this, request, result, span)); } return result; } catch (Throwable e) { propagateIfFatal(e); error = e; throw e; } finally { if (isSynchronous) FinishSpan.finish(this, request, result, error, span); scope.close(); } }
Source:
<code>public static CustomTxtTraceDefinition load(String definitionName) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); EntityResolver resolver = new EntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) { String empty = ""; ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes()); return new InputSource(bais); } }; db.setEntityResolver(resolver); db.setErrorHandler(new ErrorHandler() { @Override public void error(SAXParseException saxparseexception) throws SAXException { } @Override public void warning(SAXParseException saxparseexception) throws SAXException { } @Override public void fatalError(SAXParseException saxparseexception) throws SAXException { throw saxparseexception; } }); CustomTxtTraceDefinition value = lookupDefinition(definitionName, db, CUSTOM_TXT_TRACE_DEFINITIONS_PATH_NAME); <START> if( value == null ) { <END> return lookupDefinition(definitionName, db, CUSTOM_TXT_TRACE_DEFINITIONS_DEFAULT_PATH_NAME); } return value; } catch (ParserConfigurationException e) { Activator.logError("Error loading CustomTxtTraceDefinition: definitionName=" + definitionName, e); } catch (SAXException e) { Activator.logError("Error loading CustomTxtTraceDefinition: definitionName=" + definitionName, e); } catch (IOException e) { Activator.logError("Error loading CustomTxtTraceDefinition: definitionName=" + definitionName, e); } return null; }</code><technical_language>whitespace</technical_language>

Target:
public static CustomTxtTraceDefinition load(String definitionName) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); EntityResolver resolver = new EntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) { String empty = ""; ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes()); return new InputSource(bais); } }; db.setEntityResolver(resolver); db.setErrorHandler(new ErrorHandler() { @Override public void error(SAXParseException saxparseexception) throws SAXException { } @Override public void warning(SAXParseException saxparseexception) throws SAXException { } @Override public void fatalError(SAXParseException saxparseexception) throws SAXException { throw saxparseexception; } }); CustomTxtTraceDefinition value = lookupDefinition(definitionName, db, CUSTOM_TXT_TRACE_DEFINITIONS_PATH_NAME); if (value == null) { return lookupDefinition(definitionName, db, CUSTOM_TXT_TRACE_DEFINITIONS_DEFAULT_PATH_NAME); } return value; } catch (ParserConfigurationException | SAXException | IOException e ) { Activator.logError("Error loading CustomTxtTraceDefinition: definitionName=" + definitionName, e); } return null; }
Source:
<code>public String <START> getRoutingStyle() { <END> ConnectorStyle connectorStyle = getConnectorStyle(); if (connectorStyle != null) { return connectorStyle.getRouting().getLiteral(); } return null; }</code><technical_language>return litteral enum. simplier</technical_language>

Target:
public Routing getRoutingStyle() { ConnectorStyle connectorStyle = getConnectorStyle(); if (connectorStyle != null) { return connectorStyle.getRouting(); } return null; }
Source:
<code>public boolean hasNext() { if (newEpoch || epochs == numEpochs) { <START> log.info("Epoch " + epochs + ", number of batches completed " + lastBatch); <END> newEpoch = false; } if (iter == null) return (epochs < numEpochs) && ((batchedDS.size() != 0 && batchedDS.size() > batch) || batchedDS.size() == 0); else return (epochs < numEpochs) || (iter.hasNext() && (epochs == 0 || epochs == numEpochs)); }</code><technical_language>Please remove this change condition is incorrect if accept anytime epochs == numEpochs achieved epoch. If newEpoch for condition</technical_language>

Target:
public boolean hasNext() { if (newEpoch) { log.info("Epoch " + epochs + ", number of batches completed " + lastBatch); newEpoch = false; } if (iter == null) return (epochs < numEpochs) && ((!batchedDS.isEmpty() && batchedDS.size() > batch) || batchedDS.isEmpty()); else return (epochs < numEpochs) || (iter.hasNext() && (epochs == 0 || epochs == numEpochs)); }
Source:
<code><START> static <E,T> Validation<E,T> invalid(Supplier<? extends E> supplier) { <END> return new Invalid<>(supplier.get()); }</code><technical_language>Please add a check Objects.requireNonNull(supplier, "supplier is null");</technical_language>

Target:
static <E,T> Validation<E,T> invalid(Supplier<? extends E> supplier) { Objects.requireNonNull(supplier, "supplier is null"); return new Invalid<>(supplier.get()); }
Source:
<code>private void verifyAndMergeCheckpoints(final Collection<TaskGroup> taskGroupsToVerify) { final List<ListenableFuture<Boolean>> futures = new ArrayList<>(); for (TaskGroup taskGroup : taskGroupsToVerify) { futures.add(workerExec.submit(() -> { verifyAndMergeCheckpoints(taskGroup); <START> return true; <END> })); } try { Futures.allAsList(futures).get(futureTimeoutInSeconds, TimeUnit.SECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { throw new RuntimeException(e); } }</code><technical_language>this return is used. Is this intentional? If not, I this Runnable instead of Callable</technical_language>

Target:
private void verifyAndMergeCheckpoints(final Collection<TaskGroup> taskGroupsToVerify) { final List<ListenableFuture<?>> futures = new ArrayList<>(); for (TaskGroup taskGroup : taskGroupsToVerify) { futures.add(workerExec.submit(() -> verifyAndMergeCheckpoints(taskGroup))); } try { Futures.allAsList(futures).get(futureTimeoutInSeconds, TimeUnit.SECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { throw new RuntimeException(e); } }
Source:
<code>private List<T> convertToT(List<String> vals) { List<T> convertedList = new ArrayList<T>(); for(String val : vals) { <START> convertedList.add(super.convertToT(val)); <END> } return convertedList; }</code><technical_language>need for super</technical_language>

Target:
private List<T> convertToT(List<String> vals) { List<T> convertedList = new ArrayList<T>(); for(String val : vals) { convertedList.add(convertToT(val)); } return convertedList; }
Source:
<code>private static boolean isJavaxScriptSource(String source) { return isJavascriptSource(source); <START> } <END></code><technical_language>of isJavaxScriptSource/isJavascriptSource necessary</technical_language>

Target:
public static boolean isJavaxScriptSource(String source) { return isJavascriptSource(source) || isRubySource(source); }
Source:
<code>public AboutPageView(final Binder uiBinder) { initWidget(uiBinder.createAndBindUi(this)); $(buttonCanada).click(new Function() { @Override <START> public boolean f(Event e) { <END> $(canada).show(); $(quebec).hide(); return false; } }); $(buttonQuebec).click(new Function() { @Override public boolean f(Event e) { $(quebec).show(); $(canada).hide(); return false; } }); }</code><technical_language>if need event, is override function : java public void f(); gain a line of code :)</technical_language>

Target:
public AboutPageView(final Binder uiBinder) { initWidget(uiBinder.createAndBindUi(this)); $(buttonCanada).click(new Function() { @Override public void f() { $(canada).show(); $(quebec).hide(); } }); $(buttonQuebec).click(new Function() { @Override public void f() { $(quebec).show(); $(canada).hide(); } }); }
Source:
<code>private void cleanUpForRetry() { runtime.getAddressSpaceView().invalidateClientCache(); runtime.getObjectsView().getObjectCache().clear(); runtime.getStreamsView().getStreamCache().clear(); findAndSetLogHead(); <START> findAndSetLogTail(); <END> nextRead = logHead; resetAddressProcessed(); }</code><technical_language>loadMaps failing if spans a trim, load partial checkpoints</technical_language>

Target:
private void cleanUpForRetry() { runtime.getAddressSpaceView().invalidateClientCache(); runtime.getObjectsView().getObjectCache().clear(); runtime.getStreamsView().getStreamCache().clear(); log.info("retry fastobject loader head " + logHead + " tail " + logTail); }
Source:
<code>public void showInherited(boolean visible) { for (int r = 0; r < table.getRowCount(); r++) { <START> if (table.getWidget(r, 2) instanceof Hyperlink) { <END> table.getRowFormatter().setVisible(r, visible); } } }</code><technical_language>a identify if access right is inherited checking is a UI widget is instance of Hyperlink</technical_language>

Target:
public void showInherited(boolean visible) { for (int r = 0; r < table.getRowCount(); r++) { if (getRowItem(r) != null && getRowItem(r).isInherited()) { table.getRowFormatter().setVisible(r, visible); } } }
Source:
<code>public static String getRandomEmail() { StringBuilder sb = new StringBuilder(UUID.randomUUID().toString().toLowerCase()); sb.append('@'); <START> sb.append("realm.io"); <END> return sb.toString(); }</code><technical_language>a domain javatest.realm.io</technical_language>

Target:
public static String getRandomEmail() { StringBuilder sb = new StringBuilder(UUID.randomUUID().toString().toLowerCase()); sb.append('@'); sb.append("androidtest.realm.io"); return sb.toString(); }
Source:
<code>public SamzaResourceRequest(int numCores, int memoryMB, String preferredHost, String processorId, Instant requestTimestamp) { this.numCores = numCores; this.memoryMB = memoryMB; this.preferredHost = preferredHost; this.requestId = UUID.randomUUID().toString(); this.processorId = processorId; this.requestTimestamp = requestTimestamp; this.faultDomains = new HashSet<>(); <START> log.info("SamzaResourceRequest created for Processor ID: on host: at time: with Request ID: {}", this.processorId, this.preferredHost, this.requestTimestamp, this.requestId); <END> }</code><technical_language>nit: adding fault domains log useful for debugging</technical_language>

Target:
public SamzaResourceRequest(int numCores, int memoryMB, String preferredHost, String processorId, Instant requestTimestamp) { this.numCores = numCores; this.memoryMB = memoryMB; this.preferredHost = preferredHost; this.requestId = UUID.randomUUID().toString(); this.processorId = processorId; this.requestTimestamp = requestTimestamp; this.faultDomains = new HashSet<>(); log.info("SamzaResourceRequest created for Processor ID: on host: at time: with Request ID: {}, and the following list of fault domains: {}", this.processorId, this.preferredHost, this.requestTimestamp, this.requestId, this.faultDomains); }
Source:
<code>public LineItemBean create(final LineItem lineItem) { final LineItemBean bean = fillBean(new LineItemBean(), lineItem); final List<ProductAttributeBean> attributes = lineItem.getVariant().getAttributes().stream() .filter(attr -> productDataConfig.getSelectableAttributes().contains(attr.getName())) .map(attr -> productAttributeBeanFactory.create(attr)) .collect(toList()); bean.setAttributes(attributes); <START> return bean; <END> }</code><technical_language>I put this in another fillBean follow structure everywhere, developer rewrite attributes part. like: Java public LineItemBean create(final LineItem lineItem) { return fillBean(new LineItemBean(), lineItem); } protected <T extends LineItemBean> T fillBean(final T bean, LineItem lineItem) { T updatedBean = super.fillBean(bean, lineItem); final List<ProductAttributeBean> attributes = lineItem.getVariant().getAttributes().stream() .filter(attr -> productDataConfig.getSelectableAttributes().contains(attr.getName())) .map(attr -> productAttributeBeanFactory.create(attr)) .collect(toList()); updatedBean.setAttributes(attributes); return updatedBean; }</technical_language>

Target:
public LineItemBean create(final LineItem lineItem) { final LineItemBean bean = new LineItemBean(); initialize(bean, lineItem); return bean; }
Source:
<code>public Stream(int column, StreamKind streamKind, int length, boolean useVInts) { <START> this(column, streamKind, length, useVInts, ColumnEncoding.ORC_SEQUENCE_ID); <END> }</code><technical_language>I understand I suggests name constant ORC_SEQUENCE_ID, I realized Stream constructor called construct DWRF stream well. this is accurate. I call DEFAULT_SEQUENCE for (although name is a bit confusing). add a TO-DO deprecate this constructor. Thoughts ? @haozhun</technical_language>

Target:
public Stream(int column, StreamKind streamKind, int length, boolean useVInts) { this(column, streamKind, length, useVInts, ColumnEncoding.DEFAULT_SEQUENCE_ID); }
Source:
<code>public void onBindViewHolder(ViewHolder vh, int position) { switch (vh.getItemViewType()) { case CONTENT_CARD_VIEW_TYPE: ContentViewHolder holder = (ContentViewHolder) vh; int quotePosition = position - position / adModulus; Quote q = generator.getQuote(quotePosition); holder.txtName.setText(q.name); holder.txtQuote.setText(q.quote); setHeadShot(holder.imgHeadShot, q.url); break; case AD_CARD_VIEW_TYPE: final AdViewHolder adViewHolder = (AdViewHolder) vh; sdk.request( new Request.Builder() .addPlacement(new Placement("div1", NETWORK_ID, SITE_ID, 5)) .build(), new ResponseListener() { @Override public void success(Response response) { Decision decision = response.getDecision("div1"); Content content = decision.getContents().get(0); adViewHolder.setClickUrl(decision.getClickUrl()); loadAdContent(adViewHolder, content, decision.getImpressionUrl()); <START> Log.d(TAG, "Title: " + content.getTitle()); <END> adViewHolder.txtName.setText(content.getTitle()); Object q = content.getCustomData("quote"); if (q != null) { Log.d(TAG, "Quote: " + q.toString()); adViewHolder.txtQuote.setText(q.toString()); } else { adViewHolder.txtQuote.setText("Quote unavailable"); } } @Override public void error(RetrofitError error) { Log.d(TAG, "Error: " + error.getMessage()); } } ); default: break; } }</code><technical_language>sense move title quote assignment loadAdContent method. do binding there, a scattered this in 2 places</technical_language>

Target:
public void onBindViewHolder(ViewHolder vh, int position) { switch (vh.getItemViewType()) { case CONTENT_CARD_VIEW_TYPE: ContentViewHolder holder = (ContentViewHolder) vh; int quotePosition = position - position / adModulus; Quote q = generator.getQuote(quotePosition); holder.txtName.setText(q.name); holder.txtQuote.setText(q.quote); setHeadShot(holder.imgView, q.url); break; case AD_CARD_VIEW_TYPE: final AdViewHolder adViewHolder = (AdViewHolder) vh; sdk.request( new Request.Builder() .addPlacement(new Placement("div1", NETWORK_ID, SITE_ID, 5).setFlightId(FLIGHT_ID)) .build(), new ResponseListener() { @Override public void success(Response response) { Decision decision = response.getDecision("div1"); loadAdContent(adViewHolder, decision); } @Override public void error(RetrofitError error) { Log.d(TAG, "Error: " + error.getMessage()); } } ); default: break; } }
Source:
<code>public Collection<RunningTask> awaitRunningTasks() { try { runningTaskLatch.await(); <START> } catch (InterruptedException e) { <END> throw new RuntimeException(e); } return runningTasks.values(); }</code><technical_language>Exceptions caught declared final. #228</technical_language>

Target:
public Collection<RunningTask> awaitRunningTasks() { try { runningTaskLatch.await(); } catch (final InterruptedException e) { throw new RuntimeException(e); } return runningTasks.values(); }
Source:
<code>public LocalCorruptionHandler( List<TimeLockCorruptionNotifier> corruptionNotifiers) { this.corruptionNotifiers = corruptionNotifiers; <START> this.executorService = PTExecutors.newFixedThreadPool(corruptionNotifiers.size()); <END> this.corruptionNotifyRetryer = new Retryer<>(StopStrategies.stopAfterAttempt(5), WaitStrategies.fixedWait(200, TimeUnit.MILLISECONDS), attempt -> !attempt.hasResult()); }</code><technical_language>This is a bit resource intensive now, creating this executor service, corruption happened (also forgot shut eventually). is need do this asynchronously this point really, run synchronously</technical_language>

Target:
public LocalCorruptionHandler( List<TimeLockCorruptionNotifier> corruptionNotifiers) { this.corruptionNotifiers = corruptionNotifiers; this.corruptionNotifyRetryer = new Retryer<>(StopStrategies.stopAfterAttempt(5), WaitStrategies.fixedWait(200, TimeUnit.MILLISECONDS), attempt -> !attempt.hasResult()); }
Source:
<code>public PushButtonMsg(String rawMsg) { super(rawMsg); logger.debug(this.msgType+" Payload Len -> "+this.payload.length); if (this.payload.length == PUSH_BUTTON_PAYLOAD_LEN) { if (this.payload[0] == 0x50) isRetransmission = true; if (this.payload[1] == 0x0) mode = PushButtonMode.ECO; else if (this.payload[1] == 0x1) mode = PushButtonMode.AUTO; } <START> else logger.error("Got "+this.msgType+" message with incorrect length!"); <END> }</code><technical_language>please add curly braces</technical_language>

Target:
public PushButtonMsg(String rawMsg) { super(rawMsg); logger.debug(this.msgType + " Payload Len -> " + this.payload.length); if (this.payload.length == PUSH_BUTTON_PAYLOAD_LEN) { if (this.payload[0] == 0x50) isRetransmission = true; if (this.payload[1] == 0x0) mode = PushButtonMode.ECO; else if (this.payload[1] == 0x1) mode = PushButtonMode.AUTO; } else { logger.error("Got " + this.msgType + " message with incorrect length!"); } }
Source:
<code>public void initRepo() throws Exception { section = session.createDocumentModel("/", "Section", "Section"); section.setPropertyValue("dc:title", "Section"); section = session.createDocument(section); session.save(); section = session.getDocument(section.getRef()); fileToPublish = session.createDocumentModel("/", "FileToPublish", "File"); <START> fileToPublish.setPropertyValue("dc:title", "File"); <END> fileToPublish = session.createDocument(fileToPublish); session.save(); fileToPublish = session.getDocument(fileToPublish.getRef()); }</code><technical_language>indeed, fast copy/past</technical_language>

Target:
public void initRepo() throws Exception { section = session.createDocumentModel("/", "Section", "Section"); section.setPropertyValue("dc:title", "Section"); section = session.createDocument(section); fileToPublish = session.createDocumentModel("/", "FileToPublish", "File"); fileToPublish.setPropertyValue("dc:title", "File"); fileToPublish = session.createDocument(fileToPublish); session.save(); }
Source:
<code>private String getHttpResponse(String endpoint, String requestMethod, String payload) { StringBuilder jsonString = new StringBuilder(); BufferedReader br = null; try { String line; URL url = new URL(endpoint); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestProperty("charset", "UTF-8"); connection.setReadTimeout(10000); connection.setRequestMethod(requestMethod); connection.setRequestProperty("Accept", "application/json"); if (null != payload) { connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Content-Length", String.valueOf(payload.length())); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); writer.write(payload); writer.close(); } br = new BufferedReader(new InputStreamReader(connection.getInputStream())); while (null != (line = br.readLine())) { jsonString.append(line); } connection.disconnect(); } catch (IOException e) { log.error("IO exception occurred, " + e.getMessage()); } finally { try { if (null != br) { br.close(); } } catch (IOException e) { <START> log.error("IO exception occurred while closing the reader, " + e.getMessage()); <END> } } return jsonString.toString(); }</code><technical_language>log exception (so stack trace printed)</technical_language>

Target:
private String getHttpResponse(String endpoint, String requestMethod, String payload) { StringBuilder jsonString = new StringBuilder(); BufferedReader br = null; try { String line; URL url = new URL(endpoint); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestProperty("charset", "UTF-8"); connection.setReadTimeout(10000); connection.setRequestMethod(requestMethod); connection.setRequestProperty("Accept", "application/json"); if (null != payload) { connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Content-Length", String.valueOf(payload.length())); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); writer.write(payload); writer.close(); } br = new BufferedReader(new InputStreamReader(connection.getInputStream())); while (null != (line = br.readLine())) { jsonString.append(line); } connection.disconnect(); } catch (IOException e) { log.error("IO exception occurred, " + e.getMessage(), e); } finally { try { if (null != br) { br.close(); } } catch (IOException e) { log.error("IO exception occurred while closing the reader, " + e.getMessage(), e); } } return jsonString.toString(); }
Source:
<code>private List<PID> makePidList(int numPids) { <START> List<PID> pids = new ArrayList<PID>(); <END> int i = 0; while(i < numPids) { PID pidMock = mock(PID.class); when(pidMock.getId()).thenReturn("uuid:" + UUID.randomUUID().toString()); pids.add(pidMock); i++; } return pids; }</code><technical_language>Change new ArrayList<>();</technical_language>

Target:
private List<PID> makePidList(int numPids) { List<PID> pids = new ArrayList<>(); int i = 0; while(i < numPids) { PID pidMock = mock(PID.class); when(pidMock.getId()).thenReturn("uuid:" + UUID.randomUUID().toString()); pids.add(pidMock); i++; } return pids; }
Source:
<code>public static String loadWikiTextContent(String filename) { StringBuilder textContent = new StringBuilder(); String separator = System.getProperty("line.separator"); <START> Scanner scanner = null; <END> String path = String.format(TEXT_FILES_PATH_FORMAT, filename); try { scanner = new Scanner(new File(ClassLoader.getSystemResource(path).getPath()), "UTF-8"); } catch (FileNotFoundException e) { PageObjectLogging.logError("File was not loaded", e); } if (scanner != null) { try { while (scanner.hasNextLine()) { textContent.append(scanner.nextLine()).append(separator); } } finally { scanner.close(); } } else { throw new NullPointerException("Could not initialize scanner!"); } return textContent.toString(); }</code><technical_language>here, extract initialisation a method</technical_language>

Target:
public static String loadWikiTextContent(String filename) { StringBuilder textContent = new StringBuilder(); String separator = System.getProperty("line.separator"); String path = String.format(TEXT_FILES_PATH_FORMAT, filename); try (Scanner scanner = new Scanner(new File(ClassLoader.getSystemResource(path).getPath()), "UTF-8")) { while (scanner.hasNextLine()) { textContent.append(scanner.nextLine()).append(separator); } } catch (NullPointerException | FileNotFoundException ex) { throw new ContentLoaderException("Error when loading file!", ex); } return textContent.toString(); }
Source:
<code>public void validate(JobParameters parameters) throws JobParametersInvalidException { String configRestartabilityAllowValue = parameters.getString(JobParametersNames.CONFIG_RESTARTABILITY_ALLOW); ParametersValidatorUtil .checkNullOrEmptyString(configRestartabilityAllowValue, JobParametersNames.CONFIG_RESTARTABILITY_ALLOW); ParametersValidatorUtil.checkBooleanStringSyntax(configRestartabilityAllowValue, <START> JobParametersNames.CONFIG_RESTARTABILITY_ALLOW); <END> }</code><technical_language>Please indentation consistent</technical_language>

Target:
public void validate(JobParameters parameters) throws JobParametersInvalidException { String configRestartabilityAllowValue = parameters.getString(JobParametersNames.CONFIG_RESTARTABILITY_ALLOW); ParametersValidatorUtil .checkIsNotNullOrEmptyString(configRestartabilityAllowValue, JobParametersNames.CONFIG_RESTARTABILITY_ALLOW); ParametersValidatorUtil .checkIsBoolean(configRestartabilityAllowValue, JobParametersNames.CONFIG_RESTARTABILITY_ALLOW); }
Source:
<code><START> public static String getBasicUserSecretFromHttpReq(HttpServletRequest httpReq) <END> { try { String authHeader = httpReq.getHeader("Authorization"); if (authHeader == null) { return null; } if (!authHeader.substring(0, 6).equals("Basic ")) { return null; } String encodedUserSecret = authHeader.substring(6); return StringUtils.fromUtf8(DECODER.decode(encodedUserSecret)); } catch (Exception e) { return null; } }</code><technical_language>Please address <LINK_0></technical_language>

Target:
public static String getBasicUserSecretFromHttpReq(HttpServletRequest httpReq) { String authHeader = httpReq.getHeader("Authorization"); if (authHeader == null) { return null; } if (authHeader.length() < 7) { return null; } if (!authHeader.substring(0, 6).equals("Basic ")) { return null; } String encodedUserSecret = authHeader.substring(6); try { return StringUtils.fromUtf8(Base64.getDecoder().decode(encodedUserSecret)); } catch (IllegalArgumentException iae) { return null; } }
Source:
<code><START> public JSONArray(JSONArray array) { <END> if (array == null) { this.myArrayList = new ArrayList<Object>(); } else { this.myArrayList = new ArrayList<Object>(array.length()); this.addAll(array.myArrayList); } }</code><technical_language>Do support this for JSONObject? If not, support for JSONArray either</technical_language>

Target:
public JSONArray(JSONArray array) { if (array == null) { this.myArrayList = new ArrayList<Object>(); } else { this.myArrayList = new ArrayList<Object>(array.myArrayList); } }
Source:
<code>private IModuleResource[] getCleanedChildren(IModuleResource[] children) { <START> ArrayList<IModuleResource> cleaned = new ArrayList<IModuleResource>(); <END> IModuleResource tmp = null; for( int i = 0; i < children.length; i++ ) { tmp = getCleanedResource(children[i]); if( tmp != null ) cleaned.add(tmp); } return cleaned.toArray(new IModuleResource[cleaned.size()]); }</code><technical_language>initialize list size children.length</technical_language>

Target:
private IModuleResource[] getCleanedChildren(IModuleResource[] children) { ArrayList<IModuleResource> cleaned = new ArrayList<IModuleResource>(children.length); IModuleResource tmp = null; for( int i = 0; i < children.length; i++ ) { tmp = getCleanedResource(children[i]); if( tmp != null ) cleaned.add(tmp); } return cleaned.toArray(new IModuleResource[cleaned.size()]); }
Source:
<code>public void checkUserCredentials(final PluginTask task) { try { authorizeAndRequestWithGet(task, JiraUtil.buildPermissionUrl(task.getUri())); } catch (JiraException e) { LOGGER.error(String.format("JIRA return status (%s), reason (%s)", e.getStatusCode(), e.getMessage())); if (e.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { throw new ConfigException("Could not authorize with your credential."); } else { <START> throw new ConfigException("Could not authorize with your credential due to problem when contacting JIRA API"); <END> } } }</code><technical_language>this is a user facing message: "due problem" "due a problem" "due problems"</technical_language>

Target:
public void checkUserCredentials(final PluginTask task) { try { authorizeAndRequest(task, JiraUtil.buildPermissionUrl(task.getUri()), null); } catch (JiraException e) { LOGGER.error(String.format("JIRA return status (%s), reason (%s)", e.getStatusCode(), e.getMessage())); if (e.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { throw new ConfigException("Could not authorize with your credential."); } else { throw new ConfigException("Could not authorize with your credential due to problems when contacting JIRA API."); } } }
Source:
<code>public static String findPermissionId(String id) { List<PermissionGroup> pgs = PermissionGroup.getAll(); Matcher m = PERMISSION_PATTERN.matcher(id); if(m.matches()) { String owner = m.group(1); String name = m.group(2); for(PermissionGroup pg : pgs) { if(pg.owner.equals(Permission.class)) { continue; } <START> if(pg.title.toString(Locale.US).equals(owner)) { <END> return pg.owner.getName() + "." + name; } } } return null; }</code><technical_language>targeting a newer core. pg.getId() <LINK_0> suggestion if(pg.getId().equals(owner)) {</technical_language>

Target:
public static String findPermissionId(String id) { List<PermissionGroup> pgs = PermissionGroup.getAll(); Matcher m = PERMISSION_PATTERN.matcher(id); if(m.matches()) { String owner = m.group(1); String name = m.group(2); for(PermissionGroup pg : pgs) { if(pg.owner.equals(Permission.class)) { continue; } if(pg.getId().equals(owner)) { return pg.owner.getName() + "." + name; } } } return null; }
Source:
<code>private void additionalValidation() throws ParseException { if(noRetry && retry!=DEFAULT_RETRY_PERIOD) <START> throw new ParseException("The \"--retry\" and \"--no-retry\" options are mutually exclusive!"); <END> }</code><technical_language>avoid exclamation marks in error messages</technical_language>

Target:
private void additionalValidation() throws ParseException { if(noRetry && retry!=DEFAULT_RETRY_PERIOD) throw new ParseException("The \"--retry\" and \"--no-retry\" options are mutually exclusive"); }
Source:
<code>public void move(String folderPath, String newFolderPath , AuthenticationInfo subject) throws IOException { <START> LOG.info("====move folder {}:{}", folderPath, newFolderPath); <END> if (folderPath.equals(newFolderPath)) { return; } String[] pathArray = toPathArray(folderPath, true); String[] newPathArray = toPathArray(newFolderPath, true); String[] newFolderParentArray = Arrays.copyOfRange(newPathArray, 0, newPathArray.length - 1); String id = findFolder(pathArray); String newPId = completeFolder(newFolderParentArray); String newFolderName = newPathArray[newPathArray.length - 1]; Document doc = new Document("$set" , new Document(Fields.ID, id) .append(Fields.PID, newPId) .append(Fields.IS_DIR, true) .append(Fields.NAME, newFolderName)); folders.updateOne(eq(Fields.ID, id), doc); }</code><technical_language>other places</technical_language>

Target:
public void move(String folderPath, String newFolderPath, AuthenticationInfo subject) throws IOException { LOG.debug("move folder, folderPath: {}, newFolderPath: {}", folderPath, newFolderPath); if (StringUtils.equals(folderPath, newFolderPath)) { return; } String[] pathArray = toPathArray(folderPath, true); String[] newPathArray = toPathArray(newFolderPath, true); String[] newFolderParentArray = Arrays.copyOfRange(newPathArray, 0, newPathArray.length - 1); try (AutoLock autoLock = lock.lockForWrite()) { String id = findFolder(pathArray); String newPId = completeFolder(newFolderParentArray); String newFolderName = newPathArray[newPathArray.length - 1]; Document doc = new Document("$set", new Document(Fields.ID, id) .append(Fields.PID, newPId) .append(Fields.IS_DIR, true) .append(Fields.NAME, newFolderName)); folders.updateOne(eq(Fields.ID, id), doc); } }
Source:
<code>private void getMethodsToProxy(Set<MethodSetEntry> sink, Set<MethodSetEntry> seenFinalMethods, Class<?> c) { for (Method method : c.getDeclaredMethods()) { MethodSetEntry entry = new MethodSetEntry(method); if ((method.getModifiers() & Modifier.FINAL) != 0) { <START> seenFinalMethods.add(new MethodSetEntry(method)); <END> if (sink.contains(entry)) { sink.remove(entry); } continue; } if ((method.getModifiers() & STATIC) != 0) { continue; } if (method.getName().equals("finalize") && method.getParameterTypes().length == 0) { continue; } if (seenFinalMethods.contains(entry)) { continue; } sink.add(entry); } for (Class<?> i : c.getInterfaces()) { getMethodsToProxy(sink, seenFinalMethods, i); } }</code><technical_language>entry</technical_language>

Target:
private void getMethodsToProxy(Set<MethodSetEntry> sink, Set<MethodSetEntry> seenFinalMethods, Class<?> c) { for (Method method : c.getDeclaredMethods()) { MethodSetEntry entry = new MethodSetEntry(method); if ((method.getModifiers() & Modifier.FINAL) != 0) { seenFinalMethods.add(entry); if (sink.contains(entry)) { sink.remove(entry); } continue; } if ((method.getModifiers() & STATIC) != 0) { continue; } if (method.getName().equals("finalize") && method.getParameterTypes().length == 0) { continue; } if (seenFinalMethods.contains(entry)) { continue; } sink.add(entry); } for (Class<?> i : c.getInterfaces()) { getMethodsToProxy(sink, seenFinalMethods, i); } }
Source:
<code>protected Hardware resolveHardware(Set<? extends Hardware> hardwarel, final Iterable<? extends Image> images) { try { return super.resolveHardware(hardwarel, images); } catch (Exception NoSuchElementException) { if (super.minCores != 0 && super.minRam != 0) { return automaticHardwareForCpuAndRam(minCores, minRam); } <START> else throw throwNoSuchElementExceptionAfterLoggingHardwareIds("Invalid hardware", hardwarel); <END> } }</code><technical_language>here. Consider propagating current exception</technical_language>

Target:
protected Hardware resolveHardware(Set<? extends Hardware> hardwarel, final Iterable<? extends Image> images) { try { return super.resolveHardware(hardwarel, images); } catch (NoSuchElementException ex) { if (super.minCores != 0 && super.minRam != 0) { return automaticHardwareForCpuAndRam(minCores, minRam); } else throw new IllegalArgumentException("No hardware profile matching the given criteria was found. If " + "you want to use exact values, please set the minCores and minRam values", ex); } }
Source:
<code>protected void handlePrimaryRequest(final ConcreteShardRequest<Request> request, final TransportChannel channel, final Task task) { Releasable releasable = checkPrimaryLimits(request.getRequest()); ActionListener<Response> listener = ActionListener.runAfter(new ChannelActionListener<>(channel, transportPrimaryAction, request), releasable::close); <START> threadPool.executor(executor).execute(new ActionRunnable<>(listener) { <END> @Override protected void doRun() { new AsyncPrimaryAction(request, listener, (ReplicationTask) task).run(); } }); }</code><technical_language>need forceExecutionOnPrimary account here, right</technical_language>

Target:
protected void handlePrimaryRequest(final ConcreteShardRequest<Request> request, final TransportChannel channel, final Task task) { Releasable releasable = checkPrimaryLimits(request.getRequest()); ActionListener<Response> listener = ActionListener.runAfter(new ChannelActionListener<>(channel, transportPrimaryAction, request), releasable::close); try { new AsyncPrimaryAction(request, listener, (ReplicationTask) task).run(); } catch (RuntimeException e) { listener.onFailure(e); } }
Source:
<code>void fun(String strPath, String StrParent, String StrChild, String prefix, String suffix, java.net.URI uri) throws Exception { new File(strPath); new File(StrParent, StrChild); File parent = new File(uri); new File(parent, StrChild); <START> File.createTempFile(prefix, suffix); END> }</code><technical_language>I add other createTempFile method enforce fact explicitly target this only</technical_language>

Target:
void fun(String strPath, String StrParent, String StrChild, String prefix, String suffix, java.net.URI uri) throws Exception { new File(strPath); new File(StrParent, StrChild); File parent = new File(uri); new File(parent, StrChild); File.createTempFile(prefix, suffix); File.createTempFile(prefix, suffix, parent); }
Source:
<code>public boolean solutionEquals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } <START> final Match match = (Match) o; <END> return Objects.equals(id, match.id) && Objects.equals(homeTeam, match.homeTeam) && Objects.equals(awayTeam, match.awayTeam) && Objects.equals(day, match.day); }</code><technical_language>Nitpick: variable name other</technical_language>

Target:
public boolean solutionEquals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final Match other = (Match) o; return Objects.equals(id, other.id) && Objects.equals(homeTeam, other.homeTeam) && Objects.equals(awayTeam, other.awayTeam) && Objects.equals(day, other.day); }
Source:
<code>public void enable(Integer pin) { lastActivityTime = System.currentTimeMillis(); controller.servoEnable(this); <START> this.pin = pin + ""; <END> enabled = true; broadcastState(); invoke("publishServoEnable", getName()); }</code><technical_language>set pin controller enable</technical_language>

Target:
public void enable(Integer pin) { log.info("Enable called on {}", getName()); if (this.pin != null && this.pin != pin) { disable(); } lastActivityTime = System.currentTimeMillis(); this.pin = pin; if (controller != null) { enabled = true; controller.servoEnable(this); } broadcastState(); }
Source:
<code>private void buildUnaryExpression(UnaryExpressionTree tree) { <START> if(tree.is(Tree.Kind.PREFIX_DECREMENT, Tree.Kind.PREFIX_INCREMENT)) { <END> build(tree.expression()); currentBlock.elements.add(tree); } else { currentBlock.elements.add(tree); build(tree.expression()); } }</code><technical_language>@benzonico fact postfix operators return modification change order in CFG, loading of happen operation, i.e. order same</technical_language>

Target:
private void buildUnaryExpression(UnaryExpressionTree tree) { currentBlock.elements.add(tree); build(tree.expression()); }
Source:
<code><START> public synchronized void stop() <END> { synchronized (lifecycleLock) { if (!lifecycleLock.canStop()) { throw new ISE("LookupCoordinatorManager can't stop."); } try { LOG.debug("Stopping"); if (backgroundManagerFuture != null && !backgroundManagerFuture.cancel(true)) { LOG.warn("Background lookup manager thread could not be cancelled"); } if (executorService != null) { executorService.shutdownNow(); } LOG.debug("Stopped"); } catch (Exception ex) { LOG.makeAlert(ex, "Got Exception while stop()").emit(); } finally { lifecycleLock.exitStop(); lifecycleLock.reset(); } } }</code><technical_language>Extra synchronized</technical_language>

Target:
public void stop() { synchronized (lifecycleLock) { if (!lifecycleLock.canStop()) { throw new ISE("LookupCoordinatorManager can't stop."); } try { LOG.debug("Stopping"); if (backgroundManagerFuture != null && !backgroundManagerFuture.cancel(true)) { LOG.warn("Background lookup manager thread could not be cancelled"); } if (executorService != null) { executorService.shutdownNow(); } LOG.debug("Stopped"); } catch (Exception ex) { LOG.makeAlert(ex, "Got Exception while stop()").emit(); } finally { lifecycleLock.exitStop(); lifecycleLock.reset(); } } }
Source:
<code>public static Condition text(String text) { if (StringUtils.isBlank(text)) { <START> throw new IllegalArgumentException("No expected text given"); <END> } return new Text(text); }</code><technical_language>I nice more meaningful error message. E.g. "Text condition empty string." smth else explain problem comparing actual text empty string</technical_language>

Target:
public static Condition text(String text) { if (StringUtils.isBlank(text)) { throw new IllegalArgumentException("Text condition must not be null or empty string"); } return new Text(text); }