auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Result(List<MetricComparison> metricComparisons) { <START> Preconditions.checkArgument(metricComparisons.isEmpty(), "No metric "); <END> this.metricComparisons = ImmutableList.copyOf(metricComparisons); }</code><technical_language>static import & remove trailing whitespace string literal & negate condition Since: TestTpchDistributedStats pass this commit *and* StatisticsAssertion is totally rewritten later, squash this commit _later_ (whichever is appropriate)</technical_language>

Target:
public Result(List<MetricComparison> metricComparisons) { checkArgument(!metricComparisons.isEmpty(), "No metric comparisons given"); this.metricComparisons = ImmutableList.copyOf(metricComparisons); }
Source:
<code>public Collection<ArticleRevision> getPreprintArticlesWithoutVor() { return hibernateTemplate.execute(session -> { String subQuery = "" + "SELECT DISTINCT fi.ingestion " + "FROM ArticleFile fi " + "INNER JOIN fi.ingestion ai " + "WHERE fi.bucketName = 'preprints' " + "AND ai.isPreprintOfDoi IS NULL"; String queryString = "" + "SELECT DISTINCT ar " + "FROM ArticleRevision ar " + <START> "WHERE ar.ingestion IN (" + subQuery + ")"; <END> Query query = session.createQuery(queryString); final Collection<ArticleRevision> revisions = query.list(); return revisions; }); }</code><technical_language>HQL "EXISTS"? If so, EXISTS IN produce a faster query, need DISTINCT fi.ingestion</technical_language>

Target:
public Collection<ArticleRevision> getPreprintArticlesWithoutVor() { return hibernateTemplate.execute(session -> { String subQuery = "" + "SELECT fi.ingestion " + "FROM ArticleFile fi " + "INNER JOIN fi.ingestion ai " + "WHERE fi.bucketName = 'preprints' " + "AND ai.isPreprintOfDoi IS NULL"; String queryString = "" + "SELECT DISTINCT ar " + "FROM ArticleRevision ar " + "WHERE ar.ingestion EXISTS (" + subQuery + ")"; Query query = session.createQuery(queryString); final Collection<ArticleRevision> revisions = query.list(); return revisions; }); }
Source:
<code>public void testItemUse(BlockFace face) { PlayerMock player = server.addPlayer(); ClimbingPick pick = registerSlimefunItem(plugin, "TEST_CLIMBING_PICK_" + face.name()); <START> boolean shouldCancel = false; if (face == BlockFace.DOWN || face == BlockFace.UP) shouldCancel = true; <END> BlockMock block1 = new BlockMock(Material.STONE); simulateRightClickBlock(player, pick, block1, face); server.getPluginManager().assertEventFired(ClimbingPickLaunchEvent.class); if (!shouldCancel) player.assertSoundHeard(Sound.ENTITY_ENDERMAN_TELEPORT); BlockMock block2 = new BlockMock(Material.DIRT); simulateRightClickBlock(player, pick, block2, face); server.getPluginManager().assertEventFired(ClimbingPickLaunchEvent.class); if (!shouldCancel) player.assertSoundHeard(Sound.ENTITY_ENDERMAN_TELEPORT); }</code><technical_language>know... done shouldCancel = face == BlockFace.DOWN || face == BlockFace.UP ..</technical_language>

Target:
public void testItemUse(BlockFace face) { PlayerMock player = server.addPlayer(); ClimbingPick pick = registerSlimefunItem(plugin, "TEST_CLIMBING_PICK_" + face.name()); Location blockLocation = new Location(player.getLocation().getWorld(), player.getLocation().getBlockX() + 1, player.getLocation().getBlockY(), player.getLocation().getBlockZ()); boolean shouldCancel = face == BlockFace.DOWN || face == BlockFace.UP; BlockMock block1 = new BlockMock(Material.STONE, blockLocation); simulateRightClickBlock(player, pick, block1, face); server.getPluginManager().assertEventFired(ClimbingPickLaunchEvent.class); if (!shouldCancel) player.assertSoundHeard(Sound.ENTITY_ENDERMAN_TELEPORT); BlockMock block2 = new BlockMock(Material.DIRT, blockLocation); simulateRightClickBlock(player, pick, block2, face); server.getPluginManager().assertEventFired(ClimbingPickLaunchEvent.class); if (!shouldCancel) player.assertSoundHeard(Sound.ENTITY_ENDERMAN_TELEPORT); }
Source:
<code>public ManageGlusterServiceCommand(GlusterServiceParameters params) { super(params); this.clusterId = params.getClusterId(); <START> this.serverId = params.getServerId(); <END> this.serviceType = params.getServiceType(); this.actionType = params.getActionType(); }</code><technical_language>call setVdsGroupId based parameters for server check in Gluster command base</technical_language>

Target:
public ManageGlusterServiceCommand(GlusterServiceParameters params) { super(params); this.clusterId = params.getClusterId(); this.serverId = params.getServerId(); this.serviceType = params.getServiceType(); this.actionType = params.getActionType(); setVdsGroupId(params.getClusterId()); }
Source:
<code>default BundleSpecBuilder extension(Extension extension) { requireNonNull(extension, "Extension cannot be null"); <START> directive("extension", extension.value); <END> return this; }</code><technical_language>extension.toString()</technical_language>

Target:
default BundleSpecBuilder extension(Extension extension) { requireNonNull(extension, "Extension cannot be null"); directive("extension", extension.toString()); return this; }
Source:
<code>public static String getStringFromDocument(Document doc) throws TransformerException { DOMSource domSource = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); <START> TransformerFactory transformerFactory = TransformerFactory.newInstance("org.apache.xalan.processor.TransformerFactoryImpl",null); <END> Transformer transformer = transformerFactory.newTransformer(); transformer.transform(domSource, result); return writer.toString().substring(writer.toString().indexOf('>') + 1); }</code><technical_language>I get processor name system property somewhere, default previous newInstance. apache library optimal needed for some other cases. WDYT</technical_language>

