auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void setPaymentAccountsCellFactory() { paymentAccountsListView.setCellFactory(new Callback<>() { @Override public ListCell<PaymentAccount> call(ListView<PaymentAccount> list) { return new ListCell<>() { final InfoAutoTooltipLabel label = new InfoAutoTooltipLabel("", ContentDisplay.RIGHT); final ImageView icon = ImageUtil.getImageViewById(ImageUtil.REMOVE_ICON); final Button removeButton = new AutoTooltipButton("", icon); final AnchorPane pane = new AnchorPane(label, removeButton); { label.setLayoutY(5); removeButton.setId("icon-button"); AnchorPane.setRightAnchor(removeButton, 0d); } @Override public void updateItem(final PaymentAccount item, boolean empty) { super.updateItem(item, empty); if (item != null && !empty) { label.setText(item.getAccountName()); boolean needsSigning = PaymentMethod.hasChargebackRisk(item.getPaymentMethod(), item.getTradeCurrencies()); if (needsSigning) { AccountAgeWitnessService.SignState signState = accountAgeWitnessService.getSignState(accountAgeWitnessService.getMyWitness( item.paymentAccountPayload)); String info = StringUtils.capitalize(signState.getPresentation()); switch (signState) { case PEER_SIGNER: case ARBITRATOR: case PEER_LIMIT_LIFTED: case PEER_INITIAL: label.setIcon(MaterialDesignIcon.APPROVAL, info); break; default: label.setIcon(MaterialDesignIcon.ALERT_CIRCLE_OUTLINE, info); } } else { label.hideIcon(); } removeButton.setOnAction(e -> onDeleteAccount(item)); setGraphic(pane); } else { setGraphic(null); } } }; } }); }

Target:
protected void setPaymentAccountsCellFactory() { paymentAccountsListView.setCellFactory(new Callback<>() { @Override public ListCell<PaymentAccount> call(ListView<PaymentAccount> list) { return new ListCell<>() { final InfoAutoTooltipLabel label = new InfoAutoTooltipLabel("", ContentDisplay.RIGHT); final ImageView icon = ImageUtil.getImageViewById(ImageUtil.REMOVE_ICON); final Button removeButton = new AutoTooltipButton("", icon); final AnchorPane pane = new AnchorPane(label, removeButton); { label.setLayoutY(5); removeButton.setId("icon-button"); AnchorPane.setRightAnchor(removeButton, 0d); } @Override public void updateItem(final PaymentAccount item, boolean empty) { super.updateItem(item, empty); if (item != null && !empty) { label.setText(item.getAccountName()); boolean needsSigning = PaymentMethod.hasChargebackRisk(item.getPaymentMethod(), item.getTradeCurrencies()); if (needsSigning) { AccountAgeWitnessService.SignState signState = accountAgeWitnessService.getSignState(accountAgeWitnessService.getMyWitness( item.paymentAccountPayload)); String info = StringUtils.capitalize(signState.getPresentation()); switch (signState) { case PEER_SIGNER: case ARBITRATOR: label.setIcon(MaterialDesignIcon.APPROVAL, info); break; default: label.setIcon(MaterialDesignIcon.ALERT_CIRCLE_OUTLINE, info); } } else { label.hideIcon(); } removeButton.setOnAction(e -> onDeleteAccount(item)); setGraphic(pane); } else { setGraphic(null); } } }; } }); }
Source:
public IndexProxy removeIndexProxy( long indexId ) { IndexProxy removedProxy = indexesById.remove( indexId ); if ( removedProxy == null ) { return null; } SchemaDescriptor schema = removedProxy.getDescriptor().schema(); indexesByDescriptor.remove( schema ); if ( schema.entityType() == EntityType.NODE ) { if ( schema.getEntityTokenIds() == SchemaDescriptor.ANY_ENTITY_TOKEN ) { descriptorsForAllLabels.remove( schema ); } for ( int entityTokenId : schema.getEntityTokenIds() ) { removeFromLookup( entityTokenId, schema, descriptorsByLabel ); } for ( int propertyId : schema.getPropertyIds() ) { removeFromLookup( propertyId, schema, descriptorsByProperty ); } } else if ( schema.entityType() == EntityType.RELATIONSHIP ) { if ( schema.getEntityTokenIds().length == 0 ) { descriptorsForAllReltypes.remove( schema ); } for ( int entityTokenId : schema.getEntityTokenIds() ) { removeFromLookup( entityTokenId, schema, descriptorsByReltype ); } for ( int propertyId : schema.getPropertyIds() ) { removeFromLookup( propertyId, schema, relationshipDescriptorsByProperty ); } } return removedProxy; }

Target:
public IndexProxy removeIndexProxy( long indexId ) { IndexProxy removedProxy = indexesById.remove( indexId ); if ( removedProxy == null ) { return null; } SchemaDescriptor schema = removedProxy.getDescriptor().schema(); indexesByDescriptor.remove( schema ); if ( schema.entityType() == EntityType.NODE ) { if ( SchemaDescriptor.isAnyEntityTokenSchema( schema ) ) { descriptorsForAllLabels.remove( schema ); } removeFromLookup( schema.getEntityTokenIds(), schema, descriptorsByLabel ); removeFromLookup( schema.getPropertyIds(), schema, nodeDescriptorsByProperty ); } else if ( schema.entityType() == EntityType.RELATIONSHIP ) { if ( SchemaDescriptor.isAnyEntityTokenSchema( schema ) ) { descriptorsForAllReltypes.remove( schema ); } removeFromLookup( schema.getEntityTokenIds(), schema, descriptorsByReltype ); removeFromLookup( schema.getPropertyIds(), schema, relationshipDescriptorsByProperty ); } return removedProxy; }
Source:
public static Chain decode(StructDecoder<?> decoder) { StructArrayDecoder<? extends StructDecoder<?>> elementsDecoder = decoder.structs("elements"); final List<Element> elements = new ArrayList<>(); for (int i = 0; i < elementsDecoder.length(); i++) { StructDecoder<?> elementDecoder = elementsDecoder.next(); Long sequence = elementDecoder.int64("sequence"); ByteBuffer byteBuffer = elementDecoder.byteBuffer("payload"); elementDecoder.end(); if (sequence == null) { elements.add(byteBuffer::duplicate); } else { elements.add(new SequencedElement() { @Override public long getSequenceNumber() { return sequence; } @Override public ByteBuffer getPayload() { return byteBuffer.duplicate(); } }); } } elementsDecoder.end(); return chainFromList(elements); }

