auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public HttpClient get() { final DruidHttpClientConfig config = getConfigProvider().get().get(); final HttpClientConfig.Builder builder = HttpClientConfig .builder() .withNumConnections(config.getNumConnections()) .withReadTimeout(config.getReadTimeout()) .withWorkerCount(config.getNumMaxThreads()) .withCompressionCodec( HttpClientConfig.CompressionCodec.valueOf(StringUtils.toUpperCase(config.getCompressionCodec())) ) .withUnusedConnectionTimeoutDuration(config.getUnusedConnectionTimeout().toStandardDuration()); if (getSslContextBinding() != null) { builder.withSslContext(getSslContextBinding().getProvider().get()); } HttpClient client = HttpClientInit.createClient( builder.build(), LifecycleUtils.asMmxLifecycle(getLifecycleProvider().get()) ); if (isEscalated) { return escalator.createEscalatedClient(client); } else { return client; } }

Target:
public HttpClient get() { final DruidHttpClientConfig config = getConfigProvider().get().get(); final HttpClientConfig.Builder builder = HttpClientConfig .builder() .withNumConnections(config.getNumConnections()) .withReadTimeout(config.getReadTimeout()) .withWorkerCount(config.getNumMaxThreads()) .withCompressionCodec( HttpClientConfig.CompressionCodec.valueOf(StringUtils.toUpperCase(config.getCompressionCodec())) ) .withUnusedConnectionTimeoutDuration(config.getUnusedConnectionTimeout()); if (getSslContextBinding() != null) { builder.withSslContext(getSslContextBinding().getProvider().get()); } HttpClient client = HttpClientInit.createClient( builder.build(), LifecycleUtils.asMmxLifecycle(getLifecycleProvider().get()) ); if (isEscalated) { return escalator.createEscalatedClient(client); } else { return client; } }
Source:
public Manager() { super(); this.templateManager = new ApplicationTemplateMngrDelegate(); this.appManager = new ApplicationMngrDelegate(); this.instanceManager = new InstanceMngrDelegate( this ); this.messagingType = MessagingConstants.FACTORY_RABBIT_MQ; }

Target:
public Manager() { super(); this.templateManager = new ApplicationTemplateMngrDelegate(); this.appManager = new ApplicationMngrDelegate(); this.instanceManager = new InstanceMngrDelegate( this ); }
Source:
public void detach() { if (getWindow() != null) { return; } ConfirmationModel model = new ConfirmationModel(); setWindow(model); model.setTitle(ConstantsManager.getInstance().getConstants().detachStorageTitle()); model.setHelpTag(HelpTag.detach_storage); model.setHashName("detach_storage"); model.setMessage(ConstantsManager.getInstance().getConstants().areYouSureYouWantDetachFollowingStoragesMsg()); ArrayList<String> list = new ArrayList<String>(); boolean shouldAddressWarnning = false; for (StorageDomain item : Linq.<StorageDomain> cast(getSelectedItems())) { list.add(item.getStorageName()); if (item.getStorageDomainType() == StorageDomainType.Data || item.getStorageDomainType() == StorageDomainType.Master) { shouldAddressWarnning = true; } } model.setItems(list); if (containsLocalStorage(model)) { model.getLatch().setIsAvailable(true); model.getLatch().setIsChangable(true); model.setNote(ConstantsManager.getInstance().getMessages().detachNote(getLocalStoragesFormattedString())); } if (shouldAddressWarnning) { model.setNote(ConstantsManager.getInstance().getConstants().detachWarnningNote()); } UICommand tempVar = new UICommand("OnDetach", this); tempVar.setTitle(ConstantsManager.getInstance().getConstants().ok()); tempVar.setIsDefault(true); model.getCommands().add(tempVar); UICommand tempVar2 = new UICommand("Cancel", this); tempVar2.setTitle(ConstantsManager.getInstance().getConstants().cancel()); tempVar2.setIsCancel(true); model.getCommands().add(tempVar2); }

Target:
public void detach() { if (getWindow() != null) { return; } ConfirmationModel model = new ConfirmationModel(); setWindow(model); model.setTitle(ConstantsManager.getInstance().getConstants().detachStorageTitle()); model.setHelpTag(HelpTag.detach_storage); model.setHashName("detach_storage"); model.setMessage(ConstantsManager.getInstance().getConstants().areYouSureYouWantDetachFollowingStoragesMsg()); ArrayList<String> list = new ArrayList<String>(); boolean shouldAddressWarnning = false; for (StorageDomain item : Linq.<StorageDomain> cast(getSelectedItems())) { list.add(item.getStorageName()); if (item.getStorageDomainType().isDataDomain()) { shouldAddressWarnning = true; break; } } model.setItems(list); if (containsLocalStorage(model)) { shouldAddressWarnning = false; model.getLatch().setIsAvailable(true); model.getLatch().setIsChangable(true); model.setNote(ConstantsManager.getInstance().getMessages().detachNote(getLocalStoragesFormattedString())); } if (shouldAddressWarnning) { model.setNote(ConstantsManager.getInstance().getConstants().detachWarnningNote()); } UICommand tempVar = new UICommand("OnDetach", this); tempVar.setTitle(ConstantsManager.getInstance().getConstants().ok()); tempVar.setIsDefault(true); model.getCommands().add(tempVar); UICommand tempVar2 = new UICommand("Cancel", this); tempVar2.setTitle(ConstantsManager.getInstance().getConstants().cancel()); tempVar2.setIsCancel(true); model.getCommands().add(tempVar2); }
Source:
private static SqlScalarFunction castFunctionFromDecimalTo(TypeSignature to, String... methodNames) { Signature signature = Signature.builder() .kind(SCALAR) .operatorType(CAST) .argumentTypes(parseTypeSignature("decimal(precision,scale)", ImmutableSet.of("precision", "scale"))) .returnType(to) .build(); return SqlScalarFunction.builder(DecimalCasts.class) .signature(signature) .deterministic(true) .choice(c -> c .implementation(b -> b .methods(methodNames) .withExtraParameters((context) -> { long precision = context.getLiteral("precision"); long scale = context.getLiteral("scale"); Number tenToScale; if (isShortDecimal(context.getParameterTypes().get(0))) { tenToScale = longTenToNth(intScale(scale)); } else { tenToScale = bigIntegerTenToNth(intScale(scale)); } return ImmutableList.of(precision, scale, tenToScale); }))) .build(); }

