auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void getApplicationByCandidateIdShouldReturnEmptyListWhenCandidateIdIsNotFound() { given(candidateRepository.findOne(NON_EXISTENT_CANDIDATE_ID)).willReturn(null); given(applicationsRepository.findByCandidateEntity(null, DEFAULT_PAGE_REQUEST)) .willReturn(new PageImpl<ApplicationEntity>(Collections.emptyList())); PagingResponse<CandidateApplicationDTO> <START> result = <END> applicationsService .getApplicationsByCandidateId(NON_EXISTENT_CANDIDATE_ID, PAGE_NUMBER_ZERO, PAGE_SIZE_TEN); assertThat(result.getTotal(), is(0L)); assertTrue(result.getRows().isEmpty()); }</code><technical_language>This variable final</technical_language>

Target:
public void getApplicationByCandidateIdShouldReturnEmptyListWhenCandidateIdIsNotFound() { given(candidateRepository.findOne(NON_EXISTENT_CANDIDATE_ID)).willReturn(null); given(applicationsRepository.findByCandidateEntity(null, DEFAULT_PAGE_REQUEST)) .willReturn(new PageImpl<ApplicationEntity>(Collections.emptyList())); final PagingResponse<CandidateApplicationDTO> result = applicationsService .getApplicationsByCandidateId(NON_EXISTENT_CANDIDATE_ID, PAGE_NUMBER_ZERO, PAGE_SIZE_TEN); assertThat(result.getTotal(), is(0L)); assertTrue(result.getRows().isEmpty()); }
Source:
<code>public void accept(NotificationEvent event) { String dbName; String tableName; switch (event.getEventType()) { case MessageBuilder.ADD_PARTITION_EVENT: case MessageBuilder.ALTER_PARTITION_EVENT: case MessageBuilder.DROP_PARTITION_EVENT: case MessageBuilder.ALTER_TABLE_EVENT: case MessageBuilder.DROP_TABLE_EVENT: case MessageBuilder.INSERT_EVENT: dbName = event.getDbName(); tableName = event.getTableName(); break; default: return; } if (dbName == null || tableName == null) { LOG.info("Possibly malformed notification event, missing db or table name: {}", event); return; } LOG.debug("Handling event on table {}.{}", event.getEventType(), dbName, tableName); QueryResultsCache cache = QueryResultsCache.getInstance(); if (cache != null) { long eventTime = event.getEventTime() * 1000L; <START> cache.notifyTableChanged(TableName.fromString(tableName, null, dbName), eventTime); <END> } else { LOG.debug("Cache not instantiated, skipping event on {}.{}", dbName, tableName); } }</code><technical_language>I if sense leave out category for now....it's - instead of passing null a separate method for (db,name)</technical_language>

Target:
public void accept(NotificationEvent event) { String dbName; String tableName; switch (event.getEventType()) { case MessageBuilder.ADD_PARTITION_EVENT: case MessageBuilder.ALTER_PARTITION_EVENT: case MessageBuilder.DROP_PARTITION_EVENT: case MessageBuilder.ALTER_TABLE_EVENT: case MessageBuilder.DROP_TABLE_EVENT: case MessageBuilder.INSERT_EVENT: dbName = event.getDbName(); tableName = event.getTableName(); break; default: return; } if (dbName == null || tableName == null) { LOG.info("Possibly malformed notification event, missing db or table name: {}", event); return; } LOG.debug("Handling event on table {}.{}", event.getEventType(), dbName, tableName); QueryResultsCache cache = QueryResultsCache.getInstance(); if (cache != null) { long eventTime = event.getEventTime() * 1000L; cache.notifyTableChanged(TableName.fromString(tableName, dbName), eventTime); } else { LOG.debug("Cache not instantiated, skipping event on {}.{}", dbName, tableName); } }
Source:
<code>public static Region parseRegion(String regionString) { Region region = null; if (regionString != null && !regionString.equals("")) { if (regionString.indexOf(':') != -1) { String[] fields = regionString.split("[:-]", -1); if (fields.length == 3) { region = new Region(fields[0], Integer.parseInt(fields[1]), Integer.parseInt(fields[2])); } else if (fields.length == 2) { <START> region = new Region(fields[0], Integer.parseInt(fields[1]), Integer.MAX_VALUE); <END> } } else { region = new Region(regionString, 0, Integer.MAX_VALUE); } } return region; }</code><technical_language>arg constructor, centralises default values. e.g.: region = new Region(fields[0], Integer.parseInt(fields[1]));</technical_language>

Target:
public static Region parseRegion(String regionString) { Region region = null; if (regionString != null && !regionString.equals("")) { if (regionString.indexOf(':') != -1) { String[] fields = regionString.split("[:-]", -1); if (fields.length == 3) { region = new Region(fields[0], Integer.parseInt(fields[1]), Integer.parseInt(fields[2])); } else if (fields.length == 2) { region = new Region(fields[0], Integer.parseInt(fields[1])); } } else { region = new Region(regionString); } } return region; }
Source:
<code>public Object execute(ExecutionEvent event) throws ExecutionException { Shell activeShell= HandlerUtil.getActiveShell(event); Object newNameValue= HandlerUtil.getVariable(event, LTK_RENAME_COMMAND_NEWNAME_PARAMETER_KEY); String newName= null; if (newNameValue instanceof String) { newName= (String) newNameValue; } else { <START> RefactoringUIPlugin.logErrorMessage("Rename refactoring command new name parameter, expected String but got a " + <END> newNameValue.getClass().getName()); } ISelection sel= HandlerUtil.getCurrentSelection(event); if (sel instanceof IStructuredSelection) { IResource resource= getCurrentResource((IStructuredSelection) sel); if (resource != null) { RenameResourceWizard refactoringWizard; if (newName != null) { refactoringWizard= new RenameResourceWizard(resource, newName); } else { refactoringWizard= new RenameResourceWizard(resource); } RefactoringWizardOpenOperation op= new RefactoringWizardOpenOperation(refactoringWizard); try { op.run(activeShell, RefactoringUIMessages.RenameResourceHandler_title); } catch (InterruptedException e) { } } } return null; }</code><technical_language>I this string externalized</technical_language>

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { Shell activeShell= HandlerUtil.getActiveShell(event); Object newNameValue= HandlerUtil.getVariable(event, LTK_RENAME_COMMAND_NEWNAME_PARAMETER_KEY); String newName= null; if (newNameValue instanceof String) { newName= (String) newNameValue; } else if (newNameValue != null) { RefactoringUIPlugin.logErrorMessage(RefactoringUIMessages.RenameResourceHandler_ERROR_EXPECTED_STRING + newNameValue.getClass().getName()); } ISelection sel= HandlerUtil.getCurrentSelection(event); if (sel instanceof IStructuredSelection) { IResource resource= getCurrentResource((IStructuredSelection) sel); if (resource != null) { RenameResourceWizard refactoringWizard; if (newName != null) { refactoringWizard= new RenameResourceWizard(resource, newName); } else { refactoringWizard= new RenameResourceWizard(resource); } RefactoringWizardOpenOperation op= new RefactoringWizardOpenOperation(refactoringWizard); try { op.run(activeShell, RefactoringUIMessages.RenameResourceHandler_title); } catch (InterruptedException e) { } } } return null; }
Source:
<code>public int getFixedSize() { if (isDynamicType()) { <START> return 32; <END> } else { return elementType.getFixedSize() * size; } }</code><technical_language>is this magic number from</technical_language>