Target:
public static Chain decode(StructDecoder<?> decoder) { StructArrayDecoder<? extends StructDecoder<?>> elementsDecoder = decoder.structs("elements"); final List<Element> elements = new ArrayList<>(); for (int i = 0; i < elementsDecoder.length(); i++) { StructDecoder<?> elementDecoder = elementsDecoder.next(); Long sequence = elementDecoder.int64("sequence"); ByteBuffer byteBuffer = elementDecoder.byteBuffer("payload"); elementDecoder.end(); if (sequence == null) { elements.add(byteBuffer::asReadOnlyBuffer); } else { elements.add(new SequencedElement() { @Override public long getSequenceNumber() { return sequence; } @Override public ByteBuffer getPayload() { return byteBuffer.asReadOnlyBuffer(); } }); } } elementsDecoder.end(); return chainFromList(elements); }
Source:
public void test4_09BringToTop() { SWTBotUtils.openTrace(TRACE_PROJECT_NAME, fTestFile.getAbsolutePath(), CUSTOM_TEXT_LOG.getTraceType()); SWTBotTreeItem traceItem = SWTBotUtils.getTraceProjectItem(fBot, SWTBotUtils.selectTracesFolder(fBot, TRACE_PROJECT_NAME), TRACE_NAME); traceItem.doubleClick(); fBot.waitUntil(new ConditionHelpers.ActiveEventsEditor(fBot, TRACE_NAME)); IEditorReference originalEditor = fBot.activeEditor().getReference(); createCopy(traceItem, true); SWTBotTreeItem copiedItem = SWTBotUtils.getTraceProjectItem(fBot, SWTBotUtils.selectTracesFolder(fBot, TRACE_PROJECT_NAME), RENAMED_TRACE_NAME); copiedItem.doubleClick(); fBot.waitUntil(new ConditionHelpers.ActiveEventsEditor(fBot, RENAMED_TRACE_NAME)); SWTBotUtils.delay(1000); traceItem.doubleClick(); fBot.waitUntil(new ConditionHelpers.ActiveEventsEditor(fBot, TRACE_NAME)); assertTrue(originalEditor == fBot.activeEditor().getReference()); fBot.closeAllEditors(); SWTBotUtils.clearTracesFolderUI(fBot, TRACE_PROJECT_NAME); }

Target:
public void test4_09BringToTop() { SWTBotUtils.openTrace(TRACE_PROJECT_NAME, fTestFile.getAbsolutePath(), CUSTOM_TEXT_LOG.getTraceType()); SWTBotTreeItem traceItem = SWTBotUtils.getTraceProjectItem(fBot, SWTBotUtils.selectTracesFolder(fBot, TRACE_PROJECT_NAME), TRACE_NAME); fBot.viewByTitle(PROJECT_EXPLORER_VIEW_NAME).setFocus(); traceItem.doubleClick(); fBot.waitUntil(new ConditionHelpers.ActiveEventsEditor(fBot, TRACE_NAME)); IEditorReference originalEditor = fBot.activeEditor().getReference(); createCopy(traceItem, true); SWTBotTreeItem copiedItem = SWTBotUtils.getTraceProjectItem(fBot, SWTBotUtils.selectTracesFolder(fBot, TRACE_PROJECT_NAME), RENAMED_TRACE_NAME); fBot.viewByTitle(PROJECT_EXPLORER_VIEW_NAME).setFocus(); copiedItem.doubleClick(); fBot.waitUntil(new ConditionHelpers.ActiveEventsEditor(fBot, RENAMED_TRACE_NAME)); SWTBotUtils.delay(1000); fBot.viewByTitle(PROJECT_EXPLORER_VIEW_NAME).setFocus(); traceItem.doubleClick(); fBot.waitUntil(new ConditionHelpers.ActiveEventsEditor(fBot, TRACE_NAME)); assertTrue(originalEditor == fBot.activeEditor().getReference()); fBot.closeAllEditors(); SWTBotUtils.clearTracesFolderUI(fBot, TRACE_PROJECT_NAME); }
Source:
public void ensureValid(String name, Object value) { if (value == null) { return; } if (!(value instanceof List)) { throw new ConfigException("Invalid value type (list expected)."); } List items = (List) value; if (items.isEmpty()) { return; } for (Object item: items) { if (!(item instanceof String)) { throw new ConfigException("Invalid type for admin listener (expected String)."); } if (((String) item).length() == 0) { throw new ConfigException("Empty listener found when parsing list."); } } }

Target:
public void ensureValid(String name, Object value) { if (value == null) { return; } if (!(value instanceof List)) { throw new ConfigException("Invalid value type (list expected)."); } List items = (List) value; if (items.isEmpty()) { return; } for (Object item: items) { if (!(item instanceof String)) { throw new ConfigException("Invalid type for admin listener (expected String)."); } if (((String) item).trim().isEmpty()) { throw new ConfigException("Empty listener found when parsing list."); } } }
Source:
private List<SqlStageExecution> getStagesReadyForExecution() { return stream(forTree(StreamingPlanSection::getChildren).depthFirstPreOrder(sectionedPlan)) .filter(this::isReadyForExecution) .flatMap(section -> stream(forTree(SubPlan::getChildren).depthFirstPreOrder(section.getPlan()))) .map(SubPlan::getFragment) .map(PlanFragment::getId) .map(this::getFragmentExecution) .collect(toImmutableList()); }

Target:
private List<SqlStageExecution> getStagesReadyForExecution() { return stream(forTree(StreamingPlanSection::getChildren).depthFirstPreOrder(sectionedPlan)) .filter(this::isReadyForExecution) .flatMap(section -> stream(forTree(StreamingSubPlan::getChildren).depthFirstPreOrder(section.getPlan()))) .map(StreamingSubPlan::getFragment) .map(PlanFragment::getId) .map(this::getStageExecution) .collect(toImmutableList()); }
Source:
public static void main(String[] args) { if (args.length < 2) { System.out.println("Please specify your access key and a voice call flow ID"); return; } final MessageBirdService wsr = new MessageBirdServiceImpl(args[0]); final MessageBirdClient messageBirdClient = new MessageBirdClient(wsr); try { System.out.println("Deleting a Voice Call Flow"); VoiceCallFlow voiceCallFlow = messageBirdClient .deleteVoiceCallFlow(args[1]); System.out.println("Voice call flow deleted "); } catch (GeneralException | UnauthorizedException exception) { exception.printStackTrace(); } }