Target:
private static SqlScalarFunction castFunctionFromDecimalTo(TypeSignature to, String... methodNames) { Signature signature = Signature.builder() .kind(SCALAR) .operatorType(CAST) .argumentTypes(parseTypeSignature("decimal(precision,scale)", ImmutableSet.of("precision", "scale"))) .returnType(to) .build(); return SqlScalarFunction.builder(DecimalCasts.class) .signature(signature) .deterministic(true) .choice(choice -> choice .implementation(methodsGroup -> methodsGroup .methods(methodNames) .withExtraParameters((context) -> { long precision = context.getLiteral("precision"); long scale = context.getLiteral("scale"); Number tenToScale; if (isShortDecimal(context.getParameterTypes().get(0))) { tenToScale = longTenToNth(intScale(scale)); } else { tenToScale = bigIntegerTenToNth(intScale(scale)); } return ImmutableList.of(precision, scale, tenToScale); }))) .build(); }
Source:
public void resourceChanged(IResourceChangeEvent event) { if (event.getDelta() == null) { return; } try { final Set<IProject> modifiedProjects = new HashSet<>(); event.getDelta().accept(new IResourceDeltaVisitor() { @Override public boolean visit(IResourceDelta delta) { if (delta.getResource() != null && delta.getResource().getType() == IResource.PROJECT && (delta.getKind() == IResourceDelta.ADDED || delta.getKind() == IResourceDelta.CHANGED)) { modifiedProjects.add((IProject) delta.getResource()); } return delta.getResource() == null || delta.getResource().getType() == IResource.ROOT; } }); updateMarkers(modifiedProjects); } catch (CoreException e) { ResourcesPlugin.getPlugin().getLog().log(new Status(IStatus.ERROR, ResourcesPlugin.getPlugin().getBundle().getSymbolicName(), e.getMessage(), e)); } }

Target:
public void resourceChanged(IResourceChangeEvent event) { if (event.getDelta() == null) { return; } try { final Set<IProject> modifiedProjects = new HashSet<>(); event.getDelta().accept(delta -> { if (delta.getResource() != null && delta.getResource().getType() == IResource.PROJECT && (delta.getKind() == IResourceDelta.ADDED || delta.getKind() == IResourceDelta.CHANGED)) { modifiedProjects.add((IProject) delta.getResource()); } return delta.getResource() == null || delta.getResource().getType() == IResource.ROOT; }); updateMarkers(modifiedProjects); } catch (CoreException e) { ResourcesPlugin.getPlugin().getLog().log(new Status(IStatus.ERROR, ResourcesPlugin.getPlugin().getBundle().getSymbolicName(), e.getMessage(), e)); } }
Source:
public Query.QueryBuilder visitQueryable(Queryable plan) { if (invoked == false) { invoked = true; if (plan.isNested()) { return visitOuterQueryPlan(plan); } else { return visitUnnestedQueryPlan(plan); } } else { if (plan.isNested()) { return visitMiddleQueryPlan(plan); } else { return visitInnerQueryPlan(plan); } } }

Target:
public Query.QueryBuilder visitQueryable(Queryable plan) { if (! invoked) { invoked = true; if (plan.isNested()) { return visitOuterQueryPlan(plan); } else { return visitUnnestedQueryPlan(plan); } } else { if (plan.isNested()) { return visitMiddleQueryPlan(plan); } else { return visitInnerQueryPlan(plan); } } }
Source:
public WebSocketClientProtocolHandler(WebSocketClientHandshaker handshaker, boolean handleCloseFrames, boolean dropPongFrames, long handshakeTimeoutMillis) { super(dropPongFrames); this.handshaker = handshaker; this.handleCloseFrames = handleCloseFrames; this.handshakeTimeoutMillis = handshakeTimeoutMillis; }

Target:
public WebSocketClientProtocolHandler(WebSocketClientHandshaker handshaker, boolean handleCloseFrames, boolean dropPongFrames, long handshakeTimeoutMillis) { super(dropPongFrames); this.handshaker = handshaker; this.handleCloseFrames = handleCloseFrames; this.handshakeTimeoutMillis = checkPositive(handshakeTimeoutMillis, "handshakeTimeoutMillis"); }
Source:
public Catalog getCatalog(String catalogName) throws NoSuchObjectException, MetaException { if (!sharedCache.isCatalogCachePrewarmed()) { return rawStore.getCatalog(catalogName); } catalogName = catalogName.toLowerCase(); Catalog cat = sharedCache.getCatalogFromCache(catalogName); if (cat == null) { throw new NoSuchObjectException(); } return cat; }

Target:
public Catalog getCatalog(String catalogName) throws NoSuchObjectException, MetaException { if (!sharedCache.isCatalogCachePrewarmed()) { return rawStore.getCatalog(catalogName); } Catalog cat = sharedCache.getCatalogFromCache(normalizeIdentifier(catalogName)); if (cat == null) { throw new NoSuchObjectException(); } return cat; }
Source:
public CommandStatus runTimed(long timeout, IRunUtil.IRunnableResult runnable, boolean logErrors) { mInterrupter.checkInterrupted(); RunnableNotifier runThread = new RunnableNotifier(runnable, logErrors); if (logErrors) { if (timeout > 0l) { CLog.d("Running command with timeout: %dms", timeout); } else { CLog.d("Running command without timeout."); } } try { runThread.start(); long startTime = System.currentTimeMillis(); long pollInterval = 0; if (timeout > 0L && timeout < THREAD_JOIN_POLL_INTERVAL) { pollInterval = timeout; } else { pollInterval = THREAD_JOIN_POLL_INTERVAL; } do { try { runThread.join(pollInterval); } catch (InterruptedException e) { if (isInterruptAllowed()) { CLog.i("runTimed: interrupted while joining the runnable"); break; } else { CLog.i("runTimed: currently uninterruptible, ignoring interrupt"); } } mInterrupter.checkInterrupted(); } while ((timeout == 0L || (System.currentTimeMillis() - startTime) < timeout) && runThread.isAlive()); CommandStatus status = runThread.getStatus(); if (CommandStatus.TIMED_OUT.equals(status) || CommandStatus.EXCEPTION.equals(status)) { CLog.i("runTimed: Calling interrupt, status is %s", status); runThread.cancel(); } mInterrupter.checkInterrupted(); return status; } catch (RunInterruptedException e) { runThread.cancel(); throw e; } }

