auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected IStatus validateIfJUnitProject() { JUnitStatus status= new JUnitStatus(); IPackageFragmentRoot root= getPackageFragmentRoot(); if (root != null) { try { IJavaProject project= root.getJavaProject(); if (project.exists()) { if (null == fJUnitVersion) { <START> if (project.findType(JUnitCorePlugin.TEST_SUPERCLASS_NAME) == null) { <END> status.setWarning(WizardMessages.NewTestCaseWizardPageOne_error_junitNotOnbuildpath); return status; } } else switch (fJUnitVersion) { case VERSION_5: if (!JUnitStubUtility.is18OrHigher(project)) { status.setError(WizardMessages.NewTestCaseWizardPageOne_error_java8required); return status; } if (project.findType(JUnitCorePlugin.JUNIT5_TESTABLE_ANNOTATION_NAME) == null) { status.setWarning(WizardMessages.NewTestCaseWizardPageOne__error_junit5NotOnbuildpath); return status; } break; case VERSION_4: if (!JUnitStubUtility.is50OrHigher(project)) { status.setError(WizardMessages.NewTestCaseWizardPageOne_error_java5required); return status; } if (project.findType(JUnitCorePlugin.JUNIT4_ANNOTATION_NAME) == null) { status.setWarning(WizardMessages.NewTestCaseWizardPageOne__error_junit4NotOnbuildpath); return status; } break; default: if (project.findType(JUnitCorePlugin.TEST_SUPERCLASS_NAME) == null) { status.setWarning(WizardMessages.NewTestCaseWizardPageOne_error_junitNotOnbuildpath); return status; } break; } } } catch (JavaModelException e) { } } return status; }</code><technical_language>This is another case null logic default logic combined in place boolean noMatch= false; if (fJunitVersion != null) { switch .... default: noMatch= true; } if (noMatch) { default/null logic }</technical_language>

Target:
protected IStatus validateIfJUnitProject() { JUnitStatus status= new JUnitStatus(); IPackageFragmentRoot root= getPackageFragmentRoot(); if (root != null) { try { IJavaProject project= root.getJavaProject(); if (project.exists()) { boolean noMatch= false; if (fJUnitVersion != null) { switch (fJUnitVersion) { case VERSION_5: if (!JUnitStubUtility.is18OrHigher(project)) { status.setError(WizardMessages.NewTestCaseWizardPageOne_error_java8required); return status; } if (project.findType(JUnitCorePlugin.JUNIT5_TESTABLE_ANNOTATION_NAME) == null) { status.setWarning(WizardMessages.NewTestCaseWizardPageOne__error_junit5NotOnbuildpath); return status; } break; case VERSION_4: if (!JUnitStubUtility.is50OrHigher(project)) { status.setError(WizardMessages.NewTestCaseWizardPageOne_error_java5required); return status; } if (project.findType(JUnitCorePlugin.JUNIT4_ANNOTATION_NAME) == null) { status.setWarning(WizardMessages.NewTestCaseWizardPageOne__error_junit4NotOnbuildpath); return status; } break; default: noMatch= true; break; } if (noMatch) { if (project.findType(JUnitCorePlugin.TEST_SUPERCLASS_NAME) == null) { status.setWarning(WizardMessages.NewTestCaseWizardPageOne_error_junitNotOnbuildpath); return status; } } } } } catch (JavaModelException e) { } } return status; }
Source:
<code>public void writeHeader(VCFHeader header) { if (isHeaderWritten) { <START> throw new IllegalStateException("Header is already written"); <END> } setVcfHeader(header); try { final ByteArrayOutputStream capture = new ByteArrayOutputStream(); final OutputStreamWriter writer = new OutputStreamWriter(capture); this.header = VCFWriter.writeHeader(header, writer, VCFWriter.getVersionLine(), "BCF2 stream"); writer.append('\0'); writer.close(); final byte[] headerBytes = capture.toByteArray(); new BCFVersion(MAJOR_VERSION, MINOR_VERSION).write(outputStream); BCF2Type.INT32.write(headerBytes.length, outputStream); outputStream.write(headerBytes); isHeaderWritten = true; } catch (IOException e) { throw new RuntimeIOException("BCF2 stream: Got IOException while trying to write BCF2 header", e); } }</code><technical_language>This code block redundant - next statement is a call setVcfheader, handles this</technical_language>

