auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void validate() { async.validate(); singletonStore.validate(); boolean shared = attributes.attribute(SHARED).get(); boolean fetchPersistentState = attributes.attribute(FETCH_PERSISTENT_STATE).get(); boolean purgeOnStartup = attributes.attribute(PURGE_ON_STARTUP).get(); boolean preload = attributes.attribute(PRELOAD).get(); boolean transactional = attributes.attribute(TRANSACTIONAL).get(); ConfigurationBuilder builder = getBuilder(); Class storeClazz = attributes.getKlass(); if (storeClazz != null && storeClazz.isAnnotationPresent(Store.class)) { Store storeProps = (Store) storeClazz.getAnnotation(Store.class); if (!storeProps.shared() && shared) { throw log.nonSharedStoreConfiguredAsShared(attributes.getName()); } } if (!shared && !fetchPersistentState && !purgeOnStartup && builder.clustering().cacheMode().isClustered()) log.staleEntriesWithoutFetchPersistentStateOrPurgeOnStartup(); if (fetchPersistentState && attributes.attribute(FETCH_PERSISTENT_STATE).isModified() && clustering().cacheMode().isInvalidation()) { throw log.attributeNotAllowedInInvalidationMode(FETCH_PERSISTENT_STATE.name()); } if (shared && !preload && builder.indexing().enabled() && builder.indexing().indexLocalOnly()) log.localIndexingWithSharedCacheLoaderRequiresPreload(); if (transactional && !builder.transaction().transactionMode().isTransactional()) throw log.transactionalStoreInNonTransactionalCache(); if (transactional && builder.persistence().passivation()) throw log.transactionalStoreInPassivatedCache(); }

Target:
public void validate() { async.validate(); singletonStore.validate(); boolean shared = attributes.attribute(SHARED).get(); boolean fetchPersistentState = attributes.attribute(FETCH_PERSISTENT_STATE).get(); boolean purgeOnStartup = attributes.attribute(PURGE_ON_STARTUP).get(); boolean preload = attributes.attribute(PRELOAD).get(); boolean transactional = attributes.attribute(TRANSACTIONAL).get(); ConfigurationBuilder builder = getBuilder(); Class storeClazz = attributes.getKlass(); if (storeClazz != null && storeClazz.isAnnotationPresent(Store.class)) { Store storeProps = (Store) storeClazz.getAnnotation(Store.class); if (!storeProps.shared() && shared) { throw log.nonSharedStoreConfiguredAsShared(attributes.getName()); } } else { log.warnStoreAnnotationMissing(attributes.getName()); } if (!shared && !fetchPersistentState && !purgeOnStartup && builder.clustering().cacheMode().isClustered()) log.staleEntriesWithoutFetchPersistentStateOrPurgeOnStartup(); if (fetchPersistentState && attributes.attribute(FETCH_PERSISTENT_STATE).isModified() && clustering().cacheMode().isInvalidation()) { throw log.attributeNotAllowedInInvalidationMode(FETCH_PERSISTENT_STATE.name()); } if (shared && !preload && builder.indexing().enabled() && builder.indexing().indexLocalOnly()) log.localIndexingWithSharedCacheLoaderRequiresPreload(); if (transactional && !builder.transaction().transactionMode().isTransactional()) throw log.transactionalStoreInNonTransactionalCache(); if (transactional && builder.persistence().passivation()) throw log.transactionalStoreInPassivatedCache(); }
Source:
public List<VDS> listFailedAutorecoverables() { return new SimpleJdbcTemplate(jdbcTemplate).query("select * from vds where recoverable and status = " + VDSStatus.NonOperational.getValue(), VdsRowMapper.instance); }

Target:
public List<VDS> listFailedAutorecoverables() { return getCallsHandler().executeReadList("GetFailingVdss", VdsRowMapper.instance, null); }
Source:
public static PreparedStatement prepareTableSelectStatement(Connection c, String storageKey, String[] fields, String[] values, Persistable p) throws IllegalArgumentException{ org.commcare.modern.database.TableBuilder mTableBuilder = new org.commcare.modern.database.TableBuilder(storageKey); mTableBuilder.addData(p); Pair<String, String[]> mPair = DatabaseHelper.createWhere(fields, values, p); try { String queryString = "SELECT * FROM " + storageKey + " WHERE " + mPair.first + ";"; PreparedStatement preparedStatement = c.prepareStatement(queryString); for (int i = 0; i < mPair.second.length; i++) { preparedStatement.setString(i + 1, mPair.second[i]); } return preparedStatement; } catch (SQLException e) { throw new RuntimeException(e); } }

Target:
public static PreparedStatement prepareTableSelectStatement(Connection c, String storageKey, String[] fields, String[] values, Persistable p) { org.commcare.modern.database.TableBuilder mTableBuilder = new org.commcare.modern.database.TableBuilder(storageKey); mTableBuilder.addData(p); Pair<String, String[]> mPair = DatabaseHelper.createWhere(fields, values, p); try { String queryString = "SELECT * FROM " + storageKey + " WHERE " + mPair.first + ";"; PreparedStatement preparedStatement = c.prepareStatement(queryString); for (int i = 0; i < mPair.second.length; i++) { preparedStatement.setString(i + 1, mPair.second[i]); } return preparedStatement; } catch (SQLException e) { throw new RuntimeException(e); } }
Source:
public Optional<ValueT> invalidate(final IdT id) { final Optional<ValueT> value = get(id); cache.invalidate(id); value.ifPresent(valueT -> removalListener.accept(new CacheEntry<>(id, valueT))); return value; }

Target:
public Optional<ValueT> invalidate(final IdT id) { final Optional<ValueT> value = Optional.ofNullable(cache.asMap().remove(id)); value.ifPresent(valueT -> removalListener.accept(id, valueT)); return value; }
Source:
private static AbstractLongAssert<?> assertThatGetConnectonTimeoutForTarget(WebTarget webTarget) { final long startTime = System.currentTimeMillis(); ProcessingException processingException = null; try { webTarget .request() .get(Response.class); } catch (ProcessingException e) { processingException = e; } final long endTime = System.currentTimeMillis(); assertThat(processingException).isNotNull(); assertThat(processingException.getCause()).isNotNull(); assertThat(processingException.getCause()).isInstanceOf(ConnectTimeoutException.class); return assertThat(endTime - startTime); }