Target:
public CommandStatus runTimed(long timeout, IRunUtil.IRunnableResult runnable, boolean logErrors) { mInterrupter.checkInterrupted(); RunnableNotifier runThread = new RunnableNotifier(runnable, logErrors); if (logErrors) { if (timeout > 0l) { CLog.d("Running command with timeout: %dms", timeout); } else { CLog.d("Running command without timeout."); } } try { runThread.start(); long startTime = System.currentTimeMillis(); long pollInterval = 0; if (timeout > 0L && timeout < THREAD_JOIN_POLL_INTERVAL) { pollInterval = timeout; } else { pollInterval = THREAD_JOIN_POLL_INTERVAL; } do { try { runThread.join(pollInterval); } catch (InterruptedException e) { if (isInterruptAllowed()) { CLog.i("runTimed: interrupted while joining the runnable"); break; } else { CLog.i("runTimed: currently uninterruptible, ignoring interrupt"); } } mInterrupter.checkInterrupted(); } while ((timeout == 0L || (System.currentTimeMillis() - startTime) < timeout) && runThread.isAlive()); CommandStatus status = runThread.getStatus(); if (CommandStatus.TIMED_OUT.equals(status) || CommandStatus.EXCEPTION.equals(status)) { CLog.i("runTimed: Calling interrupt, status is %s", status); runThread.cancel(); } mInterrupter.checkInterrupted(); return status; } finally { runThread.cancel(); } }
Source:
public MojioWebSocket(String baseUrl, Authenticator authenticator) { factory = new WebSocketFactory(); listenerWebSocketMap = new HashMap<>(); this.baseUrl = baseUrl; this.authenticator = authenticator; setAccessToken(); }

Target:
public MojioWebSocket(String baseUrl, Authenticator authenticator) { factory = new WebSocketFactory(); listenerWebSocketMap = new HashMap<>(); this.baseUrl = baseUrl; this.authenticator = authenticator; }
Source:
public DispatchRequest undo(LogInAction action, LogInResult result, AsyncCallback<Void> callback, UndoCommand<LogInAction, LogInResult> undoCommand) { undoCommand.undo(action, result, callback); return new CompletedDispatchRequest(); }

Target:
public DispatchRequest undo(LogInAction action, LogInResult result, AsyncCallback<Void> callback, UndoCommand<LogInAction, LogInResult> undoCommand) { return undoCommand.undo(action, result, callback); }
Source:
public boolean canHandle(ActionContext context) { return false; }

Target:
public boolean canHandle(ActionContext context) { return !context.getSelectedManifestations().isEmpty(); }
Source:
private Collection<View> getViewsToUpdate(Diagram gmdDiagram) { Collection<View> viewsToUpdate = Sets.newLinkedHashSet(); TreeIterator<EObject> childIterator = gmdDiagram.eAllContents(); EReference elementReference = NotationPackage.eINSTANCE.getView_Element(); while (childIterator.hasNext()) { EObject child = childIterator.next(); if (child instanceof View && !child.eIsSet(elementReference)) { boolean childIsANoteOrAText = child instanceof Shape && ("Note".equals(((Shape) child).getType()) || "Text".equals(((Shape) child).getType())); boolean childIsANoteAttachement = child instanceof Connector && "NoteAttachment".equals(((Connector) child).getType()); boolean childIsADecorationNode = child instanceof BasicDecorationNode; if (childIsANoteOrAText || childIsANoteAttachement || childIsADecorationNode) { viewsToUpdate.add((View) child); } } } return viewsToUpdate; }

Target:
private Collection<View> getViewsToUpdate(Diagram gmdDiagram) { Collection<View> viewsToUpdate = Sets.newLinkedHashSet(); TreeIterator<EObject> childIterator = gmdDiagram.eAllContents(); EReference elementReference = NotationPackage.eINSTANCE.getView_Element(); while (childIterator.hasNext()) { EObject child = childIterator.next(); if (child instanceof View && !child.eIsSet(elementReference)) { boolean childIsANoteOrAText = child instanceof Shape && (ViewType.NOTE.equals(((Shape) child).getType()) || ViewType.TEXT.equals(((Shape) child).getType())); boolean childIsANoteAttachement = child instanceof Connector && ViewType.NOTEATTACHMENT.equals(((Connector) child).getType()); boolean childIsADecorationNode = child instanceof BasicDecorationNode; if (childIsANoteOrAText || childIsANoteAttachement || childIsADecorationNode) { viewsToUpdate.add((View) child); } } } return viewsToUpdate; }
Source:
public void testCpuLoad() { SystemInfo si = new SystemInfo(); HardwareAbstractionLayer hal = si.getHardware(); System.out.println(hal.getProcessorLoad()); }

Target:
public void testCpuLoad() { SystemInfo si = new SystemInfo(); HardwareAbstractionLayer hal = si.getHardware(); assertTrue(hal.getProcessors()[0].getLoad() >= 0 && hal.getProcessors()[0].getLoad() <= 100); }
Source:
public void accumulate(final VariantContext vc) { if (sample == null){ final List<String> samples = vc.getSampleNamesOrderedByName(); if (samples == null || samples.size() != 1){ throw new IllegalArgumentException("Expected to have exactly 1 sample in a GVCF, found " + ((samples == null) ? "NULL" : samples.size())); } sample = samples.get(0); } VariantContext subContext = vc.subContextFromSample(sample); super.accumulate(subContext); }

Target:
public void accumulate(final VariantContext vc) { final VariantContext subContext = vc.subContextFromSample(sample); super.accumulate(subContext); }
Source:
public boolean equals(@Nullable Object object) { if (!(object instanceof DoubleStateValue)) { return false; } DoubleStateValue other = (DoubleStateValue) object; return this.unboxDouble() == other.unboxDouble(); }

Target:
public boolean equals(@Nullable Object object) { if (!(object instanceof DoubleStateValue)) { return false; } DoubleStateValue other = (DoubleStateValue) object; return Double.compare(this.value, other.value) == 0; }
Source:
public String toString() { return String.format("%s, skipMgmtNetwork=%s", super.toString(), Boolean.valueOf(skipMgmtNetwork())); }

Target:
public String toString() { return String.format("%s, skipMgmtNetwork=%s", super.toString(), isManagementNetworkSkipped()); }
Source:
public URLMapInfo processURLMap(final UrlMapContext context) throws DotSecurityException, DotDataException { if (this.shouldLoadPatterns()) { this.loadPatterns(); } if (containsRegEx(context.getUri())) { final Matches matches = this.findPatternChange(context.getUri()); final Structure structure = CacheLocator.getContentTypeCache() .getStructureByInode(matches.getPatternChange().getStructureInode()); final Field hostField = this.findHostField(structure); final Contentlet contentlet = this.getContentlet(matches, structure, hostField, context); if (contentlet == null) { return null; } final Identifier pageUriIdentifier = this.getDetailtPageUri(structure); return new URLMapInfo(contentlet, pageUriIdentifier); } else { return null; } }