Target:
public static String getStringFromDocument(Document doc) throws TransformerException { DOMSource domSource = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); String transformerFactoryClassName = System.getProperty("org.wso2.balana.TransformerFactory"); if(transformerFactoryClassName == null) { transformerFactoryClassName = "org.apache.xalan.processor.TransformerFactoryImpl"; } TransformerFactory transformerFactory = TransformerFactory.newInstance(transformerFactoryClassName, null); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(domSource, result); return writer.toString().substring(writer.toString().indexOf('>') + 1); }
Source:
<code>public FormValidation doCheckUrl(@QueryParameter String value) { try { URLConnection conn = ProxyConfiguration.open(new URL(value)); conn.connect(); if (conn instanceof HttpURLConnection) { int responseCode = ((HttpURLConnection)conn).getResponseCode(); if (HttpURLConnection.HTTP_MOVED_PERM == responseCode || HttpURLConnection.HTTP_MOVED_TEMP == responseCode || HttpURLConnection.HTTP_SEE_OTHER == responseCode) { <START> String redirection = ((HttpURLConnection) conn).getHeaderField("Location"); <END> conn = ProxyConfiguration.open(new URL(redirection)); responseCode = ((HttpURLConnection) conn).getResponseCode(); } if (responseCode != HttpURLConnection.HTTP_OK) { return FormValidation.error(Messages.ZipExtractionInstaller_bad_connection()); } } return FormValidation.ok(); } catch (MalformedURLException x) { return FormValidation.error(Messages.ZipExtractionInstaller_malformed_url()); } catch (IOException x) { return FormValidation.error(x,Messages.ZipExtractionInstaller_could_not_connect()); } }</code><technical_language>is this inline instead of method in ProxyConfiguration</technical_language>

Target:
public FormValidation doCheckUrl(@QueryParameter String value) { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); try { ProxyConfiguration.openURLAllowingCrossProtocolRedirects(new URL(value)); return FormValidation.ok(); } catch (MalformedURLException x) { return FormValidation.error(Messages.ZipExtractionInstaller_malformed_url()); } catch (IOException x) { return FormValidation.error(x,Messages.ZipExtractionInstaller_could_not_connect()); } }
Source:
<code>public int read() throws IOException { int ret = 0; <START> while (ret == 0) { <END> ret = read(oneByteBuf, 0, 1); } if (ret == -1) { return -1; } else { return oneByteBuf[0] & 0xff; } }</code><technical_language>code more compact. while logic depending initial of "ret". For example: int n; while ( (n = read(oneByteBuf, 0, 1)) == 0); return (n == -1) ? -1 : oneByteBuf[0] & 0xff;</technical_language>

Target:
public int read() throws IOException { int n; while ((n = read(oneByteBuf, 0, 1)) == 0) ; return (n == -1) ? -1 : oneByteBuf[0] & 0xff; }
Source:
<code>private Void handleError(Throwable ex, EmailType messageType, String emailBody, List<String> to, List<String> notifyOnFailureEmails) { log.error("Failed email \n\n\n{}\n\n\n, to: {}", messageType, emailBody, to, ex); if (CollectionUtils.isNotEmpty(notifyOnFailureEmails)) { final Map<String, Object> parameters = ImmutableMap.of("exception", ex.getCause()); <START> send(EmailType.FAILED_SENDING_TO_ADMIN, parameters, emptyList(), notifyOnFailureEmails, emptyList()); <END> } return null; }</code><technical_language>If I understand correctly infinite recursion in case of network exception(or other constantly reproducible exception). I log exception for EmailType.FAILED_SENDING_TO_ADMIN</technical_language>

Target:
private Void handleError(Throwable ex, EmailType messageType, String emailBody, List<String> to, List<String> notifyOnFailureEmails) { log.error("Failed email \n\n\n{}\n\n\n, to: {}", messageType, emailBody, to, ex); if (CollectionUtils.isNotEmpty(notifyOnFailureEmails)) { final Map<String, Object> parameters = Collections.singletonMap("exception", ex.getCause()); send(EmailType.FAILED_SENDING_TO_ADMIN, parameters, emptyList(), notifyOnFailureEmails, emptyList()); } return null; }
Source:
<code>public int read(byte b[], int off, int len) throws IOException { if (off < 0 || len < 0 || len > b.length - off) { throw new IndexOutOfBoundsException(); <START> } <END> if (currentOffset >= messageReadSet.sizeInBytes(indexToRead)) { return -1; } ByteBuffer buf = ByteBuffer.wrap(b); buf.position(off); ByteBufferOutputStream bufferStream = new ByteBufferOutputStream(buf); long sizeToRead = Math.min(len, messageReadSet.sizeInBytes(indexToRead) - currentOffset); long bytesWritten = messageReadSet.writeTo(indexToRead, Channels.newChannel(bufferStream), currentOffset, sizeToRead); currentOffset += bytesWritten; return (int) bytesWritten; }</code><technical_language>Contract 0 returned if len == 0. another if condition (and a check in test)</technical_language>