Target:
public int getFixedSize() { if (isDynamicType()) { return Int32Size; } else { return elementType.getFixedSize() * size; } }
Source:
<code>public StreamTaskListener(Writer w) throws IOException { <START> this(new WriterOutputStream(w), StandardCharsets.UTF_8); <END> }</code><technical_language>WriterOutputStream constructor needs encoding too, I think, get junk</technical_language>

Target:
public StreamTaskListener(Writer w) throws IOException { this(new WriterOutputStream(w, StandardCharsets.UTF_8), StandardCharsets.UTF_8); }
Source:
<code>public ConnectorFactory usingConnectionInfo(ConnectionInfo connectionInfo) { <START> this.info = (ConnectionInfoImpl) connectionInfo; <END> return this; }</code><technical_language>Setting type ConnectionInfo eliminate this cast</technical_language>

Target:
public ConnectorFactory usingConnectionInfo(ConnectionInfo connectionInfo) { this.properties = connectionInfo.getProperties(); this.token = connectionInfo.getAuthenticationToken(); return this; }
Source:
<code>public boolean areLoaded() { boolean result = true; int i = 1; List<WebElement> widgetIFrameList = getWidgetIFrameList(); if (widgetIFrameList.isEmpty()) { <START> result = false; <END> } for (WebElement widgetIFrame: widgetIFrameList) { if (!isWidgetVisible(widgetIFrame, getWidgetBody())) { result = false; PageObjectLogging.log(getTagName() + " #" + i, MercuryMessages.VISIBLE_MSG, result); break; } PageObjectLogging.log(getTagName() + " #" + i++, MercuryMessages.VISIBLE_MSG, result); } PageObjectLogging.log("all " + getTagName() + " widgets", MercuryMessages.VISIBLE_MSG, result); return result; }</code><technical_language>setting flag false, unnecessary loop operations executed</technical_language>

Target:
public boolean areLoaded() { boolean result = true; int i = 1; List<WebElement> widgetIFrameList = getWidgetIFrameList(); if (widgetIFrameList.isEmpty()) { result = false; } else { for (WebElement widgetIFrame : widgetIFrameList) { if (!isWidgetVisible(widgetIFrame, getWidgetBody())) { result = false; PageObjectLogging.log(getTagName() + " #" + i, MercuryMessages.VISIBLE_MSG, result); break; } PageObjectLogging.log(getTagName() + " #" + i++, MercuryMessages.VISIBLE_MSG, result); } } PageObjectLogging.log("all " + getTagName() + " widgets", MercuryMessages.VISIBLE_MSG, result); return result; }
Source:
<code>public LandingStrip(Context context, AttributeSet attrs) { super(context, attrs); setFillViewport(true); setWillNotDraw(false); setHorizontalScrollBarEnabled(false); this.attributes = Attributes.readAttributes(context, attrs); this.layoutInflater = LayoutInflater.from(context); this.indicatorPaint = new Paint(); this.state = new State(); this.tabsContainer = new LinearLayout(context); this.indicatorCoordinatesCalculator = IndicatorCoordinatesCalculator.newInstance(); state.updateDelegateOnPageListener(new ViewPager.SimpleOnPageChangeListener()); state.updatePosition(0); <START> state.updatePositionOffset(0); <END> tabsContainer.setOrientation(LinearLayout.HORIZONTAL); tabsContainer.setPadding(attributes.getTabsPaddingLeft(), 0, attributes.getTabsPaddingRight(), 0); indicatorPaint.setAntiAlias(true); indicatorPaint.setStyle(Paint.Style.FILL); indicatorPaint.setColor(getResources().getColor(attributes.getIndicatorColour())); addView(tabsContainer, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); }</code><technical_language>done in ctor of State</technical_language>

Target:
public LandingStrip(Context context, AttributeSet attrs) { super(context, attrs); setFillViewport(true); setWillNotDraw(false); setHorizontalScrollBarEnabled(false); this.attributes = Attributes.readAttributes(context, attrs); this.layoutInflater = LayoutInflater.from(context); this.indicatorPaint = new Paint(); this.state = new State(); this.tabsContainer = new LinearLayout(context); this.indicatorCoordinatesCalculator = IndicatorCoordinatesCalculator.newInstance(); state.updateDelegateOnPageListener(new ViewPager.SimpleOnPageChangeListener()); state.updatePosition(0); state.updatePositionOffset(0); tabsContainer.setOrientation(LinearLayout.HORIZONTAL); tabsContainer.setPadding(attributes.getTabsPaddingLeft(), 0, attributes.getTabsPaddingRight(), 0); indicatorPaint.setAntiAlias(true); indicatorPaint.setStyle(Paint.Style.FILL); indicatorPaint.setColor(getResources().getColor(attributes.getIndicatorColor())); addView(tabsContainer, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); }
Source:
<code>public void testGetTicketInControlTeamMemberTicket() { User user = createUser(); createTicketForUser(user); User teammate = createUser(); createTicketForUser(teammate); Team team = createTeamWithCaptain(user); <START> team.addMember(teammate); <END> given(). header(getXAuthTokenHeaderForUser(user)). when(). get(TICKETS_ENDPOINT + "/teammembers"). then(). statusCode(HttpStatus.SC_OK). body("owner.username", containsInAnyOrder(user.getUsername(), teammate.getUsername())); }</code><technical_language>This is persisted in database, is request a team member</technical_language>

