auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private boolean restore(PageStoreOptions options) { LOG.info("Attempt to restore PageStore with {}", options); Path rootDir = Paths.get(options.getRootDir()); if (!Files.exists(rootDir)) { LOG.error("Failed to restore PageStore: Directory does not exist", rootDir); return false; } long discardedPages = 0; long discardedBytes = 0; try (Stream<PageInfo> stream = mPageStore.getPages()) { Iterator<PageInfo> iterator = stream.iterator(); while (iterator.hasNext()) { PageInfo pageInfo = iterator.next(); if (pageInfo == null) { LOG.error("Invalid page info"); return false; } PageId pageId = pageInfo.getPageId(); ReadWriteLock pageLock = getPageLock(pageId); <START> try (LockResource r = new LockResource(pageLock.readLock())) { <END> boolean enoughSpace; try (LockResource r2 = new LockResource(mMetaLock.writeLock())) { enoughSpace = mMetaStore.bytes() + pageInfo.getPageSize() <= mPageStore.getCacheSize(); if (enoughSpace) { mMetaStore.addPage(pageId, pageInfo); } } if (!enoughSpace) { mPageStore.delete(pageId); discardedPages++; discardedBytes += pageInfo.getPageSize(); } } } } catch (Exception e) { LOG.error("Failed to restore PageStore", e); return false; } LOG.info("Complete Restored PageStore with pages ({} bytes), discarded pages ({} bytes)", mMetaStore.pages(), mMetaStore.bytes(), discardedPages, discardedBytes); return true; }</code><technical_language>this a write lock delete page if is enough space</technical_language>

Target:
private boolean restore(PageStoreOptions options) { LOG.info("Attempt to restore PageStore with {}", options); Path rootDir = Paths.get(options.getRootDir()); if (!Files.exists(rootDir)) { LOG.error("Failed to restore PageStore: Directory does not exist", rootDir); return false; } long discardedPages = 0; long discardedBytes = 0; try (Stream<PageInfo> stream = mPageStore.getPages()) { Iterator<PageInfo> iterator = stream.iterator(); while (iterator.hasNext()) { PageInfo pageInfo = iterator.next(); if (pageInfo == null) { LOG.error("Failed to restore PageStore: Invalid page info"); return false; } PageId pageId = pageInfo.getPageId(); ReadWriteLock pageLock = getPageLock(pageId); try (LockResource r = new LockResource(pageLock.writeLock())) { boolean enoughSpace; try (LockResource r2 = new LockResource(mMetaLock.writeLock())) { enoughSpace = mMetaStore.bytes() + pageInfo.getPageSize() <= mPageStore.getCacheSize(); if (enoughSpace) { mMetaStore.addPage(pageId, pageInfo); } } if (!enoughSpace) { mPageStore.delete(pageId); discardedPages++; discardedBytes += pageInfo.getPageSize(); } } } } catch (Exception e) { LOG.error("Failed to restore PageStore: ", e); return false; } LOG.info("Successfully restored PageStore with pages ({} bytes), " + "discarded pages ({} bytes)", mMetaStore.pages(), mMetaStore.bytes(), discardedPages, discardedBytes); return true; }
Source:
<code>void checkExpiration() { if (!active.get()) { <START> return; <END> } final Timestamp currentTime = Timestamps.getCurrentTime(); if (Timestamps.compare(currentTime, expirationTime) > 0) { log().warn( "Completing bulk write operation before all the events are processed. Took at least seconds.", expirationTime.getSeconds()); complete(); } }</code><technical_language>test this execution branch</technical_language>

Target:
void checkExpiration() { if (!isInProgress()) { return; } final Timestamp currentTime = Timestamps.getCurrentTime(); if (Timestamps.compare(currentTime, expirationTime) > 0) { log().warn("Completing bulk write operation before all the events are processed."); complete(); } }
Source:
<code>public void savePatientOnThread(UserContext ctx, Patient patient) { Context.setUserContext(ctx); <START> Context.openSessionWithCurrentUser(); <END> authenticate(); PatientIdentifier patientIdentifier = new PatientIdentifier("103-9", new PatientIdentifierType(1), new Location(1)); patientIdentifier.setPreferred(true); patient.addIdentifier(patientIdentifier); try { patientService.savePatient(patient); } catch(org.openmrs.api.IdentifierNotUniqueException e) { isSavePatientThreadsafe.set(true); } Context.closeSessionWithCurrentUser(); }</code><technical_language>fix indention? a couple of other places in commit</technical_language>

Target:
public void savePatientOnThread(UserContext ctx, Patient patient) { Context.setUserContext(ctx); Context.openSessionWithCurrentUser(); authenticate(); PatientIdentifier patientIdentifier = new PatientIdentifier("103-9", new PatientIdentifierType(1), new Location(1)); patientIdentifier.setPreferred(true); patient.addIdentifier(patientIdentifier); try { patientService.savePatient(patient); } catch(org.openmrs.api.IdentifierNotUniqueException e) { isSavePatientThreadUnSafe.set(true); } Context.closeSessionWithCurrentUser(); }
Source:
<code>public void visitDistanceType(VisitableElement<Double> visitable) { Double value = visitable.getValue(); <START> if (value == null) { <END> LOGGER.debug("No values found on distance type"); return; } builder.setDistance(value); }</code><technical_language>Do need a traceName(visitable) here</technical_language>

Target:
public void visitDistanceType(VisitableElement<Double> visitable) { super.visitDistanceType(visitable); Double value = visitable.getValue(); if (value == null) { LOGGER.debug("No values found on distance type"); return; } builder.setDistance(value); }
Source:
<code>public Bundle performBitstreamMove(Context context, Bitstream bitstream, Bundle targetBundle) throws SQLException, IOException, AuthorizeException { if (bitstream.getBundles().contains(targetBundle)) { throw new DSpaceBadRequestException("The provided bitstream is already in the target bundle"); } List<Bundle> bundles = new LinkedList<>(); bundles.addAll(bitstream.getBundles()); <START> if (hasSufficientMovePermissions(context, bundles, targetBundle)) { <END> bundleService.addBitstream(context, targetBundle, bitstream); bundleService.update(context, targetBundle); for (Bundle bundle : bundles) { bundleService.removeBitstream(context, bundle, bitstream); bundleService.update(context, bundle); } } return targetBundle; }</code><technical_language>create a service method for moving a bitstream permissions verified services layer. This is a must-have, simply allow for easier authorization management</technical_language>

