auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>SweepOutcome runOnce() { Optional<TableToSweep> tableToSweep = getTableToSweep(); if (!tableToSweep.isPresent()) { log.debug("Skipping sweep because no table has enough new writes to be worth sweeping at the moment."); return SweepOutcome.NOTHING_TO_SWEEP; } else { <START> specificTableSweeper.runOnceAndSaveResults(tableToSweep.get()); <END> return SweepOutcome.SUCCESS; } }</code><technical_language>This throw a runtimeException, catch set Outcome ERROR</technical_language>

Target:
SweepOutcome runOnce() { Optional<TableToSweep> tableToSweep = getTableToSweep(); if (!tableToSweep.isPresent()) { log.debug("Skipping sweep because no table has enough new writes to be worth sweeping at the moment."); return SweepOutcome.NOTHING_TO_SWEEP; } SweepBatchConfig batchConfig = sweepBatchConfigSource.getAdjustedSweepConfig(); try { specificTableSweeper.runOnceAndSaveResults(tableToSweep.get(), batchConfig); return SweepOutcome.SUCCESS; } catch (InsufficientConsistencyException e) { log.warn("Could not sweep because not all nodes of the database are online.", e); return SweepOutcome.NOT_ENOUGH_DB_NODES_ONLINE; } catch (RuntimeException e) { specificTableSweeper.getSweepMetrics().sweepError(); return determineCauseOfFailure(e, tableToSweep.get()); } }
Source:
<code>private Figure getGroupFigure(List<Figure> dDiagramElementDecorationFigures, Position position, Rectangle expectedGroupBounds) { Figure groupFigure = null; for (Figure currentGroupFigure : dDiagramElementDecorationFigures) { <START> System.out.println("figure bounds " + currentGroupFigure.getBounds()); <END> if (currentGroupFigure.getBounds().equals(expectedGroupBounds)) { groupFigure = currentGroupFigure; break; } } assertNotNull("Bad group decoration position at " + position.getName(), groupFigure); return groupFigure; }</code><technical_language>remove</technical_language>

Target:
private Figure getGroupFigure(List<Figure> dDiagramElementDecorationFigures, Position position, Rectangle expectedGroupBounds) { Figure groupFigure = null; for (Figure currentGroupFigure : dDiagramElementDecorationFigures) { if (currentGroupFigure.getBounds().equals(expectedGroupBounds)) { groupFigure = currentGroupFigure; break; } } assertNotNull("Bad group decoration position at " + position.getName(), groupFigure); return groupFigure; }
Source:
<code>public void testHotReloadSequence() { String storageConf = StorageConfiguration.defaultSystemProperty(StorageConfiguration.CORE_PROPERTY, StorageConfiguration.DEFAULT_CORE); <START> assumeTrue(StorageConfiguration.CORE_VCS.equals(storageConf)); <END> assertEquals(1, getSequence()); assertEquals(2, getSequence()); assertEquals(3, getSequence()); }</code><technical_language>Please add a message argument explain this assume</technical_language>

Target:
public void testHotReloadSequence() { String storageConf = StorageConfiguration.defaultSystemProperty(StorageConfiguration.CORE_PROPERTY, StorageConfiguration.DEFAULT_CORE); assumeTrue("This test only works with VCS", StorageConfiguration.CORE_VCS.equals(storageConf)); Map<String, Object> parameters = new HashMap<>(); parameters.put("sequenceName", "hibernateSequencer"); RestHelper.operation("javascript.getSequence", parameters); }
Source:
<code>public void processHtmlFile(String htmlFile) throws Exception { String fileContent = FileSystemManager.getFileContents(htmlFile); JerryParser parser = new Jerry.JerryParser(); parser.enableHtmlMode(); <START> Jerry htmlParser = parser.parse(fileContent); <END> htmlParser.$("div[data-vault-guid]").each(new JerryFunction() { @Override public boolean onNode(Jerry $this, int index) { String safety = $this.attr("data-vault-guid"); try { $this.html(loader.getSafety(safety)); } catch(SafetyMissingException e) { safetyMissing = true; } catch(IOException e) { log.error("Failed to process update!", e); error = true; } return true; } }); String newContents = htmlParser.html(); if(newContents != null && newContents.trim().length() > 0 && !fileContent.equals(newContents)) { File htmlFileObj = new File(htmlFile); FileSystemManager.writeStringToFile(htmlFileObj.getParent(), htmlFileObj.getName(), newContents); } }</code><technical_language>properly parsing content html? If find a problem parsing HTML, please grep for places this is done. search/src/main/java/com/meltmedia/cadmium/search/SearchContentPreprocessor.java code related this</technical_language>

Target:
public void processHtmlFile(String htmlFile) throws Exception { String fileContent = FileSystemManager.getFileContents(htmlFile); Jerry htmlParser = jerry().parse(fileContent); Jerry divs = htmlParser.$("div[data-vault-guid]"); if(divs.size() > 0) { divs.each(new JerryFunction() { @Override public boolean onNode(Jerry $this, int index) { String safety = $this.attr("data-vault-guid"); try { $this.html(loader.getSafety(safety)); } catch(SafetyMissingException e) { safetyMissing = true; } catch(IOException e) { log.error("Failed to process update!", e); error = true; } return true; } }); String newContents = htmlParser.html(); if(newContents != null && newContents.trim().length() > 0 && !fileContent.equals(newContents)) { File htmlFileObj = new File(htmlFile); FileSystemManager.writeStringToFile(htmlFileObj.getParent(), htmlFileObj.getName(), newContents); } } }
Source:
<code>public synchronized void save(Note note, AuthenticationInfo subject) throws IOException { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setPrettyPrinting(); Gson gson = gsonBuilder.create(); String json = gson.toJson(note); FileObject rootDir = getRootDir(); FileObject noteDir = rootDir.resolveFile(note.getId(), NameScope.CHILD); if (!noteDir.exists()) { noteDir.createFolder(); } if (!isDirectory(noteDir)) { throw new IOException(noteDir.getName().toString() + " is not a directory"); } FileObject noteJson = noteDir.resolveFile(".note.zpln", NameScope.CHILD); OutputStream out = noteJson.getContent().getOutputStream(false); out.write(json.getBytes(conf.getString(ConfVars.ZEPPELIN_ENCODING))); out.close(); <START> setFileName(note, noteJson, noteDir); <END> }</code><technical_language>code this line write file .note.zpln, setFileName do move operation. logic is a confusing me. BTW, method signature setFileName convey do move operation</technical_language>