Target:
private static AbstractLongAssert<?> assertThatGetConnectonTimeoutForTarget(WebTarget webTarget) { final long startTime = System.nanoTime(); try { webTarget .request() .get(Response.class); } catch (ProcessingException e) { final long endTime = System.nanoTime(); assertThat(e).isNotNull(); assertThat(e.getCause()).isNotNull(); assertThat(e.getCause()).isInstanceOf(ConnectTimeoutException.class); return assertThat((endTime - startTime)/1000000); } throw new AssertionError("ProcessingException expected but not thrown"); }
Source:
public Reply<?> findQueryList(@Named("id") String id) { Optional<Operator> operator = repository.findAssociatedOperator(id); if (!operator.isPresent()) { return Reply.saying().notFound(); } IpAddressType type = operator.get().ipAddressType; Integer response = catalog.get(type); return Reply.with(response).ok(); }

Target:
public Reply<?> findQueryList(@Named("id") String id) { QueryList queryList = repository.findQueryList(id); QueryListDTO dto = new QueryListDTO(queryList.values); return Reply.with(dto).as(Json.class).ok(); }
Source:
public void testShouldRetainImplicitlyWaitFromTheReturnedWebDriverOfFrameSwitchTo() { driver.manage().timeouts().implicitlyWait(3, SECONDS); driver.get(pages.xhtmlTestPage); driver.findElement(By.name("windowOne")).click(); String handle = (String)driver.getWindowHandles().toArray()[1]; WebDriver newWindow = driver.switchTo().window(handle); long start = System.currentTimeMillis(); newWindow.findElements(By.id("This crazy thing doesn't exist")); long end = System.currentTimeMillis(); long time = end - start; assertTrue(time >= 3000); }

Target:
public void testShouldRetainImplicitlyWaitFromTheReturnedWebDriverOfFrameSwitchTo() { driver.manage().timeouts().implicitlyWait(1, SECONDS); driver.get(pages.xhtmlTestPage); driver.findElement(By.name("windowOne")).click(); String handle = (String)driver.getWindowHandles().toArray()[1]; WebDriver newWindow = driver.switchTo().window(handle); long start = System.currentTimeMillis(); newWindow.findElements(By.id("This crazy thing doesn't exist")); long end = System.currentTimeMillis(); long time = end - start; assertTrue(time >= 1000); }
Source:
public ImmutableSet<E> getTreeFrom(E root, Set<E> endPoints) { final ImmutableSet.Builder<E> builder = ImmutableSet.builder(); builder.addAll(graph.getTreeFrom(root, endPoints)); return builder.build(); }

Target:
public ImmutableSet<E> getTreeFrom(E root, Set<E> endPoints) { return ImmutableSet.copyOf(graph.getTreeFrom(root, endPoints)); }
Source:
protected void sharedPeriodic(){ xScheduler.run(); this.updateTelemetrySubsystems(); }

Target:
protected void sharedPeriodic() { xScheduler.run(); this.updateTelemetrySources(); }
Source:
private CreateImageVDSCommandParameters getCreateVDSCommandParameters() { CreateVolumeVDSCommandParameters parameters = new CreateVolumeVDSCommandParameters(getParameters().getStoragePoolId(), getParameters().getStorageDomainId(), getParameters().getImageGroupID(), getParameters().getSrcImageId(), getParameters().getSize(), getType(), getParameters().getVolumeFormat(), getParameters().getSrcImageGroupId(), getParameters().getImageId(), getParameters().getDescription(), getStoragePool().getCompatibilityVersion(), DiskContentType.DATA); if (getType() != VolumeType.Preallocated && getStorageDomain().getStorageType().isBlockDomain()) { parameters.setImageInitialSizeInBytes(Optional.ofNullable(getParameters().getInitialSize()).orElse(0L)); } else if ( FeatureSupported.isDeferringFileVolumePreallocationSupported(getStoragePool().getCompatibilityVersion()) && getType() == VolumeType.Preallocated && getStorageDomain().getStorageType().isFileDomain()) { parameters.setImageInitialSizeInBytes(Optional.ofNullable(getParameters().getInitialSize()).orElse(1L)); } return parameters; }