Target:
public void testGetTicketInControlTeamMemberTicket() { User user = createUser(); createTicketForUser(user); User teammate = createUser(); createTicketForUser(teammate); Team team = createTeamWithCaptain(user); addMemberToTeam(team, teammate); given(). header(getXAuthTokenHeaderForUser(user)). when(). get(TICKETS_ENDPOINT + "/teammembers"). then(). statusCode(HttpStatus.SC_OK). body("owner.username", containsInAnyOrder(user.getUsername(), teammate.getUsername())); }
Source:
<code>public final Map<String, Integer> getSeverityNumDiff() { final Map<String, Integer> severityNumDiff = new HashMap<>(severityNumRemoved); <START> severityNumAdded.forEach((key, value) -> severityNumDiff.merge(key, value, Math::addExact)); <END> return severityNumDiff; }</code><technical_language>Math::addExact throw error if is overflow. I want this. alot more instances of this. @romani ping</technical_language>

Target:
public final Map<String, BigInteger> getSeverityNumDiff() { final Map<String, BigInteger> severityNumDiff = new HashMap<>(severityNumDiffRemoved); severityNumDiffAdded.forEach( (key, value) -> severityNumDiff.merge(key, value, BigInteger::add)); return severityNumDiff; }
Source:
<code><START> public void setProgressMonitor(ProgressMonitor pm) { <END> this.pm = ((pm == null) ? NullProgressMonitor.INSTANCE : pm); }</code><technical_language>optional: consider returning this setters support chaining configuration</technical_language>

Target:
public GC setProgressMonitor(ProgressMonitor pm) { this.pm = (pm == null) ? NullProgressMonitor.INSTANCE : pm; return this; }
Source:
<code>public static String decrypt(String source, String keyFile, String passwd, String alias) throws Exception { try { String result = ""; <START> if (!StringHelper.isNullOrEmpty(source.trim())) { <END> KeyStore store = EncryptionUtils.getKeyStore(keyFile, passwd, certType); result = decrypt(source, store.getKey(alias, passwd.toCharArray())); } return result; } catch (Exception e) { log.error("Failed to decrypt " + e.getMessage()); log.debug("Failed to decrypt", e); throw e; } }</code><technical_language>StringUtils.isNotEmpty()</technical_language>

Target:
public static String decrypt(String source, String keyFile, String passwd, String alias) throws Exception { try { String result = ""; if (source.trim().length() > 0) { KeyStore store = EncryptionUtils.getKeyStore(keyFile, passwd, certType); result = decrypt(source, store.getKey(alias, passwd.toCharArray())); } return result; } catch (Exception e) { log.error("Failed to decrypt " + e.getMessage()); log.debug("Failed to decrypt", e); throw e; } }
Source:
<code><START> public AbfsClientContext( <END> ExponentialRetryPolicy exponentialRetryPolicy, AbfsPerfTracker abfsPerfTracker, AbfsCounters abfsCounters) { this.exponentialRetryPolicy = exponentialRetryPolicy; this.abfsPerfTracker = abfsPerfTracker; this.abfsCounters = abfsCounters; }</code><technical_language>this package private now, creating</technical_language>

Target:
AbfsClientContext( ExponentialRetryPolicy exponentialRetryPolicy, AbfsPerfTracker abfsPerfTracker, AbfsCounters abfsCounters) { this.exponentialRetryPolicy = exponentialRetryPolicy; this.abfsPerfTracker = abfsPerfTracker; this.abfsCounters = abfsCounters; }
Source:
<code>protected void putDocuments(String indexName, List<SearchDocument> documents) { List<Document> searchDocuments = new ArrayList<Document>(); for (SearchDocument document : documents) { searchDocuments.add(document.build()); } try { SearchManager.putDocuments(indexName, searchDocuments); } catch (Exception e) { log.info("Failed to batch put searchable documents in " + indexName + " for " + documents.toString()); <START> } <END> }</code><technical_language>this logged severe level, triggering email admin</technical_language>

Target:
protected void putDocuments(String indexName, List<SearchDocument> documents) { List<Document> searchDocuments = new ArrayList<Document>(); for (SearchDocument document : documents) { searchDocuments.add(document.build()); } try { SearchManager.putDocuments(indexName, searchDocuments); } catch (Exception e) { log.severe("Failed to batch put searchable documents in " + indexName + " for " + documents.toString()); } }
Source:
<code>protected void runAutonomous() throws InterruptedException, AutonomousModeOverException { pickupContainer(nudge.get()); setClampHeight(1.0f); singleSideTurn((long) (containerTurnTime.get() * 1000), false); boolean elevatorAtTop = Elevator.atTop.get(); if (!elevatorAtTop) { Elevator.setTop.event(); <START> } <END> float currentClampHeight = Clamp.heightReadout.get(); if (currentClampHeight < AutoLoader.clampHeightThreshold.get()) { Clamp.mode.set(Clamp.MODE_HEIGHT); Clamp.height.set(AutoLoader.clampHeightThreshold.get()); if (elevatorAtTop) { waitUntil(Clamp.atDesiredHeight); } else { waitUntil(BooleanMixing.andBooleans(Clamp.atDesiredHeight, Elevator.atTop)); } } else { if (!elevatorAtTop) { waitUntil(Elevator.atTop); } } Rollers.direction.set(Rollers.REVERSE); Rollers.running.set(true); Rollers.closed.set(true); waitUntil(AutoLoader.crateInPosition); Rollers.running.set(false); Rollers.closed.set(false); turn(autoZoneAngle.get(), true); waitForTime(500); drive(autoZoneDistance.get(), autoZoneSpeed.get()); waitForTime(500); depositContainer(containerHeight.get()); }</code><technical_language>bother. This help, out</technical_language>

Target:
protected void runAutonomous() throws InterruptedException, AutonomousModeOverException { pickupContainer(nudge.get()); setClampHeight(topClampHeight.get()); singleSideTurn((long) (containerTurnTime.get() * 1000), false); collectTote(); turn(autoZoneAngle.get(), true); waitForTime(500); drive(autoZoneDistance.get(), autoZoneSpeed.get()); waitForTime(500); depositContainer(containerHeight.get()); }
Source:
<code>private FalsePositiveTableWriter(final File output) throws IOException { <START> super(output, new TableColumnCollection("filename", "snp", "indel")); <END> }</code><technical_language>Extract constants for "filename," "snp," "indel" want edit this code change place mistake</technical_language>