Target:
public Optional<URLMapInfo> processURLMap(final UrlMapContext context) throws DotSecurityException, DotDataException { if (this.shouldLoadPatterns()) { this.loadPatterns(); } if (containsRegEx(context.getUri())) { final Matches matches = this.findPatternChange(context.getUri()); final Structure structure = CacheLocator.getContentTypeCache() .getStructureByInode(matches.getPatternChange().getStructureInode()); final Field hostField = this.findHostField(structure); final Contentlet contentlet = this.getContentlet(matches, structure, hostField, context); if (contentlet == null) { return Optional.empty(); } final Identifier pageUriIdentifier = this.getDetailtPageUri(structure); return Optional.of(new URLMapInfo(contentlet, pageUriIdentifier)); } else { return Optional.empty(); } }
Source:
protected int run() throws Exception { boolean errorOccurred = false; final Jenkins jenkins = Jenkins.getActiveInstance(); final HashSet<String> hs = new HashSet<String>(); hs.addAll(nodes); List<String> names = null; for (String node_s : hs) { Computer computer = null; try { computer = jenkins.getComputer(node_s); if (computer == null) { if (names == null) { names = new ArrayList<String>(); for (Computer c : jenkins.getComputers()) { if (!c.getName().isEmpty()) { names.add(c.getName()); } } } String adv = EditDistance.findNearest(node_s, names); throw new IllegalArgumentException(adv == null ? hudson.model.Messages.Computer_NoSuchSlaveExistsWithoutAdvice(node_s) : hudson.model.Messages.Computer_NoSuchSlaveExists(node_s, adv)); } computer.cliOnline(); } catch (Exception e) { if (hs.size() == 1) { throw e; } final String errorMsg = String.format(node_s + ": " + e.getMessage()); stderr.println(errorMsg); errorOccurred = true; continue; } } if (errorOccurred){ throw new AbortException("Error occured while performing this command, see previous stderr output."); } return 0; }

Target:
protected int run() throws Exception { boolean errorOccurred = false; final Jenkins jenkins = Jenkins.getActiveInstance(); final HashSet<String> hs = new HashSet<String>(nodes); List<String> names = null; for (String node_s : hs) { Computer computer = null; try { computer = jenkins.getComputer(node_s); if (computer == null) { if (names == null) { names = new ArrayList<String>(); for (Computer c : jenkins.getComputers()) { if (!c.getName().isEmpty()) { names.add(c.getName()); } } } String adv = EditDistance.findNearest(node_s, names); throw new IllegalArgumentException(adv == null ? hudson.model.Messages.Computer_NoSuchSlaveExistsWithoutAdvice(node_s) : hudson.model.Messages.Computer_NoSuchSlaveExists(node_s, adv)); } computer.cliOnline(); } catch (Exception e) { if (hs.size() == 1) { throw e; } final String errorMsg = node_s + ": " + e.getMessage(); stderr.println(errorMsg); errorOccurred = true; continue; } } if (errorOccurred){ throw new AbortException("Error occured while performing this command, see previous stderr output."); } return 0; }
Source:
private Option[] configureSolr() { return options( editConfigurationFilePut(SYSTEM_PROPERTIES_REL_PATH, "solr.client", "HttpSolrClient"), editConfigurationFilePut( SYSTEM_PROPERTIES_REL_PATH, "solr.http.url", "http://localhost:9994/solr"), editConfigurationFilePut( SYSTEM_PROPERTIES_REL_PATH, "solr.data.dir", new File("target/solr/server/solr").getAbsolutePath()), editConfigurationFilePut(SYSTEM_PROPERTIES_REL_PATH, "solr.cloud.zookeeper", "")); }

Target:
private Option[] configureSolr() { return options( editConfigurationFilePut(SYSTEM_PROPERTIES_REL_PATH, "solr.client", "HttpSolrClient"), editConfigurationFilePut( SYSTEM_PROPERTIES_REL_PATH, "solr.http.url", "http://localhost:9994/solr"), editConfigurationFilePut(SYSTEM_PROPERTIES_REL_PATH, "solr.http.port", "9994"), editConfigurationFilePut( SYSTEM_PROPERTIES_REL_PATH, "solr.data.dir", new File("target/solr/server/solr").getAbsolutePath()), editConfigurationFilePut(SYSTEM_PROPERTIES_REL_PATH, "solr.cloud.zookeeper", "")); }
Source:
public void setup() throws IOException { Leader leader = mock(Leader.class); when(leader.getQuorumAuthServer()).thenReturn(null); Socket socket = mock(Socket.class); when(socket.getRemoteSocketAddress()).thenReturn(new InetSocketAddress(32)); BinaryOutputArchive oa = mock(BinaryOutputArchive.class); doAnswer(invocationOnMock -> {Thread.sleep(5); return null;}) .when(oa).writeRecord(any(QuorumPacket.class), Matchers.anyString()); BufferedOutputStream bos = mock(BufferedOutputStream.class); doAnswer(invocationOnMock -> {allSentLatch.countDown(); return null;}).when(bos).flush(); learnerHandler = new MockLearnerHandler(socket, leader); learnerHandler.setOutputArchive(oa); learnerHandler.setBufferedOutput(bos); learnerHandler.sid = sid; }

Target:
public void setup() throws IOException { Leader leader = mock(Leader.class); when(leader.getQuorumAuthServer()).thenReturn(null); Socket socket = mock(Socket.class); when(socket.getRemoteSocketAddress()).thenReturn(new InetSocketAddress(32)); BinaryOutputArchive oa = mock(BinaryOutputArchive.class); doAnswer(invocationOnMock -> {Thread.sleep(5); return null;}) .when(oa).writeRecord(any(QuorumPacket.class), anyString()); BufferedOutputStream bos = mock(BufferedOutputStream.class); doAnswer(invocationOnMock -> { if (allSentLatch != null) { allSentLatch.countDown(); } return null; }).when(bos).flush(); learnerHandler = new MockLearnerHandler(socket, leader); learnerHandler.setOutputArchive(oa); learnerHandler.setBufferedOutput(bos); learnerHandler.sid = sid; }
Source:
public boolean isEnabled() { IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); IWorkbenchPart part = page.getActivePart(); if (part == null) { return false; } ISelectionProvider selectionProvider = part.getSite().getSelectionProvider(); if (selectionProvider == null) { return false; } ISelection selection = selectionProvider.getSelection(); Object firstElement = ((IStructuredSelection) selection).getFirstElement(); final TmfCommonProjectElement traceElem = (firstElement instanceof TmfTraceElement) ? ((TmfTraceElement) firstElement).getElementUnderTraceFolder() : (TmfCommonProjectElement) firstElement; ITmfTrace trace = traceElem.getTrace(); if (!(trace instanceof OpenTracingTrace)) { return false; } String path = trace.getPath(); int arraySize = 0; try (FileReader fileReader = new FileReader(path)) { try (JsonReader reader = new JsonReader(fileReader);) { Gson gson = new Gson(); JsonObject object = gson.fromJson(reader, JsonObject.class); arraySize = object.get(DATA_KEY).getAsJsonArray().size(); reader.close(); } catch (IOException e) { return false; } fileReader.close(); } catch (IOException e1) { return false; } return arraySize > 1; }