Target:
private CreateImageVDSCommandParameters getCreateVDSCommandParameters() { CreateVolumeVDSCommandParameters parameters = new CreateVolumeVDSCommandParameters(getParameters().getStoragePoolId(), getParameters().getStorageDomainId(), getParameters().getImageGroupID(), getParameters().getSrcImageId(), getParameters().getSize(), getType(), getParameters().getVolumeFormat(), getParameters().getSrcImageGroupId(), getParameters().getImageId(), getParameters().getDescription(), getStoragePool().getCompatibilityVersion(), DiskContentType.DATA); if (getType() != VolumeType.Preallocated && getStorageDomain().getStorageType().isBlockDomain()) { parameters.setImageInitialSizeInBytes(Optional.ofNullable(getParameters().getInitialSize()).orElse(0L)); } else if (supportsDeferredPrallocation()) { Long initialSize = Optional.ofNullable(getParameters().getInitialSize()).orElse(1L); parameters.setImageInitialSizeInBytes(initialSize); } return parameters; }
Source:
public void close() { try { recoverableZooKeeper.close(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } zkEventProcessor.shutdownNow(); }

Target:
public void close() { try { recoverableZooKeeper.close(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { zkEventProcessor.shutdownNow(); } }
Source:
public void testMessagingGateway() { String payload = "bar"; assertEquals(payload.toUpperCase(), this.testGateway.echo(payload)); assertEquals(payload.toUpperCase() + "2", this.testGateway2.echo2(payload)); StopWatch stopWatch = new StopWatch(); stopWatch.start(); this.testGateway.sendAsync("foo"); stopWatch.stop(); assertThat(stopWatch.getTotalTimeMillis(), Matchers.lessThan(1000L)); }

Target:
public void testMessagingGateway() throws InterruptedException { String payload = "bar"; assertEquals(payload.toUpperCase(), this.testGateway.echo(payload)); assertEquals(payload.toUpperCase() + "2", this.testGateway2.echo2(payload)); this.testGateway.sendAsync("foo"); assertTrue(this.asyncAnnotationProcessLatch.await(1, TimeUnit.SECONDS)); assertNotSame(Thread.currentThread(), this.asyncAnnotationProcessThread.get()); }
Source:
private static Slice scaleQuantileDigest(Slice input, double scale) { if (scale < 0) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "scale factor must be > 0"); } QuantileDigest digest = new QuantileDigest(input); digest.scale(scale); return digest.serialize(); }

Target:
private static Slice scaleQuantileDigest(Slice input, double scale) { if (scale <= 0) throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Scale factor should be positive."); QuantileDigest digest = new QuantileDigest(input); digest.scale(scale); return digest.serialize(); }
Source:
public void testRemoveIfEmpty() { Collection<Integer> collection = new ArrayList<>(); collection.removeIf(truth); assertTrue(collection.isEmpty()); }

Target:
public void testRemoveIfEmpty() { for (Supplier<Collection<Integer>> impl : collectionImpls) { Collection<Integer> collection = impl.get(); collection.removeIf(truth); assertTrue(collection.isEmpty()); } }
Source:
protected String getPreviousPath(Repository repository, ObjectReader reader, RevCommit headCommit, RevCommit previousCommit, String path) throws IOException { TreeWalk walk = new TreeWalk(reader); walk.addTree(previousCommit.getTree()); walk.addTree(headCommit.getTree()); List<DiffEntry> entries = DiffEntry.scan(walk); if (entries.size() < 2) return path; for (DiffEntry diff : entries) if (diff.getChangeType() == ChangeType.MODIFY && path.equals(diff.getNewPath())) return path; RenameDetector detector = new RenameDetector(repository); detector.addAll(entries); List<DiffEntry> renames = detector.compute(walk.getObjectReader(), NullProgressMonitor.INSTANCE); for (DiffEntry diff : renames) if (diff.getChangeType() == ChangeType.RENAME && path.equals(diff.getNewPath())) return diff.getOldPath(); return path; }

Target:
protected String getPreviousPath(Repository repository, ObjectReader reader, RevCommit headCommit, RevCommit previousCommit, String path) throws IOException { TreeWalk walk = new TreeWalk(reader); walk.setRecursive(true); walk.addTree(previousCommit.getTree()); walk.addTree(headCommit.getTree()); List<DiffEntry> entries = DiffEntry.scan(walk); if (entries.size() < 2) return path; for (DiffEntry diff : entries) if (diff.getChangeType() == ChangeType.MODIFY && path.equals(diff.getNewPath())) return path; RenameDetector detector = new RenameDetector(repository); detector.addAll(entries); List<DiffEntry> renames = detector.compute(walk.getObjectReader(), NullProgressMonitor.INSTANCE); for (DiffEntry diff : renames) if (diff.getChangeType() == ChangeType.RENAME && path.equals(diff.getNewPath())) return diff.getOldPath(); return path; }
Source:
RexNode simplifyAnd2(List<RexNode> terms, List<RexNode> notTerms) { for (RexNode term : terms) { if (term.isAlwaysFalse()) { return rexBuilder.makeLiteral(false); } } if (terms.isEmpty() && notTerms.isEmpty()) { return rexBuilder.makeLiteral(true); } List<RexNode> notSatisfiableNullables = null; for (RexNode notDisjunction : notTerms) { final List<RexNode> terms2 = RelOptUtil.conjunctions(notDisjunction); if (!terms.containsAll(terms2)) { continue; } if (!notDisjunction.getType().isNullable()) { return rexBuilder.makeLiteral(false); } if (notSatisfiableNullables == null) { notSatisfiableNullables = new ArrayList<>(); } notSatisfiableNullables.add(notDisjunction); } if (notSatisfiableNullables != null) { terms.removeAll(notSatisfiableNullables); notTerms.removeAll(notSatisfiableNullables); List<RexNode> nullAndIsNullTerms = new ArrayList<>(); nullAndIsNullTerms.add(rexBuilder.makeNullLiteral(notSatisfiableNullables.get(0).getType())); for (RexNode notSatisfiableNullable : notSatisfiableNullables) { nullAndIsNullTerms.add( simplifyIs((RexCall) rexBuilder.makeCall(SqlStdOperatorTable.IS_NULL, notSatisfiableNullable))); } terms.addAll(nullAndIsNullTerms); } for (RexNode notDisjunction : notTerms) { terms.add( simplify_( rexBuilder.makeCall(SqlStdOperatorTable.NOT, notDisjunction))); } return RexUtil.composeConjunction(rexBuilder, terms, false); }

Target:
RexNode simplifyAnd2(List<RexNode> terms, List<RexNode> notTerms) { for (RexNode term : terms) { if (term.isAlwaysFalse()) { return rexBuilder.makeLiteral(false); } } if (terms.isEmpty() && notTerms.isEmpty()) { return rexBuilder.makeLiteral(true); } List<RexNode> notSatisfiableNullables = null; for (RexNode notDisjunction : notTerms) { final List<RexNode> terms2 = RelOptUtil.conjunctions(notDisjunction); if (!terms.containsAll(terms2)) { continue; } if (!notDisjunction.getType().isNullable()) { return rexBuilder.makeLiteral(false); } if (notSatisfiableNullables == null) { notSatisfiableNullables = new ArrayList<>(); } notSatisfiableNullables.add(notDisjunction); } if (notSatisfiableNullables != null) { terms.removeAll(notSatisfiableNullables); notTerms.removeAll(notSatisfiableNullables); terms.add(rexBuilder.makeNullLiteral(notSatisfiableNullables.get(0).getType())); for (RexNode notSatisfiableNullable : notSatisfiableNullables) { terms.add( simplifyIs((RexCall) rexBuilder.makeCall(SqlStdOperatorTable.IS_NULL, notSatisfiableNullable))); } } for (RexNode notDisjunction : notTerms) { terms.add( simplify_( rexBuilder.makeCall(SqlStdOperatorTable.NOT, notDisjunction))); } return RexUtil.composeConjunction(rexBuilder, terms, false); }
Source:
public boolean isAccepted(LocalSearchMoveScope moveScope) { Score moveScore = moveScope.getScore(); double[] moveScoreLevels = ScoreUtils.extractLevelDoubles(moveScore); for (int i = 0; i < levelsLength; i++) { double moveScoreLevel = moveScoreLevels[i]; double levelScoreLevel = levelScoreLevels[i]; if (moveScoreLevel > -levelScoreLevel) { return true; } else if (!(Math.abs(moveScoreLevel + levelScoreLevel) < THRESHOLD)) { return false; } else if (i == levelsLength -1){ return true; } } return true; }

Target:
public boolean isAccepted(LocalSearchMoveScope moveScope) { Score moveScore = moveScope.getScore(); return moveScore.compareTo(currentWaterLevel.negate()) >= 0; }
Source:
public IntervalList padded(final int before, final int after) { if (before < 0 || after < 0) throw new IllegalArgumentException("Padding values must be >= 0."); final IntervalList padded = new IntervalList(this.getHeader()); final SAMSequenceDictionary dict = padded.getHeader().getSequenceDictionary(); for (final Interval i : this) { final int start = Math.max(1, i.getStart()-before); final int end = Math.min(dict.getSequence(i.getContig()).getSequenceLength(), i.getEnd()+after); padded.add(new Interval(i.getContig(), start, end, i.isNegativeStrand(), i.getName())); } return padded; }

Target:
public IntervalList padded(final int before, final int after) { if (before < 0 || after < 0) throw new IllegalArgumentException("Padding values must be >= 0."); final IntervalList padded = new IntervalList(this.getHeader().clone()); final SAMSequenceDictionary dict = padded.getHeader().getSequenceDictionary(); for (final Interval i : this) { final SAMSequenceRecord seq = dict.getSequence(i.getContig()); final int start = Math.max(1, i.getStart() - before); final int end = Math.min((seq == null ? Integer.MAX_VALUE : seq.getSequenceLength()), i.getEnd()+after); padded.add(new Interval(i.getContig(), start, end, i.isNegativeStrand(), i.getName())); } return padded; }
Source:
@Override public void createSnapshot(String snpName) { mgr.createSnapshot(snpName).get(); }

Target:
@Override public void createSnapshot(String snpName) { mgr.createSnapshot(snpName); }
Source:
private void initRevisionsAction(ChangeInfo info, String revision, NativeMap<ActionInfo> actions) { int currentPatchSet; if (info.current_revision() != null && info.revisions().containsKey(info.current_revision())) { currentPatchSet = info.revision(info.current_revision())._number(); } else { JsArray<RevisionInfo> revList = info.revisions().values(); RevisionInfo.sortRevisionInfoByNumber(revList); currentPatchSet = revList.get(revList.length() - 1)._number(); } String currentlyViewedPatchSet; boolean isPatchSetCurrent = true; final String revisionId = info.revision(revision).id(); if (revisionId.equals("edit")) { currentlyViewedPatchSet = Resources.M.editPatchSet(RevisionInfo.findEditParent(info.revisions() .values())); currentPatchSet = info.revisions().values().length() - 1; } else { currentlyViewedPatchSet = revisionId; if (currentlyViewedPatchSet != Integer.toString(currentPatchSet)) { isPatchSetCurrent = false; } } patchSetsText.setInnerText(Resources.M.patchSets( currentlyViewedPatchSet, currentPatchSet)); if (isPatchSetCurrent) { patchSetsText.removeClassName(style.notCurrentPatchSet()); } else { patchSetsText.addClassName(style.notCurrentPatchSet()); } patchSetsAction = new PatchSetsAction( info.legacy_id(), revision, style, headerLine, patchSets); RevisionInfo revInfo = info.revision(revision); if (revInfo.draft()) { if (actions.containsKey("publish")) { publish.setVisible(true); publish.setTitle(actions.get("publish").title()); } if (actions.containsKey("/")) { deleteRevision.setVisible(true); deleteRevision.setTitle(actions.get("/").title()); } } }

Target:
private void initRevisionsAction(ChangeInfo info, String revision, NativeMap<ActionInfo> actions) { int currentPatchSet; if (info.current_revision() != null && info.revisions().containsKey(info.current_revision())) { currentPatchSet = info.revision(info.current_revision())._number(); } else { JsArray<RevisionInfo> revList = info.revisions().values(); RevisionInfo.sortRevisionInfoByNumber(revList); currentPatchSet = revList.get(revList.length() - 1)._number(); } String currentlyViewedPatchSet; boolean isPatchSetCurrent = true; String revisionId = info.revision(revision).id(); if (revisionId.equals("edit")) { currentlyViewedPatchSet = Resources.M.editPatchSet(RevisionInfo.findEditParent(info.revisions() .values())); currentPatchSet = info.revisions().values().length() - 1; } else { currentlyViewedPatchSet = revisionId; if (!currentlyViewedPatchSet.equals(Integer.toString(currentPatchSet))) { isPatchSetCurrent = false; } } patchSetsText.setInnerText(Resources.M.patchSets( currentlyViewedPatchSet, currentPatchSet)); if (isPatchSetCurrent) { patchSetsText.removeClassName(style.notCurrentPatchSet()); } else { patchSetsText.addClassName(style.notCurrentPatchSet()); } patchSetsAction = new PatchSetsAction( info.legacy_id(), revision, style, headerLine, patchSets); RevisionInfo revInfo = info.revision(revision); if (revInfo.draft()) { if (actions.containsKey("publish")) { publish.setVisible(true); publish.setTitle(actions.get("publish").title()); } if (actions.containsKey("/")) { deleteRevision.setVisible(true); deleteRevision.setTitle(actions.get("/").title()); } } }
Source:
private static int getTokenType(ParseTree node) { final int tokenType; if (node.getChildCount() == 0) { final int antlrTokenType = ((TerminalNode) node).getSymbol().getType(); if (antlrTokenType == JavadocTokenTypes.HTML_TAG_NAME) { tokenType = JavadocTokenTypes.EMBED_HTML_TAG_NAME; } else if (antlrTokenType == JavadocTokenTypes.EMBED_HTML_TAG_NAME) { tokenType = JavadocTokenTypes.HTML_TAG_NAME; } else { tokenType = antlrTokenType; } } else { final String className = getNodeClassNameWithoutContext(node); final String typeName = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, className); tokenType = JavadocUtils.getTokenId(typeName); } return tokenType; }

Target:
private static int getTokenType(ParseTree node) { final int tokenType; if (node.getChildCount() == 0) { final int antlrTokenType = ((TerminalNode) node).getSymbol().getType(); tokenType = mapAntlrTokenTypeToJavadocTokenType(antlrTokenType); } else { final String className = getNodeClassNameWithoutContext(node); final String typeName = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, className); tokenType = JavadocUtils.getTokenId(typeName); } return tokenType; }
Source:
public ProjectSpace getTransferringProjectSpace() { return transferringProjectSpace; }