Target:
private FalsePositiveTableWriter(final File output) throws IOException { super(output, new TableColumnCollection(ID_COLUMN_NAME, SNP_COLUMN_NAME, INDEL_COLUMN_NAME)); }
Source:
<code>public void StoringData() throws ExecutionException, InterruptedException { RiakClient client = new RiakClient(cluster); final String tableName = "time_series"; final Calendar date1 = new GregorianCalendar(TimeZone.getTimeZone("UTC")); date1.add(Calendar.MILLISECOND, -10); final Calendar date2 = new GregorianCalendar(TimeZone.getTimeZone("UTC")); <START> date1.add(Calendar.MILLISECOND, -5); <END> final Calendar date3 = new GregorianCalendar(TimeZone.getTimeZone("UTC")); final List<Row> rows = Arrays.asList(new Row(new Cell(date1), new Cell("bryce"), new Cell(305.37)), new Row(new Cell(date2), new Cell("bryce"), new Cell(300.12)), new Row(new Cell(date3), new Cell("bryce"), new Cell(295.95))); Store store = new Store.Builder(tableName).withRows(rows).build(); RiakFuture<Void, BinaryValue> execFuture = client.executeAsync(store); execFuture.await(); assertTrue(execFuture.isSuccess()); }</code><technical_language>date2.add..</technical_language>

Target:
public void StoringData() throws ExecutionException, InterruptedException { RiakClient client = new RiakClient(cluster); Store store = new Store.Builder(tableName).withRows(rows).build(); RiakFuture<Void, String> execFuture = client.executeAsync(store); execFuture.await(); String errorMessage = execFuture.cause() != null? execFuture.cause().getMessage() : ""; assertNull(errorMessage, execFuture.cause()); assertEquals(true, execFuture.isSuccess()); }
Source:
<code>public void testTrace() { long[] time = new long[LOOP_COUNT]; for (int i = 0; i < LOOP_COUNT; i++) { IAnalysisModule module = new LttngKernelAnalysisModule(); module.setId("test"); try (LttngKernelTrace trace = new LttngKernelTrace()) { trace.initTrace(null, testTrace.getPath(), CtfTmfEvent.class); module.setTrace(trace); long start = System.nanoTime(); TmfTestHelper.executeAnalysis(module); long end = System.nanoTime(); File suppDir = new File(TmfTraceManager.getSupplementaryFileDir(trace)); for (File file : suppDir.listFiles()) { file.delete(); } <START> trace.dispose(); <END> time[i] = end - start; } catch (TmfAnalysisException | TmfTraceException e) { fail(e.getMessage()); } } double avg = 0, avgHot = 0; for (int i = 0; i < LOOP_COUNT; i++) { avg += time[i]; if (i > 2) { avgHot += time[i]; } } System.out.println("Cache cold : " + String.format("%.3f", 0.000001 * time[0]) + "ms\t average time : " + String.format("%.3f", 0.000001 * avg / LOOP_COUNT) + " ms\t average (cache hot) time : " + String.format("%.3f", 0.000001 * (avgHot / LOOP_COUNT - 3))); }</code><technical_language>I this trace.dispose is unnecessary is in a try-with-resource. module.dispose() good. put in try too</technical_language>

Target:
public void testTrace() { long[] time = new long[LOOP_COUNT]; for (int i = 0; i < LOOP_COUNT; i++) { try (IAnalysisModule module = new LttngKernelAnalysisModule(); LttngKernelTrace trace = new LttngKernelTrace()) { module.setId("test"); trace.initTrace(null, testTrace.getPath(), CtfTmfEvent.class); module.setTrace(trace); long start = System.nanoTime(); TmfTestHelper.executeAnalysis(module); long end = System.nanoTime(); File suppDir = new File(TmfTraceManager.getSupplementaryFileDir(trace)); for (File file : suppDir.listFiles()) { file.delete(); } time[i] = end - start; } catch (TmfAnalysisException | TmfTraceException e) { fail(e.getMessage()); } } double avg = 0, avgHot = 0; for (int i = 0; i < LOOP_COUNT; i++) { avg += time[i]; if (i > 2) { avgHot += time[i]; } } System.out.println("Cache cold : " + String.format("%.3f", 0.000001 * time[0]) + "ms\t average time : " + String.format("%.3f", 0.000001 * avg / LOOP_COUNT) + " ms\t average (cache hot) time : " + String.format("%.3f", 0.000001 * (avgHot / LOOP_COUNT - 3))); }
Source:
<code>public void addCondition(Condition condition) { <START> if (condition != null) { <END> condition.setEncounter(this); getConditions().add(condition); } }</code><technical_language>I silently ignore passing a null parameter. In other words, i remove if check assume condition is null. If turns out null, for caller automatically get a NullPointerException chewing quietly</technical_language>

Target:
public void addCondition(Condition condition) { condition.setEncounter(this); getConditions().add(condition); }
Source:
<code>protected void installScheduler() { if (senderJob != null) { uninstallScheduler(); } if (refreshTime > 0) { <START> senderJob = scheduler.scheduleWithFixedDelay(packetSender, 1, refreshTime, TimeUnit.MILLISECONDS); <END> logger.trace("started scheduler for thing {}", this.thing.getUID()); } else { logger.info("refresh disabled for thing {}", this.thing.getUID()); } }</code><technical_language>DMX protocol is pretty sensitive wrt timing - guess is ...AtFixedRate is intention. @J-N-K please a quick look</technical_language>

Target:
protected void installScheduler() { if (senderJob != null) { uninstallScheduler(); } if (refreshTime > 0) { senderJob = scheduler.scheduleAtFixedRate(() -> { logger.trace("runnable packet sender for universe called, state {}/{}", universe.getUniverseId(), getThing().getStatus(), isMuted); if (!isMuted) { sendDmxData(); } else { logger.trace("bridge is muted", getThing().getUID()); } }, 1, refreshTime, TimeUnit.MILLISECONDS); logger.trace("started scheduler for thing {}", this.thing.getUID()); } else { logger.info("refresh disabled for thing {}", this.thing.getUID()); } }
Source:
<code>public boolean isApplicable(Item item) { <START> return item instanceof Job; <END> }</code><technical_language>java && SCMTriggerItems.asSCMTriggerItem(job) != null && job instanceof ParameterizedJobMixIn.ParameterizedJob :bug:</technical_language>