Target:
public Bundle performBitstreamMove(Context context, Bitstream bitstream, Bundle targetBundle) throws SQLException, IOException, AuthorizeException { if (bitstream.getBundles().contains(targetBundle)) { throw new DSpaceBadRequestException("The provided bitstream is already in the target bundle"); } bundleService.moveBitstreamToBundle(context, targetBundle, bitstream); return targetBundle; }
Source:
<code>public void handleRequest(Conveyor conv) throws GeoWebCacheException { ConveyorKMLTile tile = (ConveyorKMLTile) conv; TileLayer layer; if (tile.getHint() == HINT_DEBUGGRID) { layer = KMLDebugGridLayer.getInstance(); if (tile.getWrapperMimeType() == null) { tile.setTileLayer(layer); try { layer.getTile(tile); } catch (Exception e) { e.printStackTrace(); } String mimeStr = getMimeTypeOverride(tile); writeTileResponse(tile, false, stats, mimeStr); return; } } else if (tile.getHint() == HINT_SITEMAP_GLOBAL) { layer = null; } else { layer = tld.getTileLayer(tile.getLayerId()); if (layer == null) { throw new ServiceException("No layer provided, request parsed to: " + tile.getLayerId()); } } tile.setTileLayer(layer); if(Objects.nonNull(tile.getLayer())) { if(tile.getTileIndex()[2]<0) { <START> secDispatcher.checkSecurity(tile.getLayer(), null, null); <END> } else { secDispatcher.checkSecurity(tile); } } if (tile.getTileIndex()[2] == -1) { if (log.isDebugEnabled()) { log.debug("Request for super overlay for " + tile.getLayerId() + " received"); } handleSuperOverlay(tile); } else { if (log.isDebugEnabled()) { log.debug("Request for overlay for " + tile.getLayerId()); } handleOverlay(tile); } }</code><technical_language>a follow-up above, do need bounding box / srs here? calculated SecurityDispatcher if in else clause</technical_language>

Target:
public void handleRequest(Conveyor conv) throws GeoWebCacheException { ConveyorKMLTile tile = (ConveyorKMLTile) conv; TileLayer layer; if (tile.getHint() == HINT_DEBUGGRID) { layer = KMLDebugGridLayer.getInstance(); if (tile.getWrapperMimeType() == null) { tile.setTileLayer(layer); try { layer.getTile(tile); } catch (Exception e) { e.printStackTrace(); } String mimeStr = getMimeTypeOverride(tile); writeTileResponse(tile, false, stats, mimeStr); return; } } else if (tile.getHint() == HINT_SITEMAP_GLOBAL) { layer = null; } else { layer = tld.getTileLayer(tile.getLayerId()); if (layer == null) { throw new ServiceException("No layer provided, request parsed to: " + tile.getLayerId()); } } tile.setTileLayer(layer); if(Objects.nonNull(tile.getLayer())) { if(tile.getTileIndex()[2]<0) { getSecurityDispatcher().checkSecurity(tile.getLayer(), null, null); } else { getSecurityDispatcher().checkSecurity(tile); } } if (tile.getTileIndex()[2] == -1) { if (log.isDebugEnabled()) { log.debug("Request for super overlay for " + tile.getLayerId() + " received"); } handleSuperOverlay(tile); } else { if (log.isDebugEnabled()) { log.debug("Request for overlay for " + tile.getLayerId()); } handleOverlay(tile); } }
Source:
<code>public void maxUrisTestWithQueryTask() { DataMovementManager dmManager = client.newDataMovementManager(); List<String> outputUris = Collections.synchronizedList(new ArrayList<String>()); DocumentMetadataHandle documentMetadata = new DocumentMetadataHandle().withCollections("maxUrisTest"); WriteBatcher batcher = moveMgr.newWriteBatcher().withDefaultMetadata(documentMetadata); moveMgr.startJob(batcher); for(int i=0; i<100; i++) { batcher.addAs("test"+i+".txt", new StringHandle().with("Test"+i)); } batcher.flushAndWait(); moveMgr.stopJob(batcher); AtomicInteger counter = new AtomicInteger(0); QueryBatcher queryBatcher = dmManager.newQueryBatcher(new StructuredQueryBuilder().collection("maxUrisTest")); int forest_count = queryBatcher.getForestConfig().listForests().length; <START> int maxBatches = forest_count-1; <END> queryBatcher.setMaxBatches(maxBatches); queryBatcher.withBatchSize(10) .onUrisReady(batch -> { outputUris.addAll(Arrays.asList(batch.getItems())); counter.incrementAndGet(); }) .onQueryFailure((QueryBatchException failure) -> { System.out.println(failure.getMessage()); }); dmManager.startJob(queryBatcher); queryBatcher.awaitCompletion(); dmManager.stopJob(queryBatcher); assertTrue("Counter value not as expected", (counter.get() >= maxBatches) && (counter.get()<= (forest_count+maxBatches))); assertTrue("Output list does not contain expected number of outputs", (outputUris.size() >= (maxBatches*10)) && outputUris.size()<= (10*(forest_count+maxBatches))); }</code><technical_language>sufficient set maxBatches 1</technical_language>

Target:
public void maxUrisTestWithQueryTask() { DataMovementManager dmManager = client.newDataMovementManager(); List<String> outputUris = Collections.synchronizedList(new ArrayList<String>()); DocumentMetadataHandle documentMetadata = new DocumentMetadataHandle().withCollections("maxUrisTest"); WriteBatcher batcher = moveMgr.newWriteBatcher().withDefaultMetadata(documentMetadata); int forests = batcher.getForestConfig().listForests().length; int batchSize = 10; moveMgr.startJob(batcher); for(int i=0; i<((forests+2)*batchSize); i++) { batcher.addAs("test"+i+".txt", new StringHandle().with("Test"+i)); } batcher.flushAndWait(); moveMgr.stopJob(batcher); AtomicInteger counter = new AtomicInteger(0); QueryBatcher queryBatcher = dmManager.newQueryBatcher(new StructuredQueryBuilder().collection("maxUrisTest")); int forest_count = queryBatcher.getForestConfig().listForests().length; queryBatcher.setMaxBatches(1); queryBatcher.withBatchSize(batchSize) .onUrisReady(batch -> { outputUris.addAll(Arrays.asList(batch.getItems())); counter.incrementAndGet(); }) .onQueryFailure((QueryBatchException failure) -> { System.out.println(failure.getMessage()); }); dmManager.startJob(queryBatcher); queryBatcher.awaitCompletion(); dmManager.stopJob(queryBatcher); assertTrue("Counter value not as expected", (counter.get() >= 1) && (counter.get()<= (forest_count+1))); assertTrue("Output list does not contain expected number of outputs", (outputUris.size() >= 10) && outputUris.size()<= (10*(forest_count+1))); }
Source:
<code>void dispatchAirplaneModeChange(boolean airplaneMode) { <START> handler.sendMessage(handler.obtainMessage(AIRPLANE_MODE_CHANGE, airplaneMode ? 1 : 0, 0)); <END> }</code><technical_language>1 0 constants AIRPLANE_MODE_ON AIRPLANE_MODE_OFF</technical_language>