Target:
public Optional<ProjectSpace> getTransferringProjectSpace() { return Optional.fromNullable(transferringProjectSpace); }
Source:
public static void createIndex(SamReader reader, File output, Log log) { BAMIndexer indexer = new BAMIndexer(output, reader.getFileHeader()); int totalRecords = 0; for (SAMRecord rec : reader) { if (++totalRecords % 1000000 == 0) { if (null != log) log.debug(totalRecords + " reads processed ..."); } indexer.processAlignment(rec); } indexer.finish(); }

Target:
public static void createIndex(SamReader reader, File output, Log log) { BAMIndexer indexer = new BAMIndexer(output, reader.getFileHeader()); int totalRecords = 0; for (SAMRecord rec : reader) { if (++totalRecords % 1000000 == 0) { if (null != log) log.info(totalRecords + " reads processed ..."); } indexer.processAlignment(rec); } indexer.finish(); }
Source:
public SplunkServiceFactory(SplunkServer splunkServer) { this.splunkServers = Arrays.asList(splunkServer); }

Target:
public SplunkServiceFactory(SplunkServer splunkServer) { Assert.notNull(splunkServer); this.splunkServers = Arrays.asList(splunkServer); }
Source:
public void testPrefixedText() throws Exception { assertEquals(new PageTitle(null, "Test title").getPrefixedText(), "Test_title"); assertEquals(new PageTitle(null, "Test title").getPrefixedText(), "Test_title"); assertEquals(new PageTitle("Talk", "Test title").getPrefixedText(), "Talk:Test_title"); assertEquals(new PageTitle(null, "Test title").getText(), "Test_title"); }