Target:
public synchronized void save(Note note, AuthenticationInfo subject) throws IOException { String json = note.toJson(); FileObject noteDir = getNoteDir(note.getId()); FileObject noteJson = noteDir.resolveFile(".note.zpln", NameScope.CHILD); OutputStream out = noteJson.getContent().getOutputStream(false); out.write(json.getBytes(conf.getString(ConfVars.ZEPPELIN_ENCODING))); out.close(); String filename = note.getFilename(); if (StringUtils.isBlank(filename)) { filename = Util.convertTitleToFilename(note.getName()); if (StringUtils.isBlank(note.getDirPath())) { note.setDirPath(note.getId() + File.separator); } } noteJson.moveTo(noteDir.resolveFile(filename, NameScope.CHILD)); note.setFilename(filename); String targetFilename = Util.convertTitleToFilename(note.getName()); if (requiresRename(note)) { rename(note.getFilepath(), note.getDirPath() + targetFilename); note.setFilename(targetFilename); } }
Source:
<code>protected byte[] evaluateMessage(int state, final byte[] message) throws SaslException { switch (state) { case INITIAL_STATE: if (message != null && message.length > 0) { throw log.saslInvalidServerMessage(getMechanismName()); } NameCallback nameCallback = new NameCallback("Authentication name"); handleCallbacks(nameCallback); String name = nameCallback.getName(); if (name == null) { throw log.saslNotProvidedUserName(getMechanismName()); } if (name.length() > 255) { throw log.saslAuthenticationNameTooLong(getMechanismName()); } if (name.isEmpty()) { throw log.saslAuthenticationNameIsEmpty(getMechanismName()); } ByteStringBuilder b = new ByteStringBuilder(); StringPrep.encode(name, b, 0 | StringPrep.MAP_TO_NOTHING | StringPrep.MAP_TO_SPACE | StringPrep.FORBID_ASCII_CONTROL | StringPrep.FORBID_NON_ASCII_CONTROL | StringPrep.FORBID_PRIVATE_USE | StringPrep.FORBID_NON_CHARACTER | StringPrep.FORBID_SURROGATE | StringPrep.FORBID_INAPPROPRIATE_FOR_PLAIN_TEXT | StringPrep.FORBID_CHANGE_DISPLAY_AND_DEPRECATED | StringPrep.FORBID_TAGGING | StringPrep.NORMALIZE_KC ); negotiationComplete(); return b.toArray(); } <START> throw new IllegalStateException(); <END> }</code><technical_language>Assert.unreachableCode and/or Assert.impossibleSwitchCase for this case</technical_language>

Target:
protected byte[] evaluateMessage(int state, final byte[] message) throws SaslException { switch (state) { case INITIAL_STATE: if (message != null && message.length > 0) { throw log.saslInvalidServerMessage(getMechanismName()); } NameCallback nameCallback = new NameCallback("Authentication name"); handleCallbacks(nameCallback); String name = nameCallback.getName(); if (name == null) { throw log.saslNotProvidedUserName(getMechanismName()); } if (name.length() > 255) { throw log.saslAuthenticationNameTooLong(getMechanismName()); } if (name.isEmpty()) { throw log.saslAuthenticationNameIsEmpty(getMechanismName()); } ByteStringBuilder b = new ByteStringBuilder(); StringPrep.encode(name, b, 0 | StringPrep.MAP_TO_NOTHING | StringPrep.MAP_TO_SPACE | StringPrep.FORBID_ASCII_CONTROL | StringPrep.FORBID_NON_ASCII_CONTROL | StringPrep.FORBID_PRIVATE_USE | StringPrep.FORBID_NON_CHARACTER | StringPrep.FORBID_SURROGATE | StringPrep.FORBID_INAPPROPRIATE_FOR_PLAIN_TEXT | StringPrep.FORBID_CHANGE_DISPLAY_AND_DEPRECATED | StringPrep.FORBID_TAGGING | StringPrep.NORMALIZE_KC ); negotiationComplete(); return b.toArray(); } throw Assert.impossibleSwitchCase(state); }
Source:
<code>public static List<Object> replaceByteBuffersByHexString(Object... values) { ArrayList<Object> boundValues = new ArrayList<>(Arrays.asList(values)); for (int valuePos = 0; valuePos < boundValues.size(); valuePos++) { Object boundValue = boundValues.get(valuePos); if (boundValue instanceof ByteBuffer) { ByteBuffer byteBuffer = (ByteBuffer) boundValue; byte[] extracted = new byte[min(byteBuffer.remaining(), HEX_STRING_LOG_LIMIT)]; byteBuffer.get(extracted).rewind(); boundValues.set(valuePos, Bytes.toHexString(extracted) + ((byteBuffer.remaining() > HEX_STRING_LOG_LIMIT) ? "..." : "")); } else if (boundValue instanceof byte[]) { byte[] byteArray = (byte[]) boundValue; <START> boundValues.set(valuePos, Bytes.toHexString(((byteArray.length > HEX_STRING_LOG_LIMIT) ? Arrays.copyOfRange(byteArray, 0, HEX_STRING_LOG_LIMIT) : byteArray)) + ((byteArray.length > HEX_STRING_LOG_LIMIT) ? "..." : "")); <END> } } return boundValues; }</code><technical_language>put ? "..." : "" logic appearrs in branches worse in else a nested ternary op in a method</technical_language>

Target:
public static List<Object> replaceByteBuffersByHexString(Object... values) { ArrayList<Object> boundValues = new ArrayList<>(Arrays.asList(values)); for (int valuePos = 0; valuePos < boundValues.size(); valuePos++) { Object boundValue = boundValues.get(valuePos); if (boundValue instanceof ByteBuffer) { ByteBuffer bbBoundedValue = (ByteBuffer) boundValue; byte[] firstBytes = new byte[min(bbBoundedValue.remaining(), HEX_STRING_LOG_LIMIT)]; bbBoundedValue.get(firstBytes).rewind(); boundValues.set(valuePos, toHexString(firstBytes, bbBoundedValue.remaining())); } else if (boundValue instanceof byte[]) { byte[] baBoundedValue = (byte[]) boundValue; byte[] firstBytes = baBoundedValue.length > HEX_STRING_LOG_LIMIT ? Arrays.copyOfRange(baBoundedValue, 0, HEX_STRING_LOG_LIMIT) : baBoundedValue; boundValues.set(valuePos, toHexString(firstBytes, baBoundedValue.length)); } } return boundValues; }
Source:
<code>public void showAssigneePicker_pickAUser_userPickedAssigned() { TurboIssue issue = getIssueCell(0, 9).getIssue(); triggerAssigneePicker(issue); type("User 1"); push(KeyCode.ENTER); assertEquals("User 1", issue.getAssignee().get()); <START> exitCleanly(); <END> }</code><technical_language>put a @Before for exitCleanly(); means manually call in @Test method</technical_language>