Target:
public static void main(String[] args) { if (args.length < 2) { System.out.println("Please specify your access key and a voice call flow ID"); return; } final MessageBirdService wsr = new MessageBirdServiceImpl(args[0]); final MessageBirdClient messageBirdClient = new MessageBirdClient(wsr); try { System.out.println("Deleting a Voice Call Flow"); messageBirdClient.deleteVoiceCallFlow(args[1]); System.out.println("Voice call flow deleted "); } catch (GeneralException | NotFoundException | UnauthorizedException exception) { exception.printStackTrace(); } }
Source:
public void addPropertyListener(IPropertyListener listener) { for (AbstractJavaBreakpointEditor fEditor : fEditors) { fEditor.addPropertyListener(listener); } }

Target:
public void addPropertyListener(IPropertyListener listener) { for (AbstractJavaBreakpointEditor editor : fEditors) { editor.addPropertyListener(listener); } }
Source:
private static boolean isOverrideExchange(ExchangeType exchange) { return null != exchange.getOrganizationList() && CollectionUtils.isNotEmpty(exchange.getOrganizationList().getOrganization()) && StringUtils.isNotEmpty(exchange.getType()) && StringUtils.equalsIgnoreCase( EXCHANGE_TYPE.OVERRIDES.toString(), exchange.getType()); }

Target:
private static boolean isOverrideExchange(ExchangeType exchange) { return null != exchange.getOrganizationList() && CollectionUtils.isNotEmpty(exchange.getOrganizationList().getOrganization()) && StringUtils.equalsIgnoreCase(EXCHANGE_TYPE.OVERRIDES.toString(), exchange.getType()); }
Source:
public void process(GeneratingRegion region) { Border3D border = region.getBorderForFacet(BaseFacet.class).extendBy(0, 8, 4); BaseFacet facet = new BaseFacet(region.getRegion(), border); for (Base base : fixedBases) { facet.add(base); } region.setRegionFacet(BaseFacet.class, facet); }

Target:
public void process(GeneratingRegion region) { Border3D border = region.getBorderForFacet(BaseFacet.class); BaseFacet facet = new BaseFacet(region.getRegion(), border); for (Base base : fixedBases) { facet.add(base); } region.setRegionFacet(BaseFacet.class, facet); }
Source:
private boolean doVisitDelta(IResourceDelta delta) throws Exception { if (delta.getResource() instanceof IProject) { IProject project = (IProject) delta.getResource(); IPath fromPath = delta.getMovedFromPath(); IPath toPath = delta.getMovedToPath(); if (delta.getKind() == IResourceDelta.REMOVED) { if (fromPath == null && toPath == null) { CorePlugin.listenerRegistry().dispatch(new ProjectDeletedEvent(project)); } } else if (delta.getKind() == IResourceDelta.ADDED) { if (fromPath == null && toPath == null) { CorePlugin.listenerRegistry().dispatch(new ProjectCreatedEvent(project)); } else if (fromPath != null) { CorePlugin.listenerRegistry().dispatch(new ProjectMovedEvent(project, fromPath.lastSegment())); } } else if (delta.getFlags() == IResourceDelta.OPEN) { if (project.isOpen()) { CorePlugin.listenerRegistry().dispatch(new ProjectOpenedEvent(project)); } else if (!project.isOpen()) { CorePlugin.listenerRegistry().dispatch(new ProjectClosedEvent(project)); } } return false; } else { return delta.getResource() instanceof IWorkspaceRoot; } }

Target:
private boolean doVisitDelta(IResourceDelta delta) throws Exception { if (delta.getResource() instanceof IProject) { IProject project = (IProject) delta.getResource(); IPath fromPath = delta.getMovedFromPath(); IPath toPath = delta.getMovedToPath(); if (delta.getKind() == IResourceDelta.REMOVED) { if (fromPath == null && toPath == null) { CorePlugin.listenerRegistry().dispatch(new ProjectDeletedEvent(project)); } } else if (delta.getKind() == IResourceDelta.ADDED) { if (fromPath == null && toPath == null) { CorePlugin.listenerRegistry().dispatch(new ProjectCreatedEvent(project)); } else if (fromPath != null) { CorePlugin.listenerRegistry().dispatch(new ProjectMovedEvent(project, fromPath.lastSegment())); } } else if (delta.getFlags() == IResourceDelta.OPEN) { if (project.isOpen()) { CorePlugin.listenerRegistry().dispatch(new ProjectOpenedEvent(project)); } else { CorePlugin.listenerRegistry().dispatch(new ProjectClosedEvent(project)); } } return false; } else { return delta.getResource() instanceof IWorkspaceRoot; } }
Source:
public static ExpectedCondition<WebElement> visibilityOfNestedElementsLocatedBy(final By locator, final By sub_locator) { return new ExpectedCondition<WebElement>() { @Override public WebElement apply(WebDriver webDriver) { Boolean displayed = false; Boolean exists = false; try { exists = webDriver.findElement(locator).findElements(sub_locator).size() > 0; displayed = webDriver.findElement(locator).findElement(sub_locator).isDisplayed(); } catch (Exception e) { } return (exists && displayed) ? webDriver.findElement(locator).findElement(sub_locator) : null; } @Override public String toString() { return "visibility of element located by " + locator + sub_locator; } }; }

Target:
public static ExpectedCondition<List<WebElement>> visibilityOfNestedElementsLocatedBy( final By locator, final By sub_locator) { return new ExpectedCondition<List<WebElement>>() { @Override public List<WebElement> apply(WebDriver webDriver) { Boolean displayed = false; Boolean exists = false; try { exists = webDriver.findElement(locator).findElements(sub_locator).size() > 0; displayed = webDriver.findElement(locator).findElement(sub_locator).isDisplayed(); } catch (Exception e) { int i = 0; } return (exists && displayed) ? webDriver.findElement(locator).findElements(sub_locator) : null; } @Override public String toString() { return "visibility of elements located by " + locator + sub_locator; } }; }
Source:
private void removeFormNameFromLabel(Map<String, FormElement> formElementMap) { for (String key : formElementMap.keySet()) { FormElement element = formElementMap.get(key); String label = element.getLabel(); element.setLabel(label.substring(label.substring(1).indexOf('/') + 1)); } }

Target:
private void removeFormNameFromLabel(Map<String, FormElement> formElementMap) { for (String key : formElementMap.keySet()) { FormElement element = formElementMap.get(key); String label = FormUtils.removeFormNameFromLabel(element.getLabel()); element.setLabel(label); } }
Source:
protected Value<Boolean> constructValue(Boolean actualValue) { return new SpongeValue<>(Keys.ENTITY_HAS_GRAVITY, actualValue); }