Target:
public void testPrefixedText() throws Exception { assertEquals(new PageTitle(null, "Test title").getPrefixedText(), "Test title"); assertEquals(new PageTitle(null, "Test title").getPrefixedText(), "Test title"); assertEquals(new PageTitle("Talk", "Test title").getPrefixedText(), "Talk:Test title"); assertEquals(new PageTitle(null, "Test title").getText(), "Test title"); }
Source:
public IconDataParcelable(Parcel im) { type = im.readInt(); path = im.readString(); image = im.readInt(); loadingImage = im.readInt(); isImageBroken = im.readInt() == 1; hashCode = im.readInt(); }

Target:
public IconDataParcelable(Parcel im) { type = im.readInt(); path = im.readString(); image = im.readInt(); loadingImage = im.readInt(); isImageBroken = im.readInt() == 1; }
Source:
private static void alterTable(Runnable alterTableFunction) { try { alterTableFunction.run(); } catch (Exception e) { log.info("Alter table failed: %s", e); } }

Target:
private static void alterTable(Runnable alterTableFunction) { try { alterTableFunction.run(); } catch (Exception e) { log.warn("Alter table failed: %s", e.getMessage()); } }
Source:
private void importUserDefinitions(EList<UserDef> userDefs) throws OseeCoreException { for (UserDef dslUserDef : userDefs) { String dslUserName = Strings.unquote(dslUserDef.getName()); Artifact userArt = null; userArt = UserManager.createUser(getOseeUser(dslUserDef), transaction); if (userArt == null) { userArt = ArtifactTypeManager.addArtifact(CoreArtifactTypes.User, AtsUtil.getAtsBranch(), dslUserName); } if (userArt == null) { throw new OseeStateException(String.format("No user found in datbase with name [%s] from [%s]", dslUserName, modelName), modelName); } } }

Target:
private void importUserDefinitions(EList<UserDef> userDefs) throws OseeCoreException { for (UserDef dslUserDef : userDefs) { String dslUserName = Strings.unquote(dslUserDef.getName()); Artifact userArt = null; if (dslUserDef.getUserDefOption().contains("GetOrCreate")) { userArt = UserManager.createUser(getOseeUser(dslUserDef), transaction); } if (userArt == null) { userArt = ArtifactTypeManager.addArtifact(CoreArtifactTypes.User, AtsUtil.getAtsBranch(), dslUserName); } if (userArt == null) { throw new OseeStateException(String.format("No user found in datbase with name [%s] from [%s]", dslUserName, modelName), modelName); } } }
Source:
private void initializeAnimators() { if (hasSetAnimations()) return; mCircleOneAnimationSet = getAnimatiorSet(mCircleOne); mCircleTwoAnimationSet = getAnimatiorSet(mCircleTwo); mCircleThreeAnimationSet = getAnimatiorSet(mCircleThree); mCircleTwoAnimationSet.setStartDelay(100); mCircleThreeAnimationSet.setStartDelay(200); mCircleOneAnimationSet.start(); mCircleTwoAnimationSet.start(); mCircleThreeAnimationSet.start(); }

Target:
private void initializeAnimators() { if (hasSetAnimations()) return; mCircleOneAnimationSet = getAnimatorSet(mCircleOne); mCircleTwoAnimationSet = getAnimatorSet(mCircleTwo); mCircleThreeAnimationSet = getAnimatorSet(mCircleThree); mCircleTwoAnimationSet.setStartDelay(100); mCircleThreeAnimationSet.setStartDelay(200); mCircleOneAnimationSet.start(); mCircleTwoAnimationSet.start(); mCircleThreeAnimationSet.start(); }
Source:
public SAMFileWriter makeWriter(final SAMFileHeader header, final boolean presorted, final File outputFile, final File referenceFasta) { if (outputFile.getName().endsWith(".cram")) try { return makeCRAMWriter(header, new FileOutputStream(outputFile), referenceFasta); } catch (final FileNotFoundException e) { throw new RuntimeException(e); } return makeSAMOrBAMWriter(header, presorted, outputFile); }