Target:
void dispatchAirplaneModeChange(boolean airplaneMode) { handler.sendMessage(handler.obtainMessage(AIRPLANE_MODE_CHANGE, airplaneMode ? AIRPLANE_MODE_ON : AIRPLANE_MODE_OFF, 0)); }
Source:
<code>static void schedule(Event event) { <START> QUEUE.add(event); <END> if (ENABLED) { if (QUEUE.size() >= MAX_QUEUE_SIZE) { sendAllScheduled(); } else { TIMER.cancel(); TIMER = new Timer(); TIMER.schedule(new Task(), WAIT_MS); } } }</code><technical_language>Presumably, scheduling events done concurrently parts of app, i.e. threads. QUEUE is thread-safe</technical_language>

Target:
static synchronized void schedule(Event event) { if (ENABLED || QUEUE.size() <= MAX_QUEUE_SIZE) { QUEUE.add(event); } if (ENABLED) { if (QUEUE.size() >= MAX_QUEUE_SIZE) { sendAllScheduled(); } else { TIMER.cancel(); TIMER.purge(); TIMER = new Timer(); TIMER.schedule(new Task(), WAIT_MS); } } }
Source:
<code>public void verifyReadyForGodMode() { if (!inst().isDevServer()) { Assumption.fail("God mode regeneration works only in dev server."); } if (areTestAccountsDefaultValues()) { Assumption.fail("Please change ALL the default accounts in test.properties in order to use God mode," <START> + "e.g change test.student1.account from alice.tmms to alice.tmms.example"); <END> } if (!areAllTestAccountsDifferent()) { Assumption.fail("ALL test accounts used must be different, including after truncation, " + "e.g veryveryveryveryverylong and veryveryveryveryverylengthy are not " + "accepted as two different accounts."); } if (!areAppUrlsDifferent()) { Assumption.fail("App URLs defined in test.properties and build.properties must be different, " + "and neither one can be a substring of the other, e.g localhost:8888 and " + "localhost:88889 are not accepted as two different app URLs."); } }</code><technical_language>Instead of simply asking change it, ask append names. This dont need handle special cases. do think? this a convention avert problem :-)</technical_language>

Target:
public void verifyReadyForGodMode() { if (!inst().isDevServer()) { Assumption.fail("God mode regeneration works only in dev server."); } if (!areTestAccountsReadyForGodMode()) { Assumption.fail("Please append a unique id (e.g your name) to each of the default account in" + "test.properties in order to use God mode, e.g change alice.tmms to " + "alice.tmms.<yourName>, charlie.tmms to charlie.tmms.<yourName>, etc."); } if (!areAppUrlsDifferent()) { Assumption.fail("App URLs defined in test.properties and build.properties must be different, " + "and neither one can be a substring of the other, e.g localhost:8888 as " + "the URL in test.properties, and localhost:88889 as the URL in build.properties, " + "or vice versa, is not an acceptable combination."); } }
Source:
<code>public void testTargetBranch() throws Exception { Repository remoteDb = createBareRepository(); Repository tempDb = createWorkRepository(); try { <START> StringBuilder xmlContent = new StringBuilder(); <END> xmlContent .append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") .append("<manifest>") .append("<remote name=\"remote1\" fetch=\".\" />") .append("<default revision=\"master\" remote=\"remote1\" />") .append("<project path=\"foo\" name=\"").append(defaultUri) .append("\" />").append("</manifest>"); JGitTestUtil.writeTrashFile(tempDb, "manifest.xml", xmlContent.toString()); RepoCommand command = new RepoCommand(remoteDb); command.setPath( tempDb.getWorkTree().getAbsolutePath() + "/manifest.xml") .setURI(rootUri).setTargetBranch("test").call(); File directory = createTempDirectory("testBareRepo"); Repository localDb = Git .cloneRepository().setDirectory(directory).setBranch("test") .setURI(remoteDb.getDirectory().toURI().toString()).call() .getRepository(); File gitmodules = new File(localDb.getWorkTree(), ".gitmodules"); assertTrue("The .gitmodules file should exist", gitmodules.exists()); BufferedReader reader = new BufferedReader(new FileReader( gitmodules)); String content = reader.readLine(); reader.close(); assertEquals( "The first line of .gitmodules file should be as expected", "[submodule \"foo\"]", content); String gitlink = localDb.resolve(Constants.R_HEADS + "test:foo").name(); localDb.close(); String remote = defaultDb.resolve(Constants.HEAD).name(); assertEquals("The gitlink should be the same as remote head", remote, gitlink); } finally { tempDb.close(); remoteDb.close(); } }</code><technical_language>Is this in some other tests? sense a method constant allow sharing them</technical_language>