Target:
public int read(byte b[], int off, int len) throws IOException { if (off < 0 || len < 0 || len > b.length - off) { throw new IndexOutOfBoundsException(); } if (len == 0) { return 0; } if (currentOffset >= messageReadSet.sizeInBytes(indexToRead)) { return -1; } ByteBuffer buf = ByteBuffer.wrap(b); buf.position(off); ByteBufferOutputStream bufferStream = new ByteBufferOutputStream(buf); long sizeToRead = Math.min(len, messageReadSet.sizeInBytes(indexToRead) - currentOffset); long bytesWritten = messageReadSet.writeTo(indexToRead, Channels.newChannel(bufferStream), currentOffset, sizeToRead); currentOffset += bytesWritten; return (int) bytesWritten; }
Source:
<code>private void loadMapPreviews() { mMMPkTitle = mMobileMapPackage.getItem().getTitle(); for (int i = 0; i < mMobileMapPackage.getMaps().size(); i++) { ArcGISMap currMap = mMobileMapPackage.getMaps().get(i); <START> final MapPreview map = new MapPreview(); <END> map.setMapNum(i); if (currMap.getItem() != null && currMap.getItem().getTitle() != null) { map.setTitle(currMap.getItem().getTitle()); } else { map.setTitle("Map " + i); } if (currMap.getItem() != null && currMap.getItem().getDescription() != null) { map.setDesc(currMap.getItem().getDescription()); } else { map.setDesc(mMobileMapPackage.getItem().getDescription()); } if (currMap.getTransportationNetworks().size() > 0) { map.setTransportNetwork(true); } if (mMobileMapPackage.getLocatorTask() != null) { map.setGeocoding(true); } final ListenableFuture<byte[]> thumbnailAsync; if (currMap.getItem() != null && currMap.getItem().fetchThumbnailAsync() != null) { thumbnailAsync = currMap.getItem().fetchThumbnailAsync(); } else { thumbnailAsync = mMobileMapPackage.getItem().fetchThumbnailAsync(); } thumbnailAsync.addDoneListener(new Runnable() { @Override public void run() { if (thumbnailAsync.isDone()) { try { map.setThumbnailByteStream(thumbnailAsync.get()); mMapPreviews.add(map); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } } }); } }</code><technical_language>Refactor variable name assign map ArcGISMap in another local reference, e.g. mapPreview</technical_language>

Target:
private void loadMapPreviews() { mMMPkTitle = mMobileMapPackage.getItem().getTitle(); for (int i = 0; i < mMobileMapPackage.getMaps().size(); i++) { ArcGISMap currMap = mMobileMapPackage.getMaps().get(i); final MapPreview mapPreview = new MapPreview(); mapPreview.setMapNum(i); if (currMap.getItem() != null && currMap.getItem().getTitle() != null) { mapPreview.setTitle(currMap.getItem().getTitle()); } else { mapPreview.setTitle("Map " + i); } if (currMap.getItem() != null && currMap.getItem().getDescription() != null) { mapPreview.setDesc(currMap.getItem().getDescription()); } else { mapPreview.setDesc(mMobileMapPackage.getItem().getDescription()); } if (currMap.getTransportationNetworks().size() > 0) { mapPreview.setTransportNetwork(true); } if (mMobileMapPackage.getLocatorTask() != null) { mapPreview.setGeocoding(true); } final ListenableFuture<byte[]> thumbnailAsync; if (currMap.getItem() != null && currMap.getItem().fetchThumbnailAsync() != null) { thumbnailAsync = currMap.getItem().fetchThumbnailAsync(); } else { thumbnailAsync = mMobileMapPackage.getItem().fetchThumbnailAsync(); } thumbnailAsync.addDoneListener(new Runnable() { @Override public void run() { if (thumbnailAsync.isDone()) { try { mapPreview.setThumbnailByteStream(thumbnailAsync.get()); mMapPreviews.add(mapPreview); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } } }); } }
Source:
<code>public void ungetOAuthService(String handle) { OAuthClientServiceImpl clientImpl = oauthClientServiceCache.get(handle); if (clientImpl == null) { <START> logger.error("{} handle not found. Cannot unregisterOAuthServie", handle); <END> return; } clientImpl.close(); }</code><technical_language>here: reduce DEBUG throw exception</technical_language>

Target:
public void ungetOAuthService(String handle) { OAuthClientServiceImpl clientImpl = oauthClientServiceCache.get(handle); if (clientImpl == null) { logger.debug("{} handle not found. Cannot unregisterOAuthServie", handle); return; } clientImpl.close(); oauthClientServiceCache.remove(handle); }
Source:
<code>private void testRenewToken(boolean setDoAsUser, String doAsUser) throws Exception { final String testToken = "ABCDEFG123456"; KnoxSession knoxSession = createMock(KnoxSession.class); expect(knoxSession.base()).andReturn("http://localhost/base").atLeastOnce(); expect(knoxSession.getHeaders()).andReturn(Collections.emptyMap()).atLeastOnce(); expect(knoxSession.executeNow(isA(HttpRequest.class))).andReturn(null).atLeastOnce(); replay(knoxSession); Renew.Request request = (setDoAsUser) ? Token.renew(knoxSession, testToken, doAsUser) : Token.renew(knoxSession, testToken); boolean shouldHaveDoAs = false; if (setDoAsUser) { assertEquals(doAsUser, request.getDoAsUser()); shouldHaveDoAs = StringUtils.isNotEmpty(doAsUser); } else { assertNull(request.getDoAsUser()); } assertEquals("http://localhost/base/knoxtoken/api/v1/token/renew" + (shouldHaveDoAs ? ("?doAs=" + doAsUser) : ""), request.getRequestURI().toString()); assertEquals(testToken, request.getToken()); Callable<TokenLifecycleResponse> callable = request.callable(); try { callable.call(); } catch (Exception e) { <START> e.printStackTrace(); <END> } HttpEntity entity = request.getRequest().getEntity(); assertNotNull("Missing expected POST data.", entity); String postData = null; try { postData = EntityUtils.toString(entity); } catch (IOException e) { e.printStackTrace(); } assertEquals(testToken, postData); assertSame(knoxSession, request.getSession()); verify(knoxSession); }</code><technical_language>this fail test? (same other catch locations)</technical_language>

Target:
private void testRenewToken(boolean setDoAsUser, String doAsUser) throws Exception { final String testToken = "RENEW+ABCDEFG123456"; final KnoxSession knoxSession = createMockKnoxSession(); Renew.Request request = (setDoAsUser) ? Token.renew(knoxSession, testToken, doAsUser) : Token.renew(knoxSession, testToken); if (setDoAsUser) { assertEquals(doAsUser, request.getDoAsUser()); } else { assertNull(request.getDoAsUser()); } testTokenLifecyle(request, testToken); assertSame(knoxSession, request.getSession()); verify(knoxSession); }
Source:
<code>public Page getNextPage() { Page page = delegate.getNextPage(); if (page == null || page.getPositionCount() == 0) { return page; } int positionCount = page.getPositionCount(); int[] positions = new int[positionCount]; for (int i = 0; i < positionCount; i++) { positions[i] = i; } for (int i = 0; i < page.getChannelCount(); i++) { TupleDomainFilter domainFilter = domainFilters[i]; if (domainFilter != null) { positionCount = filterBlock(page.getBlock(i), columnTypes[i], domainFilter, positions, positionCount); if (positionCount == 0) { return new Page(0); } } } if (filterFunction != null) { RuntimeException[] errors = new RuntimeException[positionCount]; int[] inputChannels = filterFunction.getInputChannels(); Block[] inputBlocks = new Block[inputChannels.length]; for (int i = 0; i < inputChannels.length; i++) { inputBlocks[i] = page.getBlock(this.functionInputs.get(inputChannels[i])); } Page inputPage = new Page(page.getPositionCount(), inputBlocks); positionCount = filterFunction.filter(inputPage, positions, positionCount, errors); for (int i = 0; i < positionCount; i++) { if (errors[i] != null) { throw errors[i]; } } } <START> if (positionCount == 0) { <END> return new Page(0); } if (outputBlockCount == page.getChannelCount()) { return page.getPositions(positions, 0, positionCount); } Block[] blocks = new Block[outputBlockCount]; for (int i = 0; i < outputBlockCount; i++) { blocks[i] = page.getBlock(i); } return new Page(page.getPositionCount(), blocks).getPositions(positions, 0, positionCount); }</code><technical_language>@bhhari nit: this if (filterFunction != null) block</technical_language>

Target:
public Page getNextPage() { Page page = delegate.getNextPage(); if (page == null || page.getPositionCount() == 0) { return page; } int positionCount = page.getPositionCount(); int[] positions = new int[positionCount]; for (int i = 0; i < positionCount; i++) { positions[i] = i; } for (int i = 0; i < page.getChannelCount(); i++) { TupleDomainFilter domainFilter = domainFilters[i]; if (domainFilter != null) { positionCount = filterBlock(page.getBlock(i), columnTypes[i], domainFilter, positions, positionCount); if (positionCount == 0) { return new Page(0); } } } if (filterFunction != null) { RuntimeException[] errors = new RuntimeException[positionCount]; int[] inputChannels = filterFunction.getInputChannels(); Block[] inputBlocks = new Block[inputChannels.length]; for (int i = 0; i < inputChannels.length; i++) { inputBlocks[i] = page.getBlock(this.functionInputs.get(inputChannels[i])); } Page inputPage = new Page(page.getPositionCount(), inputBlocks); positionCount = filterFunction.filter(inputPage, positions, positionCount, errors); for (int i = 0; i < positionCount; i++) { if (errors[i] != null) { throw errors[i]; } } if (positionCount == 0) { return new Page(0); } } if (outputBlockCount == page.getChannelCount()) { return page.getPositions(positions, 0, positionCount); } Block[] blocks = new Block[outputBlockCount]; for (int i = 0; i < outputBlockCount; i++) { blocks[i] = page.getBlock(i); } return new Page(page.getPositionCount(), blocks).getPositions(positions, 0, positionCount); }
Source:
<code><START> public AFCRHiddenState(double minorAlleleFraction, double log2CopyRatio) { <END> this.minorAlleleFraction = minorAlleleFraction; this.log2CopyRatio = log2CopyRatio; }</code><technical_language>hurt validate MAF</technical_language>

Target:
public AFCRHiddenState(double minorAlleleFraction, double log2CopyRatio) { this.minorAlleleFraction = ParamUtils.inRange(minorAlleleFraction, 0, 0.5, "Minor fraction must be in [0, 1/2]."); this.log2CopyRatio = log2CopyRatio; }
Source:
<code>private static Comparator<Unit> getRemovableUnitsOrder() { return Comparator.comparing( <START> Function.identity(), <END> (u1, u2) -> { if (UnitAttachment.get(u1.getType()).getTransportCapacity() != -1) { return Comparator.<Unit, Collection<Unit>>comparing( Unit::getTransporting, Comparator.comparingInt(TransportUtils::getTransportCost).reversed()) .thenComparing(Unit::getMovementLeft) .thenComparingInt(Object::hashCode) .compare(u1, u2); } return Comparator.comparing(Unit::getMovementLeft) .thenComparingInt(Object::hashCode) .compare(u1, u2); }); }</code><technical_language>in this case point surrounding Comparator.comparing, return lambda</technical_language>

Target:
private static Comparator<Unit> getRemovableUnitsOrder() { return (u1, u2) -> { if (UnitAttachment.get(u1.getType()).getTransportCapacity() != -1) { return Comparator.<Unit, Collection<Unit>>comparing( Unit::getTransporting, Comparator.comparingInt(TransportUtils::getTransportCost).reversed()) .thenComparing(Unit::getMovementLeft) .thenComparingInt(Object::hashCode) .compare(u1, u2); } return Comparator.comparing(Unit::getMovementLeft) .thenComparingInt(Object::hashCode) .compare(u1, u2); }; }
Source:
<code>public Iterator<Chain> iterator() throws TimeoutException { EhcacheEntityResponse.IteratorBatch iteratorBatch = openIterator(); if (iteratorBatch.isTerminated()) { return iteratorBatch.getChains().iterator(); } else { UUID iteratorId = iteratorBatch.getIdentity(); return new Iterator<Chain>() { private boolean terminalBatch = false; private Iterator<Chain> batch = iteratorBatch.getChains().iterator(); @Override public boolean hasNext() { <START> return !terminalBatch || batch.hasNext(); <END> } @Override public Chain next() { if (batch.hasNext()) { return batch.next(); } else { try { EhcacheEntityResponse.IteratorBatch batchResponse = fetchBatch(iteratorId); batch = batchResponse.getChains().iterator(); terminalBatch = batchResponse.isTerminated(); return batch.next(); } catch (TimeoutException e) { throw new RuntimeException(e); } } } @Override protected void finalize() throws Throwable { entity.invokeAndWaitForReceive(new ServerStoreOpMessage.IteratorCloseMessage(iteratorId), false); } }; } }</code><technical_language>Hmmm ... If in batch, need ask batch if more items. But, if in batch, consumed item in penultimate batch need ask next batch if _it_ items -- -- receive batch if items</technical_language>

Target:
public Iterator<Chain> iterator() throws TimeoutException { EhcacheEntityResponse.IteratorBatch iteratorBatch = openIterator(); if (iteratorBatch.isLast()) { return iteratorBatch.getChains().iterator(); } else { UUID iteratorId = iteratorBatch.getIdentity(); return new Iterator<Chain>() { private boolean lastBatch = false; private Iterator<Chain> batch = iteratorBatch.getChains().iterator(); @Override public boolean hasNext() { return !lastBatch || batch.hasNext(); } @Override public Chain next() { if (batch.hasNext()) { return batch.next(); } else { try { EhcacheEntityResponse.IteratorBatch batchResponse = fetchBatch(iteratorId); batch = batchResponse.getChains().iterator(); lastBatch = batchResponse.isLast(); return batch.next(); } catch (TimeoutException e) { throw new RuntimeException(e); } } } @Override protected void finalize() throws Throwable { if (!lastBatch) { entity.invokeAndWaitForReceive(new ServerStoreOpMessage.IteratorCloseMessage(iteratorId), false); } } }; } }
Source:
<code>private void populateCanRunStatus(Username username, PipelineInstanceModel pipelineInstanceModel) { for (StageInstanceModel stageHistoryItem : pipelineInstanceModel.getStageHistory()) { ServerHealthStateOperationResult result = new ServerHealthStateOperationResult(); boolean canRun = scheduleService.canRun( pipelineInstanceModel.getPipelineIdentifier(), stageHistoryItem.getName(), CaseInsensitiveString.str(username.getUsername()), pipelineInstanceModel.hasPreviousStageBeenScheduled( stageHistoryItem.getName()), result); stageHistoryItem.setCanRun(canRun); <START> stageHistoryItem.setErrorMessage(canRun || result.getServerHealthState() == null ? "" : result.getServerHealthState().getMessage()); <END> } populatePipelineCanRunStatus(username, pipelineInstanceModel); }</code><technical_language>Setting a blank error message feels odd</technical_language>

Target:
private void populateCanRunStatus(Username username, PipelineInstanceModel pipelineInstanceModel) { for (StageInstanceModel stageHistoryItem : pipelineInstanceModel.getStageHistory()) { ServerHealthStateOperationResult result = new ServerHealthStateOperationResult(); boolean canRun = scheduleService.canRun( pipelineInstanceModel.getPipelineIdentifier(), stageHistoryItem.getName(), CaseInsensitiveString.str(username.getUsername()), pipelineInstanceModel.hasPreviousStageBeenScheduled( stageHistoryItem.getName()), result); stageHistoryItem.setCanRun(canRun); if (!canRun && result.getServerHealthState() != null && result.getServerHealthState().getType().equals(HealthStateType.forbidden())) { stageHistoryItem.setErrorMessage(result.getServerHealthState().getMessage()); } } populatePipelineCanRunStatus(username, pipelineInstanceModel); }
Source:
<code>protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { this.mc.getTextureManager().bindTexture(BACKGROUND); GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); scala.draw(8, 16); mouseX -= guiLeft; mouseY -= guiTop; if(8 <= mouseX && mouseX < 114 && 16 <= mouseY && mouseY < 122) { FluidStack hovered = getFluidHovered(122 - mouseY - 1); List<String> text = Lists.newArrayList(); <START> if(hovered == null) { <END> int usedCap = tinkerTank.getTank().getFluidAmount(); int maxCap = tinkerTank.getTank().getCapacity(); text.add(TextFormatting.WHITE + Util.translate("gui.smeltery.capacity")); RenderUtil.liquidToString(null, maxCap, text); text.add(Util.translateFormatted("gui.smeltery.capacity_available")); RenderUtil.liquidToString(null, maxCap - usedCap, text); } else { text.add(TextFormatting.WHITE + hovered.getLocalizedName()); RenderUtil.liquidToString(hovered, text); } this.drawHoveringText(text, mouseX, mouseY); } }</code><technical_language>Duplicate code</technical_language>

Target:
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { this.mc.getTextureManager().bindTexture(BACKGROUND); GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); scala.draw(8, 16); mouseX -= guiLeft; mouseY -= guiTop; List<String> tooltip = GuiUtil.drawTankTooltip(tinkerTank.getTank(), mouseX, mouseY, 8, 16, 114, 122); if(tooltip != null) { this.drawHoveringText(tooltip, mouseX, mouseY); } }
Source:
<code>public void apply(List<? extends Node> acuList, RuleContext ctx) { TimeTracker.startOperation(TimedOperationCategory.RULE); for (Rule rule : rules) { try { if (!rule.isRuleChain() && applies(rule, ctx.getLanguageVersion())) { TimeTracker.startOperation(TimedOperationCategory.RULE, rule.getName()); rule.apply(acuList, ctx); TimeTracker.finishOperation(); } } catch (RuntimeException e) { if (ctx.isIgnoreExceptions()) { <START> TimeTracker.finishOperation(); <END> ctx.getReport().addError(new Report.ProcessingError(e, ctx.getSourceCodeFilename())); if (LOG.isLoggable(Level.WARNING)) { LOG.log(Level.WARNING, "Exception applying rule " + rule.getName() + " on file " + ctx.getSourceCodeFilename() + ", continuing with next rule", e); } } else { throw e; } } } TimeTracker.finishOperation(); }</code><technical_language>This work right ctx.isIgnoreException is false. _also_ guaranteed paired startOperation if exception is if conditional line 499 immediately above. Nice attempt, right track! Bullet proof exception handling easy. for this reason I find try-with-resouces style appealing, flow-logic bugs possible. This is original code loosing time for in regression testing</technical_language>