Target:
protected Value<Boolean> constructValue(Boolean actualValue) { return new SpongeValue<>(this.key, DataConstants.DEFAULT_HAS_GRAVITY, actualValue); }
Source:
public void afterCheckProject(@NonNull Context context) { if (mLocation != null && !mIgnore) { String message = "Potentially insecure random numbers on some versions of " + "Android. Read " + BLOG_URL + " for more info."; context.report(ISSUE, mLocation, message, null); } }

Target:
public void afterCheckProject(@NonNull Context context) { if (mLocation != null && !mIgnore) { String message = "Potentially insecure random numbers on Android 4.3 and older. " + "Read " + BLOG_URL + " for more info."; context.report(ISSUE, mLocation, message, null); } }
Source:
public void cancelTask() { if (currentTask != null) { currentTask.cancel(false); if (currentTask instanceof DataPullTask) { ((DataPullTask)currentTask).abortRequest(); } } }

Target:
public void cancelTask() { if (currentTask != null) { currentTask.cancel(false); currentTask.tryAbort(); } }
Source:
public CloseableHttpResponse getResponse(HttpUriRequest target) throws IOException { CloseableHttpClient client = createClient(); boolean returningResponse = false; CloseableHttpResponse response = null; try { try { response = client.execute(target); } catch (HttpHostConnectException e) { throw new ServiceConnectionException(e); } StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (isErrorStatus(statusCode)) { URI targetUri = target.getURI(); String address = targetUri.getPath(); if (!Strings.isNullOrEmpty(targetUri.getQuery())) { address += "?" + targetUri.getQuery(); } if (statusCode == HttpStatus.NOT_FOUND.value()) { throw new NotFoundException(address); } else { String responseBody = IOUtils.toString(response.getEntity().getContent()); String message = String.format("Request to \"%s\" failed (%d): %s.", address, statusCode, statusLine.getReasonPhrase()); throw new ServiceRequestException(statusCode, message, responseBody); } } returningResponse = true; return response; } finally { if (!returningResponse && response != null) { response.close(); } } }

Target:
public CloseableHttpResponse getResponse(HttpUriRequest target) throws IOException { CloseableHttpClient client = createClient(); boolean returningResponse = false; CloseableHttpResponse response = null; try { try { response = client.execute(target); } catch (HttpHostConnectException e) { throw new ServiceConnectionException(e); } StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (isErrorStatus(statusCode)) { URI targetUri = target.getURI(); String address = targetUri.getPath(); if (!Strings.isNullOrEmpty(targetUri.getQuery())) { address += "?" + targetUri.getQuery(); } if (statusCode == HttpStatus.NOT_FOUND.value()) { throw new EntityNotFoundException(address); } else { String responseBody = IOUtils.toString(response.getEntity().getContent()); String message = String.format("Request to \"%s\" failed (%d): %s.", address, statusCode, statusLine.getReasonPhrase()); throw new ServiceRequestException(statusCode, message, responseBody); } } returningResponse = true; return response; } finally { if (!returningResponse && response != null) { response.close(); } } }
Source:
public Schema generateSchema() { final Schema inputSchema = getChild().getSchema(); final List<String> outputColumnNames = new ArrayList<>(inputSchema.getColumnNames()); final String splitColumnName = outputColumnNames.get(splitColumnIndex); final String splitResultsColumnName = splitColumnName + "_splits"; outputColumnNames.set(splitColumnIndex, splitResultsColumnName); return Schema.of(inputSchema.getColumnTypes(), outputColumnNames); }

Target:
public Schema generateSchema() { final Schema inputSchema = getChild().getSchema(); final String splitColumnName = inputSchema.getColumnNames().get(splitColumnIndex); final String splitResultsColumnName = splitColumnName + "_splits"; return Schema.appendColumn(inputSchema, Type.STRING_TYPE, splitResultsColumnName); }
Source:
public ConvertIIFEArgsToVars(AbstractCompiler compiler) { this.compiler = compiler; validIifes = new ArrayList(); }

Target:
public ConvertIIFEArgsToVars(AbstractCompiler compiler) { this.compiler = compiler; }
Source:
List<ResourceRequest> getStarvedResourceRequests() { List<ResourceRequest> ret = new ArrayList<>(); Map<Priority, List<Resource>> visitedRRs= new HashMap<>(); Resource pending = getStarvation(); for (ResourceRequest rr : appSchedulingInfo.getAllResourceRequests()) { if (Resources.isNone(pending)) { break; } if (checkAndMarkRRVisited(visitedRRs, rr)) { continue; } int ratio = (int) Math.floor( Resources.ratio(scheduler.getResourceCalculator(), pending, rr.getCapability())); if (ratio == 0) { continue; } if (ratio < rr.getNumContainers()) { rr = ResourceRequest.newInstance( rr.getPriority(), rr.getResourceName(), rr.getCapability(), ratio); } ret.add(rr); Resources.subtractFromNonNegative(pending, Resources.multiply(rr.getCapability(), ratio)); } return ret; }

Target:
List<ResourceRequest> getStarvedResourceRequests() { List<ResourceRequest> ret = new ArrayList<>(); VisitedResourceRequestTracker visitedRRs = new VisitedResourceRequestTracker(scheduler.getNodeTracker()); Resource pending = getStarvation(); for (ResourceRequest rr : appSchedulingInfo.getAllResourceRequests()) { if (Resources.isNone(pending)) { break; } if (!visitedRRs.visit(rr)) { continue; } int numContainersThatFit = (int) Math.floor( Resources.ratio(scheduler.getResourceCalculator(), pending, rr.getCapability())); if (numContainersThatFit == 0) { continue; } if (numContainersThatFit < rr.getNumContainers()) { rr = ResourceRequest.newInstance(rr.getPriority(), rr.getResourceName(), rr.getCapability(), numContainersThatFit); } ret.add(rr); Resources.subtractFromNonNegative(pending, Resources.multiply(rr.getCapability(), rr.getNumContainers())); } return ret; }
Source:
private void fetch() throws IOException { if (output != null) { return; } outpuTupletList = scanner.getNextTupleRows(count); StringBuilder sb = new StringBuilder(); if (startOffset == 0) { Schema schema = this.scanner.getLogicalSchema(); List<Column> columns = schema.getAllColumns(); boolean first = true; for (Column column : columns) { if (first == false) { sb.append(","); } sb.append(StringEscapeUtils.escapeCsv(column.getSimpleName())); first = false; } sb.append("\r\n"); } for (Tuple tuple : outpuTupletList) { Datum[] datums = tuple.getValues(); int size = datums.length; for (int i = 0; i < size; i++) { if (i != 0) { sb.append(","); } Datum datum = datums[i]; sb.append(StringEscapeUtils.escapeCsv(datum.toString())); } sb.append("\r\n"); } output = sb.toString(); }