Target:
public void showAssigneePicker_pickAUser_userPickedAssigned() { TurboIssue issue = getIssueCell(0, 9).getIssue(); triggerAssigneePicker(issue); type("User 1"); push(KeyCode.ENTER); assertEquals("User 1", issue.getAssignee().get()); }
Source:
<code>public static byte[] decode(String s) { <START> int delta = s.endsWith("==") ? 2 : endsWithEqualSymbol(s); <END> byte[] buffer = new byte[s.length() * 3 / 4 - delta]; int mask = 0xFF; int index = 0; for (int i = 0; i < s.length(); i += 4) { int c0 = toInt[s.charAt(i)]; int c1 = toInt[s.charAt(i + 1)]; buffer[index++] = (byte) (((c0 << 2) | (c1 >> 4)) & mask); if (index >= buffer.length) return buffer; int c2 = toInt[s.charAt(i + 2)]; buffer[index++] = (byte) (((c1 << 4) | (c2 >> 2)) & mask); if (index >= buffer.length) return buffer; int c3 = toInt[s.charAt(i + 3)]; buffer[index++] = (byte) (((c2 << 6) | c3) & mask); } return buffer; }</code><technical_language>I this improves readability. a boolean returns int. prefer if wrap this expression in parentheses improve readability</technical_language>

Target:
public static byte[] decode(String s) { int delta = s.endsWith("==") ? 2 : (s.endsWith("=") ? 1 : 0); byte[] buffer = new byte[s.length() * 3 / 4 - delta]; int mask = 0xFF; int index = 0; for (int i = 0; i < s.length(); i += 4) { int c0 = toInt[s.charAt(i)]; int c1 = toInt[s.charAt(i + 1)]; buffer[index++] = (byte) (((c0 << 2) | (c1 >> 4)) & mask); if (index >= buffer.length) { return buffer; } int c2 = toInt[s.charAt(i + 2)]; buffer[index++] = (byte) (((c1 << 4) | (c2 >> 2)) & mask); if (index >= buffer.length) { return buffer; } int c3 = toInt[s.charAt(i + 3)]; buffer[index++] = (byte) (((c2 << 6) | c3) & mask); } return buffer; }
Source:
<code>public static void assertRunIsUnloadable(Class<? extends Runnable> runnable, ClassLoader parent) { System.setProperty("java.util.logging.manager", LogManager.class.getName()); assertThat(LogManager.getLogManager().getClass()).isSameAs(LogManager.class); WeakReference<ClassLoader> loader; try { loader = invokeRunFromNewClassLoader(runnable, parent); } catch (Exception e) { throw new AssertionError(e); } try { GarbageCollectors.blockOnGC(loader); <START> } catch (ConditionTimeoutException t) { <END> } assertThat(loader.get()) .withFailMessage(runnable + " includes state that couldn't be garbage collected") .isNull(); }</code><technical_language>this exception bites times is of reasons I dislike awaitility. crashes test instead of failing it</technical_language>

Target:
public static void assertRunIsUnloadable(Class<? extends Runnable> runnable, ClassLoader parent) { System.setProperty("java.util.logging.manager", LogManager.class.getName()); assertThat(LogManager.getLogManager().getClass()).isSameAs(LogManager.class); WeakReference<ClassLoader> loader; try { loader = invokeRunFromNewClassLoader(runnable, parent); } catch (Exception e) { throw new AssertionError(e); } GarbageCollectors.blockOnGC(loader); assertThat(loader.get()) .withFailMessage(runnable + " includes state that couldn't be garbage collected") .isNull(); }
Source:
<code><START> public static Operation createDeploymentAddOperation(final Path content, final String name, final String runtimeName) { <END> Assertions.requiresNotNullParameter(content, "content"); final ModelNode address = createAddress(DEPLOYMENT, name); final ModelNode addOperation = createAddOperation(address); if (runtimeName != null) { addOperation.get(RUNTIME_NAME).set(runtimeName); } final CompositeOperationBuilder builder = CompositeOperationBuilder.create(true); addContent(builder, addOperation, content); builder.addStep(addOperation); return builder.build(); }</code><technical_language>Do need this one, createDeployOperation(final Deployment deployment)</technical_language>

Target:
public static Operation createDeploymentAddOperation(final Path content, final String name, final String runtimeName) { Assertions.requiresNotNullParameter(content, "content"); final ModelNode address = createAddress(DEPLOYMENT, name); final ModelNode addOperation = createAddOperation(address); if (runtimeName != null) { addOperation.get(RUNTIME_NAME).set(runtimeName); } final CompositeOperationBuilder builder = CompositeOperationBuilder.create(true); DeploymentContent.of(content).addContentToOperation(builder, addOperation); builder.addStep(addOperation); return builder.build(); }
Source:
<code>public int numbered() { <START> return getInt("numbered"); <END> }</code><technical_language>return type of numbered (or isNumbered) a boolean</technical_language>