Target:
public void apply(List<? extends Node> acuList, RuleContext ctx) { try (TimedOperation to = TimeTracker.startOperation(TimedOperationCategory.RULE)) { for (Rule rule : rules) { if (!rule.isRuleChain() && applies(rule, ctx.getLanguageVersion())) { try (TimedOperation rto = TimeTracker.startOperation(TimedOperationCategory.RULE, rule.getName())) { rule.apply(acuList, ctx); } catch (RuntimeException e) { if (ctx.isIgnoreExceptions()) { ctx.getReport().addError(new Report.ProcessingError(e, ctx.getSourceCodeFilename())); if (LOG.isLoggable(Level.WARNING)) { LOG.log(Level.WARNING, "Exception applying rule " + rule.getName() + " on file " + ctx.getSourceCodeFilename() + ", continuing with next rule", e); } } else { throw e; } } } } } }
Source:
<code>public Map<String, DbParameterAccessor> getAllProcedureParameters( String procName) throws SQLException { String objectDatabaseName = ""; String[] objnameParts = procName.split("\\."); if (objnameParts.length == 3) { objectDatabaseName = objnameParts[0] + "."; <START> } <END> return readIntoParams( procName, "select [name], [Type], max_length, is_output, is_cursor_ref from " + "(" + " select " + " p.[name], TYPE_NAME(p.system_type_id) as [Type], " + " p.max_length, p.is_output, p.is_cursor_ref, " + " p.parameter_id, 0 as set_id, p.object_id " + " from " + objectDatabaseName + "sys.parameters p " + " union all select " + " '' as [name], 'int' as [Type], " + " 4 as max_length, 1 as is_output, 0 as is_cursor_ref, " + " null as parameter_id, 1 as set_id, object_id " + " from " + objectDatabaseName + "sys.objects where type in (N'P', N'PC') " + ") as u where object_id = OBJECT_ID(?) order by set_id, parameter_id"); }</code><technical_language>snippet is basically other. move a single place</technical_language>