Target:
public boolean isApplicable(Item item) { return item instanceof Job && SCMTriggerItems.asSCMTriggerItem(item) != null && item instanceof ParameterizedJobMixIn.ParameterizedJob; }
Source:
<code>public void testCloseTaskManagerConnectionOnWorkerTerminated() throws Exception { new Context() {{ final ResourceID tmResourceId = ResourceID.generate(); final CompletableFuture<TaskExecutorProcessSpec> requestWorkerFromDriverFuture = new CompletableFuture<>(); final CompletableFuture<Void> disconnectResourceManagerFuture = new CompletableFuture<>(); final TestingTaskExecutorGateway taskExecutorGateway = new TestingTaskExecutorGatewayBuilder() .setDisconnectResourceManagerConsumer((ignore) -> disconnectResourceManagerFuture.complete(null)) .createTestingTaskExecutorGateway(); driverBuilder.setRequestResourceFunction(taskExecutorProcessSpec -> { requestWorkerFromDriverFuture.complete(taskExecutorProcessSpec); return CompletableFuture.completedFuture(tmResourceId); }); runTest(() -> { runInMainThread(() -> getResourceManager().startNewWorker(WORKER_RESOURCE_SPEC)) <START> .thenCompose((ignrore) -> registerTaskExecutor(tmResourceId, taskExecutorGateway)) <END> .thenRun(() -> runInMainThread(() -> getResourceManager().onWorkerTerminated(tmResourceId, new Exception()))); disconnectResourceManagerFuture.get(TIMEOUT_SEC, TimeUnit.SECONDS); }); }}; }</code><technical_language>suggestion .thenCompose((ignore) -> registerTaskExecutor(tmResourceId, taskExecutorGateway))</technical_language>

Target:
public void testCloseTaskManagerConnectionOnWorkerTerminated() throws Exception { new Context() {{ final ResourceID tmResourceId = ResourceID.generate(); final CompletableFuture<TaskExecutorProcessSpec> requestWorkerFromDriverFuture = new CompletableFuture<>(); final CompletableFuture<Void> disconnectResourceManagerFuture = new CompletableFuture<>(); final TestingTaskExecutorGateway taskExecutorGateway = new TestingTaskExecutorGatewayBuilder() .setDisconnectResourceManagerConsumer((ignore) -> disconnectResourceManagerFuture.complete(null)) .createTestingTaskExecutorGateway(); driverBuilder.setRequestResourceFunction(taskExecutorProcessSpec -> { requestWorkerFromDriverFuture.complete(taskExecutorProcessSpec); return CompletableFuture.completedFuture(tmResourceId); }); runTest(() -> { runInMainThread(() -> getResourceManager().startNewWorker(WORKER_RESOURCE_SPEC)) .thenCompose((ignore) -> registerTaskExecutor(tmResourceId, taskExecutorGateway)) .thenRun(() -> runInMainThread(() -> getResourceManager().onWorkerTerminated(tmResourceId, "terminate for testing"))); disconnectResourceManagerFuture.get(TIMEOUT_SEC, TimeUnit.SECONDS); }); }}; }
Source:
<code>private String getAddressesString(Collection<MailAddress> addresses) { if (addresses == null) { return "null"; } Iterator<MailAddress> iter = addresses.iterator(); StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = 0; iter.hasNext(); i++) { if (i > 0) { <START> sb.append(", "); <END> } sb.append(iter.next()); } sb.append(']'); return sb.toString(); }</code><technical_language>i+1 < addresses.size() i < addesses.size() - 1 i > 0 IMO if want fix it, simply extract size call in a variable out of loop</technical_language>

Target:
private String getAddressesString(Collection<MailAddress> addresses) { if (addresses == null) { return "null"; } StringBuilder sb = new StringBuilder(); sb.append('['); Joiner.on(", ").appendTo(sb, addresses); sb.append(']'); return sb.toString(); }
Source:
<code>private Discover findDiscoveryMode(Resource beansResource) { if (beansResource == null) { return Discover.none; } Document document = readXMLResource(beansResource); if (!document.hasAttributes() && !document.hasChildNodes()) { return Discover.all; } try { XPath xPath = XPathFactory.newInstance() .newXPath(); XPathExpression expression = xPath.compile("/beans/@version"); Object versionResult = expression.evaluate(beansResource, XPathConstants.STRING); Version version = Version.valueOf(versionResult.toString()); if (CDIAnnotationReader.CDI_ARCHIVE_VERSION.compareTo(version) <= 0) { try { <START> xPath = XPathFactory.newInstance() <END> .newXPath(); expression = xPath.compile("/beans/@bean-discovery-mode"); Object beanDiscoveryMode = expression.evaluate(beansResource, XPathConstants.STRING); return Discover.valueOf(beanDiscoveryMode.toString()); } catch (NullPointerException | XPathExpressionException e) { return Discover.annotated; } } return Discover.all; } catch (NullPointerException | XPathExpressionException e) { return Discover.all; } }</code><technical_language>put xpath expressions in statics compile multiple times</technical_language>

Target:
private Discover findDiscoveryMode(Resource beansResource) { if (beansResource == null) { return Discover.none; } Document document = readXMLResource(beansResource); if (!document.hasAttributes() && !document.hasChildNodes()) { return Discover.all; } try { Object versionResult = versionExpression.evaluate(beansResource, XPathConstants.STRING); Version version = Version.valueOf(versionResult.toString()); if (CDIAnnotationReader.CDI_ARCHIVE_VERSION.compareTo(version) <= 0) { try { Object beanDiscoveryMode = discoveryModeExpression.evaluate(beansResource, XPathConstants.STRING); return Discover.valueOf(beanDiscoveryMode.toString()); } catch (NullPointerException | XPathExpressionException e) { return Discover.annotated; } } return Discover.all; } catch (NullPointerException | XPathExpressionException e) { return Discover.all; } }
Source:
<code>private void makeRemoteDirectoriesIfNotExist(FTPClient ftpClient, Path path) throws IOException { if (path.getParent() == null) { createRemoteDirectoryIfNotExists(ftpClient, path.toString()); <START> return; <END> } else { makeRemoteDirectoriesIfNotExist(ftpClient, path.getParent()); createRemoteDirectoryIfNotExists(ftpClient, path.getFileName().toString()); } }</code><technical_language>need return</technical_language>