Target:
public boolean numbered() { return isNumbered(); }
Source:
<code>public void testImportVMFromConfigurationWhenVMDoesNotExists() { initCommand(null); assertFalse(cmd.canDoAction()); <START> Assert.assertTrue(cmd.getReturnValue() <END> .getCanDoActionMessages() .contains(VdcBllMessages.ACTION_TYPE_FAILED_UNSUPPORTED_OVF.toString())); }</code><technical_language>remove 'Assert.' (there's a static import)</technical_language>

Target:
public void testImportVMFromConfigurationWhenVMDoesNotExists() { initCommand(null); assertFalse(cmd.canDoAction()); assertTrue(cmd.getReturnValue() .getCanDoActionMessages() .contains(VdcBllMessages.ACTION_TYPE_FAILED_UNSUPPORTED_OVF.toString())); }
Source:
<code>public static boolean isNACKPacket(ByteArrayBuffer baf) { int rc = RTCPHeaderUtils.getReportCount(baf); <START> return isRTPFBPacket(baf) && rc == FMT; <END> }</code><technical_language>i talked swapping order of short-circuit</technical_language>

Target:
public static boolean isNACKPacket(ByteArrayBuffer baf) { int rc = RTCPHeaderUtils.getReportCount(baf); return rc == FMT && isRTPFBPacket(baf); }
Source:
<code>public ApiResponse getCountersForInterval(ArrayList<String> counterArray, Date startTime, Date endTime, String resolution) { String counters = "?counter=" + counterArray.get(0); for (int i = 1; i < counterArray.size(); i++) { counters += "&counter="; counters += counterArray.get(i); } counters += "&start_time="; <START> counters += Long.toString(startTime.getTime()); <END> counters += "&end_time="; counters += Long.toString(endTime.getTime()); counters += "&resolution="; counters += resolution; return apiRequest(HTTP_METHOD_GET, null, null, organizationId, applicationId, "counters", counters); }</code><technical_language>checking for null a toString()</technical_language>

Target:
public ApiResponse getCountersForInterval(ArrayList<String> counterArray, Date startTime, Date endTime, String resolution) { String counters = null; if (counterArray != null) { counters = "?counter=" + counterArray.get(0); for (int i = 1; i < counterArray.size(); i++) { counters += "&counter="; counters += counterArray.get(i); } if (startTime != null) { counters += "&start_time="; counters += startTime.getTime(); } if (endTime != null) { counters += "&end_time="; counters += endTime.getTime(); } counters += "&resolution="; counters += resolution; } return apiRequest(HTTP_METHOD_GET, null, null, organizationId, applicationId, "counters", counters); }
Source:
<code>protected CompletionStage<Void> asyncWritePart(AsyncOutputStream entityStream, byte[] boundaryBytes, OutputPart part, MultivaluedMap<String, Object> headers) { headers.putAll(part.getHeaders()); headers.putSingle(HttpHeaderNames.CONTENT_TYPE, part.getMediaType()); Object entity = part.getEntity(); Class<?> entityType = part.getType(); Type entityGenericType = part.getGenericType(); AsyncMessageBodyWriter writer = (AsyncMessageBodyWriter) workers.getMessageBodyWriter(entityType, entityGenericType, null, part.getMediaType()); LogMessages.LOGGER.debugf("MessageBodyWriter: %s", writer.getClass().getName()); return entityStream.asyncWrite(boundaryBytes) <START> .thenCompose(v -> entityStream.asyncWrite("\r\n".getBytes())) <END> .thenCompose(v -> writer.asyncWriteTo(entity, entityType, entityGenericType, null, part.getMediaType(), headers, new HeaderFlushedAsyncOutputStream(headers, entityStream))) .thenCompose(v -> entityStream.asyncWrite("\r\n".getBytes())); }</code><technical_language>"-r-n".getBytes() a constant (and a charset)</technical_language>

Target:
protected CompletionStage<Void> asyncWritePart(AsyncOutputStream entityStream, byte[] boundaryBytes, OutputPart part, MultivaluedMap<String, Object> headers) { headers.putAll(part.getHeaders()); headers.putSingle(HttpHeaderNames.CONTENT_TYPE, part.getMediaType()); Object entity = part.getEntity(); Class<?> entityType = part.getType(); Type entityGenericType = part.getGenericType(); AsyncMessageBodyWriter writer = (AsyncMessageBodyWriter) workers.getMessageBodyWriter(entityType, entityGenericType, null, part.getMediaType()); LogMessages.LOGGER.debugf("MessageBodyWriter: %s", writer.getClass().getName()); return entityStream.asyncWrite(boundaryBytes) .thenCompose(v -> entityStream.asyncWrite(LINE_SEPARATOR_BYTES)) .thenCompose(v -> writer.asyncWriteTo(entity, entityType, entityGenericType, null, part.getMediaType(), headers, new HeaderFlushedAsyncOutputStream(headers, entityStream))) .thenCompose(v -> entityStream.asyncWrite(LINE_SEPARATOR_BYTES)); }
Source:
<code>public static void checkMaxLength(String propertyName, String actualValue, int maxLength) throws MaxSizeExceededException{ <START> if(actualValue.length() > maxLength) throw new MaxSizeExceededException("Length of '" + propertyName + "' is too long! MaxLength=" + maxLength + ", ActualLength=" + actualValue.length()); <END> }</code><technical_language>cover case, passed is null, Candidate params titleBefore/titleAfter null empty</technical_language>

Target:
public static void checkMaxLength(String propertyName, String actualValue, int maxLength) throws MaxSizeExceededException { if (actualValue == null) { return; } if (actualValue.length() > maxLength) { throw new MaxSizeExceededException("Length of '" + propertyName + "' is too long! MaxLength=" + maxLength + ", ActualLength=" + actualValue.length()); } }
Source:
<code>public Map<String, String[]> asMap() { Map<String, String[]> map = new HashMap<>(); if (href != null) { map.put("href", new String[]{ href.toString() }); } if (params != null) { for (Entry<String, String> entry : params.entrySet()) { <START> map.put(entry.getKey(), new String[] { entry.getValue() }); <END> } } return Collections.unmodifiableMap(map); }</code><technical_language>guaranteed of entries a key = href? I safer clearer map key params.xxx</technical_language>

Target:
public Map<String, String[]> asMap() { Map<String, String[]> map = new HashMap<>(); if (href != null) { map.put(HREF, new String[]{ href.toString() }); } if (params != null) { for (Entry<String, String> entry : params.entrySet()) { map.put(String.format(PARAMS_PREFIX, entry.getKey()), new String[] { entry.getValue() }); } } return Collections.unmodifiableMap(map); }
Source:
<code><START> public void testDoNotPushdownPredicateIfNonFilteredAggregateIsPresent() <END> { assertPlan( "SELECT sum(totalprice) FILTER(WHERE totalprice > 0), sum(custkey) FROM orders", anyTree( aggregation( ImmutableMap.of("sum_2", functionCall("sum", ImmutableList.of("sum_13")), "sum", functionCall("sum", ImmutableList.of("sum_12"))), exchange( aggregation( ImmutableMap.of("sum_12", functionCall("sum", ImmutableList.of("totalprice")), "sum_13", functionCall("sum", ImmutableList.of("custkey"))), project( tableScan( "orders", ImmutableMap.of("totalprice", "totalprice", "custkey", "custkey")))))))); }</code><technical_language>instead like: com.facebook.presto.sql.planner.TestLogicalPlanner#assertPlanContainsNoApplyOrAnyJoin if is filter node</technical_language>

Target:
public void testDoNotPushdownPredicateIfNonFilteredAggregateIsPresent() { assertPlanContainsNoFilter("SELECT sum(totalprice) FILTER(WHERE totalprice > 0), sum(custkey) FROM orders"); }
Source:
<code><START> public void updateFeedbackResponseOptimized(FeedbackResponseAttributes newAttributes, FeedbackResponse fr, boolean keepUpdateTimestamp) <END> throws InvalidParametersException, EntityDoesNotExistException { Assumption.assertNotNull( Const.StatusCodes.DBLEVEL_NULL_INPUT, newAttributes); if (!newAttributes.isValid()) { throw new InvalidParametersException(newAttributes.getInvalidityInfo()); } if (fr == null) { throw new EntityDoesNotExistException( ERROR_UPDATE_NON_EXISTENT + newAttributes.toString()); } fr.keepUpdateTimestamp = keepUpdateTimestamp; fr.setAnswer(newAttributes.responseMetaData); fr.setRecipientEmail(newAttributes.recipientEmail); fr.setGiverSection(newAttributes.giverSection); fr.setRecipientSection(newAttributes.recipientSection); log.info(newAttributes.getBackupIdentifier()); getPM().close(); }</code><technical_language>if some of updateFeedbackResponse methods private. I a feeling need public, now</technical_language>

Target:
private void updateFeedbackResponseOptimized(FeedbackResponseAttributes newAttributes, FeedbackResponse fr, boolean keepUpdateTimestamp) throws InvalidParametersException, EntityDoesNotExistException { Assumption.assertNotNull( Const.StatusCodes.DBLEVEL_NULL_INPUT, newAttributes); if (!newAttributes.isValid()) { throw new InvalidParametersException(newAttributes.getInvalidityInfo()); } if (fr == null) { throw new EntityDoesNotExistException( ERROR_UPDATE_NON_EXISTENT + newAttributes.toString()); } fr.keepUpdateTimestamp = keepUpdateTimestamp; fr.setAnswer(newAttributes.responseMetaData); fr.setRecipientEmail(newAttributes.recipientEmail); fr.setGiverSection(newAttributes.giverSection); fr.setRecipientSection(newAttributes.recipientSection); log.info(newAttributes.getBackupIdentifier()); getPM().close(); }
Source:
<code>private boolean isValidTag(GoTag tag) { <START> StringBuilder tagText = new StringBuilder(tag.getText().substring(1, tag.getTextLength() - 1)); <END> while (tagText.length() > 0) { int i; i = 0; while (i < tagText.length() && tagText.charAt(i) == ' ') { i++; } tagText.delete(0, i); if (tagText.length() == 0) { return true; } i = 0; while (i < tagText.length() && tagText.charAt(i) > ' ' && tagText.charAt(i) != ':' && tagText.charAt(i) != '"' && tagText.charAt(i) != 0x7f) { i++; } if (i == 0 || (i + 1) > tagText.length() || tagText.charAt(i) != ':') { return false; } tagText.delete(0, i + 1); i = 1; while (i < tagText.length() && tagText.charAt(i) != '"') { if (tagText.charAt(i) == '\\') { i++; } i++; } if (i >= tagText.length()) { return false; } tagText.delete(0, i + 1); } return true; }</code><technical_language>I insist GoPsiImplUtil#unquote. Remember IDE handle incomplete go-code, this substring is unsafe produce IOOBE e.g. this code: package demo; type demoBrokenTags struct { WrongTag9 string</technical_language>

Target:
private boolean isValidTag(GoTag tag) { StringBuilder tagText = new StringBuilder(GoPsiImplUtil.unquote(tag.getText())); if (tagText.length() != tag.getText().length() - 2) { return false; } while (tagText.length() > 0) { int i; i = 0; while (i < tagText.length() && tagText.charAt(i) == ' ') { i++; } tagText.delete(0, i); if (tagText.length() == 0) { return true; } i = 0; while (i < tagText.length() && tagText.charAt(i) > ' ' && tagText.charAt(i) != ':' && tagText.charAt(i) != '"' && tagText.charAt(i) != 0x7f) { i++; } if (i == 0 || (i + 1) > tagText.length() || tagText.charAt(i) != ':') { return false; } tagText.delete(0, i + 1); i = 1; while (i < tagText.length() && tagText.charAt(i) != '"') { if (tagText.charAt(i) == '\\') { i++; } i++; } if (i >= tagText.length()) { return false; } String unquotedValue = GoPsiImplUtil.unquote(tagText.substring(0, i + 1)); if (unquotedValue.length() != i - 1) { return false; } tagText.delete(0, i + 1); } return true; }
Source:
<code>private Result(EventProducer producer, Object rawMethodResult) { super(producer, rawMethodResult); List<Message> eventMessages = toMessages(rawMethodResult); List<Message> withoutEmpty = filterEmpty(eventMessages); checkResultNonEmpty(withoutEmpty, rawMethodResult, producer); <START> setMessages(withoutEmpty); <END> }</code><technical_language>withoutEmtpy is confusing in 2 lines above. read "check result non-empty in empty" "set messages empty". filteredMessages, filtered else? read java checkResultNonEmpty(filteredMessages, rawMethodResult, producer); setMessages(filteredMessages);</technical_language>

Target:
private Result(EventProducer producer, Object rawMethodResult) { super(producer, rawMethodResult); List<Message> eventMessages = toMessages(rawMethodResult); List<Message> filtered = filterEmpty(eventMessages); ensureNotEmptyIfNotProcessManager(filtered, rawMethodResult, producer); setMessages(filtered); }
Source:
<code>public void addDataCollector(Module module, String monitoringManagerIp, int monitoringManagerPort, String influxdbIp, int influxdbPort) { <START> if(module.getHost().getDeploymentType().equals("IaaS")){ <END> logger.info("Generating required deployment script for the MODAClouds Data Collector."); Map<String, Object> dataCollector = this.generateDcNodeTemplate(this .getRequiredEnvVars(module, monitoringManagerIp, monitoringManagerPort, influxdbIp, influxdbPort), module); module.addDataCollector(dataCollector); } }</code><technical_language>IaaS part of enum WDYT</technical_language>

Target:
public void addDataCollector(Module module, String monitoringManagerIp, int monitoringManagerPort, String influxdbIp, int influxdbPort) { if(module.getHost().getDeploymentType().equals(DeploymentType.IaaS)){ logger.info("Generating required deployment script for the MODAClouds Data Collector."); Map<String, Object> dataCollector = this.generateDcNodeTemplate(this .getRequiredEnvVars(module, monitoringManagerIp, monitoringManagerPort, influxdbIp, influxdbPort), module); module.addDataCollector(dataCollector); } }
Source:
<code>private LayoutAlgorithmTransition( LayoutModelAware<N, E, P> visualizationModel, LayoutAlgorithm<N, P> endLayoutAlgorithm) { if (log.isTraceEnabled()) { log.trace( "transition from to {}", visualizationModel.getLayoutAlgorithm(), endLayoutAlgorithm); } this.layoutModelAware = visualizationModel; this.layoutModel = visualizationModel.getLayoutModel(); layoutModel.stopRelaxer(); this.pointModel = layoutModel.getPointModel(); LayoutAlgorithm<N, P> transitionLayoutAlgorithm = new StaticLayoutAlgorithm(pointModel); visualizationModel.setLayoutAlgorithm(transitionLayoutAlgorithm); this.transitionLayoutModel = new LoadingCacheLayoutModel.Builder() .setGraph(visualizationModel.getNetwork().asGraph()) <START> .setPointModel(layoutModel.getPointModel()) <END> .setSize(layoutModel.getWidth(), layoutModel.getHeight(), layoutModel.getDepth()) .build(); transitionLayoutModel.accept(endLayoutAlgorithm); this.endLayoutAlgorithm = endLayoutAlgorithm; if (animator != null) { animator.stop(); } animator = new Animator(this); animator.start(); }</code><technical_language>I missing something, if a lot of data is coming LayoutModel, reason a LayoutModel setter builder, thus? this.transitionLayoutModel = LoadingCacheLayoutModel.builder() .setGraph(visualizationModel.getNetwork().asGraph()) .setLayoutModel(layoutModel) .build(); WDYT? do need setters for point model dimensions for cases in deriving a LayoutModel--or appears--but if this is a common case consider supporting more elegantly</technical_language>

Target:
private LayoutAlgorithmTransition( LayoutModelAware<N, E, P> visualizationModel, LayoutAlgorithm<N, P> endLayoutAlgorithm) { if (log.isTraceEnabled()) { log.trace( "transition from to {}", visualizationModel.getLayoutAlgorithm(), endLayoutAlgorithm); } this.layoutModelAware = visualizationModel; this.layoutModel = visualizationModel.getLayoutModel(); layoutModel.stopRelaxer(); this.pointModel = layoutModel.getPointModel(); LayoutAlgorithm<N, P> transitionLayoutAlgorithm = new StaticLayoutAlgorithm(); visualizationModel.setLayoutAlgorithm(transitionLayoutAlgorithm); this.transitionLayoutModel = LoadingCacheLayoutModel.<N, P>builder() .setGraph(visualizationModel.getNetwork().asGraph()) .setLayoutModel(layoutModel) .build(); transitionLayoutModel.accept(endLayoutAlgorithm); this.endLayoutAlgorithm = endLayoutAlgorithm; if (animator != null) { animator.stop(); } animator = new Animator(this); animator.start(); }
Source:
<code>public void invoke_put_once_when_calling_getDefaultState_in_multithreaded_environment() { int numberOfEntities = 1000; Collection<Callable<Object>> tasks = newArrayListWithExpectedSize(numberOfEntities); for (int i = 0; i < numberOfEntities; i++) { <START> tasks.add(Executors.callable(() -> { <END> TestEntity testEntity = Given.entityOfClass(TestEntity.class) .build(); testEntity.getDefaultState(); })); } runParallel(tasks); int expected = 1; verify(spyMap, times(expected)).put(any(), any()); assertEquals(expected, spyMap.size()); }</code><technical_language>Please add a static import</technical_language>

Target:
public void invoke_put_once_when_calling_getDefaultState_in_multithreaded_environment() { int numberOfEntities = 1000; Collection<Callable<Object>> tasks = newArrayListWithExpectedSize(numberOfEntities); for (int i = 0; i < numberOfEntities; i++) { tasks.add(callable(() -> { TestEntity testEntity = Given.entityOfClass(TestEntity.class) .build(); testEntity.getDefaultState(); })); } runParallel(tasks); int expected = 1; verify(spyMap, times(expected)).put(any(), any()); assertEquals(expected, spyMap.size()); }
Source:
<code>protected void doInit() { super.doInit(); _tableSchema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType); Preconditions.checkState(_tableSchema != null, "Failed to find schema for table: %s", _tableNameWithType); _primaryKeyColumns = _tableSchema.getPrimaryKeyColumns(); Preconditions.checkState(!CollectionUtils.isEmpty(_primaryKeyColumns), <START> "Primary key columns must be configured for dimension table: %s", _tableNameWithType); <END> }</code><technical_language>Please move this check table creation code in controller. ensure other checks well: (1) table type OFFLINE (2) table ingestion REFRESH</technical_language>