Target:
private void fetch() throws IOException { if (output != null) { return; } List<Tuple> outputTupletList = scanner.getNextTupleRows(count); size = outputTupletList.size(); StringBuilder sb = new StringBuilder(); if (startOffset == 0) { Schema schema = this.scanner.getLogicalSchema(); List<Column> columns = schema.getAllColumns(); boolean first = true; for (Column column : columns) { if (!first) { sb.append(","); } sb.append(StringEscapeUtils.escapeCsv(column.getSimpleName())); first = false; } sb.append("\r\n"); } for (Tuple tuple : outputTupletList) { Datum[] datums = tuple.getValues(); int size = datums.length; for (int i = 0; i < size; i++) { if (i != 0) { sb.append(","); } Datum datum = datums[i]; sb.append(StringEscapeUtils.escapeCsv(datum.toString())); } sb.append("\r\n"); } output = sb.toString(); }
Source:
private void assertRewritten(String from, String to) { assertEquals(rewrite(PlanBuilder.expression(from)), PlanBuilder.expression(to)); }

Target:
private static void assertRewritten(String from, String to) { assertEquals(CanonicalizeExpressionRewriter.rewrite(PlanBuilder.expression(from)), PlanBuilder.expression(to)); }
Source:
public static AuthUI getInstance(@NonNull FirebaseApp app) { String releaseUrl = "<LINK_0>"; String devWarning = "Beginning with FirebaseUI 6.2.0 you no longer need to include %s to " + "sign in with %s. Go to %s for more information"; if (ProviderAvailability.IS_TWITTER_AVAILABLE) { Log.w(TAG, String.format(devWarning, "the TwitterKit SDK", "Twitter", releaseUrl)); } if (ProviderAvailability.IS_GITHUB_AVAILABLE) { Log.w(TAG, String.format(devWarning, "auth-github", "GitHub", releaseUrl)); } AuthUI authUi; synchronized (INSTANCES) { authUi = INSTANCES.get(app); if (authUi == null) { authUi = new AuthUI(app); INSTANCES.put(app, authUi); } } return authUi; }

Target:
public static AuthUI getInstance(@NonNull FirebaseApp app) { String releaseUrl = "<LINK_0>"; String devWarning = "Beginning with FirebaseUI 6.2.0 you no longer need to include %s to " + "sign in with %s. Go to %s for more information"; if (ProviderAvailability.IS_TWITTER_AVAILABLE) { Log.w(TAG, String.format(devWarning, "the TwitterKit SDK", "Twitter", releaseUrl)); } if (ProviderAvailability.IS_GITHUB_AVAILABLE) { Log.w(TAG, String.format(devWarning, "com.firebaseui:firebase-ui-auth-github", "GitHub", releaseUrl)); } AuthUI authUi; synchronized (INSTANCES) { authUi = INSTANCES.get(app); if (authUi == null) { authUi = new AuthUI(app); INSTANCES.put(app, authUi); } } return authUi; }
Source:
public static void getExcel(OutputStream outputStream, long userId, Collection<Long> deviceIds, Collection<Long> groupIds, Date from, Date to) throws SQLException, IOException { Collection<SummaryReport> summaries = getObjects(userId, deviceIds, groupIds, from, to); String templatePath = Context.getConfig().getString("report.templatesPath", "templates/export/"); try (InputStream inputStream = new FileInputStream(templatePath + "/summary.xlsx")) { org.jxls.common.Context jxlsContext = PoiTransformer.createInitialContext(); jxlsContext.putVar("summaries", summaries); jxlsContext.putVar("from", from); jxlsContext.putVar("to", to); jxlsContext.putVar("distanceUnit", ReportUtils.getDistanceUnit(userId)); jxlsContext.putVar("speedUnit", ReportUtils.getSpeedUnit(userId)); jxlsContext.putVar("webUrl", Context.getVelocityEngine().getProperty("web.url")); jxlsContext.putVar("dateTool", new DateTool()); jxlsContext.putVar("timezone", ReportUtils.getTimezone(userId)); jxlsContext.putVar("locale", Locale.getDefault()); JxlsHelper.getInstance().setUseFastFormulaProcessor(false) .processTemplate(inputStream, outputStream, jxlsContext); } }

Target:
public static void getExcel(OutputStream outputStream, long userId, Collection<Long> deviceIds, Collection<Long> groupIds, Date from, Date to) throws SQLException, IOException { Collection<SummaryReport> summaries = getObjects(userId, deviceIds, groupIds, from, to); String templatePath = Context.getConfig().getString("report.templatesPath", "templates/export/"); try (InputStream inputStream = new FileInputStream(templatePath + "/summary.xlsx")) { org.jxls.common.Context jxlsContext = ReportUtils.initializeContext(userId); jxlsContext.putVar("summaries", summaries); jxlsContext.putVar("from", from); jxlsContext.putVar("to", to); JxlsHelper.getInstance().setUseFastFormulaProcessor(false) .processTemplate(inputStream, outputStream, jxlsContext); } }
Source:
public String toData() { if (url != null) { return url; } try { JSONObject jsonObject = new JSONObject(); if (groupId > 0) { jsonObject.put("groupId", groupId); } if (!uuid.equals(EMPTY_STRING)) { jsonObject.put("uuid", uuid); } if (!title.equals(EMPTY_STRING)) { jsonObject.put("title", title); } if (!version.equals(EMPTY_STRING)) { jsonObject.put("version", version); } return jsonObject.toString(); } catch (JSONException ex) { return null; } }

Target:
public String toData() { if (url != null) { return url; } try { JSONObject jsonObject = new JSONObject(); if (groupId > 0) { jsonObject.put("groupId", groupId); } if (!EMPTY_STRING.equals(uuid)) { jsonObject.put("uuid", uuid); } if (!EMPTY_STRING.equals(title)) { jsonObject.put("title", title); } if (!EMPTY_STRING.equals(version)) { jsonObject.put("version", version); } return jsonObject.toString(); } catch (JSONException ex) { return null; } }
Source:
void adaptTypedFilterTo( FilterContext context, ColumnRangeFilter filter, OutputStream outputStream) throws IOException { byte lowerBoundMarker = (byte) (filter.getMinColumnInclusive() ? '[' : '('); byte upperBoundMarker = (byte) (filter.getMaxColumnInclusive() ? ']' : ')'); try (ReaderExpressionScope scope = new ReaderExpressionScope(outputStream, "(col(", "))")) { outputStream.write(lowerBoundMarker); outputStream.write(getSingleFamily(context.getScan())); outputStream.write(BigtableConstants.BIGTABLE_COLUMN_SEPARATOR_BYTE); helper.writeQuotedExpression(filter.getMinColumn(), outputStream); outputStream.write((byte) ','); outputStream.write(getSingleFamily(context.getScan())); outputStream.write(BigtableConstants.BIGTABLE_COLUMN_SEPARATOR_BYTE); helper.writeQuotedExpression(filter.getMaxColumn(), outputStream); outputStream.write(upperBoundMarker); outputStream.write((byte)','); outputStream.write(ReaderExpressionHelper.ALL_VERSIONS_BYTES); } }