Target:
public boolean isEnabled() { IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); IWorkbenchPart part = page.getActivePart(); if (part == null) { return false; } ISelectionProvider selectionProvider = part.getSite().getSelectionProvider(); if (selectionProvider == null) { return false; } ISelection selection = selectionProvider.getSelection(); Object firstElement = ((IStructuredSelection) selection).getFirstElement(); final TmfCommonProjectElement traceElem = (firstElement instanceof TmfTraceElement) ? ((TmfTraceElement) firstElement).getElementUnderTraceFolder() : (TmfCommonProjectElement) firstElement; if (!traceElem.getTraceType().equals(TRACE_TYPE_ID)) { return false; } int arraySize = 0; try (FileReader fileReader = new FileReader(traceElem.getLocation().getPath())) { try (JsonReader reader = new JsonReader(fileReader);) { Gson gson = new Gson(); JsonObject object = gson.fromJson(reader, JsonObject.class); arraySize = object.get(DATA_KEY).getAsJsonArray().size(); reader.close(); } catch (IOException e) { return false; } fileReader.close(); } catch (IOException e1) { return false; } return arraySize > 1; }
Source:
public Value<String> lockToken() { return new SpongeValue<String>(Keys.LOCK_TOKEN, this.getValue()); }

Target:
public Value<String> lockToken() { return new SpongeValue<String>(Keys.LOCK_TOKEN, "", this.getValue()); }
Source:
public void getAverageDownloadProgress(final DataCallback<Integer> callback) { IDatabase db = DatabaseFactory.getInstance( DatabaseFactory.TYPE_DATABASE_NATIVE ); db.getListOfOngoingDownloads(new DataCallback<List<VideoModel>>() { @Override public void onResult(List<VideoModel> result) { long[] dmids = new long[result.size()]; for (int i=0; i< result.size(); i++) { dmids[i] = result.get(i).getDmId(); logger.debug("xxxxxxxx =" +dmids[i]); } int averageProgress = dm.getAverageProgressForDownloads(dmids); callback.onResult(averageProgress); } @Override public void onFail(Exception ex) { callback.onFail(ex); } }); }

Target:
public void getAverageDownloadProgress(final DataCallback<Integer> callback) { IDatabase db = DatabaseFactory.getInstance( DatabaseFactory.TYPE_DATABASE_NATIVE ); db.getListOfOngoingDownloads(new DataCallback<List<VideoModel>>() { @Override public void onResult(List<VideoModel> result) { long[] dmids = new long[result.size()]; for (int i=0; i< result.size(); i++) { dmids[i] = result.get(i).getDmId(); } int averageProgress = dm.getAverageProgressForDownloads(dmids); callback.onResult(averageProgress); } @Override public void onFail(Exception ex) { callback.onFail(ex); } }); }
Source:
public void testDynamicLinkUniqueAfterTransition() throws Exception { AnalysisMock.get() .ccSupport() .setupCcToolchainConfig( mockToolsConfig, CcToolchainConfig.builder() .withFeatures( CppRuleClasses.COPY_DYNAMIC_LIBRARIES_TO_BINARY, CppRuleClasses.SUPPORTS_DYNAMIC_LINKER)); prepareCustomTransition(); scratch.file( "transition/BUILD", "load(':custom_transition.bzl', 'apply_custom_transition')", "cc_binary(", " name = \"main\",", " srcs = [\"main.cc\"],", " linkstatic = 0,", " deps = [", " \"dep2\",", " \"dep3\",", " ],", ")", "", "apply_custom_transition(", " name = \"dep1\",", " deps = [", " \":dep2\",", " ],", ")", "", "cc_library(", " name = \"dep2\",", " srcs = [\"test.cc\"],", " hdrs = [\"test.h\"],", ")", "", "cc_library(", " name = \"dep3\",", " srcs = [\"other_test.cc\"],", " hdrs = [\"other_test.h\"],", ")"); assertNoEvents(); }