Target:
private void makeRemoteDirectoriesIfNotExist(FTPClient ftpClient, Path path) throws IOException { if (path.getParent() == null) { createRemoteDirectoryIfNotExists(ftpClient, path.toString()); } else { makeRemoteDirectoriesIfNotExist(ftpClient, path.getParent()); createRemoteDirectoryIfNotExists(ftpClient, path.getFileName().toString()); } }
Source:
<code>public static EnvInjectPluginConfiguration getInstance() { final Jenkins j = Jenkins.getInstance(); if (j == null) { return null; } <START> ExtensionList<EnvInjectPluginConfiguration> extensionList = <END> j.getExtensionList(EnvInjectPluginConfiguration.class); return extensionList.isEmpty() ? null : extensionList.get(0); }</code><technical_language>simplified java EnvInjectPluginConfiguration.all().get(EnvInjectPluginConfiguration.class)</technical_language>

Target:
public static EnvInjectPluginConfiguration getInstance() { return EnvInjectPluginConfiguration.all().get(EnvInjectPluginConfiguration.class); }
Source:
<code>public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { final IServerModule appModule = retrieveServerModuleFromSelectedElement(receiver); if(appModule == null) { return false; } final IServer appServer = appModule.getServer(); <START> return appServer != null && "localhost".equals(appServer.getHost()); <END> }</code><technical_language>this limiting IMO. kind of local ip host work perfectly. issue is NPE matching server/proxy openshift redirect. I this patch simple fix NPE - ssh redirect issue limitation</technical_language>

Target:
public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { final IServerModule appModule = retrieveServerModuleFromSelectedElement(receiver); if(appModule == null) { return false; } final IServer appServer = appModule.getServer(); return appServer != null && !WSTUtils.OPENSHIFT_SERVER_TYPE.equals(appServer.getServerType().getId()); }
Source:
<code>public void executeHostScript(final String script, final String engine, final String host, final Callback<String, String> syncCallBack) { rm.executeHostScript(LoginModel.getInstance().getSessionId(), script, engine, host, new AsyncCallback<String>() { public void onFailure(Throwable caught) { String msg = JSONUtils.getJsonErrorMessage(caught); LogModel.getInstance().logImportantMessage("Failed to execute a script " + script + " on host " + host + " : " + msg); <START> if (msg.equals("HTTP 500 Internal Server Error")) { <END> syncCallBack.onFailure("You are not authorized to execute scripts on this host. Please contact the administrator."); } else { syncCallBack.onFailure(msg); } } public void onSuccess(String result) { syncCallBack.onSuccess(parseListScriptResult(result)); } }); }</code><technical_language>reuse handleError method</technical_language>

Target:
public void executeHostScript(final String script, final String engine, final String host, final Callback<String, String> syncCallBack) { rm.executeHostScript(LoginModel.getInstance().getSessionId(), script, engine, host, new AsyncCallback<String>() { public void onFailure(Throwable caught) { reportScriptExecutionFailure(caught, script, host, syncCallBack); } public void onSuccess(String result) { syncCallBack.onSuccess(parseAllScriptResults(result)); } }); }
Source:
<code>public Object call(final String command, final String... args) throws IOException { <START> final List<String> argsList = new ArrayList<String>(); <END> for (final String arg : args) { argsList.add(arg); } return this.call(command, argsList); }</code><technical_language>simplified just: java public Object call(final String command, final String... args) throws IOException { return call(command, Arrays.asList(args)); }</technical_language>

Target:
public Object call(final String command, final String... args) throws IOException { return this.call(command, Arrays.asList(args)); }
Source:
<code>protected void onCommonModelChange() { super.onCommonModelChange(); getModel().getItemsChangedEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { if (hasModel() && handleItemsChangedEvent()) { updateData(); } } }); getModel().getPropertyChangedEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { <START> if (args instanceof PropertyChangedEventArgs) { <END> PropertyChangedEventArgs pcArgs = (PropertyChangedEventArgs) args; if (PropertyChangedEventArgs.Args.PROGRESS.toString().equals(pcArgs.propertyName)) { clearData(); } } } }); }</code><technical_language>For PropertyChangedEvent, "args" instance of PropertyChangedEventArgs. cast "args" directly, for example: String propName = ((PropertyChangedEventArgs) args).propertyName; simplify code a bit. consideration, for instanceof is unnecessary complexity. BTW, a BZ for this issue: <LINK_0></technical_language>

Target:
protected void onCommonModelChange() { super.onCommonModelChange(); getModel().getItemsChangedEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { if (hasModel() && handleItemsChangedEvent()) { updateData(); } } }); getModel().getPropertyChangedEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { if (args instanceof PropertyChangedEventArgs) { PropertyChangedEventArgs pcArgs = (PropertyChangedEventArgs) args; if (PropertyChangedEventArgs.PROGRESS.equals(pcArgs.propertyName)) { clearData(); } } } }); }
Source:
<code>public String toString() { <START> return "Checkpoint [inputOffsets=" + inputOffsets + "]"; <END> }</code><technical_language>Print checkpointId, stateCheckpointMarkers well</technical_language>

Target:
public String toString() { return "Checkpoint [PROTOCOL_VERSION=" + PROTOCOL_VERSION + ", checkpointId=" + checkpointId + ", inputOffsets=" + inputOffsets + ", stateCheckpoint=" + stateCheckpoints + "]"; }
Source:
<code>private void doTestValidModifiedBonds(CreateOrUpdateBond createOrUpdateBond, ValidationResult interfaceIsBondValidationResult, ValidationResult expectedValidationResult, ValidationResult slavesValidationValidationResult) { HostSetupNetworksValidator validator = spy(new HostSetupNetworksValidatorBuilder() .setParams(new ParametersBuilder().addBonds(createOrUpdateBond)) .addExistingInterfaces((List<VdsNetworkInterface>) null) .addExistingAttachments((List<NetworkAttachment>) null) .addNetworks((Collection<Network>) null) .build()); HostInterfaceValidator hostInterfaceValidatorMock = mock(HostInterfaceValidator.class); when(hostInterfaceValidatorMock.interfaceIsBondOrNull()).thenReturn(interfaceIsBondValidationResult); doReturn(hostInterfaceValidatorMock).when(validator).createHostInterfaceValidator(any(VdsNetworkInterface.class)); doReturn(slavesValidationValidationResult).when(validator).validateModifiedBondSlaves(any(CreateOrUpdateBond.class)); if (expectedValidationResult.isValid()) { assertThat(validator.validNewOrModifiedBonds(), isValid()); } else { assertThat(validator.validNewOrModifiedBonds(), <START> failsWith(expectedValidationResult.getMessages().get(0), expectedValidationResult.getVariableReplacements())); <END> } }</code><technical_language>formatter</technical_language>