Target:
public void writeHeader(VCFHeader header) { setVCFHeader(header); try { final ByteArrayOutputStream capture = new ByteArrayOutputStream(); final OutputStreamWriter writer = new OutputStreamWriter(capture); this.header = VCFWriter.writeHeader(this.header, writer, VCFWriter.getVersionLine(), "BCF2 stream"); writer.append('\0'); writer.close(); final byte[] headerBytes = capture.toByteArray(); new BCFVersion(MAJOR_VERSION, MINOR_VERSION).write(outputStream); BCF2Type.INT32.write(headerBytes.length, outputStream); outputStream.write(headerBytes); outputHasBeenWritten = true; } catch (IOException e) { throw new RuntimeIOException("BCF2 stream: Got IOException while trying to write BCF2 header", e); } }
Source:
<code>public String getFullNameOfWorkspacesListItem(int index) { String itemXpath = String.format(Locators.WORKSPACE_LIST_ITEM, index); String fullNameXpath = itemXpath + " return seleniumWebDriverHelper <START> .waitVisibility(By.xpath(fullNameXpath)) <END> .getAttribute("id") .replace("ws-full-name-", ""); }</code><technical_language>simplified seleniumWebDriverHelper.waitVisibilityAndGetAttribute() method</technical_language>

Target:
public String getFullNameOfWorkspacesListItem(int index) { String itemXpath = String.format(Locators.WORKSPACE_LIST_ITEM, index); String fullNameXpath = itemXpath + " return seleniumWebDriverHelper .waitVisibilityAndGetAttribute(By.xpath(fullNameXpath), "id") .replace("ws-full-name-", ""); }
Source:
<code>public void setAlignment(String value) { if (privateAlignment == null || !privateAlignment.equals(value)) { privateAlignment = value; <START> onPropertyChanged(new PropertyChangedEventArgs("Alignment")); END> } }</code><technical_language>if privateAlignment is null received is null, this called unneeded (nothing changed)</technical_language>

Target:
public void setAlignment(String value) { if (!StringHelper.stringsEqual(privateAlignment, value)) { privateAlignment = value; onPropertyChanged(new PropertyChangedEventArgs("Alignment")); } }
Source:
<code>protected int doWork() { final SamReader reader = SamReaderFactory.makeDefault().referenceSequence(REFERENCE_SEQUENCE).open(INPUT); final SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(reader.getFileHeader(), true, OUTPUT); writer.setProgressLogger( new ProgressLogger(log, (int) 1e7, "Wrote", "records")); OverlapDetector overlapDetector = getOverlapDetectorFromIntervalListFile(INTERVAL_LIST, 0, 0); for (SAMRecord rec : reader) { if (!rec.getReadUnmappedFlag() && (overlapDetector == null || overlapDetector.overlapsAny(rec))) { setOATag(rec, OVERWRITE_TAG); } writer.addAlignment(rec); } <START> CloserUtil.close(reader); <END> writer.close(); return 0; }</code><technical_language>Instead of closing this, I suggest a try-with-resources: java try(final SamReader reader = SamReaderFactory.makeDefault().referenceSequence(REFERENCE_SEQUENCE).open(INPUT)) { ... } include writer there..</technical_language>

Target:
protected int doWork() { try (final SamReader reader = SamReaderFactory.makeDefault().referenceSequence(REFERENCE_SEQUENCE).open(IOUtil.getPath(INPUT)); final SAMFileWriter writer = new SAMFileWriterFactory().makeWriter(reader.getFileHeader(), true, IOUtil.getPath(OUTPUT), REFERENCE_SEQUENCE)) { writer.setProgressLogger( new ProgressLogger(log, (int) 1e7, "Wrote", "records")); final OverlapDetector overlapDetector = getOverlapDetectorFromIntervalListFile(INTERVAL_LIST, 0, 0); for (final SAMRecord rec : reader) { if (overlapDetector == null || overlapDetector.overlapsAny(rec)) { setOATag(rec); } writer.addAlignment(rec); } } catch (IOException e) { log.error(e); return 1; } return 0; }
Source:
<code>public Response afterLRA(@HeaderParam(LRA.LRA_HTTP_ENDED_CONTEXT_HEADER) URI endedLRAId) { <START> if (afterLRACounter.getAndIncrement() < 2) { <END> return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } return Response.ok().build(); }</code><technical_language>@tomjenkinson no, start failing. recovery replayed times</technical_language>

Target:
public Response afterLRA(@HeaderParam(LRA.LRA_HTTP_ENDED_CONTEXT_HEADER) URI endedLRAId) { if (afterLRACounter.getAndIncrement() < 1) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } return Response.ok().build(); }
Source:
<code>private static void copyFile(File from, File to, Filter onlyCopy) throws IOException { if (!onlyCopy.isRequired(from)) { return; } try (OutputStream out = new FileOutputStream(to)) { final long copied = Files.copy(from.toPath(), out); final long length = from.length(); if (copied != length) { <START> throw new IOException("Could not transfer all bytes of " + from.toPath()); <END> } } }</code><technical_language>reasonable want include 'to' location</technical_language>

Target:
private static void copyFile(File from, File to, Filter onlyCopy) throws IOException { if (!onlyCopy.isRequired(from)) { return; } try (OutputStream out = new FileOutputStream(to)) { final long copied = Files.copy(from.toPath(), out); final long length = from.length(); if (copied != length) { throw new IOException("Could not transfer all bytes from " + from + " to " + to); } } }
Source:
<code>public EmbeddedQuery(AdvancedCache<?, ?> cache, String jpaQuery, Class<? extends Matcher> matcherImplClass) { <START> retriever = cache.getComponentRegistry().getComponent(EntryRetriever.class); <END> this.jpaQuery = jpaQuery; this.matcherImplClass = matcherImplClass; }</code><technical_language>I instead planning filterEntries method AdvancedCache. in list method try (CloseableIterable<Map.Entry<Object, Object>> myIterable = cache.getAdvancedCache().filterEntries(filter).converter(filter)) { for (Map.Entry<Object, Object> entry : myIterable) { .... } } catch (IOException e) { // exception }</technical_language>

Target:
public EmbeddedQuery(AdvancedCache<?, ?> cache, String jpaQuery, Class<? extends Matcher> matcherImplClass) { this.cache = cache; this.jpaQuery = jpaQuery; this.matcherImplClass = matcherImplClass; }
Source:
<code>public static void getObject_test6() throws Exception { if (!mintEnv) { System.out.println("Test: getObject(String bucketName, String objectName) zero size object"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(0)) { client.putObject(bucketName, objectName, is, 0, nullContentType); } try { client.getObject(bucketName, objectName).close(); } catch (final ErrorResponseException e) { if (!e.toString().contains("message=The requested range is not satisfiable")) { throw e; } <START> } <END> client.removeObject(bucketName, objectName); mintSuccessLog("getObject(String bucketName, String objectName)", null, startTime); } catch (Exception e) { mintFailedLog("getObject(String bucketName, String objectName)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } }</code><technical_language>Unable understand this change. is required for this test</technical_language>

Target:
public static void getObject_test6() throws Exception { if (!mintEnv) { System.out.println("Test: getObject(String bucketName, String objectName) zero size object"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(0)) { client.putObject(bucketName, objectName, is, 0, nullContentType); } client.getObject(bucketName, objectName) .close(); client.removeObject(bucketName, objectName); mintSuccessLog("getObject(String bucketName, String objectName)", null, startTime); } catch (Exception e) { mintFailedLog("getObject(String bucketName, String objectName)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } }
Source:
<code>public Long findPublishedEntries(String username) { <START> final Query query = namedQuery("io.dockstore.webservice.core.User.countPublishedEntries").setParameter("username", username); <END> return (Long)query.uniqueResult(); }</code><technical_language>this query is written (a count), I get a null result I cast to/return a long</technical_language>

Target:
public long findPublishedEntries(String username) { final Query query = namedQuery("io.dockstore.webservice.core.User.countPublishedEntries").setParameter("username", username); return (long)query.uniqueResult(); }
Source:
<code>public byte[] contentMD5() { <START> return contentMD5; <END> }</code><technical_language>clone this return</technical_language>

Target:
public byte[] contentMD5() { return ImplUtils.clone(contentMD5); }
Source:
<code>public void testEqualsAndHashCode(final CigarElement element, final Object other, final boolean isEquals) { Assert.assertEquals(element.equals(other), isEquals); <START> Assert.assertEquals(element.hashCode() == other.hashCode(), isEquals); <END> }</code><technical_language>I this test technically correct. for A != B A.hashCode() == B.hashCode(). I correct assertion for hashCode part be. if( element.equals(other)) { Assert.assertEquals(element.hashCode(), other.hashCode()); }</technical_language>

Target:
public void testEqualsAndHashCode(final CigarElement element, final Object other, final boolean isEquals) { Assert.assertEquals(element.equals(other), isEquals); if (isEquals) { Assert.assertEquals(element.hashCode(), other.hashCode()); } }
Source:
<code><START> protected Collection<Artifact> setRelationsOfType(AtsArtifactConfigCache cache, Artifact artifact, Collection<? extends IAtsObject> atsObjects, IRelationTypeSide side) throws OseeCoreException { <END> List<Artifact> newArts = new ArrayList<Artifact>(); for (IAtsObject version : atsObjects) { Artifact verArt = cache.getSoleArtifact(version); newArts.add(verArt); } artifact.setRelations(side, newArts); return newArts; }</code><technical_language>Suggest check artifact != null</technical_language>

Target:
protected Collection<Artifact> setRelationsOfType(AtsArtifactConfigCache cache, Artifact artifact, Collection<? extends IAtsObject> atsObjects, IRelationTypeSide side) throws OseeCoreException { Conditions.checkNotNull(artifact, "artifact"); List<Artifact> newArts = new ArrayList<Artifact>(); for (IAtsObject version : atsObjects) { Artifact verArt = cache.getSoleArtifact(version); newArts.add(verArt); } artifact.setRelations(side, newArts); return newArts; }
Source:
<code>public void queueEvent(Event event) { <START> if (log.isDebugEnabled()) { <END> log.debug("Queuing event: " + event); } getEventQueue().add(event); }</code><technical_language>Logback, need types of guards. java log.debug("Queing event: {}", event) do trick penalty in performance</technical_language>

Target:
public void queueEvent(Event event) { log.debug("Queuing event: " + event); getEventQueue().add(event); }
Source:
<code><START> public void setPageBufferClientMaxCallbackThreads(int pageBufferClientMaxCallbackThreads) <END> { this.pageBufferClientMaxCallbackThreads = pageBufferClientMaxCallbackThreads; }</code><technical_language>need update TestExchangeClientConfig for this</technical_language>

Target:
public ExchangeClientConfig setPageBufferClientMaxCallbackThreads(int pageBufferClientMaxCallbackThreads) { this.pageBufferClientMaxCallbackThreads = pageBufferClientMaxCallbackThreads; return this; }
Source:
<code>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); <START> if (getArguments() != null) { <END> fieldName = getArguments().getString(NAME); listener.setActionBarTitle(fieldName); } }</code><technical_language>in places call getArguments() in a conditional value. I assume this getArguments change out you, is a costly method call. reader, hard that</technical_language>

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { fieldName = getArguments().getString(NAME); changeListener.setActionBarTitle(fieldName); } }
Source:
<code><START> void setTopics(ArrayList<String> topics) { <END> this.topics = topics; }</code><technical_language>fix issue suggestion public void setTopics(ArrayList<String> topics) {</technical_language>

Target:
public void setTopics(ArrayList<String> topics) { this.topics = topics; }
Source:
<code>private VM mockVm(VMStatus vmStatus) { vm.setStatus(vmStatus); vm.setId(vmId); vm.setRunOnVds(Guid.newGuid()); when(vmDao.get(command.getParameters().getVmId())).thenReturn(vm); <START> return vm; <END> }</code><technical_language>If wrong, method return void, other mockXYZ methods. return is used</technical_language>

Target:
private void mockVm(VMStatus vmStatus) { vm.setStatus(vmStatus); vm.setId(vmId); vm.setRunOnVds(Guid.newGuid()); when(vmDao.get(command.getParameters().getVmId())).thenReturn(vm); }
Source:
<code>protected boolean canDoAction() { if (!(!Guid.Empty.equals(getVds().getstorage_pool_id()) <START> && DbFacade.getInstance().getVdsSpmIdMapDao().get(getVdsId()) == null)) { <END> return false; } vds_spm_id_mapList = DbFacade.getInstance().getVdsSpmIdMapDao().getAll( getVds().getstorage_pool_id()); if (vds_spm_id_mapList.size() >= Config.<Integer> GetValue(ConfigValues.MaxNumberOfHostsInStoragePool)) { VdcFault fault = new VdcFault(); fault.setMessage("The maximum number of Hosts allowed in the Data Center has been reached"); getReturnValue().setFault(fault); return false; } return true; }</code><technical_language>consider applying De Morgan's law here, more readable</technical_language>

Target:
protected boolean canDoAction() { if (Guid.Empty.equals(getVds().getstorage_pool_id()) || DbFacade.getInstance().getVdsSpmIdMapDao().get(getVdsId()) != null) { return false; } vds_spm_id_mapList = DbFacade.getInstance().getVdsSpmIdMapDao().getAll( getVds().getstorage_pool_id()); if (vds_spm_id_mapList.size() >= Config.<Integer> GetValue(ConfigValues.MaxNumberOfHostsInStoragePool)) { VdcFault fault = new VdcFault(); fault.setError(VdcBllErrors.ReachedMaxNumberOfHostsInDC); fault.setMessage(Backend.getInstance() .getVdsErrorsTranslator() .TranslateErrorTextSingle(fault.getError().toString())); getReturnValue().setFault(fault); return false; } return true; }
Source:
<code>private void traceRequest(final RequestLogInfo requestLogInfo, final int statusCode, final Long timeSpentMs, final Span publishingSpan) { if (!isPublishingRequest(requestLogInfo)) { return; } final Scope scope = TracingService.activateSpan(publishingSpan, false); String sloBucket = "5K-50K"; if (requestLogInfo.contentLength > 50000 || requestLogInfo.contentLength == 0) { sloBucket = ">50K"; } else if (requestLogInfo.contentLength < 5000) { sloBucket = "<5K"; } final String eventType = requestLogInfo.path.substring("/event-types/".length(), requestLogInfo.path.lastIndexOf("/events")); TracingService.setCustomTags(scope, ImmutableMap.<String, Object>builder() .put("event_type", eventType) .put("http.status_code", statusCode) .put("slo_bucket", sloBucket) .put("content_length", requestLogInfo.contentLength) <START> .put("error", statusCode == 207 || statusCode >= 500).build()); <END> }</code><technical_language>error set in controller</technical_language>

Target:
private void traceRequest(final RequestLogInfo requestLogInfo, final int statusCode, final Long timeSpentMs, final Span publishingSpan) { if (!isPublishingRequest(requestLogInfo)) { return; } final Scope scope = TracingService.activateSpan(publishingSpan, false); String sloBucket = "5K-50K"; if (requestLogInfo.contentLength > 50000 || requestLogInfo.contentLength == 0) { sloBucket = ">50K"; } else if (requestLogInfo.contentLength < 5000) { sloBucket = "<5K"; } final String eventType = requestLogInfo.path.substring("/event-types/".length(), requestLogInfo.path.lastIndexOf("/events")); TracingService.setCustomTags(scope, ImmutableMap.<String, Object>builder() .put("event_type", eventType) .put("http.status_code", statusCode) .put("slo_bucket", sloBucket) .put("content_length", requestLogInfo.contentLength).build()); }
Source:
<code>private void checkFieldType(int field, Set<Type> expectedTypes) { <START> checkArgument(expectedTypes.contains(getType(field)), "Field %s expected type inconsistent with %s", field, getType(field)); <END> }</code><technical_language>Field %s unexpected type %s</technical_language>

Target:
private void checkFieldType(int field, Set<Type> expectedTypes) { checkArgument(expectedTypes.contains(getType(field)), "Field %s has unexpected type %s", field, getType(field)); }
Source:
<code>public <T> T makeRequest(Invocation<T> invocation, boolean countForTx) throws OperationLogic.RequestException { if (recording()) { <START> requests = stats.requestSet(); <END> } if (useTransactions && txRemainingOperations <= 0) { try { ongoingTx = stage.transactional.getTransaction(); logic.transactionStarted(); Request beginRequest = startTransaction(); if (requests != null && beginRequest != null) { requests.add(beginRequest); } txRemainingOperations = stage.transactionSize; } catch (TransactionException e) { throw new OperationLogic.RequestException(e); } } T result = null; Exception exception = null; Request request = nextRequest(); Operation operation = isUseTransactions() ? invocation.txOperation() : invocation.operation(); try { result = invocation.invoke(); succeeded(request, operation); Blackhole.consume(result); if (countForTx) { txRemainingOperations--; } } catch (Exception e) { failed(request, operation); log.warn("Error in request", e); txRemainingOperations = 0; exception = e; } endTransactionAndRegisterStats(useTransactions && txRemainingOperations <= 0, request); if (exception != null) { throw new OperationLogic.RequestException(exception); } return result; }</code><technical_language>requestSet created start a transaction - ongoing transaction multiple writes do request</technical_language>

Target:
public <T> T makeRequest(Invocation<T> invocation, boolean countForTx) throws OperationLogic.RequestException { if (useTransactions && txRemainingOperations <= 0) { try { ongoingTx = stage.transactional.getTransaction(); logic.transactionStarted(); if (recording()) { requests = stats.requestSet(); } Request beginRequest = startTransaction(); if (requests != null && beginRequest != null) { requests.add(beginRequest); } txRemainingOperations = stage.transactionSize; } catch (TransactionException e) { throw new OperationLogic.RequestException(e); } } T result = null; Exception exception = null; Request request = nextRequest(); try { result = invocation.invoke(); succeeded(request, invocation.operation()); Blackhole.consume(result); if (countForTx) { txRemainingOperations--; } } catch (Exception e) { failed(request, invocation.operation()); log.warn("Error in request", e); txRemainingOperations = 0; exception = e; } if (requests != null && request != null && recording()) { requests.add(request); } if (useTransactions && txRemainingOperations <= 0) { endTransactionAndRegisterStats(stage.isSingleTxType() ? invocation.txOperation() : null); } if (exception != null) { throw new OperationLogic.RequestException(exception); } return result; }
Source:
<code>public String openDialog(String title) { if (this.m_parent == null) { this.m_parent = new Frame(); } if (this.m_fileDialog == null) { this.m_fileDialog = new FileDialog(this.m_parent, title, 0); } this.m_fileDialog.setVisible(true); this.m_fileDialog.toFront(); String file = this.m_fileDialog.getFile(); String directory = this.m_fileDialog.getDirectory(); this.m_fileDialog.setVisible(false); this.m_parent.setVisible(false); if ((file == null) || (file.length() == 0)) { return "{success:false,path:\"\"}"; } else { String path = directory + file; path = path.replace("\\", "\\\\"); <START> return "{\"success\":\"true\",\"path\":\"" + path + "\"}"; <END> } }</code><technical_language>JSONObject</technical_language>

Target:
public String openDialog(String title) { if (this.m_parent == null) { this.m_parent = new Frame(); } if (this.m_fileDialog == null) { this.m_fileDialog = new FileDialog(this.m_parent, title, 0); } this.m_fileDialog.setVisible(true); this.m_fileDialog.toFront(); String file = this.m_fileDialog.getFile(); String directory = this.m_fileDialog.getDirectory(); this.m_fileDialog.setVisible(false); this.m_parent.setVisible(false); if ((file == null) || (file.length() == 0)) { return "{\"success\":\"false\",\"path\":\"\"}"; } else { String path = directory + file; path = path.replace("\\", "\\\\"); return "{\"success\":\"true\",\"path\":\"" + path + "\"}"; } }
Source:
<code>public DataBucket(String commandId, long count, byte[] data) { <START> this(commandId, count, data, new byte[]{}, new byte[]{}); <END> }</code><technical_language>new byte[]{} -> new byte[0]</technical_language>

Target:
public DataBucket(String commandId, long count, byte[] data) { this(commandId, count, data, new byte[0], new byte[0]); }
Source:
<code>private PreparedStatement prepareStatementFromFieldsAndTableName() { StringBuilder queryfields = new StringBuilder(); StringBuilder values = new StringBuilder(); for (FieldInfo fieldInfo : fieldInfos) { if (queryfields.length() == 0) { queryfields.append(fieldInfo.getColumnName()); values.append("?"); } else { queryfields.append(",").append(fieldInfo.getColumnName()); values.append(",").append("?"); } } <START> String statement = "INSERT INTO " + store.keyspace + "." + tablename + " (" + queryfields.toString() + ") " + "VALUES (" + values.toString() + ");"; <END> return store.getSession().prepare(statement); }</code><technical_language>a check for null tablename, @NotNull is removed</technical_language>

Target:
private PreparedStatement prepareStatementFromFieldsAndTableName() { if (tablename == null || tablename.length() == 0) { throw new RuntimeException("Please sepcify query or table name."); } StringBuilder queryfields = new StringBuilder(); StringBuilder values = new StringBuilder(); for (FieldInfo fieldInfo : fieldInfos) { if (queryfields.length() == 0) { queryfields.append(fieldInfo.getColumnName()); values.append("?"); } else { queryfields.append(",").append(fieldInfo.getColumnName()); values.append(",").append("?"); } } String statement = "INSERT INTO " + store.keyspace + "." + tablename + " (" + queryfields.toString() + ") " + "VALUES (" + values.toString() + ");"; return store.getSession().prepare(statement); }
Source:
<code>public void requestBannerAd(Context context, MediationBannerListener listener, Bundle serverParameters, AdSize adSize, MediationAdRequest adRequest, Bundle mediationExtras) { Log.v(TAG, "Requesting Unity Ads Banner"); bannerListener = listener; String gameId = serverParameters.getString(KEY_GAME_ID); bannerPlacementId = serverParameters.getString(KEY_PLACEMENT_ID); if (!isValidIds(gameId, bannerPlacementId)) { if (bannerListener != null) { bannerListener.onAdFailedToLoad(UnityAdapter.this, AdRequest.ERROR_CODE_INVALID_REQUEST); } return; } if (context == null || !(context instanceof Activity)) { Log.e(TAG, "Context is not an Activity. Unity Ads requires an Activity context to load " + "ads."); if (bannerListener != null) { bannerListener.onAdFailedToLoad(UnityAdapter.this, AdRequest.ERROR_CODE_INVALID_REQUEST); } return; } Activity activity = (Activity) context; UnitySingleton.getInstance().initializeUnityAds(activity, gameId); <START> UnityBannerSize size = new UnityBannerSize(adSize.getWidth(), adSize.getHeight()); <END> if (mBannerView == null){ mBannerView = new BannerView((Activity)context, bannerPlacementId, size); } mBannerView.setListener(this); mBannerView.load(); }</code><technical_language>@jindoujiao Unity SDK is failing banner ad width is 320, instead throws error log, invalid adsize, is returning a banner Ad width 320. Tested requesting a banner Ad Size 250X40, I able get banner ad Size. Is this expected ? If case I ad a case map width 320 320 width</technical_language>

Target:
public void requestBannerAd(Context context, MediationBannerListener listener, Bundle serverParameters, AdSize adSize, MediationAdRequest adRequest, Bundle mediationExtras) { Log.v(TAG, "Requesting Unity Ads Banner"); bannerListener = listener; String gameId = serverParameters.getString(KEY_GAME_ID); bannerPlacementId = serverParameters.getString(KEY_PLACEMENT_ID); if (!isValidIds(gameId, bannerPlacementId)) { if (bannerListener != null) { bannerListener.onAdFailedToLoad(UnityAdapter.this, AdRequest.ERROR_CODE_INVALID_REQUEST); } return; } if (context == null || !(context instanceof Activity)) { Log.e(TAG, "Context is not an Activity. Unity Ads requires an Activity context to load " + "ads."); if (bannerListener != null) { bannerListener.onAdFailedToLoad(UnityAdapter.this, AdRequest.ERROR_CODE_INVALID_REQUEST); } return; } Activity activity = (Activity) context; UnitySingleton.getInstance().initializeUnityAds(activity, gameId); float density = context.getResources().getDisplayMetrics().density; int bannerWidth = Math.round(adSize.getWidthInPixels(context) / density); int bannerHeight = Math.round(adSize.getHeightInPixels(context) / density); UnityBannerSize size = new UnityBannerSize(bannerWidth, bannerHeight); if (mBannerView == null){ mBannerView = new BannerView((Activity)context, bannerPlacementId, size); } mBannerView.setListener(this); mBannerView.load(); }
Source:
<code>static void deleteFolder(File fileOrDirectory) throws IOException { <START> if (fileOrDirectory.getCanonicalFile().equals(fileOrDirectory.getAbsoluteFile())) { <END> File[] children = fileOrDirectory.listFiles(); if (children != null) { for (File child : children) { if (child.getCanonicalFile().equals(child.getAbsoluteFile())) { deleteFolder(child); } else { child.delete(); } } } } if (!fileOrDirectory.delete()) { throw new RuntimeException("Unable to delete " + (fileOrDirectory.isDirectory() ? "directory " : "file ") + fileOrDirectory.getAbsolutePath()); } }</code><technical_language>getCanonicialPath getAbsolutePath instead</technical_language>

Target:
static void deleteFolder(File fileOrDirectory) throws IOException { if (fileOrDirectory.getCanonicalPath().equals(fileOrDirectory.getAbsolutePath()) && fileOrDirectory.isDirectory()) { File[] children = fileOrDirectory.listFiles(); if (children != null) { for (File child : children) { deleteFolder(child); } } } if (!fileOrDirectory.delete()) { throw new RuntimeException("Unable to delete " + (fileOrDirectory.isDirectory() ? "directory " : "file ") + fileOrDirectory.getAbsolutePath()); } }
Source:
<code>void changeIndexSegments(List<File> segmentFilesToAdd, Set<Offset> segmentsToRemove) throws StoreException { TreeMap<Offset, IndexSegment> segmentsToAdd = new TreeMap<>(); Offset journalFirstOffset = journal.getFirstOffset(); for (File indexSegmentFile : segmentFilesToAdd) { IndexSegment indexSegment = new IndexSegment(indexSegmentFile, true, factory, config, metrics, journal); if (indexSegment.getEndOffset().compareTo(journalFirstOffset) > 0) { throw new IllegalArgumentException("One of the index segments has an end offset " + indexSegment.getEndOffset() + " that is higher than the first offset in the journal " + journalFirstOffset); } segmentsToAdd.put(indexSegment.getStartOffset(), indexSegment); } indexesChangeLock.lock(); try { ConcurrentSkipListMap<Offset, IndexSegment> oldIndexSegments = indexesRef.get(); ConcurrentSkipListMap<Offset, IndexSegment> newIndexSegments = new ConcurrentSkipListMap<>(); for (Map.Entry<Offset, IndexSegment> entry : oldIndexSegments.entrySet()) { if (!segmentsToRemove.contains(entry.getKey())) { newIndexSegments.put(entry.getKey(), entry.getValue()); <START> } else if (entry.getKey().compareTo(journal.getFirstOffset()) >= 0) { <END> throw new IllegalArgumentException("Offset of the one of the segments to remove [" + entry.getKey() + "] is" + " higher than the first offset in the journal"); } } newIndexSegments.putAll(segmentsToAdd); indexesRef.set(newIndexSegments); } finally { indexesChangeLock.unlock(); } }</code><technical_language>1. index segment start offset lies journal right? is this check required. 2. This bit confusing. diff loops. loop segmentsToRemove throw if of start offsets lie journal. 2nd loop create newIndexSegments. bcoz, if want to, combine previous check (segmentFilesToAdd's ) in itself. I feel separately more readable</technical_language>

Target:
void changeIndexSegments(List<File> segmentFilesToAdd, Set<Offset> segmentsToRemove) throws StoreException { Offset journalFirstOffset = journal.getFirstOffset(); TreeMap<Offset, IndexSegment> segmentsToAdd = new TreeMap<>(); for (File indexSegmentFile : segmentFilesToAdd) { IndexSegment indexSegment = new IndexSegment(indexSegmentFile, true, factory, config, metrics, journal); if (indexSegment.getEndOffset().compareTo(journalFirstOffset) > 0) { throw new IllegalArgumentException("One of the index segments has an end offset " + indexSegment.getEndOffset() + " that is higher than the first offset in the journal " + journalFirstOffset); } segmentsToAdd.put(indexSegment.getStartOffset(), indexSegment); } for (Offset offset : segmentsToRemove) { IndexSegment segmentToRemove = validIndexSegments.get(offset); if (segmentToRemove.getEndOffset().compareTo(journalFirstOffset) >= 0) { throw new IllegalArgumentException( "End Offset of the one of the segments to remove [" + segmentToRemove.getFile() + "] is" + " higher than the first offset in the journal"); } } inFluxIndexSegments = new ConcurrentSkipListMap<>(); inFluxIndexSegments.putAll(validIndexSegments); inFluxIndexSegments.keySet().removeAll(segmentsToRemove); inFluxIndexSegments.putAll(segmentsToAdd); validIndexSegments = inFluxIndexSegments; }
Source:
<code><START> @Override public void setId(String id) { <END> this.id = id; }</code><technical_language>Fix annotation line placement</technical_language>

Target:
public void setId(String id) { this.id = id; }
Source:
<code>public Description matchTry (TryTree tree, VisitorState state) { List<? extends CatchTree> catchList = tree.getCatches(); if (catchList == null || catchList.size() == 0) { return Description.NO_MATCH; } <START> CatchTree lastCatch = catchList.get(tree.getCatches().size() - 1); <END> if (overcatch(lastCatch, state)) { if (abortInCatch(lastCatch, state)) { LineMap lineMap = state.getPath().getCompilationUnit().getLineMap(); return describeMatch(lastCatch); } } return Description.NO_MATCH; }</code><technical_language>Guava's Iterables.getLast(catchList) instead</technical_language>

Target:
public Description matchTry (TryTree tree, VisitorState state) { List<? extends CatchTree> catchList = tree.getCatches(); if (catchList == null || catchList.size() == 0) { return Description.NO_MATCH; } CatchTree lastCatch = Iterables.getLast(catchList); if (overcatch(lastCatch, state)) { if (abortInCatch(lastCatch, state)) { return describeMatch(lastCatch); } } return Description.NO_MATCH; }
Source:
<code>public void initialize(Bootstrap<ConnectorConfiguration> bootstrap) { bootstrap.setConfigurationSourceProvider( new SubstitutingSourceProvider(bootstrap.getConfigurationSourceProvider(), new EnvironmentVariableSubstitutor(NON_STRICT_VARIABLE_SUBSTITUTOR) ) ); bootstrap.addBundle(new MigrationsBundle<ConnectorConfiguration>() { @Override public DataSourceFactory getDataSourceFactory(ConnectorConfiguration configuration) { return configuration.getDataSourceFactory(); } }); bootstrap.addCommand(new DependentResourceWaitCommand()); bootstrap.addCommand(new RenderStateTransitionGraphCommand()); bootstrap.getObjectMapper().getSubtypeResolver().registerSubtypes(LogstashConsoleAppenderFactory.class); bootstrap.getObjectMapper().getSubtypeResolver().registerSubtypes(GovUkPayDropwizardRequestJsonLogLayoutFactory.class); <START> java.security.Security.setProperty("networkaddress.cache.ttl" , "15"); <END> }</code><technical_language>put right beginning of method in case of other initialisation stuff do DNS first</technical_language>

Target:
public void initialize(Bootstrap<ConnectorConfiguration> bootstrap) { java.security.Security.setProperty("networkaddress.cache.ttl" , "15"); bootstrap.setConfigurationSourceProvider( new SubstitutingSourceProvider(bootstrap.getConfigurationSourceProvider(), new EnvironmentVariableSubstitutor(NON_STRICT_VARIABLE_SUBSTITUTOR) ) ); bootstrap.addBundle(new MigrationsBundle<ConnectorConfiguration>() { @Override public DataSourceFactory getDataSourceFactory(ConnectorConfiguration configuration) { return configuration.getDataSourceFactory(); } }); bootstrap.addCommand(new DependentResourceWaitCommand()); bootstrap.addCommand(new RenderStateTransitionGraphCommand()); bootstrap.getObjectMapper().getSubtypeResolver().registerSubtypes(LogstashConsoleAppenderFactory.class); bootstrap.getObjectMapper().getSubtypeResolver().registerSubtypes(GovUkPayDropwizardRequestJsonLogLayoutFactory.class); }
Source:
<code>public boolean chkAuthorization(String userName, Object accessObject, String[] userRoles) throws QuadrigaStorageException, QuadrigaAccessException { boolean haveAccess; <START> haveAccess = false; <END> String networkId = (String) accessObject; haveAccess = accessManager.checkIsNetworkEditor(networkId, userName); return haveAccess; }</code><technical_language>this a liner</technical_language>

Target:
public boolean chkAuthorization(String userName, Object accessObject, String[] userRoles) throws QuadrigaStorageException, QuadrigaAccessException { String networkId = null; if (accessObject instanceof String) { networkId = (String) accessObject; } else { try { INetwork nwObj = (Network) accessObject; networkId = nwObj.getNetworkId(); } catch (ClassCastException cce) { throw new IllegalObjectException(cce); } } return accessManager.checkIsNetworkEditor(networkId, userName); }
Source:
<code>public CannedAccessControlList getAccessControlList() { <START> return accessControlList; <END> }</code><technical_language>returning null if set. code calls a null check. set a default here, mark this potentially null @Nullable annotation Optional wrapper type check handle default situation</technical_language>

Target:
public CannedAccessControlList getAccessControlList() { CannedAccessControlList accessControlList; if(access.equalsIgnoreCase("private")) { accessControlList = CannedAccessControlList.BucketOwnerFullControl; } else { accessControlList = CannedAccessControlList.PublicRead; } return accessControlList; }
Source:
<code>Transformations(Map<String, String> transformations) { this.map = <START> unmodifiableMap(transformations); <END> int min = Integer.MAX_VALUE; for (String key : map.keySet()) { int len = key.length(); if (len < min) { min = len; } } minLen = min; }</code><technical_language>nitpick: in general transform unmodifiableMap caller side in class it. This is returns unmodifiable view guarantees original map is modified. Rule of thumb is call unmodifiableMap early possible</technical_language>

Target:
Transformations(Map<String, String> transformations) { this.map = transformations; int min = Integer.MAX_VALUE; int max = 0; for (String key : map.keySet()) { int len = key.length(); if (len < min) min = len; if (len > max) max = len; } minLen = min; maxLen = max; }
Source:
<code><START> public static Boolean getPropertyAsBoolean(String name) { <END> String value = getProperty(name); if (value == null) { return null; } return Boolean.valueOf(value); }</code><technical_language>puzzled this change. want return Boolean instead of boolean? current consumers auto unboxing boolean, I related changes this PR. So, get performance (all?) JVMs auto unboxing here. If returning null if == null, effectively pushing a NullPointerException calling code, expect a boolean, auto unboxing convert null a valid boolean, throwing a NPE instead. So, throw explicit requirements. if clients expecting Boolean instead of boolean, effectively saying: returning a "true", "false" "null". a consumer, I expect that, if method returns a Boolean</technical_language>

Target:
public static boolean getPropertyAsBoolean(String name) { String value = getProperty(name); if (value != null && value.equalsIgnoreCase("true")) { return true; } return false; }
Source:
<code>public BulkLightblueResponse(String responseText, AbstractBulkLightblueRequest<? extends AbstractLightblueRequest> reqs) throws LightblueResponseParseException, LightblueException { this(new ArrayList<LightblueResponse>(), reqs); try { json = JSON.getDefaultObjectMapper().readTree(responseText); ArrayNode resps = (ArrayNode) json.get("responses"); for (Iterator<JsonNode> it = resps.iterator(); it.hasNext();) { JsonNode resp = it.next(); LightblueResponse response = new DefaultLightblueResponse(resp.get("response").toString()); JsonNode seq = resp.get("seq"); if (!seq.isNumber()) { throw new LightblueException("Invalid sequence.", response); } <START> responses.add(resp.get("seq").intValue(), response); <END> } } catch (IOException e) { throw new LightblueResponseParseException("Error parsing lightblue response: " + responseText + "\n", e); } }</code><technical_language>This work</technical_language>

Target:
public BulkLightblueResponse(String responseText, AbstractBulkLightblueRequest<? extends AbstractLightblueRequest> reqs) throws LightblueResponseParseException, LightblueException { requests = reqs.getRequests(); this.text = responseText; try { json = JSON.getDefaultObjectMapper().readTree(responseText); ArrayNode resps = (ArrayNode) json.get("responses"); for (Iterator<JsonNode> it = resps.iterator(); it.hasNext();) { JsonNode resp = it.next(); LightblueResponse response = new DefaultLightblueResponse(resp.get("response").toString()); JsonNode seq = resp.get("seq"); if (!seq.isNumber()) { throw new LightblueException("Invalid sequence.", response); } responses.put(resp.get("seq").intValue(), response); } } catch (IOException e) { throw new LightblueResponseParseException("Error parsing lightblue response: " + responseText + "\n", e); } }
Source:
<code>public boolean unlockSimple(SimpleHeldLocksToken token) { Preconditions.checkNotNull(token); LockDescriptor fakeLockDesc = StringLockDescriptor.of("unlockSimple"); SortedLockCollection<LockDescriptor> fakeLockSet = LockCollections.of(ImmutableSortedMap.of(fakeLockDesc, LockMode.READ)); return unlock(new HeldLocksToken( token.getTokenId(), LockClient.ANONYMOUS, token.getCreationDateMs(), 0L, fakeLockSet, maxAllowedLockTimeout, 0L, <START> "fakeThread-unlockSimple")); <END> }</code><technical_language>including fakeThread</technical_language>

Target:
public boolean unlockSimple(SimpleHeldLocksToken token) { Preconditions.checkNotNull(token); LockDescriptor fakeLockDesc = StringLockDescriptor.of("unlockSimple"); SortedLockCollection<LockDescriptor> fakeLockSet = LockCollections.of(ImmutableSortedMap.of(fakeLockDesc, LockMode.READ)); return unlock(new HeldLocksToken( token.getTokenId(), LockClient.ANONYMOUS, token.getCreationDateMs(), 0L, fakeLockSet, maxAllowedLockTimeout, 0L, "UnknownThread-unlockSimple")); }
Source:
<code><START> public int getSpinnerId() { <END> return R.id.hide_variable_spinner; }</code><technical_language>Please revert if</technical_language>

Target:
protected int getSpinnerId() { return R.id.hide_variable_spinner; }
Source:
<code>public boolean equals(Object o) { <START> if (this == o) <END> return true; if (o == null || getClass() != o.getClass()) return false; DefaultDockerClientConfig that = (DefaultDockerClientConfig) o; return EqualsBuilder.reflectionEquals(this, that); }</code><technical_language>reflectionEquals checks this things</technical_language>

Target:
public boolean equals(Object o) { return EqualsBuilder.reflectionEquals(this, o); }
Source:
<code>private PreparedStatement getDeleteSqlForSession(SessionId sessionId) throws SQLException{ PreparedStatement deleteSessionStatement = connection.prepareStatement("delete from " + tableName + " where " + sessionIdCol + " like ?"); <START> deleteSessionStatement.setString(1, sessionUri(sessionId).concat("%")); <END> return deleteSessionStatement; }</code><technical_language>A session id is unique complete. need wildcard it</technical_language>

Target:
private PreparedStatement getDeleteSqlForSession(SessionId sessionId) throws SQLException{ PreparedStatement deleteSessionStatement = connection.prepareStatement(String.format("delete from %1$s where %2$s = ?", TABLE_NAME, SESSION_ID_COL)); deleteSessionStatement.setString(1, sessionId.toString()); return deleteSessionStatement; }
Source:
<code>public void networkTopologyStrategyNoNodesInDCTest() { long t1 = System.currentTimeMillis(); Map<Token, Set<Host>> replicaMap = networkTopologyStrategy(rf(DC1, 2), rf(DC2, 2)) .computeTokenToReplicaMap(largeRingTokenToPrimary, largeRing); <START> assertThat((System.currentTimeMillis() - t1) < 45000); <END> for (int node = 0; node < 99; node++) { for (int vnodes = 0; vnodes < 256; vnodes++) { Token token = token("" + ((node * 256) + vnodes)); assertReplicaPlacement(replicaMap, token, "127.0.0." + node, "127.0.0." + (node + 1)); } } assertReplicaPlacement(replicaMap, token(""+ 99 * 256), "127.0.0.99", "127.0.0.0"); }</code><technical_language>be: assertThat(System.currentTimeMillis() - t1).isLessThan(45000); Also, limit a bit. laptop, optimized version consistently runs a second</technical_language>

Target:
public void networkTopologyStrategyNoNodesInDCTest() { long t1 = System.currentTimeMillis(); Map<Token, Set<Host>> replicaMap = networkTopologyStrategy(rf(DC1, 2), rf(DC2, 2)) .computeTokenToReplicaMap(largeRingTokenToPrimary, largeRing); assertThat(System.currentTimeMillis() - t1).isLessThan(10000); for (int node = 0; node < 99; node++) { for (int vnodes = 0; vnodes < 256; vnodes++) { Token token = token("" + ((node * 256) + vnodes)); assertReplicaPlacement(replicaMap, token, "127.0.0." + node, "127.0.0." + (node + 1)); } } assertReplicaPlacement(replicaMap, token(""+ 99 * 256), "127.0.0.99", "127.0.0.0"); }
Source:
<code>public TmfModelResponse<List<ITmfTreeDataModel>> fetchTree(TimeQueryFilter filter, @Nullable IProgressMonitor monitor) { List<ITmfTreeDataModel> model = new ArrayList<>(); for (ITmfEventAspect<?> aspect : getTraceAspects(getTrace())) { long id = <START> fAtomicLong.getAndIncrement(); <END> new ColumnDataModel(id, -1, aspect.getName(), aspect.getHelpText(), aspect.isHiddenByDefault()); model.add(new ColumnDataModel(id, -1, aspect.getName(), aspect.getHelpText(), aspect.isHiddenByDefault())); fAspectMap.put(id, aspect); } return new TmfModelResponse<>(model, ITmfResponse.Status.COMPLETED, CommonStatusMessage.COMPLETED); }</code><technical_language>fAspectMap.computeIfAbsent(aspect, a -> fAtomicLong.getAndIncrement) ensure call fetchTree returns IDs for trace</technical_language>

Target:
public TmfModelResponse<List<ColumnDataModel>> fetchTree(TimeQueryFilter filter, @Nullable IProgressMonitor monitor) { List<ColumnDataModel> model = new ArrayList<>(); for (ITmfEventAspect<?> aspect : getTraceAspects(getTrace())) { Long id = fAspectMap.inverse().computeIfAbsent(aspect, a -> fAtomicLong.getAndIncrement()); model.add(new ColumnDataModel(id, -1, aspect.getName(), aspect.getHelpText(), aspect.isHiddenByDefault())); } return new TmfModelResponse<>(model, ITmfResponse.Status.COMPLETED, CommonStatusMessage.COMPLETED); }
Source:
<code>private static Channel connectionChannel(ChannelHandlerContext ctx) { final Channel ch = ctx.channel(); <START> return (ch instanceof Http2StreamChannel) ? ch.parent() : ch; <END> }</code><technical_language>nit: remove ()</technical_language>

Target:
private static Channel connectionChannel(ChannelHandlerContext ctx) { final Channel ch = ctx.channel(); return ch instanceof Http2StreamChannel ? ch.parent() : ch; }
Source:
<code>public void getStatesByApplicationIdShouldThrowIllegalArgumentExceptionWhenApplicationIdIsNull() { <START> given(applicationsRepository.findOne(null)).willThrow(IllegalArgumentException.class); <END> statesService.getStatesByApplicationId(null); }</code><technical_language>Do call repository method, detect if parameter is wrong. assert in service implementation for catching invalid parameters</technical_language>

Target:
public void getStatesByApplicationIdShouldThrowIllegalArgumentExceptionWhenApplicationIdIsNull() { statesService.getStatesByApplicationId(null); }
Source:
<code>private Optional<Session> findCurrentSession() { <START> IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); final IWorkbenchPage activePage = window.getActivePage(); final IEditorPart activeEditor = activePage.getActiveEditor(); <END> if (activeEditor instanceof SessionEditor) { return Optional.ofNullable(((SessionEditor) activeEditor).getSession()); } else { return Optional.empty(); } }</code><technical_language>org.eclipse.sirius.common.ui.tools.api.util.EclipseUIUtil.getActiveEditor(). handles potential NPE</technical_language>

Target:
private Optional<Session> findCurrentSession() { final IEditorPart activeEditor = EclipseUIUtil.getActiveEditor(); if (activeEditor instanceof SessionEditor) { return Optional.ofNullable(((SessionEditor) activeEditor).getSession()); } else { return Optional.empty(); } }