Target:
public void testDynamicLinkUniqueAfterTransition() throws Exception { AnalysisMock.get() .ccSupport() .setupCcToolchainConfig( mockToolsConfig, CcToolchainConfig.builder() .withFeatures( CppRuleClasses.COPY_DYNAMIC_LIBRARIES_TO_BINARY, CppRuleClasses.SUPPORTS_DYNAMIC_LINKER)); prepareCustomTransition(); scratch.file( "transition/BUILD", "load(':custom_transition.bzl', 'apply_custom_transition')", "cc_binary(", " name = \"main\",", " srcs = [\"main.cc\"],", " linkstatic = 0,", " deps = [", " \"dep2\",", " \"dep3\",", " ],", ")", "", "apply_custom_transition(", " name = \"dep1\",", " deps = [", " \":dep2\",", " ],", ")", "", "cc_library(", " name = \"dep2\",", " srcs = [\"test.cc\"],", " hdrs = [\"test.h\"],", ")", "", "cc_library(", " name = \"dep3\",", " srcs = [\"other_test.cc\"],", " hdrs = [\"other_test.h\"],", ")"); getConfiguredTarget(" assertNoEvents(); }
Source:
protected void executeCommand() { UpdateNicsVmInterfaceParametersFactory parameters = calculateRequiredParameters(getExistingNics()); invokeActionType(VdcActionType.AddVmInterface, parameters.createVnicParameters); invokeActionType(VdcActionType.UpdateVmInterface, parameters.updateVnicParameters); invokeActionType(VdcActionType.RemoveVmInterface, parameters.removeVnicParameters); if (getParameters().reorderNics) { VmOperationParameterBase reorderParams = new VmOperationParameterBase(getParameters().vmId); runInternalAction(VdcActionType.ReorderVmNics, reorderParams); } getReturnValue().setSucceeded(true); }

Target:
protected void executeCommand() { UpdateNicsVmInterfaceParametersFactory parametersFactory = createUpdateNicsVmInterfaceParametersFactory(); invokeActionType(VdcActionType.AddVmInterface, parametersFactory.createCreateVnicParameters()); invokeActionType(VdcActionType.UpdateVmInterface, parametersFactory.createUpdateVnicParameters()); invokeActionType(VdcActionType.RemoveVmInterface, parametersFactory.createRemoveVnicParameters()); if (getParameters().reorderNics) { VmOperationParameterBase reorderParams = new VmOperationParameterBase(getParameters().vmId); runInternalAction(VdcActionType.ReorderVmNics, reorderParams); } getReturnValue().setSucceeded(true); }
Source:
public void invalidate(final Collection<String> geocodes) { if (storedOverlay != null) { storedOverlay.invalidate(geocodes); } if (liveOverlay != null) { liveOverlay.invalidate(geocodes); } if (wpOverlay != null) { final Set<Geocache> baseCaches = DataStore.loadCaches(geocodes, LoadFlags.LOAD_WAYPOINTS); final Collection<String> invalidWpCodes = new ArrayList<String>(); for (final Geocache cache : baseCaches) { final List<Waypoint> wl = cache.getWaypoints(); for (final Waypoint w : wl) { invalidWpCodes.add(w.getGpxId()); } } wpOverlay.invalidate(invalidWpCodes); } }

Target:
public void invalidate(final Collection<String> geocodes) { if (storedOverlay != null) { storedOverlay.invalidate(geocodes); } if (liveOverlay != null) { liveOverlay.invalidate(geocodes); } if (wpOverlay != null) { wpOverlay.invalidateWaypoints(geocodes); } }
Source:
public void checkHandlesMoveColumnsToWithMultipleMetadata() throws ModelSynchronizer.MoveColumnVetoException { final MoveColumnToMetaData md0 = mock(MoveColumnToMetaData.class); final MoveColumnToMetaData md1 = mock(MoveColumnToMetaData.class); final AttributeColumnSynchronizer synchronizer = new AttributeColumnSynchronizer(); when(md0.getColumn()).thenReturn(mock(AttributeCol52.class)); when(md1.getColumn()).thenReturn(mock(AttributeCol52.class)); assertFalse(synchronizer.handlesMoveColumnsTo(new ArrayList<MoveColumnToMetaData>() {{ add(md0); add(md1); }})); }

Target:
public void checkHandlesMoveColumnsToWithMultipleMetadata() throws ModelSynchronizer.MoveColumnVetoException { final MoveColumnToMetaData md0 = mock(MoveColumnToMetaData.class); final MoveColumnToMetaData md1 = mock(MoveColumnToMetaData.class); final AttributeColumnSynchronizer synchronizer = new AttributeColumnSynchronizer(); when(md0.getColumn()).thenReturn(mock(AttributeCol52.class)); when(md1.getColumn()).thenReturn(mock(AttributeCol52.class)); assertFalse(synchronizer.handlesMoveColumnsTo(Arrays.asList(md0, md1))); }
Source:
public boolean isBlockEvictable(long blockId) { boolean pinned = isBlockPinned(blockId); boolean locked = isBlockLocked(blockId); boolean marked = isBlockMarked(blockId); LOG.debug("Block: {}. Pinned: {}, Locked: {}, Marked: {}", blockId, pinned, locked, marked); return !pinned && !locked && !marked; }

Target:
public boolean isBlockEvictable(long blockId) { boolean pinned = isBlockPinned(blockId); boolean locked = isBlockLocked(blockId); boolean marked = isBlockMarked(blockId); boolean isEvictable = !pinned && !locked && !marked; if (!isEvictable) { LOG.debug("Block not evictable: {}. Pinned: {}, Locked: {}, Marked: {}", blockId, pinned, locked, marked); } return isEvictable; }
Source:
public Class<?> getReturnType(Class<?> firstArgumentType) { return Integer.class; }

Target:
public Class<?> getReturnType(Class<?> firstArgumentType) { return Long.class; }
Source:
private InternalObjectNode getDocumentDefinition(String itemId, String partitionKeyValue) { final InternalObjectNode properties = new InternalObjectNode(String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + "}" , itemId, partitionKeyValue)); return properties; }

Target:
private ItemSample getDocumentDefinition(String itemId, String partitionKeyValue) { ItemSample itemSample = new ItemSample(); itemSample.id = itemId; itemSample.mypk = partitionKeyValue; itemSample.sgmts = "[[6519456, 1471916863], [2498434, 1455671440]]"; return itemSample; }
Source:
public void storeMessage(final MessageTree tree, final MessageId id) throws IOException { String domain = id.getDomain(); String key = domain + id.getIpAddress() + id.getTimestamp(); int abs = key.hashCode(); if (abs < 0) { abs = -abs; } int bucketIndex = abs % m_gzipThreads; m_processMessages[bucketIndex]++; LinkedBlockingQueue<MessageItem> items = m_messageQueues.get(bucketIndex); boolean result = items.offer(new MessageItem(tree, id)); if (!result) { m_error++; if (m_error % (CatConstants.ERROR_COUNT * 10) == 0) { m_logger.error("Error when offer message tree to gzip queue! overflow :" + m_error + ". Gzip thread :" + bucketIndex); } m_serverStateManager.addMessageDumpLoss(1); } m_total++; Long value = m_totals.get(domain); if (value == null) { m_totals.put(domain, 1L); } else { m_totals.put(domain, value + 1); } if (m_total % (CatConstants.SUCCESS_COUNT) == 0) { logState(tree); } if (value != null && value % CatConstants.SUCCESS_COUNT == 0) { Long lastTotalSize = m_lastTotalSizes.get(domain); if(lastTotalSize == null){ lastTotalSize = 0L; } double amount = m_totalSizes.get(domain) - lastTotalSize; m_lastTotalSizes.put(domain, m_totalSizes.get(domain)); m_serverStateManager.addMessageSize(domain, amount); m_serverStateManager.addMessageSize(amount); } }

Target:
public void storeMessage(final MessageTree tree, final MessageId id) throws IOException { String domain = id.getDomain(); String key = domain + id.getIpAddress() + id.getTimestamp(); int abs = key.hashCode(); if (abs < 0) { abs = -abs; } int bucketIndex = abs % m_gzipThreads; m_processMessages[bucketIndex]++; LinkedBlockingQueue<MessageItem> items = m_messageQueues.get(bucketIndex); boolean result = items.offer(new MessageItem(tree, id)); if (!result) { m_error++; if (m_error % (CatConstants.ERROR_COUNT * 10) == 0) { m_logger.error("Error when offer message tree to gzip queue! overflow :" + m_error + ". Gzip thread :" + bucketIndex); } m_serverStateManager.addMessageDumpLoss(1); } m_total++; Long value = m_totals.get(domain); if (value == null) { m_totals.put(domain, 1L); } else { m_totals.put(domain, value + 1); } if (m_total % (CatConstants.SUCCESS_COUNT) == 0) { logState(tree); } if (value != null && value % CatConstants.SUCCESS_COUNT == 0) { Long lastTotalSize = m_lastTotalSizes.get(domain); Long totalSize = m_totalSizes.get(domain); if(lastTotalSize == null){ lastTotalSize = 0L; } double amount = totalSize - lastTotalSize; m_lastTotalSizes.put(domain, totalSize); m_serverStateManager.addMessageSize(domain, amount); } }
Source:
public ESat isEntailed() { if (iv.isInstantiated()) { if (!set.envelopeContains(iv.getValue())) { return ESat.FALSE; } else { if (set.kernelContains(iv.getValue())) { return ESat.TRUE; } else { return ESat.UNDEFINED; } } } else { int minVal = iv.getLB(); int maxVal = iv.getUB(); boolean all = true; for (int i = minVal; i <= maxVal; i = iv.nextValue(i)) { if (!set.kernelContains(i)) { all = false; break; } } if (all) { return ESat.TRUE; } for (int i = minVal; i <= maxVal; i = iv.nextValue(i)) { if (set.envelopeContains(i)) { return ESat.UNDEFINED; } } return ESat.FALSE; } }

Target:
public ESat isEntailed() { if (iv.isInstantiated()) { if (!set.envelopeContains(iv.getValue())) { return ESat.FALSE; } else { if (set.kernelContains(iv.getValue())) { return ESat.TRUE; } else { return ESat.UNDEFINED; } } } else { int lb = iv.getLB(); int ub = iv.getUB(); boolean all = true; for (int i = lb; i <= ub; i++) { if (!set.kernelContains(i)) { all = false; break; } } if (all) { return ESat.TRUE; } for (int i = lb; i <= ub; i++) { if (set.envelopeContains(i)) { return ESat.UNDEFINED; } } return ESat.FALSE; } }
Source:
private Path expandPath(Path path) { List<Path> fileDirectories = getFileDirectoriesAsPaths(); Optional<Path> Fpath = FileHelper.expandFilenameAsPath(path.toString(), fileDirectories); if (Fpath.isPresent()) { return Fpath.get(); } else { return path; } }

Target:
private Path expandPath(Path path) { List<Path> fileDirectories = getFileDirectoriesAsPaths(); return FileHelper.expandFilenameAsPath(path.toString(), fileDirectories).orElse(path); }
Source:
static void assertLinesMatch(List<String> expectedLines, List<String> actualLines, String message) { assertLinesMatch(expectedLines, actualLines, () -> message); }

Target:
static void assertLinesMatch(List<String> expectedLines, List<String> actualLines, String message) { assertLinesMatch(expectedLines, actualLines, (Object) message); }
Source:
public void getCandidateApplicationsByCandidateIdShouldThrowIllegalArgumentExceptionWhenCandidateIdIsNull() { given(candidateRepository.findOne(null)).willThrow(IllegalArgumentException.class); statesService.getCandidateApplicationsByCandidateId(null); }

Target:
public void getCandidateApplicationsByCandidateIdShouldThrowIllegalArgumentExceptionWhenCandidateIdIsNull() { statesService.getCandidateApplicationsByCandidateId(null); }
Source:
protected void onDestroy() { if (mFormLoaderTask != null) { mFormLoaderTask.setFormLoaderListener(null); if (mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) { mFormLoaderTask.cancel(true); mFormLoaderTask.destroy(); } } if (mSaveToDiskTask != null) { mSaveToDiskTask.setFormSavedListener(null); if (mSaveToDiskTask.getStatus() == AsyncTask.Status.FINISHED) { mSaveToDiskTask.cancel(false); } } if (mNoGPSReceiver == null) { unregisterReceiver(mNoGPSReceiver); } super.onDestroy(); }

Target:
protected void onDestroy() { if (mFormLoaderTask != null) { mFormLoaderTask.setFormLoaderListener(null); if (mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) { mFormLoaderTask.cancel(true); mFormLoaderTask.destroy(); } } if (mSaveToDiskTask != null) { mSaveToDiskTask.setFormSavedListener(null); if (mSaveToDiskTask.getStatus() == AsyncTask.Status.FINISHED) { mSaveToDiskTask.cancel(false); } } if (mNoGPSReceiver != null) { unregisterReceiver(mNoGPSReceiver); } super.onDestroy(); }
Source:
public Collection<PsiElement> getPsiTargets(PsiElement psiElement) { Collection<PsiElement> targets = new ArrayList<>(); String directiveName = psiElement.getText().substring(1); FileBasedIndexImpl.getInstance().getFilesWithKey( BladeCustomDirectivesStubIndex.KEY, new HashSet<>(Collections.singletonList(directiveName)), virtualFile -> { PsiFile psiFile = PsiManager.getInstance(getProject()).findFile(virtualFile); if(psiFile == null) { return true; } psiFile.acceptChildren(new BladeCustomDirectivesVisitor(hit -> { if(directiveName.equals(hit.second)) { targets.add(hit.first); } })); return true; }, ProjectScope.getAllScope(getProject())); return targets; }

Target:
public Collection<PsiElement> getPsiTargets(PsiElement psiElement) { Collection<PsiElement> targets = new ArrayList<>(); String directiveName = psiElement.getText().substring(1); FileBasedIndex.getInstance().getFilesWithKey( BladeCustomDirectivesStubIndex.KEY, new HashSet<>(Collections.singletonList(directiveName)), virtualFile -> { PsiFile psiFile = PsiManager.getInstance(getProject()).findFile(virtualFile); if(psiFile == null) { return true; } psiFile.acceptChildren(new BladeCustomDirectivesVisitor(hit -> { if(directiveName.equals(hit.second)) { targets.add(hit.first); } })); return true; }, ProjectScope.getAllScope(getProject())); return targets; }
Source:
private List<ShardSpec> determinePartitions( final Interval interval, final int targetPartitionSize, final QueryGranularity queryGranularity ) throws IOException { log.info("Determining partitions for interval[%s] with targetPartitionSize[%d]", interval, targetPartitionSize); final FirehoseFactory firehoseFactory = ingestionSchema.getIOConfig().getFirehoseFactory(); HyperLogLogCollector collector = HyperLogLogCollector.makeLatestCollector(); try (Firehose firehose = firehoseFactory.connect(ingestionSchema.getDataSchema().getParser())) { while (firehose.hasMore()) { final InputRow inputRow = firehose.nextRow(); if (interval.contains(inputRow.getTimestampFromEpoch())) { final List<Object> groupKey = Rows.toGroupKey( queryGranularity.truncate(inputRow.getTimestampFromEpoch()), inputRow ); collector.add( hashFunction.hashBytes(jsonMapper.writeValueAsBytes(groupKey)) .asBytes() ); } } } final double numRows = collector.estimateCardinality(); log.info("Estimated approximately [%,f] rows of data.", numRows); int numberOfShards = (int) Math.ceil(numRows / targetPartitionSize); if ((double) numberOfShards > numRows) { numberOfShards = (int) numRows; } log.info("Will require [%,d] shard(s).", numberOfShards); final List<ShardSpec> shardSpecs = Lists.newArrayList(); if (numberOfShards == 1) { shardSpecs.add(new NoneShardSpec()); } else { for (int i = 0; i < numberOfShards; ++i) { shardSpecs.add( new HashBasedNumberedShardSpec( i, numberOfShards, HadoopDruidIndexerConfig.jsonMapper ) ); } } return shardSpecs; }

Target:
private List<ShardSpec> determinePartitions( final Interval interval, final int targetPartitionSize, final QueryGranularity queryGranularity ) throws IOException { log.info("Determining partitions for interval[%s] with targetPartitionSize[%d]", interval, targetPartitionSize); final FirehoseFactory firehoseFactory = ingestionSchema.getIOConfig().getFirehoseFactory(); HyperLogLogCollector collector = HyperLogLogCollector.makeLatestCollector(); try (Firehose firehose = firehoseFactory.connect(ingestionSchema.getDataSchema().getParser())) { while (firehose.hasMore()) { final InputRow inputRow = firehose.nextRow(); if (interval.contains(inputRow.getTimestampFromEpoch())) { final List<Object> groupKey = Rows.toGroupKey( queryGranularity.truncate(inputRow.getTimestampFromEpoch()), inputRow ); collector.add( hashFunction.hashBytes(jsonMapper.writeValueAsBytes(groupKey)).asBytes() ); } } } final double numRows = collector.estimateCardinality(); log.info("Estimated approximately [%,f] rows of data.", numRows); int numberOfShards = (int) Math.ceil(numRows / targetPartitionSize); if ((double) numberOfShards > numRows) { numberOfShards = (int) numRows; } log.info("Will require [%,d] shard(s).", numberOfShards); final List<ShardSpec> shardSpecs = Lists.newArrayList(); if (numberOfShards == 1) { shardSpecs.add(new NoneShardSpec()); } else { for (int i = 0; i < numberOfShards; ++i) { shardSpecs.add(new HashBasedNumberedShardSpec(i, numberOfShards, jsonMapper)); } } return shardSpecs; }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_authentication); getUsernameEdit().setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { getUsernameEdit().setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean b) { if (b) { imageView.setImageDrawable(null); } } }); return false; } }); getPasswordEdit().setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { getPasswordEdit().setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean b) { if (b) { imageView.setImageDrawable(null); } } }); return false; } }); setUpInjections(); setUpAuthentication(); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_authentication); imageView = (ImageView) findViewById(R.id.logo); getUsernameEdit().setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { FocusListener(view); return false; } }); getPasswordEdit().setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { FocusListener(view); return false; } }); setUpInjections(); setUpAuthentication(); }
Source:
private Optional<Activity> findOverlappingActivitySameApp(ActivityPayload payload, GoalDto matchingGoal) { Optional<DayActivity> dayActivity = findExistingDayActivity(payload, matchingGoal.getGoalId()); if (!dayActivity.isPresent()) { return Optional.empty(); } List<Activity> overlappingOfSameApp = activityRepository.findOverlappingOfSameApp(dayActivity.get(), payload.deviceAnonymizedId, matchingGoal.getActivityCategoryId(), payload.application.orElse(null), payload.startTime.toLocalDateTime(), payload.endTime.toLocalDateTime()); if (overlappingOfSameApp.isEmpty()) { return Optional.empty(); } else if (overlappingOfSameApp.size() == 1) { return Optional.of(overlappingOfSameApp.get(0)); } else { String relatedTo = payload.application.isPresent() ? MessageFormat.format("same app ''{0}'' activity", payload.application.get()) : "network activity"; String overlappingActivities = overlappingOfSameApp.stream() .map(overlappingActivity -> overlappingActivity.toString()).collect(Collectors.joining(", ")); logger.warn( "Multiple overlapping activities of {0} found. The payload has start time {1} and end time {2}. The overlapping activities are: {3}. The day activity ID is {4} and the activity category ID is {5}.", relatedTo, payload.startTime.toLocalDateTime(), payload.endTime.toLocalDateTime(), overlappingActivities, dayActivity.get().getId(), matchingGoal.getActivityCategoryId()); return Optional.of(overlappingOfSameApp.get(0)); } }