Target:
public SAMFileWriter makeWriter(final SAMFileHeader header, final boolean presorted, final File outputFile, final File referenceFasta) { if (outputFile.getName().endsWith(SamReader.Type.CRAM_TYPE.fileExtension())) try { return makeCRAMWriter(header, new FileOutputStream(outputFile), referenceFasta); } catch (final FileNotFoundException e) { throw new RuntimeException(e); } return makeSAMOrBAMWriter(header, presorted, outputFile); }
Source:
public void VetProvidersTests_001_article(String videoUrl, String videoName) { PageObjectLogging.log("", videoUrl, true); WikiBasePageObject base = new WikiBasePageObject(driver); base.logInCookie(credentials.userName, credentials.password, wikiURL); ArticlePageObject article = base.openRandomArticle(wikiURL); VisualEditModePageObject visualEditMode = article.goToCurrentArticleEditPage(); visualEditMode.clearContent(); VetAddVideoComponentObject vetAddVideo = visualEditMode.clickVideoButton(); VetOptionsComponentObject vetOptions = vetAddVideo.addVideoByUrl(videoUrl); vetOptions.submit(); visualEditMode.verifyVideo(); visualEditMode.submitArticle(); article.verifyVideo(); FileDetailsPageObject fileDetails = article.clickVideoDetailsButton(); fileDetails.verifyEmbeddedVideoIsPresent(); fileDetails.verifyHeader(videoName); }

Target:
public void VetProvidersTests_001_article(String videoUrl, String videoName) { PageObjectLogging.log("", videoUrl, true); WikiBasePageObject base = new WikiBasePageObject(driver); base.logInCookie(credentials.userName, credentials.password, wikiURL); ArticlePageObject article = base.openRandomArticle(wikiURL); VisualEditModePageObject visualEditMode = article.goToCurrentArticleEditPage(); visualEditMode.clearContent(); VetAddVideoComponentObject vetAddVideo = visualEditMode.clickVideoButton(); VetOptionsComponentObject vetOptions = vetAddVideo.addVideoByUrl(videoUrl); vetOptions.submit(); visualEditMode.verifyVideo(); visualEditMode.submitArticle(); article.verifyVideo(); FilePagePageObject fileDetails = article.clickVideoDetailsButton(); fileDetails.verifyEmbeddedVideoIsPresent(); fileDetails.verifyHeader(videoName); }
Source:
public void checkExceptionPlacedOnErrorChannel() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "pollingEndpointErrorHandlingTests.xml", this.getClass()); PollableChannel errorChannel = (PollableChannel) context.getBean("errorChannel"); Message errorMessage = errorChannel.receive(5000); assertNotNull("No error message received", errorMessage); assertEquals("Message received was not an ErrorMessage", ErrorMessage.class, errorMessage.getClass()); assertEquals("ErrorMessage payload was not a MessagingException", MessagingException.class, errorMessage.getPayload().getClass()); MessagingException messagingException = (MessagingException) errorMessage.getPayload(); assertNotNull(messagingException.getFailedMessage()); assertNotNull(messagingException.getCause()); context.close(); }

Target:
public void checkExceptionPlacedOnErrorChannel() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "pollingEndpointErrorHandlingTests.xml", this.getClass()); PollableChannel errorChannel = (PollableChannel) context.getBean("errorChannel"); Message errorMessage = errorChannel.receive(5000); assertNotNull("No error message received", errorMessage); assertEquals("Message received was not an ErrorMessage", ErrorMessage.class, errorMessage.getClass()); context.close(); }
Source:
public void testSetToDefaultWhenNVPMSSetToDefault() { User target = new User(); target.setAddress( "address" ); target.setEmail( "email" ); target.setName( "name" ); target.setPhone( 12345 ); target.setSettings( new String[]{ "test" } ); UserDTO source = new UserDTO(); source.setContactDataDTO( new ContactDataDTO() ); source.getContactDataDTO().setAddress( "newAddress" ); source.getContactDataDTO().setEmail( null ); source.getContactDataDTO().setPhone( null ); source.setName( null ); UserMapper.INSTANCE.updateUserFromUserAndDefaultDTO( source, target ); assertThat( target.getAddress() ).isEqualTo( "newAddress" ); assertThat( target.getEmail() ).isEqualTo( "" ); assertThat( target.getPhone() ).isEqualTo( 0 ); assertThat( target.getName() ).isEqualTo( "" ); assertThat( target.getPreferences() ).isEmpty(); assertThat( target.getSettings() ).isEmpty(); }

Target:
public void testSetToDefaultWhenNVPMSSetToDefault() { User target = new User(); target.setAddress( "address" ); target.setEmail( "email" ); target.setName( "name" ); target.setPhone( 12345 ); target.addPreference( "preference" ); target.setSettings( new String[]{ "test" } ); UserDTO source = new UserDTO(); source.setContactDataDTO( new ContactDataDTO() ); source.getContactDataDTO().setAddress( "newAddress" ); source.getContactDataDTO().setEmail( null ); source.getContactDataDTO().setPhone( null ); source.setName( null ); UserMapper.INSTANCE.updateUserFromUserAndDefaultDTO( source, target ); assertThat( target.getAddress() ).isEqualTo( "newAddress" ); assertThat( target.getEmail() ).isEqualTo( "" ); assertThat( target.getPhone() ).isEqualTo( 0 ); assertThat( target.getName() ).isEqualTo( "" ); assertThat( target.getPreferences() ).containsOnly( "preference" ); assertThat( target.getSettings() ).isEmpty(); }
Source:
public void onSucceeded(Guid cmdId, List<Guid> childCmdIds) { getCommand(cmdId).onStopVmsSucceeded(); CommandCoordinatorUtil.removeAllCommandsInHierarchy(cmdId); }

Target:
public void onSucceeded(Guid cmdId, List<Guid> childCmdIds) { RemoveVmPoolCommand<? extends VmPoolParametersBase> cmd = getCommand(cmdId); CommandCoordinatorUtil.removeAllCommandsInHierarchy(cmdId); cmd.getParameters().setTaskGroupSuccess(true); cmd.endAction(); }
Source:
public static FlowMap getFlowMap(long dpid) throws ConfigError { FVLog.log(LogLevel.TRACE,null,"FlowSpaceUtil: getFlowMap"); FlowMap fm = FVConfig.getFlowSpaceFlowMap(); switch (fm.getType()) { case LINEAR: FVLog.log(LogLevel.DEBUG,null,"FlowSpaceUtil: It is a Linear Flowmap"); return FlowSpaceUtil.getSubFlowMap(fm, dpid, new FVMatch()); case FEDERATED: FVLog.log(LogLevel.DEBUG,null,"FlowSpaceUtil: It is a Federated Flowmap"); return fm; default: FVLog.log(LogLevel.ERROR, null, "Unknown FlowMap type"); throw new RuntimeException("Unknown FlowMap type; time to quit"); } }