Target:
public void testTargetBranch() throws Exception { try ( Repository remoteDb1 = createBareRepository(); Repository remoteDb2 = createBareRepository(); Repository tempDb = createWorkRepository()) { StringBuilder xmlContent = new StringBuilder(); xmlContent .append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") .append("<manifest>") .append("<remote name=\"remote1\" fetch=\".\" />") .append("<default revision=\"master\" remote=\"remote1\" />") .append("<project path=\"foo\" name=\"").append(defaultUri) .append("\" />").append("</manifest>"); JGitTestUtil.writeTrashFile(tempDb, "manifest.xml", xmlContent.toString()); RepoCommand command = new RepoCommand(remoteDb1); command .setPath(tempDb.getWorkTree().getAbsolutePath() + "/manifest.xml") .setURI(rootUri) .setTargetBranch("test") .call(); ObjectId branchId = remoteDb1.resolve( Constants.R_HEADS + "test^{tree}"); command = new RepoCommand(remoteDb2); command .setPath(tempDb.getWorkTree().getAbsolutePath() + "/manifest.xml") .setURI(rootUri) .call(); ObjectId defaultId = remoteDb2.resolve(Constants.HEAD + "^{tree}"); assertEquals( "The tree id of branch db and default db should be the same", branchId, defaultId); } }
Source:
<code>private void init() throws Exception { mainFrame = new JFrame("Image drawer example"); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); String localDataPath = DownloaderUtility.DATAEXAMPLES.Download(); originalImage = ImageIO.read(new File(localDataPath, "Mona_Lisa.png")); BufferedImage generatedImage = new BufferedImage(originalImage.getWidth(), originalImage.getHeight(), originalImage.getType()); int width = originalImage.getWidth(); int height = originalImage.getHeight(); final JLabel originalLabel = new JLabel(new ImageIcon(originalImage)); generatedLabel = new JLabel(new ImageIcon(generatedImage)); originalLabel.setBounds(0,0, width, height); generatedLabel.setBounds(width, 0, width, height); mainFrame.add(originalLabel); mainFrame.add(generatedLabel); mainFrame.setSize(2*width, height +25); mainFrame.setLayout(null); mainFrame.setVisible(true); j2dNil = new Java2DNativeImageLoader(); nn = createNN(); xyOut = calcGrid(); INDArray imageMat = j2dNil.asMatrix(originalImage).castTo(DataType.DOUBLE).div(255.0); blueMat = imageMat .tensorAlongDimension(1, 0, 2, 3).reshape(width * height, 1); greenMat = imageMat .tensorAlongDimension(2, 0, 2, 3).reshape(width * height, 1); redMat = imageMat .tensorAlongDimension(3, 0, 2, 3).reshape(width * height, 1); <START> SwingUtilities.invokeLater(this::onCalc); <END> }</code><technical_language>a bit rusty Swing side of things, this effectively run training event dispatching thread, blocking it</technical_language>

Target:
private void init() throws Exception { mainFrame = new JFrame("Image drawer example"); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); String localDataPath = DownloaderUtility.DATAEXAMPLES.Download(); originalImage = ImageIO.read(new File(localDataPath, "Mona_Lisa.png")); BufferedImage generatedImage = new BufferedImage(originalImage.getWidth(), originalImage.getHeight(), originalImage.getType()); int width = originalImage.getWidth(); int height = originalImage.getHeight(); final JLabel originalLabel = new JLabel(new ImageIcon(originalImage)); generatedLabel = new JLabel(new ImageIcon(generatedImage)); originalLabel.setBounds(0,0, width, height); generatedLabel.setBounds(width, 0, width, height); mainFrame.add(originalLabel); mainFrame.add(generatedLabel); mainFrame.setSize(2*width, height +25); mainFrame.setLayout(null); mainFrame.setVisible(true); j2dNil = new Java2DNativeImageLoader(); random = new Random(); nn = createNN(); xyOut = calcGrid(); rgb = new FastRGB(originalImage); SwingUtilities.invokeLater(this::onCalc); }
Source:
<code>public void testSelectApplicationNamesIfNotNullReturnNameString() { Applications applications = new Applications("appsHashCode", <START> 1559658285l, new ArrayList<>(Arrays.asList( <END> new Application("foo"), new Application("bar"), new Application("baz")))); HashSet<String> strings = new HashSet<>(Arrays.asList("baz", "bar", "foo")); Assert.assertEquals(strings, EurekaEntityFunctions.selectApplicationNames(applications)); }</code><technical_language>sense a separate createApplications method accepting applications (throughout)</technical_language>

Target:
public void testSelectApplicationNamesIfNotNullReturnNameString() { Applications applications = createApplications(new Application("foo"), new Application("bar"), new Application("baz")); HashSet<String> strings = new HashSet<>(Arrays.asList("baz", "bar", "foo")); Assert.assertEquals(strings, EurekaEntityFunctions.selectApplicationNames(applications)); }
Source:
<code>public boolean equals(Object obj) { if (this == obj) { return true; <START> } <END> if (obj == null || getClass() != obj.getClass()) { return false; } return true; }</code><technical_language>return obj != null && getClass() == obj.getClass()</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } return obj != null && getClass() == obj.getClass(); }
Source:
<code>public boolean intersects(long timestamp) { <START> return (start <= timestamp && end >= timestamp); <END> }</code><technical_language>Unrelated this patch. this is a good change, adds diff noise</technical_language>

Target:
public boolean intersects(long timestamp) { if (start <= timestamp) { if (end >= timestamp) { return true; } } return false; }
Source:
<code>public void cleanUp() throws Exception { HelixStoreOperator operator = new HelixStoreOperator(helixStore); if (operator.exist("/")) { operator.delete("/"); } if (Files.exists(accountBackupDir)) { Files.walk(accountBackupDir).map(Path::toFile).forEach(File::delete); <START> Files.deleteIfExists(accountBackupDir); <END> } }</code><technical_language>deleteFileOrDirectory in Utils.java</technical_language>

Target:
public void cleanUp() throws Exception { HelixStoreOperator operator = new HelixStoreOperator(helixStore); if (operator.exist("/")) { operator.delete("/"); } if (Files.exists(accountBackupDir)) { Utils.deleteFileOrDirectory(accountBackupDir.toFile()); } }
Source:
<code><START> synchronized void addListener(Consumer<PathChildrenCacheEvent> callback) { <END> callbacks.add(callback); }</code><technical_language>I put callbacks ConcurrentLinkedQueue care listeners added</technical_language>

Target:
void addListener(Consumer<PathChildrenCacheEvent> callback) { callbacks.add(callback); }
Source:
<code>private void assertNoProductsFound(Response<Search> response) { assertTrue(response.isSuccessful()); Search search = response.body(); List<Product> products = search.getProducts(); assertTrue(products.isEmpty()); <START> Assert.assertEquals(0, (int) Integer.valueOf(search.getCount())); <END> }</code><technical_language>import assertEquals statically</technical_language>

Target:
private void assertNoProductsFound(Response<Search> response) { assertTrue(response.isSuccessful()); Search search = response.body(); List<Product> products = search.getProducts(); assertTrue(products.isEmpty()); assertEquals(0, (int) Integer.valueOf(search.getCount())); }
Source:
<code>private void cancel(UUID nodeId) { synchronized (this) { if (isDone()) return; U.log(log, ("Cancelled rebalancing [grp=" + grp.cacheOrGroupName() + ", supplier=" + nodeId + ", topVer=" + topologyVersion() + <START> "]")); <END> cleanupRemoteContexts(nodeId); remaining.remove(nodeId); onDone(false); checkIsDone(); } }</code><technical_language>@ololo3000 I need line break here. Also, [LineBreaking](<LINK_0> single quotes for ] character</technical_language>