Target:
public Map<String, DbParameterAccessor> getAllProcedureParameters( String procName) throws SQLException { return readIntoParams( procName, "select [name], [Type], max_length, is_output, is_cursor_ref from " + "(" + " select " + " p.[name], TYPE_NAME(p.system_type_id) as [Type], " + " p.max_length, p.is_output, p.is_cursor_ref, " + " p.parameter_id, 0 as set_id, p.object_id " + " from " + objectDatabasePrefix(procName) + "sys.parameters p " + " union all select " + " '' as [name], 'int' as [Type], " + " 4 as max_length, 1 as is_output, 0 as is_cursor_ref, " + " null as parameter_id, 1 as set_id, object_id " + " from " + objectDatabasePrefix(procName) + "sys.objects where type in (N'P', N'PC') " + ") as u where object_id = OBJECT_ID(?) order by set_id, parameter_id"); }
Source:
<code>public FileItem read(final FilePath filePath) throws NonExistentItemException { checkInitialization(); final GetObjectRequest getObjectRequest = new GetObjectRequest(bucketNameForFilePath(filePath), filePath.filename()); FileItem fileItem = null; try (final S3Object s3Object = amazonS3Client.getObject(getObjectRequest)) { final Map<String, String> userMetaData = getUserMetaData(s3Object); final String filename = userMetaData.get(USER_METADATA_FILENAME); final DateTime lastUpdatedTime = getLastUpdatedTime(userMetaData); try { fileItem = new FileItem(filename, s3Object.getObjectContent(), lastUpdatedTime); } catch (final IOException e) { throw new IllegalStateException(e); } } catch (final AmazonS3Exception e) { if (missingItemErrorCodes.contains(e.getErrorCode())) { throw new NonExistentItemException( "Item does not exist" + filePath.directory() + "->" + filePath.filename()); } throw e; } catch (final IOException e1) { <START> logger.error("Error occured while closing S3Object Stream"); <END> } return fileItem; }</code><technical_language>ERROR level is severe, WARN more appropriate. Also, more informative if root of problem included. Putting together, have: java logger.warn("Error closing S3Object", e1);</technical_language>