Target:
protected void doInit() { super.doInit(); _tableSchema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType); _primaryKeyColumns = _tableSchema.getPrimaryKeyColumns(); }
Source:
<code>public DeploymentBody getDeploymentTemplate() { addStorageResource(); addPublicIpAddress(); addNetworkSecurityGroup(); addNetworkInterfaceCard(); addVirtualMachine(); DeploymentTemplate.TemplateParameters templateParameters = DeploymentTemplate.TemplateParameters.create(null); <START> DeploymentTemplate.Parameters parameters = DeploymentTemplate.Parameters.create(null); <END> if (keyVaultInUse()){ String[] keyVaultInfo = options.getKeyVaultIdAndSecret().split(":"); assert keyVaultInfo.length == 2; String vaultId = keyVaultInfo[0].trim(); String secretName = keyVaultInfo[1].trim(); templateParameters = DeploymentTemplate.TemplateParameters.create(TemplateParameterType.create("securestring")); parameters = DeploymentTemplate.Parameters.create(KeyVaultReference.create(KeyVaultReference.Reference.create(IdReference.create(vaultId), secretName))); } DeploymentTemplate template = DeploymentTemplate.builder() .schema("<LINK_0>") .contentVersion("1.0.0.0") .resources(resources) .variables(variables) .parameters(templateParameters) .build(); DeploymentBody body = DeploymentBody.create(template, DEPLOYMENT_MODE, parameters); return body; }</code><technical_language>Initialize in else clause avoid creating object immediately override it</technical_language>