Target:
private void cancel(UUID nodeId) { synchronized (this) { if (isDone()) return; U.log(log, ("Cancelled rebalancing [grp=" + grp.cacheOrGroupName() + ", supplier=" + nodeId + ", topVer=" + topologyVersion() + ']')); cleanupRemoteContexts(nodeId); remaining.remove(nodeId); onDone(false); checkIsDone(); } }
Source:
<code><START> private void updateReferenceGenomeDaoDependencies() { <END> if (referenceGenomeService != null) referenceGenomeService.setReferenceGenomeDao(referenceGenomeDao); }</code><technical_language>this method call projectDao.setReferenceGenomeDao</technical_language>

Target:
private void updateReferenceGenomeDaoDependencies() { if (projectDao != null) projectDao.setReferenceGenomeDao(referenceGenomeDao); if (referenceGenomeService != null) referenceGenomeService.setReferenceGenomeDao(referenceGenomeDao); }
Source:
<code>public ComplexMetricExtractor getExtractor() { return new ComplexMetricExtractor() { @Override public Class<?> extractedClass() { <START> return ArrayOfDoublesSketch.class; <END> } @Override public Object extractValue(final InputRow inputRow, final String metricName) { final Object object = inputRow.getRaw(metricName); if (object == null || object instanceof ArrayOfDoublesSketch || object instanceof Memory) { return object; } return ArrayOfDoublesSketchOperations.deserialize(object); } }; }</code><technical_language>code of extractValue(), Memory</technical_language>

Target:
public ComplexMetricExtractor getExtractor() { return new ComplexMetricExtractor() { @Override public Class<?> extractedClass() { return ArrayOfDoublesSketch.class; } @Override public Object extractValue(final InputRow inputRow, final String metricName) { final Object object = inputRow.getRaw(metricName); if (object == null || object instanceof ArrayOfDoublesSketch) { return object; } return ArrayOfDoublesSketchOperations.deserialize(object); } }; }
Source:
<code>protected void eventHandle(ITmfEvent event) { System.out.println("Handling event from " + event.getTrace().getName()); if (!fTraces.contains(event.getTrace())) { <START> System.out.println("Trace not contained"); <END> try { int quarkId = ss.getQuarkAbsoluteAndAdd(TRACE_QUARK_NAME); ss.modifyAttribute(event.getTimestamp().getValue(), TmfStateValue.newValueInt(++fCount), quarkId); fTraces.add(event.getTrace()); } catch (TimeRangeException | AttributeNotFoundException | StateValueTypeException e) { System.out.println("Exception in handle event: " + e.getMessage()); } } }</code><technical_language>sure</technical_language>

Target:
protected void eventHandle(ITmfEvent event) { if (!fTraces.contains(event.getTrace())) { try { int quarkId = ss.getQuarkAbsoluteAndAdd(TRACE_QUARK_NAME); ss.modifyAttribute(event.getTimestamp().getValue(), TmfStateValue.newValueInt(++fCount), quarkId); fTraces.add(event.getTrace()); } catch (TimeRangeException | AttributeNotFoundException | StateValueTypeException e) { } } }
Source:
<code>convert(CompositeFilter filter, RecordSpec<I, R, ?> spec, RecordQueryBuilder<I, R> builder) { if (filter.getFilterCount() > 0) { List<Filter> childFilters = filter.getFilterList(); <START> for (Filter childFilter : childFilters) { <END> convertSingle(childFilter, builder, spec); } } return builder; }</code><technical_language>Again, please consider inlining childFilter removing if check this code nested</technical_language>

Target:
convert(CompositeFilter filter, RecordSpec<I, R, ?> spec, RecordQueryBuilder<I, R> builder) { for (Filter childFilter : filter.getFilterList()) { convertSingle(childFilter, builder, spec); } return builder; }
Source:
<code>private boolean isAccountExpired(IADsUser usr) { try { Date expirationDate = usr.accountExpirationDate(); if (expirationDate != null) { return new Date().after(expirationDate); } return false; } catch (ComException e) { <START> if (e.getHRESULT() == 0x8000500D) { <END> return false; } throw e; } }</code><technical_language>Refactor constant</technical_language>

Target:
private boolean isAccountExpired(IADsUser usr) { try { Date expirationDate = usr.accountExpirationDate(); if (expirationDate != null) { return new Date().after(expirationDate); } return false; } catch (ComException e) { if (e.getHRESULT() == E_ADS_PROPERTY_NOT_FOUND) { return false; } throw e; } }
Source:
<code>public void createPartControl(@Nullable Composite parent) { String name = getViewSite().getSecondaryId(); if (name != null) { <START> fViewInfo.setName(checkNotNull(TmfViewFactory.getBaseSecId(name))); <END> } super.createPartControl(parent); setViewTitle(); }</code><technical_language>String.valueOf()</technical_language>

Target:
public void createPartControl(@Nullable Composite parent) { String name = getViewSite().getSecondaryId(); if (name != null) { name = TmfViewFactory.getBaseSecId(name); } if (name != null) { fViewInfo.setName(name); } super.createPartControl(parent); setViewTitle(); }
Source:
<code>private String buildLookupQuery(String table, String filter, String keyColumn, String valueColumn) { <START> String query; <END> if (Strings.isNullOrEmpty(filter)) { query = StringUtils.format( "SELECT %s, %s FROM %s", keyColumn, valueColumn, table ); } else { query = StringUtils.format( "SELECT %s, %s FROM %s WHERE %s", keyColumn, valueColumn, table, filter ); } return query; }</code><technical_language>This variable is needed, return statements in if else blocks</technical_language>

Target:
private String buildLookupQuery(String table, String filter, String keyColumn, String valueColumn) { if (Strings.isNullOrEmpty(filter)) { return StringUtils.format( "SELECT %s, %s FROM %s", keyColumn, valueColumn, table ); } return StringUtils.format( "SELECT %s, %s FROM %s WHERE %s", keyColumn, valueColumn, table, filter ); }
Source:
<code><START> private String hostName(String host, int port) { <END> if (port == SSH_PORT) { return host; } return String.format("[%s]:%d", host, port); }</code><technical_language>static</technical_language>