Target:
public FileItem read(final FilePath filePath) throws NonExistentItemException { checkInitialization(); final GetObjectRequest getObjectRequest = new GetObjectRequest(bucketNameForFilePath(filePath), filePath.filename()); FileItem fileItem = null; try (final S3Object s3Object = amazonS3Client.getObject(getObjectRequest)) { final Map<String, String> userMetaData = getUserMetaData(s3Object); final String filename = userMetaData.get(USER_METADATA_FILENAME); final DateTime lastUpdatedTime = getLastUpdatedTime(userMetaData); try { fileItem = new FileItem(filename, s3Object.getObjectContent(), lastUpdatedTime); } catch (final IOException e) { throw new IllegalStateException(e); } } catch (final AmazonS3Exception e) { if (missingItemErrorCodes.contains(e.getErrorCode())) { throw new NonExistentItemException( "Item does not exist" + filePath.directory() + "->" + filePath.filename()); } throw e; } catch (final IOException e1) { logger.warn("Error closing S3Object", e1); } return fileItem; }
Source:
<code>public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable { if (!isStoreEnabled(command) || ctx.isInTxScope()) return invokeNext(ctx, command); return invokeNextThenAccept(ctx, command, (rCtx, rCommand, rv) -> { PutMapCommand putMapCommand = (PutMapCommand) rCommand; LocalizedCacheTopology cacheTopology = dm.getCacheTopology(); Map<Object, Object> map = putMapCommand.getMap(); List<MarshalledEntry> allWriterEntries = new ArrayList<>(); List<MarshalledEntry> nonSharedEntries = new ArrayList<>(); for (Object key : map.keySet()) { <START> if (isUsingLockDelegation && putMapCommand.isForwarded() && <END> !cacheTopology.getDistribution(key).primary().equals(rCtx.getOrigin())) continue; if (isProperWriter(rCtx, putMapCommand, key)) { if (skipSharedStores(ctx, key, command)) nonSharedEntries.add(createMarshalledEntry(ctx, key)); else allWriterEntries.add(createMarshalledEntry(ctx, key)); } } long flags = command.getFlagsBitSet(); persistenceManager.writeBatchToAllNonTxStores(allWriterEntries, BOTH, flags); persistenceManager.writeBatchToAllNonTxStores(nonSharedEntries, PRIVATE, flags); if (getStatisticsEnabled()) cacheStores.getAndAdd(allWriterEntries.size() + nonSharedEntries.size()); }); }</code><technical_language>please refactor this lambda handlePutMapCommandReturn store this::handlePutMapCommandReturn in field of name..</technical_language>