Target:
void adaptTypedFilterTo( FilterContext context, ColumnRangeFilter filter, OutputStream outputStream) throws IOException { byte lowerBoundMarker = (byte) (filter.getMinColumnInclusive() ? '[' : '('); byte upperBoundMarker = (byte) (filter.getMaxColumnInclusive() ? ']' : ')'); byte[] family = getSingleFamily(context.getScan()); try (ReaderExpressionScope scope = new ReaderExpressionScope(outputStream, "(col(", "))")) { outputStream.write(lowerBoundMarker); outputStream.write(family); outputStream.write(BigtableConstants.BIGTABLE_COLUMN_SEPARATOR_BYTE); helper.writeQuotedExpression(filter.getMinColumn(), outputStream); outputStream.write((byte) ','); outputStream.write(family); outputStream.write(BigtableConstants.BIGTABLE_COLUMN_SEPARATOR_BYTE); helper.writeQuotedExpression(filter.getMaxColumn(), outputStream); outputStream.write(upperBoundMarker); outputStream.write((byte)','); outputStream.write(ReaderExpressionHelper.ALL_VERSIONS_BYTES); } }
Source:
public String getVersion() { return version; }

Target:
String getVersion() { return version; }
Source:
public void createUnivocityParser() { List<FixedWidthSchema.Field> fields = schema.getFields(); FixedWidthFields fieldWidth = new FixedWidthFields(); for (int i = 0; i < fields.size(); i++) { FixedWidthSchema.Field currentField = fields.get(i); int fieldLength = currentField.getFieldLength(); FieldAlignment currentFieldAlignment; if (currentField.getAlignment().equalsIgnoreCase("centre")) { currentFieldAlignment = FieldAlignment.CENTER; } else if (currentField.getAlignment().equalsIgnoreCase("left")) { currentFieldAlignment = FieldAlignment.LEFT; } else { currentFieldAlignment = FieldAlignment.RIGHT; } fieldWidth.addField(currentField.getName(), fieldLength, currentFieldAlignment, currentField.getPadding()); } FixedWidthParserSettings settings = new FixedWidthParserSettings(fieldWidth); univocityParser = new com.univocity.parsers.fixed.FixedWidthParser(settings); }

Target:
private void createUnivocityParser() { List<FixedWidthSchema.Field> fields = schema.getFields(); FixedWidthFields fieldWidthFields = new FixedWidthFields(); for (int i = 0; i < fields.size(); i++) { FixedWidthSchema.Field currentField = fields.get(i); int fieldLength = currentField.getFieldLength(); FieldAlignment currentFieldAlignment; if (currentField.getAlignment().equalsIgnoreCase("centre")) { currentFieldAlignment = FieldAlignment.CENTER; } else if (currentField.getAlignment().equalsIgnoreCase("left")) { currentFieldAlignment = FieldAlignment.LEFT; } else { currentFieldAlignment = FieldAlignment.RIGHT; } fieldWidthFields.addField(currentField.getName(), fieldLength, currentFieldAlignment, currentField.getPadding()); } FixedWidthParserSettings settings = new FixedWidthParserSettings(fieldWidthFields); univocityParser = new com.univocity.parsers.fixed.FixedWidthParser(settings); }
Source:
public KeyStoreCredentialProvider(final KeyStore keyStore, final String keyStoreAlias, String keyStoreType, final Resource keyStoreResource, final String keyStorePath, final String storePasswd, final String privateKeyPasswd) { CommonHelper.assertTrue(keyStore != null || keyStoreResource != null || CommonHelper.isNotBlank(keyStorePath), "Either keyStore, keyStoreResource or keyStorePath must be provided"); final KeyStore keyStoreToUse; if (keyStore != null) { keyStoreToUse = keyStore; } else { final InputStream inputStream; if (keyStoreResource != null) { try { inputStream = keyStoreResource.getInputStream(); } catch (IOException e) { throw new TechnicalException(e); } } else { inputStream = CommonHelper.getInputStreamFromName(keyStorePath); } keyStoreToUse = loadKeyStore(inputStream, storePasswd, keyStoreType); } this.privateKey = getPrivateKeyAlias(keyStoreToUse, keyStoreAlias); final Map<String, String> passwords = new HashMap<String, String>(); passwords.put(this.privateKey, privateKeyPasswd); this.credentialResolver = new KeyStoreCredentialResolver(keyStoreToUse, passwords); }

Target:
public KeyStoreCredentialProvider(final KeyStore keyStore, final String keyStoreAlias, String keyStoreType, final Resource keyStoreResource, final String keyStorePath, final String storePasswd, final String privateKeyPasswd) { CommonHelper.assertTrue(keyStore != null || keyStoreResource != null || CommonHelper.isNotBlank(keyStorePath), "Either keyStore, keyStoreResource or keyStorePath must be provided"); final KeyStore keyStoreToUse; if (keyStore != null) { keyStoreToUse = keyStore; } else { InputStream inputStream = null; try { if (keyStoreResource != null) { inputStream = keyStoreResource.getInputStream(); } else { inputStream = CommonHelper.getInputStreamFromName(keyStorePath); } keyStoreToUse = loadKeyStore(inputStream, storePasswd, keyStoreType); } catch (IOException e) { throw new SAMLException("Error loading keystore", e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (final IOException e) { this.logger.debug("Error closing input stream of keystore", e); } } } } this.privateKey = getPrivateKeyAlias(keyStoreToUse, keyStoreAlias); final Map<String, String> passwords = new HashMap<String, String>(); passwords.put(this.privateKey, privateKeyPasswd); this.credentialResolver = new KeyStoreCredentialResolver(keyStoreToUse, passwords); }
Source:
protected ActionResult execute() throws EntityDoesNotExistException { String courseId = getRequestParamValue(Const.ParamsNames.COURSE_ID); Assumption.assertNotNull(courseId); String feedbackSessionName = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME); Assumption.assertNotNull(feedbackSessionName); List<InstructorAttributes> instructors = logic.getInstructorsForGoogleId(account.googleId); Assumption.assertNotNull(instructors); InstructorFeedbackEditCopyPageData data = new InstructorFeedbackEditCopyPageData(account, new ArrayList<CourseAttributes>(), courseId, feedbackSessionName); List<CourseAttributes> courses = logic.getCoursesForInstructor(account.googleId); for (CourseAttributes course : courses) { InstructorAttributes instructor = logic.getInstructorForGoogleId(course.id, account.googleId); boolean isAllowedToMakeSession = instructor.isAllowedForPrivilege(Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_SESSION); boolean isArchived = Logic.isCourseArchived(course.id, account.googleId); if (!isArchived && isAllowedToMakeSession) { data.getCourses().add(course); } } CourseAttributes.sortByCreatedDate(data.getCourses()); return createShowPageResult(Const.ViewURIs.INSTRUCTOR_FEEDBACK_COPY_MODAL, data); }