Target:
public static FlowMap getFlowMap(long dpid) throws ConfigError { FlowMap fm = FVConfig.getFlowSpaceFlowMap(); switch (fm.getType()) { case LINEAR: return FlowSpaceUtil.getSubFlowMap(fm, dpid, new FVMatch()); case FEDERATED: return fm; default: logger.error("Unknown FlowMap type"); throw new RuntimeException("Unknown FlowMap type; time to quit"); } }
Source:
private JSONObject _getJSONObject(byte[] array) throws JSONException { return new JSONObject(new JSONTokener(new String(array))); }

Target:
private JSONObject _getJSONObject(byte[] array) throws JSONException, UnsupportedEncodingException { return new JSONObject(new String(array, "UTF-8")); }
Source:
private Map.Entry<LookupBean, LookupExtractorFactoryContainer> startLookup(LookupBean lookupBean) { LookupExtractorFactoryContainer container = lookupBean.getContainer(); LOG.info("Starting lookup [%s]:[%s]", lookupBean.getName(), container); try { if (container.getLookupExtractorFactory().start()) { LOG.info("Started lookup [%s]:[%s]", lookupBean.getName(), container); return new AbstractMap.SimpleImmutableEntry<>(lookupBean, container); } else { LOG.error("Failed to start lookup [%s]:[%s]", lookupBean.getName(), container); return null; } } catch (Exception e) { LOG.error(e, "Failed to start lookup [%s]:[%s]", lookupBean.getName(), container); throw e; } }

Target:
private Map.Entry<String, LookupExtractorFactoryContainer> startLookup(LookupBean lookupBean) { LookupExtractorFactoryContainer container = lookupBean.getContainer(); LOG.info("Starting lookup [%s]:[%s]", lookupBean.getName(), container); try { if (container.getLookupExtractorFactory().start()) { LOG.info("Started lookup [%s]:[%s]", lookupBean.getName(), container); return new AbstractMap.SimpleImmutableEntry<>(lookupBean.getName(), container); } else { LOG.error("Failed to start lookup [%s]:[%s]", lookupBean.getName(), container); return null; } } catch (RuntimeException e) { throw new RE(e, "Failed to start lookup [%s]:[%s]", lookupBean.getName(), container); } }
Source:
public Endpoint referenceEndpoint(ServerLocation server, DistributedMember memberId) { Endpoint endpoint = endpointMap.get(memberId); boolean addedEndpoint = false; if (endpoint == null || endpoint.isClosed()) { synchronized (this) { endpoint = endpointMap.get(memberId); if (endpoint == null || endpoint.isClosed()) { ConnectionStats stats = getStats(server); Map<DistributedMember, Endpoint> endpointMapTemp = new HashMap<>(endpointMap); endpoint = new Endpoint(this, ds, server, stats, memberId); listener.clearPdxRegistry(endpoint); endpointMapTemp.put(memberId, endpoint); endpointMap = Collections.unmodifiableMap(endpointMapTemp); addedEndpoint = true; poolStats.setServerCount(endpointMap.size()); } } } endpoint.addReference(); if (addedEndpoint) { listener.endpointNowInUse(endpoint); } return endpoint; }

Target:
public Endpoint referenceEndpoint(ServerLocation server, DistributedMember memberId) { Endpoint endpoint = endpointMap.get(server); boolean addedEndpoint = false; if (endpoint == null || endpoint.isClosed()) { synchronized (this) { endpoint = endpointMap.get(server); if (endpoint == null || endpoint.isClosed()) { ConnectionStats stats = getStats(server); Map<ServerLocation, Endpoint> endpointMapTemp = new HashMap<>(endpointMap); endpoint = new Endpoint(this, ds, server, stats, memberId); listener.clearPdxRegistry(endpoint); endpointMapTemp.put(server, endpoint); endpointMap = Collections.unmodifiableMap(endpointMapTemp); addedEndpoint = true; poolStats.setServerCount(endpointMap.size()); } } } endpoint.addReference(); if (addedEndpoint) { listener.endpointNowInUse(endpoint); } return endpoint; }
Source:
public final This bindBeanList(String key, List<?> values, List<String> propertyNames) { if (values.isEmpty()) { throw new IllegalArgumentException( getClass().getSimpleName() + ".bindBeanList was called with no values."); } if (propertyNames.isEmpty()) { throw new IllegalArgumentException( getClass().getSimpleName() + ".bindBeanList was called with no properties."); } StringBuilder names = new StringBuilder(); for (int valueIndex = 0; valueIndex < values.size(); valueIndex++) { if (valueIndex > 0) { names.append(','); } Object bean = values.get(valueIndex); BeanPropertyArguments beanProperties = new BeanPropertyArguments(null, bean, getContext()); names.append("("); for (int propertyIndex = 0; propertyIndex < propertyNames.size(); propertyIndex++) { if (propertyIndex > 0) { names.append(","); } String propertyName = propertyNames.get(propertyIndex); String name = "__" + key + "_" + valueIndex + "_" + propertyName; names.append(':').append(name); bind(name, beanProperties.find(propertyName).get()); } names.append(")"); } return define(key, names.toString()); }

Target:
public final This bindBeanList(String key, List<?> values, List<String> propertyNames) throws UnableToCreateStatementException { if (values.isEmpty()) { throw new IllegalArgumentException( getClass().getSimpleName() + ".bindBeanList was called with no values."); } if (propertyNames.isEmpty()) { throw new IllegalArgumentException( getClass().getSimpleName() + ".bindBeanList was called with no properties."); } StringBuilder names = new StringBuilder(); for (int valueIndex = 0; valueIndex < values.size(); valueIndex++) { if (valueIndex > 0) { names.append(','); } Object bean = values.get(valueIndex); BeanPropertyArguments beanProperties = new BeanPropertyArguments(null, bean, getContext()); names.append("("); for (int propertyIndex = 0; propertyIndex < propertyNames.size(); propertyIndex++) { if (propertyIndex > 0) { names.append(","); } String propertyName = propertyNames.get(propertyIndex); String name = "__" + key + "_" + valueIndex + "_" + propertyName; names.append(':').append(name); Argument argument = beanProperties.find(propertyName) .orElseThrow(() -> new UnableToCreateStatementException("Unable to get " + propertyName + " argument for " + bean, getContext())); bind(name, argument); } names.append(")"); } return define(key, names.toString()); }
Source:
private <M extends Message> void validateVersion(@Nullable M previousMetadata, @Nullable M userMetadata) { for (Descriptors.FieldDescriptor fieldDescriptor : userMetadata.getDescriptorForType().getFields()) { if (!fieldDescriptor.getOptions().getExtension(CorfuOptions.schema).getVersion()) { continue; } if (!versionTypes.contains(fieldDescriptor.getType())) { throw new IllegalArgumentException("Version field needs to be an Integer or Long type."+ " Current type="+fieldDescriptor.getType()); } long validatingVersion = (long) userMetadata.getField(fieldDescriptor); if (validatingVersion <= 0) { continue; } long previousVersion = Optional.ofNullable(previousMetadata) .map(m -> (Long) m.getField(fieldDescriptor)) .orElse(-1L); if (validatingVersion != previousVersion) { throw new RuntimeException("Stale object Exception: " + previousVersion + " != " + validatingVersion); } } }