Target:
public DeploymentBody getDeploymentTemplate() { addStorageResource(); addPublicIpAddress(); addNetworkSecurityGroup(); addNetworkInterfaceCard(); addVirtualMachine(); DeploymentTemplate.TemplateParameters templateParameters = null; DeploymentTemplate.Parameters parameters = null; if (keyVaultInUse()){ String[] keyVaultInfo = options.getKeyVaultIdAndSecret().split(":"); Preconditions.checkArgument(keyVaultInfo.length == 2); String vaultId = keyVaultInfo[0].trim(); String secretName = keyVaultInfo[1].trim(); templateParameters = DeploymentTemplate.TemplateParameters.create(TemplateParameterType.create("securestring")); parameters = DeploymentTemplate.Parameters.create(KeyVaultReference.create(KeyVaultReference.Reference.create(IdReference.create(vaultId), secretName))); } else { templateParameters = DeploymentTemplate.TemplateParameters.create(null); parameters = DeploymentTemplate.Parameters.create(null); } DeploymentTemplate template = DeploymentTemplate.builder() .schema("<LINK_0>") .contentVersion("1.0.0.0") .resources(resources) .variables(variables) .parameters(templateParameters) .build(); DeploymentBody body = DeploymentBody.create(template, DEPLOYMENT_MODE, parameters); return body; }
Source:
<code><START> public ProjectQualityGate getQualityGateBefore52() throws Exception { <END> String url = serverUrl + API_MEASURES + "?componentKey=" + projectKey + "&metricKeys=alert_status"; String text = client.getHttp(url, username, password); JSONObject json = (JSONObject) JSONSerializer.toJSON(text); if (json.containsKey("errors")) { throw new MessageException(parseError(json)); } JSONObject component = json.getJSONObject("component"); String projectName = component.getString("name"); JSONArray measuresArray = component.getJSONArray("measures"); for (Object o : measuresArray) { JSONObject jsonObj = (JSONObject) o; String metric = jsonObj.getString("metric"); if ("alert_status".equals(metric)) { return new ProjectQualityGate(projectName, jsonObj.getString("value")); } } return null; }</code><technical_language>![MAJOR](<LINK_0> Define throw a dedicated exception instead of a generic one. [![rule](<LINK_2>](<LINK_1></technical_language>

Target:
public ProjectQualityGate getQualityGateBefore52() throws Exception { String url = serverUrl + API_RESOURCES + encode(projectKey); String text = client.getHttp(url, username, password); JSONArray resourceArray = (JSONArray) JSONSerializer.toJSON(text); if (resourceArray.size() != 1) { Logger.LOG.fine("Found " + resourceArray.size() + " resources for " + projectKey); return null; } JSONObject resource = resourceArray.getJSONObject(0); String projectName = resource.getString("name"); JSONArray measuresArray = resource.getJSONArray("msr"); for (Object o : measuresArray) { JSONObject jsonObj = (JSONObject) o; String key = jsonObj.getString("key"); if ("alert_status".equals(key)) { return new ProjectQualityGate(projectName, jsonObj.getString("data")); } } return null; }
Source:
<code>private void checkGroupingSetsCount(GroupBy node) { int crossProduct = 1; for (GroupingElement element : node.getGroupingElements()) { try { <START> int product = 1; <END> if (element instanceof Cube) { int exponent = element.getColumns().size(); if (exponent > 30) { throw new ArithmeticException(); } product = 1 << exponent; } else if (element instanceof Rollup) { product = element.getColumns().size() + 1; } else if (element instanceof GroupingSets) { product = ((GroupingSets) element).getSets().size(); } crossProduct = Math.multiplyExact(crossProduct, product); } catch (ArithmeticException e) { throw new SemanticException(TOO_MANY_GROUPING_SETS, node, "GROUP BY has more than %s grouping sets but can contain at most %s", Integer.MAX_VALUE, getMaxGroupingSets(session)); } if (crossProduct > getMaxGroupingSets(session)) { throw new SemanticException(TOO_MANY_GROUPING_SETS, node, "GROUP BY has %s grouping sets but can contain at most %s", crossProduct, getMaxGroupingSets(session)); } } }</code><technical_language>handle supported cases explicitly (or a visitor)</technical_language>

Target:
private void checkGroupingSetsCount(GroupBy node) { int crossProduct = 1; for (GroupingElement element : node.getGroupingElements()) { try { int product; if (element instanceof SimpleGroupBy) { product = 1; } else if (element instanceof Cube) { int exponent = element.getExpressions().size(); if (exponent > 30) { throw new ArithmeticException(); } product = 1 << exponent; } else if (element instanceof Rollup) { product = element.getExpressions().size() + 1; } else if (element instanceof GroupingSets) { product = ((GroupingSets) element).getSets().size(); } else { throw new UnsupportedOperationException("Unsupported grouping element type: " + element.getClass().getName()); } crossProduct = Math.multiplyExact(crossProduct, product); } catch (ArithmeticException e) { throw new SemanticException(TOO_MANY_GROUPING_SETS, node, "GROUP BY has more than %s grouping sets but can contain at most %s", Integer.MAX_VALUE, getMaxGroupingSets(session)); } if (crossProduct > getMaxGroupingSets(session)) { throw new SemanticException(TOO_MANY_GROUPING_SETS, node, "GROUP BY has %s grouping sets but can contain at most %s", crossProduct, getMaxGroupingSets(session)); } } }
Source:
<code>private void tickIfNecessary() { State oldState = state.get(); long newTick = clock.nanoTime(); long age = newTick - oldState.lastTick; <START> if (age > INTERVAL_SIZE) { <END> long currentCount = currentInterval.longValue(); long newIntervalStartTick = newTick - age % INTERVAL_SIZE; long elapsedIntervals = Math.min(age / INTERVAL_SIZE, 12); int newOffset = (int) ((oldState.offset + elapsedIntervals) % 12); long newTotal; if (elapsedIntervals == 12) { newTotal = 0; } else { newTotal = oldState.totalCount + currentCount; for (int i = 1; i <= elapsedIntervals; i++) { newTotal -= previousIntervals.get((newOffset + 12 - i) % 12); } } State newState = new State(newIntervalStartTick, newOffset, newTotal); if (state.compareAndSet(oldState, newState)) { currentInterval.add(-currentCount); previousIntervals.set(oldState.offset, elapsedIntervals < 12 ? currentCount : 0); for (int i = 1; i < elapsedIntervals; i++) { previousIntervals.set((newOffset + 12 - i) % 12, 0); } } } }</code><technical_language>Time slots in long array bound inclusive upper bound exclusive, this comparison age >= INTERVAL_SIZE</technical_language>

Target:
private void tickIfNecessary() { State oldState = state.get(); long newTick = clock.nanoTime(); long age = newTick - oldState.lastTick; if (age >= INTERVAL_SIZE) { long currentCount = currentInterval.get(); long newIntervalStartTick = newTick - age % INTERVAL_SIZE; long elapsedIntervals = Math.min(age / INTERVAL_SIZE, 12); int newOffset = (int) ((oldState.offset + elapsedIntervals) % 12); long newTotal; if (elapsedIntervals == 12) { newTotal = 0; } else { newTotal = oldState.totalCount + currentCount; for (int i = 1; i <= elapsedIntervals; i++) { newTotal -= previousIntervals.get((newOffset + 12 - i) % 12); } } State newState = new State(newIntervalStartTick, newOffset, newTotal); if (state.compareAndSet(oldState, newState)) { currentInterval.addAndGet(-currentCount); previousIntervals.set(oldState.offset, elapsedIntervals < 12 ? currentCount : 0); for (int i = 1; i < elapsedIntervals; i++) { previousIntervals.set((newOffset + 12 - i) % 12, 0); } } } }
Source:
<code>public void setAwake(Registration reg) { if (reg.usesQueueMode()) { if (!clientStatusList.containsKey(reg.getEndpoint())) { createPresenceStatusObject(reg); } boolean stateChanged = false; synchronized (this) { stateChanged = clientStatusList.get(reg.getEndpoint()).setAwake(); <START> startClientAwakeTimer(reg); <END> } if (stateChanged) { for (PresenceListener listener : listeners) { listener.onAwake(reg); } } } }</code><technical_language>needed in synchronized block</technical_language>

Target:
public void setAwake(Registration reg) { if (reg.usesQueueMode()) { PresenceStatus status = new PresenceStatus(); PresenceStatus previous = clientStatusList.putIfAbsent(reg.getEndpoint(), status); if (previous != null) { status = previous; } boolean stateChanged = false; synchronized (status) { stateChanged = status.setAwake(); startClientAwakeTimer(reg, status); } if (stateChanged) { for (PresenceListener listener : listeners) { listener.onAwake(reg); } } } }
Source:
<code><START> public static Module module() { <END> return new AbstractModule() { @Override protected void configure() { bind(ThreadLocalRequestContext.class); bind(RequestContext.class).annotatedWith(Names.named("FALLBACK")) .to(FallbackRequestContext.class); } @Provides RequestContext provideRequestContext( @Named("FALLBACK") RequestContext fallback) { return Objects.firstNonNull(local.get(), fallback); } @Provides CurrentUser provideCurrentUser(RequestContext ctx) { return ctx.getCurrentUser(); } @Provides IdentifiedUser provideCurrentUser(CurrentUser user) { if (user instanceof IdentifiedUser) { return (IdentifiedUser) user; } throw new ProvisionException(NotSignedInException.MESSAGE, new NotSignedInException()); } }; }</code><technical_language>install this module in this change? in GerritGlobalModule? try link a new module sites part of change declares it</technical_language>

Target:
public static Module module() { return new AbstractModule() { @Override protected void configure() { bind(ThreadLocalRequestContext.class); bind(RequestContext.class).annotatedWith(Names.named(FALLBACK)) .to(FallbackRequestContext.class); } @Provides RequestContext provideRequestContext( @Named(FALLBACK) RequestContext fallback) { return Objects.firstNonNull(local.get(), fallback); } @Provides CurrentUser provideCurrentUser(RequestContext ctx) { return ctx.getCurrentUser(); } @Provides IdentifiedUser provideCurrentUser(CurrentUser user) { if (user instanceof IdentifiedUser) { return (IdentifiedUser) user; } throw new ProvisionException(NotSignedInException.MESSAGE, new NotSignedInException()); } }; }
Source:
<code>public String toString() { StringBuilder builder = new StringBuilder(25); builder.append("refresh: "); builder.append(getRefresh()); builder.append(", filtered: "); <START> builder.append(getRefresh()); <END> return builder.toString(); }</code><technical_language>isFiltered()</technical_language>

Target:
public String toString() { StringBuilder builder = new StringBuilder(25); builder.append("refresh: "); builder.append(getRefresh()); builder.append(", filtered: "); builder.append(isFiltered()); return builder.toString(); }
Source:
<code>public synchronized void shutdown() { if (!canShutdown()) { LOG.debug("ZooKeeper server is not running, so not proceeding to shutdown!"); return; } LOG.info("shutting down"); setState(State.SHUTDOWN); if (sessionTracker != null) { sessionTracker.shutdown(); } if (firstProcessor != null) { firstProcessor.shutdown(); } <START> <END> unregisterJMX(); }</code><technical_language>is case want clear db - of ZooKeeper critical threads (such * processors, session trackers) fail, ZooKeeper server shutdown (see runFromConfig) invoke ZooKeeper#shutdown. In this case, I a reason clear db, fine (as argue server dead anyway), I tend lean safe side cleaning db. conditionally do is add a Boolean parameter ZooKeeper#shutdown fine grained control clear db in code path</technical_language>

Target:
public void shutdown() { shutdown(false); }
Source:
<code>public void handleNewSession() throws Exception { <START> listener.handleNewSession(null); <END> }</code><technical_language>Optional, this null better. defining a SESSION_NOT_SET constant here</technical_language>

Target:
public void handleNewSession() throws Exception { _listener.handleNewSession(null); }
Source:
<code>public static List<BatchItem> from(final String events) { final List<BatchItem> batch = new ArrayList<>(); <START> int objectStart = locateOpenSquareBracket(events) + 1; <END> final int arrayEnd = locateClosingSquareBracket(objectStart, events); while (-1 != (objectStart = navigateToObjectStart(batch.isEmpty(), objectStart, arrayEnd, events))) { final int objectEnd = navigateToObjectEnd(objectStart, arrayEnd, events, batch::add); if (objectEnd == -1) { throw new JSONException("Unclosed object staring at " + objectStart + " found."); } objectStart = objectEnd + 1; } return batch; }</code><technical_language>arrayStart compliant arrayEnd? +1 here</technical_language>

Target:
public static List<BatchItem> from(final String events) { final List<BatchItem> batch = new ArrayList<>(); int objectStart = locateOpenSquareBracket(events) + 1; final int arrayEnd = locateClosingSquareBracket(objectStart, events); while (-1 != (objectStart = navigateToObjectStart(objectStart, arrayEnd, events))) { final int objectEnd = navigateToObjectEnd(objectStart, arrayEnd, events, batch::add); if (objectEnd == -1) { throw new JSONException("Unclosed object staring at " + objectStart + " found."); } objectStart = objectEnd + 1; } return batch; }