Target:
public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable { if (!isStoreEnabled(command) || ctx.isInTxScope()) return invokeNext(ctx, command); return invokeNextThenAccept(ctx, command, handlePutMapCommandReturn); }
Source:
<code>public PooledConnectionProviderImpl(PoolConfig<W, R> poolConfig, HostConnector<W, R> hostConnector) { this.hostConnector = hostConnector; idleConnectionsHolder = poolConfig.getIdleConnectionsHolder(); limitDeterminationStrategy = poolConfig.getPoolLimitDeterminationStrategy(); maxIdleTimeMillis = poolConfig.getMaxIdleTimeMillis(); idleConnCleanupSubscription = poolConfig.getIdleConnCleanupTicker() .doOnError(LogErrorAction.INSTANCE) .retry() .concatMap(new IdleConnectionCleanupTask()) <START> .onErrorResumeNext(new Func1<Throwable, Observable<Void>>() { <END> @Override public Observable<Void> call(Throwable throwable) { logger.error("Ignoring error cleaning up idle connections.", throwable); return Observable.empty(); } }).subscribe(); hostConnector.getHost() .getCloseNotifier() .doOnTerminate(new Action0() { @Override public void call() { isShutdown = true; idleConnCleanupSubscription.unsubscribe(); } }) .onErrorResumeNext(new Func1<Throwable, Observable<Void>>() { @Override public Observable<Void> call(Throwable throwable) { logger.error("Error listening to Host close notifications. Shutting down the pool.", throwable); return Observable.empty(); } }) .subscribe(Actions.empty()); }</code><technical_language>this, I onErrorResumeNext(...) replaced a doOnError(...) log error, a retry(). current change fixes problem of pool cleaned once, if is a transient failure stop cleaning up</technical_language>

Target:
public PooledConnectionProviderImpl(PoolConfig<W, R> poolConfig, HostConnector<W, R> hostConnector) { this.hostConnector = hostConnector; idleConnectionsHolder = poolConfig.getIdleConnectionsHolder(); limitDeterminationStrategy = poolConfig.getPoolLimitDeterminationStrategy(); maxIdleTimeMillis = poolConfig.getMaxIdleTimeMillis(); idleConnCleanupSubscription = poolConfig.getIdleConnCleanupTicker() .doOnError(LogErrorAction.INSTANCE) .retry() .concatMap(new IdleConnectionCleanupTask()) .doOnError(new Action1<Throwable>() { @Override public void call(Throwable throwable) { logger.error("Ignoring error cleaning up idle connections.", throwable); } }) .retry() .subscribe(); hostConnector.getHost() .getCloseNotifier() .doOnTerminate(new Action0() { @Override public void call() { isShutdown = true; idleConnCleanupSubscription.unsubscribe(); } }) .onErrorResumeNext(new Func1<Throwable, Observable<Void>>() { @Override public Observable<Void> call(Throwable throwable) { logger.error("Error listening to Host close notifications. Shutting down the pool.", throwable); return Observable.empty(); } }) .subscribe(Actions.empty()); }
Source:
<code>public <T> T autoCommit(AutoCommitAction<T, D> action) { Handle nested = currentTransaction.get(); if (nested != null) { return action.call(nested, nested.attach(daoIface)); } else { try { return transactionRetryExecutor.runInterruptible(() -> { <START> try (Handle handle = dbi.open()) { <END> return action.call(handle, handle.attach(daoIface)); } }); } catch (RetryGiveupException ex) { Throwable innerException = ex.getCause(); throw Throwables.propagate(innerException); } catch (InterruptedException ex) { throw Throwables.propagate(ex); } } }</code><technical_language>Is call a nested transactional methods transaction() in action.call()? If so, this handle is needed set currentTransaction</technical_language>

Target:
public <T> T autoCommit(AutoCommitAction<T, D> action) { Handle nested = currentTransaction.get(); if (nested != null) { return action.call(nested, nested.attach(daoIface)); } else { try { return transactionRetryExecutor.runInterruptible(() -> { try (Handle handle = dbi.open()) { return action.call(handle, handle.attach(daoIface)); } }); } catch (RetryGiveupException ex) { Throwable innerException = ex.getCause(); throw Throwables.propagate(innerException); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw Throwables.propagate(ex); } } }
Source:
<code><START> private int emailListIndexOf(String value) { <END> int index = -1; for (int i = 0; i < emailPick.getItemCount(); i++) { if (value.equalsIgnoreCase(emailPick.getValue(i))) { index = i; break; } } return index; }</code><technical_language>Optional: this done index variable: for (int i = 0; i < emailPick.getItemCount(); i++) { if (value.equalsIgnoreCase(emailPick.getValue(i))) { return i; } } return -1</technical_language>

Target:
private int emailListIndexOf(String value) { for (int i = 0; i < emailPick.getItemCount(); i++) { if (value.equalsIgnoreCase(emailPick.getValue(i))) { return i; } } return -1; }
Source:
<code>public void should_mapProcessVariables_when_startEventMappingExists() { securityUtil.logInAs("user"); ProcessInstance process = processRuntime.start(ProcessPayloadBuilder.start() .withProcessDefinitionKey("process-b42a166d-605b-4eec-8b96-82b1253666bf") .withVariable("Text0xfems", "name_value") .withVariable("Text0rvs0o", "email_value") .withBusinessKey("my business key") .build()); assertThat(process).isNotNull(); assertThat(process.getStatus()).isEqualTo(ProcessInstance.ProcessInstanceStatus.RUNNING); List<VariableInstance> variableInstances = processRuntime.variables(ProcessPayloadBuilder.variables().withProcessInstance(process).build()); assertThat(variableInstances) .isNotNull() .hasSize(2) .extracting(VariableInstance::getName, VariableInstance::getValue) .containsOnly( tuple("name", "name_value"), tuple("email", "email_value") ); <START> processRuntime.delete(ProcessPayloadBuilder.delete(process)); <END> }</code><technical_language>skip process clean processes deleted in @After method</technical_language>