Target:
private static String hostName(String host, int port) { if (port == SSH_PORT) { return host; } return String.format("[%s]:%d", host, port); }
Source:
<code>public Map<String, String> getAllMappingUnderPath(String namespace, String path) { if (!_routingZkAddressMap.containsKey(namespace)) { throw new NoSuchElementException( "Failed to get all mapping under path: Namespace " + namespace + " is not found!"); } if (!_routingDataMap.containsKey(namespace)) { <START> throw new IllegalStateException("Failed to get all mapping under path: Namespace " + namespace + " contains invalid routing data!"); <END> } return _routingDataMap.get(namespace).getAllMappingUnderPath(path); }</code><technical_language>rephrase this say, routing data is _empty_ invalid</technical_language>

Target:
public Map<String, String> getAllMappingUnderPath(String namespace, String path) { if (!_routingZkAddressMap.containsKey(namespace)) { throw new NoSuchElementException( "Failed to get all mapping under path: Namespace " + namespace + " is not found!"); } if (!_routingDataMap.containsKey(namespace)) { throw new IllegalStateException("Failed to get all mapping under path: Namespace " + namespace + " contains either empty or invalid routing data!"); } return _routingDataMap.get(namespace).getAllMappingUnderPath(path); }
Source:
<code>public String getDicomViewerUrl(Study study) { if (study == null) throw new IllegalArgumentException("study cannot be null"); else if (study.getStudyInstanceUid() == null) throw new IllegalArgumentException("studyInstanceUid cannot be null"); <START> return study.isCompleted() ? this.radiologyProperties.getDicomViewerUrl() + "studyUID=" <END> + study.getStudyInstanceUid() : null; }</code><technical_language>this ternary behave stated in 1. annotation</technical_language>

Target:
public String getDicomViewerUrl(Study study) { if (study == null) throw new IllegalArgumentException("study cannot be null"); else if (study.getStudyInstanceUid() == null) throw new IllegalArgumentException("studyInstanceUid cannot be null"); return radiologyProperties.getDicomViewerUrl() + "studyUID=" + study.getStudyInstanceUid(); }
Source:
<code>private void updateElementDiagonosticMap() { elementDiagnosticMap.clear(); Diagnostic diagnostics = Diagnostician.INSTANCE.validate(roomModel); for (Diagnostic diagnostic : diagnostics.getChildren()) { FeatureBasedDiagnostic featureBasedDiagnostic = (FeatureBasedDiagnostic) diagnostic; EObject source = featureBasedDiagnostic.getSourceEObject(); EStructuralFeature feature = featureBasedDiagnostic.getFeature(); int index = featureBasedDiagnostic.getIndex(); EObject eObject = null; if (!feature.isMany()) eObject = (EObject) source.eGet(feature); else if (index != ValidationMessageAcceptor.INSIGNIFICANT_INDEX) { List<?> list = (List<?>) source.eGet(feature); eObject = (EObject) list.get(index); <START> } <END> if (elementDiagnosticMap.get(eObject) == null) elementDiagnosticMap.put(eObject, new ArrayList<Diagnostic>()); elementDiagnosticMap.get(eObject).add(diagnostic); } }</code><technical_language>eObject null this point. diagnostic is added key null in map. connections currently compute null business object (all) receive this entry. 1. index = -1 occur does. In this case problem parent object 2. decorations attached States, ChoicePoints etc. diagnostic attached eObject parent object of of types. If is diagnostic discarded for purpose</technical_language>

Target:
private void updateElementDiagonosticMap() { elementDiagnosticMap.clear(); Diagnostic diagnostics = Diagnostician.INSTANCE.validate(roomModel); for (Diagnostic diagnostic : diagnostics.getChildren()) { FeatureBasedDiagnostic featureBasedDiagnostic = (FeatureBasedDiagnostic) diagnostic; EObject source = featureBasedDiagnostic.getSourceEObject(); EObject eObject = null; if (source instanceof StateGraph) { EStructuralFeature feature = featureBasedDiagnostic .getFeature(); int index = featureBasedDiagnostic.getIndex(); if (!feature.isMany()) eObject = (EObject) source.eGet(feature); else if (index != ValidationMessageAcceptor.INSIGNIFICANT_INDEX) { List<?> list = (List<?>) source.eGet(feature); eObject = (EObject) list.get(index); } } else if (source instanceof Trigger) eObject = source.eContainer(); else eObject = source; if (elementDiagnosticMap.get(eObject) == null) elementDiagnosticMap.put(eObject, new ArrayList<Diagnostic>()); elementDiagnosticMap.get(eObject).add(diagnostic); } }
Source:
<code>public void testLeftBubblePosition() { Float expectedXLeft = -495.0f; Float expectedYLeft = 347.0f; Sprite sprite = new Sprite(NAME); <START> sprite.look.setX(-540.0f); sprite.look.setY(-897.0f); sprite.look.setHeight(1794.0f); sprite.look.setWidth(1080.0f); <END> ShowBubbleActor bubbleActor = new ShowBubbleActor(NAME, sprite, Constants.SAY_BRICK); assertEquals(expectedXLeft, bubbleActor.calculateLeftImageX(CALC_X_LEFT)); assertEquals(expectedYLeft, bubbleActor.calculateImageY(CALC_Y_LEFT)); }</code><technical_language>multiple of values in tests nice if move constants a descriptive name. especially height width</technical_language>

Target:
public void testLeftBubblePosition() { ShowBubbleActor bubbleActor = new ShowBubbleActor(OBJECT_NAME, sprite, Constants.SAY_BRICK); assertEquals(EXPECTED_X_STD_LEFT, bubbleActor.calculateLeftImageX(CALC_X_LEFT)); assertEquals(EXPECTED_Y_STD, bubbleActor.calculateImageY(CALC_Y_LEFT)); }
Source:
<code>public void testTopNNodeSymbolMapping() { <START> PlanBuilder builder = new PlanBuilder(new PlanNodeIdAllocator(), metadata); <END> ValuesNode values = builder.values(a, b); TopNNode topNNode = builder.topN(10, ImmutableList.of(a, b), values); TopNNode mappedTopNNode = SYMBOL_MAPPER.map(topNNode, values, topNNode.getId()); assertEquals(mappedTopNNode.getOrderBy(), singletonList(A)); }</code><technical_language>aggregation node symbols for group id, hash, aggregation mask</technical_language>