Target:
private void validateVersion(@Nullable M previousMetadata, @Nullable M userMetadata) { for (Descriptors.FieldDescriptor fieldDescriptor : userMetadata.getDescriptorForType().getFields()) { if (!fieldDescriptor.getOptions().getExtension(CorfuOptions.schema).getVersion()) { continue; } if (!versionTypes.contains(fieldDescriptor.getType())) { throw new IllegalArgumentException("Version field needs to be an Integer or Long type." + " Current type=" + fieldDescriptor.getType()); } long validatingVersion = (long) userMetadata.getField(fieldDescriptor); if (validatingVersion <= 0) { continue; } long previousVersion = Optional.ofNullable(previousMetadata) .map(m -> (Long) m.getField(fieldDescriptor)) .orElse(-1L); if (validatingVersion != previousVersion) { throw new RuntimeException("Stale object Exception: " + previousVersion + " != " + validatingVersion); } } }
Source:
private Dialog createDeleteDialog(){ return new AlertDialog.Builder(this) .setMessage(R.string.remove_folder_confirm) .setPositiveButton(android.R.string.yes, (dialogInterface, i) -> { getApi().removeFolder(mFolder.id); SharedPreferences prefs = this.getSharedPreferences(ShareActivity.SHARED_PREFS_SAVED_DIRECTORIES, MODE_PRIVATE); prefs.edit().remove(mFolder.id).apply(); finish(); }) .setNegativeButton(android.R.string.no, null) .create(); }

Target:
private Dialog createDeleteDialog(){ return new AlertDialog.Builder(this) .setMessage(R.string.remove_folder_confirm) .setPositiveButton(android.R.string.yes, (dialogInterface, i) -> { getApi().removeFolder(mFolder.id); finish(); }) .setNegativeButton(android.R.string.no, null) .create(); }
Source:
private static byte[] floatToByteArray(final float floatValue) { ByteBuffer buffer = ByteBuffer.allocate(FLOAT_BYTES_LENGTH).order(ByteOrder.LITTLE_ENDIAN); return buffer.putFloat(floatValue).array(); }

Target:
private static byte[] floatToByteArray(final float floatValue) { final ByteBuffer buffer = ByteBuffer.allocate(FLOAT_BYTES_LENGTH).order(ByteOrder.LITTLE_ENDIAN); return buffer.putFloat(floatValue).array(); }
Source:
public int getQuotaCount() { MapSqlParameterSource parameterSource = new MapSqlParameterSource(); return getCallsHandler().executeRead("GetQuotaCount", new ParameterizedRowMapper<Integer>() { @Override public Integer mapRow(ResultSet resultSet, int i) throws SQLException { return (Integer) resultSet.getObject(1); } }, parameterSource); }

Target:
public int getQuotaCount() { MapSqlParameterSource parameterSource = new MapSqlParameterSource(); return getCallsHandler().executeRead("get_quota_count", intMapper, parameterSource).intValue(); }
Source:
public void run() { if (_enablePartitionAssignment) { _datastreamTask.acquire(ACQUIRE_TIMEOUT); } super.run(); }

Target:
public void run() { if (_enablePartitionAssignment) { try { _datastreamTask.acquire(LOCK_ACQUIRE_TIMEOUT); } catch (DatastreamRuntimeException ex) { LOG.error("Failed to acquire lock for datastreamTask {}", _datastreamTask); _dynamicMetricsManager.createOrUpdateMeter(CLASS_NAME, NUM_LOCK_FAILS, 1); throw ex; } } super.run(); }
Source:
public ImageDescriptor getImageDescriptor() { if (fImageDescriptor == null) { String path = fConfig.getAttribute("icon"); if (path != null) { fImageDescriptor = AbstractUIPlugin.imageDescriptorFromPlugin(fConfig.getNamespaceIdentifier(), path); } } return fImageDescriptor; }

Target:
public ImageDescriptor getImageDescriptor() { if (fImageDescriptor == null) { String path = fConfig.getAttribute("icon"); if (path != null) { fImageDescriptor = ResourceLocator.imageDescriptorFromBundle(fConfig.getNamespaceIdentifier(), path) .orElse(null); } } return fImageDescriptor; }
Source:
public HelperPublisher(final int from, final int to, final Function<Integer, T> create, final Executor executor) { super(new Iterable<T>() { { if(from > to) throw new IllegalArgumentException("from must be equal or greater than to!"); } @Override public Iterator<T> iterator() { return new Iterator<T>() { private int at = from; @Override public boolean hasNext() { return at < to; } @Override public T next() { if (!hasNext()) return Collections.<T>emptyList().iterator().next(); else try { return create.apply(at++); } catch (Throwable t) { throw new HelperPublisherException( String.format("Failed to create element in %s for id %s!", getClass().getSimpleName(), at - 1), t); } } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }, executor); }

Target:
public HelperPublisher(final int from, final int to, final Function<Integer, T> create, final Executor executor) { super(new Iterable<T>() { { if(from > to) throw new IllegalArgumentException("from must be equal or greater than to!"); } @Override public Iterator<T> iterator() { return new Iterator<T>() { private int at = from; @Override public boolean hasNext() { return at < to; } @Override public T next() { if (!hasNext()) return Collections.<T>emptyList().iterator().next(); else try { return create.apply(at++); } catch (Throwable t) { throw new IllegalStateException(String.format("Failed to create element for id %d!", at - 1), t); } } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }, executor); }