Target:
public void should_mapProcessVariables_when_startEventMappingExists() { securityUtil.logInAs("user"); ProcessInstance process = processRuntime.start(ProcessPayloadBuilder.start() .withProcessDefinitionKey("process-b42a166d-605b-4eec-8b96-82b1253666bf") .withVariable("Text0xfems", "name_value") .withVariable("Text0rvs0o", "email_value") .withBusinessKey("my business key") .build()); assertThat(process).isNotNull(); assertThat(process.getStatus()).isEqualTo(ProcessInstance.ProcessInstanceStatus.RUNNING); List<VariableInstance> variableInstances = processRuntime.variables(ProcessPayloadBuilder.variables().withProcessInstance(process).build()); assertThat(variableInstances) .isNotNull() .hasSize(2) .extracting(VariableInstance::getName, VariableInstance::getValue) .containsOnly( tuple("name", "name_value"), tuple("email", "email_value") ); }
Source:
<code>public String getContig() { <START> return null; <END> }</code><technical_language>is this returning mReferenceName</technical_language>

Target:
public String getContig() { if( getReadUnmappedFlag()) { return null; } else { return getReferenceName(); } }
Source:
<code>public Group updateGroup(PerunSession sess, Group group) throws InternalErrorException, GroupExistsException { Utils.notNull(group.getName(), "group.getName()"); Group dbGroup; try { dbGroup = this.getGroupById(sess, group.getId()); } catch (GroupNotExistsException e) { throw new InternalErrorException("Group existence was checked at the higher level",e); } if (!dbGroup.getShortName().equals(group.getShortName())) { dbGroup.setShortName(group.getShortName()); try { jdbc.update("update groups set name=?,modified_by=?, modified_by_uid=?, modified_at=" + Compatibility.getSysdate() + " where id=?", dbGroup.getName(), sess.getPerunPrincipal().getActor(), sess.getPerunPrincipal().getUserId(), dbGroup.getId()); } catch (DataIntegrityViolationException e) { <START> throw new GroupExistsException("The name must be unique and it's already occupied.", e); <END> } catch (RuntimeException e) { throw new InternalErrorException(e); } } if (group.getDescription() != null && !group.getDescription().equals(dbGroup.getDescription())) { try { jdbc.update("update groups set dsc=?, modified_by=?, modified_by_uid=?, modified_at=" + Compatibility.getSysdate() + " where id=?", group.getDescription(), sess.getPerunPrincipal().getActor(), sess.getPerunPrincipal().getUserId(), group.getId()); } catch (RuntimeException e) { throw new InternalErrorException(e); } dbGroup.setDescription(group.getDescription()); } return dbGroup; }</code><technical_language>include name in exception text</technical_language>

Target:
public Group updateGroup(PerunSession sess, Group group) throws InternalErrorException, GroupExistsException { Utils.notNull(group.getName(), "group.getName()"); Group dbGroup; try { dbGroup = this.getGroupById(sess, group.getId()); } catch (GroupNotExistsException e) { throw new InternalErrorException("Group existence was checked at the higher level",e); } if (!dbGroup.getShortName().equals(group.getShortName())) { dbGroup.setShortName(group.getShortName()); try { jdbc.update("update groups set name=?,modified_by=?, modified_by_uid=?, modified_at=" + Compatibility.getSysdate() + " where id=?", dbGroup.getName(), sess.getPerunPrincipal().getActor(), sess.getPerunPrincipal().getUserId(), dbGroup.getId()); } catch (DataIntegrityViolationException e) { throw new GroupExistsException("The name must be unique and it's already occupied - " + dbGroup, e); } catch (RuntimeException e) { throw new InternalErrorException(e); } } if (group.getDescription() != null && !group.getDescription().equals(dbGroup.getDescription())) { try { jdbc.update("update groups set dsc=?, modified_by=?, modified_by_uid=?, modified_at=" + Compatibility.getSysdate() + " where id=?", group.getDescription(), sess.getPerunPrincipal().getActor(), sess.getPerunPrincipal().getUserId(), group.getId()); } catch (RuntimeException e) { throw new InternalErrorException(e); } dbGroup.setDescription(group.getDescription()); } return dbGroup; }
Source:
<code>public Server() { running = true; world.setServer(this); try { Instance.getPluginHandler().initPlugins(); } catch (Exception e) { e.printStackTrace(); } try { connector = new LoginConnector(); engine = new GameEngine(); engine.start(); while (!connector.isRegistered()) { Thread.sleep(100); } acceptor = new SocketAcceptor(Runtime.getRuntime().availableProcessors() + 1, Executors.newCachedThreadPool()); IoAcceptorConfig config = new SocketAcceptorConfig(); config.setDisconnectOnUnbind(true); <START> config.setThreadModel(ThreadModel.MANUAL); <END> SocketSessionConfig ssc = (SocketSessionConfig) config.getSessionConfig(); ssc.setSendBufferSize(10000); ssc.setReceiveBufferSize(10000); acceptor.bind(new InetSocketAddress(Config.SERVER_IP, Config.SERVER_PORT), new RSCConnectionHandler(engine), config); } catch (Exception e) { Logger.error(e); } }</code><technical_language>This a good do instead of removing together, check if is enabled not</technical_language>

Target:
public Server() { running = true; world.setServer(this); try { Instance.getPluginHandler().initPlugins(); } catch (Exception e) { e.printStackTrace(); } try { connector = new LoginConnector(); engine = new GameEngine(); engine.start(); while (!connector.isRegistered()) { Thread.sleep(100); } acceptor = new SocketAcceptor(Runtime.getRuntime() .availableProcessors() + 1, Executors.newCachedThreadPool()); acceptor.getFilterChain().addFirst("connectionfilter", new ConnectionFilter()); IoAcceptorConfig config = new SocketAcceptorConfig(); config.setDisconnectOnUnbind(true); config.setThreadModel(ThreadModel.MANUAL); SocketSessionConfig ssc = (SocketSessionConfig) config .getSessionConfig(); ssc.setSendBufferSize(10000); ssc.setReceiveBufferSize(10000); acceptor.bind(new InetSocketAddress(Config.SERVER_IP, Config.SERVER_PORT), new RSCConnectionHandler(engine), config); } catch (Exception e) { Logger.error(e); } }