Target:
protected ActionResult execute() throws EntityDoesNotExistException { String courseId = getRequestParamValue(Const.ParamsNames.COURSE_ID); Assumption.assertNotNull(courseId); String feedbackSessionName = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME); Assumption.assertNotNull(feedbackSessionName); List<InstructorAttributes> instructors = logic.getInstructorsForGoogleId(account.googleId); Assumption.assertNotNull(instructors); List<CourseAttributes> allCourses = logic.getCoursesForInstructor(account.googleId); List<CourseAttributes> coursesToAddToData = new ArrayList<CourseAttributes>(); for (CourseAttributes course : allCourses) { InstructorAttributes instructor = logic.getInstructorForGoogleId(course.id, account.googleId); boolean isAllowedToMakeSession = instructor.isAllowedForPrivilege(Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_SESSION); boolean isArchived = Logic.isCourseArchived(course.id, account.googleId); if (!isArchived && isAllowedToMakeSession) { coursesToAddToData.add(course); } } CourseAttributes.sortByCreatedDate(coursesToAddToData); InstructorFeedbackEditCopyPageData data = new InstructorFeedbackEditCopyPageData(account, coursesToAddToData, courseId, feedbackSessionName); return createShowPageResult(Const.ViewURIs.INSTRUCTOR_FEEDBACK_COPY_MODAL, data); }
Source:
private boolean processEvent(UpdatableProcessInstance instance, String stepId, State state) throws WorkflowException { UpdatableHistoryStep step = (UpdatableHistoryStep) instance.getHistoryStep(stepId); instance.updateHistoryStep(step); if (event.getDataRecord() != null) { instance.saveActionRecord(step, event.getDataRecord()); } state = (state != null) ? state : new StateImpl(""); instance.addWorkingUser(step.getUser(), state, step.getUserRoleName()); instance.unLock(); step.setActionStatus(3); return false; }

Target:
private boolean processEvent(UpdatableProcessInstance instance, String stepId, State state) throws WorkflowException { UpdatableHistoryStep step = (UpdatableHistoryStep) instance.getHistoryStep(stepId); instance.updateHistoryStep(step); if (event.getDataRecord() != null) { instance.saveActionRecord(step, event.getDataRecord()); } instance.addWorkingUser(step.getUser(), state, step.getUserRoleName()); instance.unLock(); step.setActionStatus(UpdatableHistoryStep.ACTION_STATUS_SAVED); return false; }
Source:
private boolean decideWhetherToLogAllPriorities() { ZonedDateTime now = ZonedDateTime.now(); boolean shouldLog = Duration.between(lastLogTime, now).compareTo(Duration.of(10, ChronoUnit.MINUTES)) > 0; if (shouldLog) { lastLogTime = now; } return shouldLog; }

Target:
private boolean decideWhetherToLogAllPriorities() { return loggingRateLimiter.tryAcquire(); }
Source:
public Node<View<Import>, ?> nodeFromDMN(org.kie.dmn.model.v1_1.Import source) { String name = source.getAdditionalAttributes().get(droolsName); String identifier = name != null ? name : source.getNamespace() + source.getLocationURI(); Node<View<Import>, ?> node = new NodeImpl<>(identifier); node.setContent(new ViewImpl<>(null, null)); LocationURI locationURI = new LocationURI(source.getLocationURI()); node.getContent().setDefinition(new Import(source.getNamespace(), locationURI, source.getImportType())); Map<QName, String> additionalAttributes = new HashMap<>(); for (Map.Entry<javax.xml.namespace.QName, String> entry : source.getAdditionalAttributes().entrySet()) { additionalAttributes.put(QNamePropertyConverter.wbFromDMN(entry.getKey()), entry.getValue()); } node.getContent().getDefinition().setAdditionalAttributes(additionalAttributes); return node; }

Target:
public static Import nodeFromDMN(org.kie.dmn.model.v1_1.Import source) { LocationURI locationURI = new LocationURI(source.getLocationURI()); Import result = new Import(source.getNamespace(), locationURI, source.getImportType()); Map<QName, String> additionalAttributes = new HashMap<>(); for (Map.Entry<javax.xml.namespace.QName, String> entry : source.getAdditionalAttributes().entrySet()) { additionalAttributes.put(QNamePropertyConverter.wbFromDMN(entry.getKey()), entry.getValue()); } result.setAdditionalAttributes(additionalAttributes); return result; }
Source:
private void processMemberListQuery(IQ packet) { MUCRole roleToUseHere = server.getChatRoom(packet.getTo().getNode()).getRole(); try { roleToUseHere.getChatRoom().getIQAdminHandler().handleIQ(packet, roleToUseHere); } catch ( ForbiddenException e ) { Log.debug("Unable to process IQ stanza: sender don't have authorization to perform the request.", e); sendErrorPacket(packet, PacketError.Condition.forbidden, "You don't have authorization to perform this request."); } catch ( ConflictException e ) { Log.debug("Unable to process IQ stanza: processing this request would leave the room in an invalid state (eg: without owners).", e); sendErrorPacket(packet, PacketError.Condition.conflict, "Processing this request would leave the room in an invalid state (eg: without owners)."); } catch ( NotAllowedException e ) { Log.debug("Unable to process IQ stanza: an owner or administrator cannot be banned from the room.", e); sendErrorPacket(packet, PacketError.Condition.not_allowed, "An owner or administrator cannot be banned from the room."); } catch ( CannotBeInvitedException e ) { Log.debug("Unable to process IQ stanza: user being invited as a result of being added to a members-only room still does not have permission.", e); sendErrorPacket(packet, PacketError.Condition.not_acceptable, "User being invited as a result of being added to a members-only room still does not have permission."); } catch ( Exception e ) { Log.error("An unexpected exception occurred while processing IQ stanza: {}", packet.toXML(), e); sendErrorPacket(packet, PacketError.Condition.internal_server_error, "An unexpected exception occurred while processing your request."); } }