Target:
private void doTestValidModifiedBonds(CreateOrUpdateBond createOrUpdateBond, ValidationResult interfaceIsBondValidationResult, ValidationResult expectedValidationResult, ValidationResult slavesValidationValidationResult) { HostSetupNetworksValidator validator = spy(new HostSetupNetworksValidatorBuilder() .setParams(new ParametersBuilder().addBonds(createOrUpdateBond)) .addExistingInterfaces((List<VdsNetworkInterface>) null) .addExistingAttachments((List<NetworkAttachment>) null) .addNetworks((Collection<Network>) null) .build()); HostInterfaceValidator hostInterfaceValidatorMock = mock(HostInterfaceValidator.class); when(hostInterfaceValidatorMock.interfaceIsBondOrNull()).thenReturn(interfaceIsBondValidationResult); doReturn(hostInterfaceValidatorMock).when(validator).createHostInterfaceValidator(any(VdsNetworkInterface.class)); doReturn(slavesValidationValidationResult).when(validator).validateModifiedBondSlaves(any(CreateOrUpdateBond.class)); if (expectedValidationResult.isValid()) { assertThat(validator.validNewOrModifiedBonds(), isValid()); } else { assertThat(validator.validNewOrModifiedBonds(), failsWith(expectedValidationResult.getMessages(), expectedValidationResult.getVariableReplacements())); } }
Source:
<code>public static boolean logException(Throwable t) { if (isAnonymousReportEnabled() && isCrashReportEnabled) { <START> Log.e(TAG, "LOG_EXCEPTION : " + t); <END> Crashlytics.logException(t); return true; } return false; }</code><technical_language>100% if log well. In places exception is logged. exception is logged twice. log exception is logged logging exception itself? remove</technical_language>

Target:
public static boolean logException(Throwable t) { if (isReportingEnabled()) { Crashlytics.logException(t); return true; } return false; }
Source:
<code>private void assertNoZombies() throws InterruptedException, IOException { String exitString = null; String zombieString = null; switch (platform) { case SLIM: case NO_INIT: <START> assumeTrue(true); <END> return; case UBUNTU_NO_BINARY: exitString = " sleep "; zombieString = ".+ Z .+"; break; default: exitString = "sh -xe " + ws.getRemote(); zombieString = ".+Z[s|\\s]\\s*\\[durable.+"; } String psFormat = setPsFormat(); String psString = null; do { Thread.sleep(1000); psString = psOut(psFormat); } while (psString.contains(exitString)); Thread.sleep(1000); Pattern zombiePattern = Pattern.compile(zombieString); Matcher zombieMatcher = zombiePattern.matcher(psOut(psFormat)); if (zombieMatcher.find()) { fail(zombieMatcher.group()); } }</code><technical_language>a debug line something? suggestion</technical_language>

Target:
private void assertNoZombies() throws InterruptedException, IOException { String exitString = null; String zombieString = null; switch (platform) { case SLIM: case NO_INIT: return; case UBUNTU_NO_BINARY: exitString = " sleep "; zombieString = ".+ Z .+"; break; default: exitString = "sh -xe " + ws.getRemote(); zombieString = ".+Z[s|\\s]\\s*\\[durable.+"; } String psFormat = setPsFormat(); String psString = null; do { Thread.sleep(1000); psString = psOut(psFormat); } while (psString.contains(exitString)); Thread.sleep(1000); Pattern zombiePattern = Pattern.compile(zombieString); Matcher zombieMatcher = zombiePattern.matcher(psOut(psFormat)); if (zombieMatcher.find()) { fail(zombieMatcher.group()); } }
Source:
<code>protected void autofill() { if (Strings.isFilled(cleartextPassword)) { cleartextPassword = cleartextPassword.trim(); if (Strings.isFilled(cleartextPassword)) { this.salt = Strings.generateCode(20); this.passwordHash = hashPassword(salt, cleartextPassword); this.generatedPassword = null; this.fingerprint = null; this.lastPasswordChange = LocalDateTime.now(); } } if (Strings.isEmpty(passwordHash) && Strings.isEmpty(generatedPassword)) { <START> forceGenerationOfPassword(Strings.generatePassword()); <END> } if (Strings.isEmpty(apiToken)) { this.apiToken = Strings.generateCode(32); } if (Strings.isEmpty(fingerprint)) { this.fingerprint = Strings.generateCode(12); } }</code><technical_language>w/o parameter - want a single place a new password is generated.</technical_language>

Target:
protected void autofill() { if (Strings.isEmpty(passwordHash) && Strings.isEmpty(generatedPassword)) { this.generatedPassword = Strings.generatePassword(); } if (Strings.isEmpty(cleartextPassword) && Strings.isFilled(generatedPassword) && checkPassword(username, generatedPassword) != PasswordVerificationResult.VALID) { this.cleartextPassword = generatedPassword; } if (Strings.isFilled(cleartextPassword)) { cleartextPassword = cleartextPassword.trim(); if (Strings.isFilled(cleartextPassword)) { this.salt = Strings.generateCode(20); this.passwordHash = hashPassword(salt, cleartextPassword); this.fingerprint = null; this.lastPasswordChange = LocalDateTime.now(); if (!Strings.areEqual(cleartextPassword, generatedPassword)) { this.generatedPassword = null; } } } if (Strings.isEmpty(apiToken)) { this.apiToken = Strings.generateCode(32); } if (Strings.isEmpty(fingerprint)) { this.fingerprint = Strings.generateCode(12); } }
Source:
<code>protected Map<String, Pair<String, String>> getSharedLocks() { <START> if (!isInternalExecution()) { <END> return Collections.singletonMap(getVmId().toString(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.VM, EngineMessage.ACTION_TYPE_FAILED_VM_IS_LOCKED)); } return null; }</code><technical_language>&& getVmId() != null</technical_language>