Target:
private Optional<Activity> findOverlappingActivitySameApp(ActivityPayload payload, GoalDto matchingGoal) { Optional<DayActivity> dayActivity = findExistingDayActivity(payload, matchingGoal.getGoalId()); if (!dayActivity.isPresent()) { return Optional.empty(); } List<Activity> overlappingOfSameApp = activityRepository.findOverlappingOfSameApp(dayActivity.get(), payload.deviceAnonymizedId, matchingGoal.getActivityCategoryId(), payload.application.orElse(null), payload.startTime.toLocalDateTime(), payload.endTime.toLocalDateTime()); if (overlappingOfSameApp.isEmpty()) { return Optional.empty(); } if (overlappingOfSameApp.size() == 1) { return Optional.of(overlappingOfSameApp.get(0)); } String overlappingActivitiesKind = payload.application.isPresent() ? MessageFormat.format("app activities of ''{0}''", payload.application.get()) : "network activities"; String overlappingActivities = overlappingOfSameApp.stream().map(overlappingActivity -> overlappingActivity.toString()) .collect(Collectors.joining(", ")); logger.warn( "Multiple overlapping found. The payload has start time and end time {}. The day activity ID is and the activity category ID is {}. The overlapping activities are: {}.", overlappingActivitiesKind, payload.startTime.toLocalDateTime(), payload.endTime.toLocalDateTime(), dayActivity.get().getId(), matchingGoal.getActivityCategoryId(), overlappingActivities); return Optional.of(overlappingOfSameApp.get(0)); }