Target:
private void processMemberListQuery(IQ packet) { MUCRole roleToUseHere = server.getChatRoom(packet.getTo().getNode()).getRole(); try { roleToUseHere.getChatRoom().getIQAdminHandler().handleIQ(packet, roleToUseHere); } catch ( ForbiddenException e ) { Log.debug("Unable to process IQ stanza: sender don't have authorization to perform the request.", e); sendErrorPacket(packet, PacketError.Condition.forbidden, "You don't have authorization to perform this request."); } catch ( ConflictException e ) { Log.debug("Unable to process IQ stanza: There was a conflict while handle the memberlist request.", e); sendErrorPacket(packet, PacketError.Condition.conflict, "There was a conflict while handle the memberlist request."); } catch ( NotAllowedException e ) { Log.debug("Unable to process IQ stanza: The user is not allowed to retrieve memberlist.", e); sendErrorPacket(packet, PacketError.Condition.not_allowed, "The user is not allowed to retrieve memberlist."); } catch ( Exception e ) { Log.error("An unexpected exception occurred while processing IQ stanza: {}", packet.toXML(), e); sendErrorPacket(packet, PacketError.Condition.internal_server_error, "An unexpected exception occurred while processing your request."); } }
Source:
protected void openConnection() { if (this.thing.getStatus().equals(ThingStatus.OFFLINE)) { try { if (senderNode.getAddress() == null) { if (senderNode.getPort() == 0) { socket = new DatagramSocket(); senderNode.setInetAddress(socket.getLocalAddress()); senderNode.setPort(socket.getLocalPort()); } else { socket = new DatagramSocket(senderNode.getPort()); senderNode.setInetAddress(socket.getLocalAddress()); } } else { socket = new DatagramSocket(senderNode.getPort(), senderNode.getAddress()); } updateStatus(ThingStatus.ONLINE); logger.debug("opened socket in bridge {}", senderNode, this.thing.getUID()); } catch (SocketException e) { logger.warn("could not open socket in bridge {}", senderNode, this.thing.getUID()); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR); } } }

Target:
protected void openConnection() { if (!this.thing.getStatus().equals(ThingStatus.ONLINE)) { try { if (senderNode.getAddress() == null) { if (senderNode.getPort() == 0) { socket = new DatagramSocket(); senderNode.setInetAddress(socket.getLocalAddress()); senderNode.setPort(socket.getLocalPort()); } else { socket = new DatagramSocket(senderNode.getPort()); senderNode.setInetAddress(socket.getLocalAddress()); } } else { socket = new DatagramSocket(senderNode.getPort(), senderNode.getAddress()); } updateStatus(ThingStatus.ONLINE); logger.debug("opened socket in bridge {}", senderNode, this.thing.getUID()); } catch (SocketException e) { logger.debug("could not open socket in bridge {}", senderNode, this.thing.getUID()); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "opening UDP socket failed"); } } }
Source:
public void reflogReader() throws IOException { Ref master = ref(MASTER, 1); Ref next = ref(NEXT, 2); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ReftableWriter writer = new ReftableWriter().setMinUpdateIndex(1) .setMaxUpdateIndex(1).begin(buffer); writer.writeRef(master); writer.writeRef(next); PersonIdent who1 = new PersonIdent("Log", "Ger", 1500079709, -8 * 60); writer.writeLog(MASTER, 3, who1, ObjectId.zeroId(), id(1), "1"); PersonIdent who2 = new PersonIdent("Log", "Ger", 1500079710, -8 * 60); writer.writeLog(MASTER, 2, who2, id(1), id(2), "2"); PersonIdent who3 = new PersonIdent("Log", "Ger", 1500079711, -8 * 60); writer.writeLog(MASTER, 1, who3, id(2), id(3), "3"); writer.finish(); byte[] table = buffer.toByteArray(); ReentrantLock lock = new ReentrantLock(); ReftableReader t = read(table); ReftableReflogReader rlr = new ReftableReflogReader(lock, t, MASTER); assertEquals(rlr.getLastEntry().getWho(), who1); List<PersonIdent> all = rlr.getReverseEntries().stream() .map(x -> x.getWho()).collect(Collectors.toList()); List<PersonIdent> more = rlr.getReverseEntries(4).stream() .map(x -> x.getWho()).collect(Collectors.toList()); assertEquals(all.size(), 3); assertEquals(rlr.getReverseEntry(1).getWho(), who2); List<ReflogEntry> entries = rlr.getReverseEntries(2); assertEquals(entries.get(1).getWho(), who2); assertEquals(all, more); }

Target:
public void reflogReader() throws IOException { Ref master = ref(MASTER, 1); Ref next = ref(NEXT, 2); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ReftableWriter writer = new ReftableWriter().setMinUpdateIndex(1) .setMaxUpdateIndex(1).begin(buffer); writer.writeRef(master); writer.writeRef(next); PersonIdent who1 = new PersonIdent("Log", "Ger", 1500079709, -8 * 60); writer.writeLog(MASTER, 3, who1, ObjectId.zeroId(), id(1), "1"); PersonIdent who2 = new PersonIdent("Log", "Ger", 1500079710, -8 * 60); writer.writeLog(MASTER, 2, who2, id(1), id(2), "2"); PersonIdent who3 = new PersonIdent("Log", "Ger", 1500079711, -8 * 60); writer.writeLog(MASTER, 1, who3, id(2), id(3), "3"); writer.finish(); byte[] table = buffer.toByteArray(); ReentrantLock lock = new ReentrantLock(); ReftableReader t = read(table); ReftableReflogReader rlr = new ReftableReflogReader(lock, t, MASTER); assertEquals(rlr.getLastEntry().getWho(), who1); List<PersonIdent> all = rlr.getReverseEntries().stream() .map(x -> x.getWho()).collect(Collectors.toList()); Matchers.contains(all, who3, who2, who1); assertEquals(rlr.getReverseEntry(1).getWho(), who2); List<ReflogEntry> reverse2= rlr.getReverseEntries(2); Matchers.contains(reverse2, who3, who2); List<PersonIdent> more = rlr.getReverseEntries(4).stream() .map(x -> x.getWho()).collect(Collectors.toList()); assertEquals(all, more); }