Target:
protected Map<String, Pair<String, String>> getSharedLocks() { if (!isInternalExecution() && getVmId() != null) { return Collections.singletonMap(getVmId().toString(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.VM, EngineMessage.ACTION_TYPE_FAILED_VM_IS_LOCKED)); } return null; }
Source:
<code>protected boolean set(EntityPlayer container, Boolean value) { container.capabilities.allowFlying = value; if (!value) { <START> container.capabilities.isFlying = value; <END> } container.sendPlayerAbilities(); return true; }</code><technical_language>No, supposed change flying state, toggle flight</technical_language>

Target:
protected boolean set(EntityPlayer container, Boolean value) { container.capabilities.allowFlying = value; container.sendPlayerAbilities(); return true; }
Source:
<code>public void testCharIsUppercase() throws Exception { assertEquals("true", SRun("char_is_uppercase('M')", null)); assertEquals("false", SRun("char_is_uppercase('m')", null)); try { SRun("char_is_uppercase('magic')", null); fail("Expected char_is_uppercase('magic') to throw an exception."); } catch (ConfigCompileException | CRECastException e) { } try { SRun("char_is_uppercase('1')", null); fail("Expected char_is_uppercase('1') to throw an exception."); } catch (ConfigCompileException | CRECastException e) { } try { SRun("char_is_uppercase('!')", null); fail("Expected char_is_uppercase('!') to throw an exception."); } catch (ConfigCompileException | CRECastException e) { } try { SRun("char_is_uppercase(1)", null); fail("Expected char_is_uppercase(1) to throw an exception."); } catch (ConfigCompileException | CREFormatException | CRECastException e) { } try { SRun("char_is_uppercase(dyn('stuff'))", null); fail("Expected char_is_uppercase(dyn('stuff')) to throw an exception."); } <START> catch (ConfigCompileException | CRECastException e) { <END> } }</code><technical_language>expect a ConfigCompileException</technical_language>

Target:
public void testCharIsUppercase() throws Exception { assertEquals("true", SRun("char_is_uppercase('M')", null)); assertEquals("false", SRun("char_is_uppercase('m')", null)); try { SRun("char_is_uppercase('magic')", null); fail("Expected char_is_uppercase('magic') to throw an exception."); } catch (ConfigCompileException e) { } try { SRun("char_is_uppercase('1')", null); fail("Expected char_is_uppercase('1') to throw an exception."); } catch (ConfigCompileException e) { } try { SRun("char_is_uppercase('!')", null); fail("Expected char_is_uppercase('!') to throw an exception."); } catch (ConfigCompileException e) { } try { SRun("char_is_uppercase(1)", null); fail("Expected char_is_uppercase(1) to throw an exception."); } catch (ConfigCompileException e) { } try { SRun("char_is_uppercase(dyn('stuff'))", null); fail("Expected char_is_uppercase(dyn('stuff')) to throw an exception."); } catch (CREFormatException e) { } try { SRun("char_is_uppercase('')", null); fail("Expected char_is_uppercase('') to throw an exception."); } catch (ConfigCompileException e) { } }
Source:
<code>private DeviceAnonymized(UUID id, int deviceIndex, OperatingSystem operatingSystem, String appVersion, Optional<String> firebaseInstanceId) { super(id); this.deviceIndex = deviceIndex; this.operatingSystem = operatingSystem; this.appVersion = Objects.requireNonNull(appVersion); <START> this.firebaseInstanceId = Objects.requireNonNull(firebaseInstanceId).orElse(null); <END> }</code><technical_language>call Objects.requireNonNull add here. If firebaseInstanceId is null, Objects.requireNonNull throw NPE, occur of call orElse</technical_language>

Target:
private DeviceAnonymized(UUID id, int deviceIndex, OperatingSystem operatingSystem, String appVersion, Optional<String> firebaseInstanceId) { super(id); this.deviceIndex = deviceIndex; this.operatingSystem = operatingSystem; this.appVersion = Objects.requireNonNull(appVersion); this.firebaseInstanceId = firebaseInstanceId.orElse(null); }
Source:
<code>public void close() { <START> db.activateOnCurrentThread(); <END> db.close(); DBUtil.closeDataStore(); }</code><technical_language>Please change this call private method activateOnCurrentThread() a single entry point</technical_language>

Target:
public void close() { activateOnCurrentThread(); db.close(); DBUtil.closeDataStore(); }
Source:
<code>public void testStatementWarnings() throws SQLException { statement.execute("CREATE SCHEMA blackhole.blackhole"); SQLWarning warning = statement.getWarnings(); <START> List<PrestoWarning> expectedWarnings = new TestingWarningCollector(new WarningCollectorConfig(), <END> new TestingWarningCollectorConfig().setPreloadedWarnings(PRELOADED_WARNINGS)).getWarnings().stream() .filter(prestoWarning -> prestoWarning.getWarningCode().getWarningType() == STATEMENT) .collect(toImmutableList()); assertStartsWithExpectedWarnings(warning, fromPrestoWarnings(expectedWarnings)); statement.clearWarnings(); assertNull(statement.getWarnings()); }</code><technical_language>This is a bit hard follow, about: TestingWarningCollectorConfig warningCollectorConfig = new TestingWarningCollectorConfig().setPreloadedWarnings(PRELOADED_WARNINGS); TestingWarningCollector warningCollector = new TestingWarningCollector(new WarningCollectorConfig(), warningCollectorConfig); List<PrestoWarning> expectedWarnings = warningCollector.getWarnings() .stream() .filter(prestoWarning -> prestoWarning.getWarningCode().getWarningType() == STATEMENT) .collect(toImmutableList());</technical_language>

Target:
public void testStatementWarnings() throws SQLException { assertFalse(statement.execute("CREATE SCHEMA blackhole.test_schema")); SQLWarning warning = statement.getWarnings(); assertNotNull(warning); TestingWarningCollectorConfig warningCollectorConfig = new TestingWarningCollectorConfig().setPreloadedWarnings(PRELOADED_WARNINGS); TestingWarningCollector warningCollector = new TestingWarningCollector(new WarningCollectorConfig(), warningCollectorConfig); List<PrestoWarning> expectedWarnings = warningCollector.getWarnings(); assertStartsWithExpectedWarnings(warning, fromPrestoWarnings(expectedWarnings)); statement.clearWarnings(); assertNull(statement.getWarnings()); }