Target:
public void testTopNNodeSymbolMapping() { PlanBuilder builder = new PlanBuilder(new PlanNodeIdAllocator(), metadata); ValuesNode values = builder.values(a, b); TopNNode topNNode = builder.topN(10, ImmutableList.of(a, b), values); TopNNode mappedTopNNode = SYMBOL_MAPPER.map(topNNode, values); assertEquals(mappedTopNNode.getOrderBy(), singletonList(A)); assertEquals(mappedTopNNode.getOrderings().keySet(), singleton(A)); }
Source:
<code>public static Set<String> getDimensionTypes(WorldProvider provider) { if (provider instanceof Handler) return ((Handler) provider).getDimensionTypes(); Set<String> types = dimensionTypes.get(provider.dimensionId); <START> return types != null ? SET_UNCATEGORIZED : Collections.<String>emptySet(); <END> }</code><technical_language>If types != null returns SET_UNCATEGORIZED if types == null, returns Collections.<String>emptySet(); case returns types. :P</technical_language>

Target:
public static Set<String> getDimensionTypes(WorldProvider provider) { if (provider instanceof Handler) return ((Handler) provider).getDimensionTypes(); Set<String> types = dimensionTypes.get(provider.dimensionId); return types != null ? types : SET_UNCATEGORIZED; }
Source:
<code>public static HtsgetErrorResponse parse(final String s) { final HtsgetErrorResponse resp = new HtsgetErrorResponse(); final mjson.Json j = mjson.Json.read(s); <START> final mjson.Json htsget = j.at("htsget"); <END> final mjson.Json errorJson = htsget.at("error"); if (errorJson != null) { resp.error = errorJson.asString(); } final mjson.Json messageJson = htsget.at("message"); if (errorJson != null) { resp.message = messageJson.asString(); } return resp; }</code><technical_language>This a clear error if this is null</technical_language>

Target:
public static HtsgetErrorResponse parse(final String s) { final mjson.Json j = mjson.Json.read(s); final mjson.Json htsget = j.at("htsget"); if (htsget == null) { throw new IllegalStateException(new HtsgetMalformedResponseException("No htsget key found in response")); } final mjson.Json errorJson = htsget.at("error"); final mjson.Json messageJson = htsget.at("message"); return new HtsgetErrorResponse( errorJson == null ? null : errorJson.asString(), messageJson == null ? null : messageJson.asString()); }
Source:
<code>public void persistTags(String sessionId, SessionMetaDataStorage metaDataStorage) { Set<TagEntity> tags = new HashSet<TagEntity>(); for (TagEntity tagEntity : metaDataStorage.getTagsForSaveOrUpdate()) { try { getHibernateTemplate().saveOrUpdate(tagEntity); } catch (HibernateException e ) { log.error("Cannot add new tag: {}", tagEntity.getName()); <START> e.printStackTrace(); <END> } } List<TagEntity> sessionTagList = getHibernateTemplate().find("from TagEntity"); for (String tagName : metaDataStorage.getSessionTags()) { for (TagEntity tagEntity : sessionTagList) { if (tagEntity.getName().equals(tagName)) tags.add(tagEntity); } } if (!tags.isEmpty()) { List<SessionData> sessionsById = getHibernateTemplate().find("from SessionData s where s.sessionId=?", sessionId); for (SessionData sessionData : sessionsById) { sessionData.setTags(tags); getHibernateTemplate().saveOrUpdate(sessionData); } } else log.info("No tags for mark session {}", sessionId); }</code><technical_language>Please logger print error messages. Read this please - <LINK_0></technical_language>

Target:
public void persistTags(String sessionId, SessionMetaDataStorage metaDataStorage) { Set<TagEntity> sessionTagList = new HashSet<TagEntity>(); for (TagEntity tagEntity : metaDataStorage.getTagsForSaveOrUpdate()) { try { getHibernateTemplate().saveOrUpdate(tagEntity); } catch (HibernateException e) { log.error("Cannot add new tag", e); } } sessionTagList.addAll(getHibernateTemplate().findByNamedParam("select tags from TagEntity as tags " + "where tags.name in (:sTagsName)", "sTagsName", metaDataStorage.getSessionTags())); if (!sessionTagList.isEmpty()) { List<SessionData> sessionsById = getHibernateTemplate().find("from SessionData s where s.sessionId=?", sessionId); for (SessionData sessionData : sessionsById) { sessionData.setTags(sessionTagList); getHibernateTemplate().saveOrUpdate(sessionData); } } else log.info("No tags for mark session {}", sessionId); }
Source:
<code>private static List<PeerDiscovery> buildDiscoveries(NetworkParameters params, String[] seeds) { <START> List<PeerDiscovery> discoveries = new ArrayList<PeerDiscovery>(seeds != null ? seeds.length : 0); <END> for (String seed : seeds) discoveries.add(new DnsSeedDiscovery(params, seed)); return discoveries; }</code><technical_language>This move NPE line lower. remove entire parameter in ArrayList constructor, useful</technical_language>

Target:
private static List<PeerDiscovery> buildDiscoveries(NetworkParameters params, String[] seeds) { List<PeerDiscovery> discoveries = new ArrayList<PeerDiscovery>(); if (seeds != null) for (String seed : seeds) discoveries.add(new DnsSeedDiscovery(params, seed)); return discoveries; }
Source:
<code>public static void checkTransactionExists(TransactionManager tm, boolean isExpectTransaction) { try { Transaction tx = tm.getTransaction(); if(!isExpectTransaction && tx != null && tx.getStatus() != Status.STATUS_NO_TRANSACTION) { <START> throw new RuntimeException("We do not expect transaction would be active - we haven't activated it in BMT bean"); <END> } else if (isExpectTransaction && (tx == null || tx.getStatus() != Status.STATUS_ACTIVE)) { throw new RuntimeException("We do expect tranaction would be active - we have alredy activated it in BMT bean"); } } catch (SystemException e) { throw new RuntimeException("Cannot get the current transaction from injected TransationManager!", e); } }</code><technical_language>fail("MESSAGE")</technical_language>

Target:
public static void checkTransactionExists(TransactionManager tm, boolean isExpectTransaction) { try { Transaction tx = tm.getTransaction(); if(!isExpectTransaction && tx != null && tx.getStatus() != Status.STATUS_NO_TRANSACTION) { Assert.fail("We do not expect transaction would be active - we haven't activated it in BMT bean"); } else if (isExpectTransaction && (tx == null || tx.getStatus() != Status.STATUS_ACTIVE)) { Assert.fail("We do expect tranaction would be active - we have alredy activated it in BMT bean"); } } catch (SystemException e) { throw new RuntimeException("Cannot get the current transaction from injected TransationManager!", e); } }
Source:
<code>public static void init(IdentityManager testIdentityManager) { config = new Config(); objectMapper = new ObjectMapper(); <START> objectWriterPrettyPrinter = objectMapper.writerWithDefaultPrettyPrinter(); <END> identityManager = testIdentityManager; }</code><technical_language>I need options time</technical_language>

Target:
public static void init(IdentityManager testIdentityManager) { config = new Config(); objectMapper = new ObjectMapper(); identityManager = testIdentityManager; }
Source:
<code>private Runnable addSecondaryWhenPrimaryIsNonNull(final MongoDBServer secondary) { return new Runnable() { @Override public void run() { Boolean isAvailable = secondary.getAttribute(MongoDBServer.SERVICE_UP); MongoDBServer primary = getPrimary(); if (isAvailable && primary != null) { primary.getClient().addMemberToReplicaSet(secondary, nextMemberId.incrementAndGet()); } else { <START> executor.schedule(this, 3, TimeUnit.SECONDS); <END> } } }; }</code><technical_language>log.debug log.trace re-scheduling secondary is service_up</technical_language>

Target:
private Runnable addSecondaryWhenPrimaryIsNonNull(final MongoDBServer secondary) { return new Runnable() { @Override public void run() { Boolean isAvailable = secondary.getAttribute(MongoDBServer.SERVICE_UP); MongoDBServer primary = getPrimary(); if (isAvailable && primary != null) { primary.getClient().addMemberToReplicaSet(secondary, nextMemberId.incrementAndGet()); if (LOG.isInfoEnabled()) { LOG.info("{} added to replica set {}", secondary, getReplicaSetName()); } } else { if (LOG.isTraceEnabled()) { LOG.trace("Rescheduling addition of member to replica set {}: service_up={}, primary={}", new Object[]{secondary, getReplicaSetName(), isAvailable, primary}); } executor.schedule(this, 3, TimeUnit.SECONDS); } } }; }
Source:
<code>public void isItemIndexChanged() { TreeItem oldItem = mock(TreeItem.class); <START> when(tree.getItemByUuid(ITEM_UUID)).thenReturn(oldItem); <END> when(oldItem.getLabel()).thenReturn(NAME); when(item.getParentItem()).thenReturn(parentItem); when(item.getUuid()).thenReturn("INDEX_CHANGED"); when(oldItem.getParentItem()).thenReturn(parentItem); when(oldItem.getUuid()).thenReturn(ITEM_UUID); when(parentItem.getUuid()).thenReturn(PARENT_UUID); when(parentItem.getChildCount()).thenReturn(2); when(parentItem.getChild(eq(0))).thenReturn(item); when(parentItem.getChild(eq(1))).thenReturn(oldItem); assertTrue(testedTreeExplorerView.isItemChanged(ITEM_UUID, PARENT_UUID, NAME, OptionalInt.of(0))); assertFalse(testedTreeExplorerView.isItemChanged(ITEM_UUID, PARENT_UUID, NAME, OptionalInt.of(1))); assertTrue(testedTreeExplorerView.isItemChanged(ITEM_UUID, PARENT_UUID, NAME, OptionalInt.of(2))); }</code><technical_language>I wondering, separate common when/then calls separate method. do it? sense here</technical_language>

Target:
public void isItemIndexChanged() { TreeItem oldItem = mockOldItem(); when(item.getUuid()).thenReturn("INDEX_CHANGED"); when(parentItem.getChildCount()).thenReturn(2); when(parentItem.getChild(eq(0))).thenReturn(item); when(parentItem.getChild(eq(1))).thenReturn(oldItem); assertTrue(testedTreeExplorerView.isItemChanged(ITEM_UUID, PARENT_UUID, NAME, OptionalInt.of(0))); assertFalse(testedTreeExplorerView.isItemChanged(ITEM_UUID, PARENT_UUID, NAME, OptionalInt.of(1))); assertTrue(testedTreeExplorerView.isItemChanged(ITEM_UUID, PARENT_UUID, NAME, OptionalInt.of(2))); }
Source:
<code>private CompletableFuture<Boolean> openRepository(String repoId, boolean isPrimaryRepository) { assert Utility.isWellFormedRepoId(repoId); if (isPrimaryRepository) prefs.setLastViewedRepository(repoId); if (isAlreadyOpen(repoId) || models.isRepositoryPending(repoId)) { if (isPrimaryRepository) refreshUI(); return Futures.unit(false); } models.queuePendingRepository(repoId); return isRepositoryValid(repoId).thenCompose(valid -> { if (!valid) { return Futures.unit(false); } else { logger.info("Opening " + repoId); UI.status.displayMessage("Opening " + repoId); <START> Platform.runLater(() -> UI.events.triggerEvent(new RepoOpeningEvent(repoId, isPrimaryRepository))); <END> return repoOpControl.openRepository(repoId) .thenApply(models::addPending) .thenRun(this::refreshUI) .thenRun(() -> Platform.runLater(() -> UI.events.triggerEvent(new RepoOpenedEvent(repoId, isPrimaryRepository)) ) ) .thenCompose(n -> getRateLimitResetTime()) .thenApply(this::updateRemainingRate) .thenApply(rateLimits -> true) .exceptionally(withResult(false)); } }); }</code><technical_language>else clause is needed here. code in this PR nice if refactor this part :-P</technical_language>

Target:
private CompletableFuture<Boolean> openRepository(String repoId, boolean isPrimaryRepository) { assert Utility.isWellFormedRepoId(repoId); if (isPrimaryRepository) prefs.setLastViewedRepository(repoId); if (isAlreadyOpen(repoId) || models.isRepositoryPending(repoId)) { if (isPrimaryRepository) refreshUI(); return Futures.unit(false); } models.queuePendingRepository(repoId); return isRepositoryValid(repoId).thenCompose(valid -> { if (!valid) { return Futures.unit(false); } logger.info("Opening " + repoId); UI.status.displayMessage("Opening " + repoId); Platform.runLater(() -> UI.events.triggerEvent(new RepoOpeningEvent(repoId, isPrimaryRepository))); return repoOpControl.openRepository(repoId) .thenApply(models::addPending) .thenRun(this::refreshUI) .thenRun(() -> Platform.runLater(() -> UI.events.triggerEvent(new RepoOpenedEvent(repoId, isPrimaryRepository)) ) ) .thenCompose(n -> getRateLimitResetTime()) .thenApply(this::updateRemainingRate) .thenApply(rateLimits -> true) .exceptionally(withResult(false)); }); }