auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void checkPage() { boolean errorFound = false; setErrorMessage(null); <START> String t = nameText.getText(); <END> if (t.length() > 0 && !Repository.isValidRefName(Constants.R_REMOTES + t)) { setErrorMessage(NLS.bind(UIText.NewRemoteDialog_InvalidRemoteName, t)); errorFound = true; } if (existingRemotes.contains(t)) { setErrorMessage(NLS.bind( UIText.NewRemoteDialog_RemoteAlreadyExistsMessage, t)); errorFound = true; } getButton(OK).setEnabled(!errorFound); }</code><technical_language>I trim() input avoid more source of errors</technical_language>

Target:
private void checkPage() { boolean errorFound = false; setErrorMessage(null); String t = getTrimmedRemoteName(); if (t.length() > 0 && !Repository.isValidRefName(Constants.R_REMOTES + t)) { setErrorMessage(NLS.bind(UIText.NewRemoteDialog_InvalidRemoteName, t)); errorFound = true; } else if (existingRemotes.contains(t)) { setErrorMessage(NLS.bind( UIText.NewRemoteDialog_RemoteAlreadyExistsMessage, t)); errorFound = true; } getButton(OK).setEnabled(!errorFound); }
Source:
<code>public static void addNewMinishiftServer(String serverAdapter, String hypervisor, String path, String profile) { NewCDKServerWizard dialog = setupFirstNewServerWizardPage(MINISHIFT_SERVER_NAME, serverAdapter); NewMinishiftServerWizardPage containerPage = new NewMinishiftServerWizardPage(); <START> if (hypervisor != null && !hypervisor.isEmpty()) { <END> log.info("Setting hypervisor to " + hypervisor); containerPage.setHypervisor(hypervisor); } log.info("Setting minishift binary file folder to " + path); containerPage.setMinishiftBinary(path); log.info("Setting minishift profile to " + profile); containerPage.setMinishiftProfile(profile); new WaitUntil(new ControlIsEnabled(new FinishButton()), TimePeriod.DEFAULT); log.info("Finishing Add new server dialog"); if (!(new FinishButton().isEnabled())) { log.error("Finish button was not enabled"); } dialog.finish(TimePeriod.MEDIUM); }</code><technical_language>StringUtils.isEmptyOrNull(hypervisor)</technical_language>

Target:
public static void addNewMinishiftServer(String serverAdapter, String hypervisor, String path, String profile) { NewCDKServerWizard dialog = setupFirstNewServerWizardPage(MINISHIFT_SERVER_NAME, serverAdapter); NewMinishiftServerWizardPage containerPage = new NewMinishiftServerWizardPage(); if (!StringUtils.isEmptyOrNull(hypervisor)) { log.info("Setting hypervisor to " + hypervisor); containerPage.setHypervisor(hypervisor); } log.info("Setting minishift binary file folder to " + path); containerPage.setMinishiftBinary(path); log.info("Setting minishift profile to " + profile); containerPage.setMinishiftProfile(profile); new WaitUntil(new ControlIsEnabled(new FinishButton()), TimePeriod.DEFAULT); log.info("Finishing Add new server dialog"); if (!(new FinishButton().isEnabled())) { log.error("Finish button was not enabled"); } dialog.finish(TimePeriod.MEDIUM); }
Source:
<code>public static void setSnapshots(MobSpawnerBaseLogic logic, WeightedTable<EntitySnapshot> table) { logic.minecartToSpawn.clear(); for (TableEntry<EntitySnapshot> entry : table) { if(!(entry instanceof WeightedObject)) continue; WeightedObject<EntitySnapshot> object = (WeightedObject<EntitySnapshot>) entry; if(!(object.get() instanceof SpongeEntitySnapshot)) continue; <START> String name = EntityList.classToStringMapping.get(object.get().getType().getEntityClass()); <END> NBTTagCompound compound = ((SpongeEntitySnapshot) object.get()).getCompound().get(); logic.minecartToSpawn.add(logic.new WeightedRandomMinecart(compound, name)); } }</code><technical_language>Forge compat done in forge side. Modifying implementation (basically, a higher priority for processor)</technical_language>

Target:
public static void setSnapshots(MobSpawnerBaseLogic logic, WeightedTable<EntitySnapshot> table) { logic.minecartToSpawn.clear(); for (TableEntry<EntitySnapshot> entry : table) { if(!(entry instanceof WeightedObject)) continue; WeightedObject<EntitySnapshot> object = (WeightedObject<EntitySnapshot>) entry; NBTTagCompound compound; if(object.get() instanceof SpongeEntitySnapshot) { SpongeEntitySnapshot snapshot = (SpongeEntitySnapshot) object.get(); compound = snapshot.getCompound().orElse(new NBTTagCompound()); } else { compound = new NBTTagCompound(); } String name = EntityList.classToStringMapping.get(object.get().getType().getEntityClass()); logic.minecartToSpawn.add(logic.new WeightedRandomMinecart(compound, name)); } }
Source:
<code>public GenericRow transform(GenericRow record) throws DataTypeConversionException { for (Map.Entry<String, PinotDataType> entry : _dataTypes.entrySet()) { String column = entry.getKey(); Object value = record.getValue(column); if (value == null) { continue; } PinotDataType dest = entry.getValue(); value = standardize(column, value, dest.isSingleValue()); if (value == null) { record.putValue(column, null); continue; } PinotDataType source; if (value instanceof Object[]) { Object[] values = (Object[]) value; source = MULTI_VALUE_TYPE_MAP.get(values[0].getClass()); if (source == null) { source = PinotDataType.OBJECT_ARRAY; } } else { source = SINGLE_VALUE_TYPE_MAP.get(value.getClass()); if (source == null) { source = PinotDataType.OBJECT; } } if (source != dest) { try { value = dest.convert(value, source); } catch (Exception e) { <START> throw new DataTypeConversionException(column, source, dest, e); <END> } } record.putValue(column, value); } return record; }</code><technical_language>this a separate PR? +1 adding more information exception message, throwing RuntimeException avoid interface change</technical_language>

Target:
public GenericRow transform(GenericRow record) { for (Map.Entry<String, PinotDataType> entry : _dataTypes.entrySet()) { String column = entry.getKey(); Object value = record.getValue(column); if (value == null) { continue; } PinotDataType dest = entry.getValue(); value = standardize(column, value, dest.isSingleValue()); if (value == null) { record.putValue(column, null); continue; } PinotDataType source; if (value instanceof Object[]) { Object[] values = (Object[]) value; source = MULTI_VALUE_TYPE_MAP.get(values[0].getClass()); if (source == null) { source = PinotDataType.OBJECT_ARRAY; } } else { source = SINGLE_VALUE_TYPE_MAP.get(value.getClass()); if (source == null) { source = PinotDataType.OBJECT; } } if (source != dest) { value = dest.convert(value, source); } record.putValue(column, value); } return record; }
Source:
<code>public void onItemLoad(AttachCapabilitiesEvent.Item event) { <START> if (!event.getItemStack().func_190926_b() && event.getItemStack().getItem() == Items.STICK) <END> event.addCapability(new ResourceLocation("forge.testcapmod:dummy_cap"), new Provider(event.getItemStack())); }</code><technical_language>event.getItemStack().getItem() == Items.STICK is enough</technical_language>

Target:
public void onItemLoad(AttachCapabilitiesEvent.Item event) { if (event.getItemStack().getItem() == Items.STICK) event.addCapability(new ResourceLocation("forge.testcapmod:dummy_cap"), new Provider(event.getItemStack())); }
Source:
<code>public void render(Canvas canvas) { for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { <START> colors[x + y * width] = palette[field[x][y]]; <END> } } canvas.scale(scale_x, scale_y); canvas.drawBitmap(colors, 0, width, 0, 0, width, height, false, paint); }</code><technical_language>updating array drawing canvas bitmap is faster drawing canvas</technical_language>

Target:
public void render(Canvas canvas) { for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { colors[x + y * width] = palette[field[x][y]]; } } canvas.save(); canvas.scale(scale_x, scale_y); canvas.drawBitmap(colors, 0, width, 0, 0, width, height, false, paint); canvas.restore(); }
Source:
<code>public void testReaderWithoutPreparedStatement() throws SQLException, IOException { Statement statement = Mockito.mock(Statement.class); Mockito.when(connection.createStatement()).thenReturn(statement); rs = Mockito.mock(ResultSet.class); ResultSetMetaData rsMetadata = Mockito.mock(ResultSetMetaData.class); Mockito.when(rs.getMetaData()).thenReturn(rsMetadata); Mockito.when(rsMetadata.getColumnCount()).thenReturn(1); Mockito.when(rs.getString(1)).thenReturn(FIELD_VALUE); Mockito.when(statement.executeQuery(Mockito.eq(query))).thenReturn(rs); Mockito.when(rs.next()).thenReturn(true, false); <START> try { <END> do { if (reader.start()) { IndexedRecord indexedRecord = reader.getCurrent(); Assert.assertEquals(FIELD_VALUE, indexedRecord.get(indexedRecord.getSchema().getField("name").pos())); } } while (reader.advance()); } catch (IOException ioe) { Assert.fail("Should not get here"); } finally { reader.close(); } Map<String, Object> resultMap = reader.getReturnValues(); Assert.assertEquals(1, resultMap.get(ComponentDefinition.RETURN_TOTAL_RECORD_COUNT)); }</code><technical_language>try-catch redundant here. declare test case throw IOException</technical_language>

Target:
public void testReaderWithoutPreparedStatement() throws SQLException, IOException { Statement statement = Mockito.mock(Statement.class); Mockito.when(connection.createStatement()).thenReturn(statement); rs = Mockito.mock(ResultSet.class); ResultSetMetaData rsMetadata = Mockito.mock(ResultSetMetaData.class); Mockito.when(rs.getMetaData()).thenReturn(rsMetadata); Mockito.when(rsMetadata.getColumnCount()).thenReturn(1); Mockito.when(rs.getString(1)).thenReturn(FIELD_VALUE); Mockito.when(statement.executeQuery(Mockito.eq(query))).thenReturn(rs); Mockito.when(rs.next()).thenReturn(true, false); try { if (reader.start()) { do { IndexedRecord indexedRecord = reader.getCurrent(); Assert.assertEquals(FIELD_VALUE, indexedRecord.get(indexedRecord.getSchema().getField("name").pos())); } while (reader.advance()); } else { Assert.fail("Shouldn't get here"); } } finally { reader.close(); } Map<String, Object> resultMap = reader.getReturnValues(); Assert.assertEquals(1, resultMap.get(ComponentDefinition.RETURN_TOTAL_RECORD_COUNT)); }
Source:
<code>public void setDeepenNots(List<ObjectId> deepenNots) { this.deepenNots = <START> deepenNots; <END> }</code><technical_language>a null check (Objects.checkNotNull)</technical_language>

Target:
public void setDeepenNots(List<ObjectId> deepenNots) { this.deepenNots = Objects.requireNonNull(deepenNots); }
Source:
<code>private String getDescription(final String propertyFile, final String propertyName) { String description = null; try { <START> if (propertyFile == null || propertyFile.trim().isEmpty()) { <END> LOG.error("propertyFile value is null"); } else if (propertyName == null || propertyName.trim().isEmpty()) { LOG.error("propertyName value is null"); } else { description = PropertyAccessor.getInstance().getProperty(propertyFile, propertyName); } } catch (final Exception e) { LOG.error("Exception while reading the property: " + propertyFile + "." + propertyName, e); } return description; }</code><technical_language>Please StringUtil instead</technical_language>

Target:
private String getDescription(final String propertyFile, final String propertyName) { String description = null; try { if (StringUtils.isBlank(propertyFile)) { LOG.error("propertyFile value is null"); } else if (StringUtils.isBlank(propertyName)) { LOG.error("propertyName value is null"); } else { description = PropertyAccessor.getInstance().getProperty(propertyFile, propertyName); } } catch (final Exception e) { LOG.error("Exception while reading the property: {}.{} : {}", propertyFile, propertyName, e.getLocalizedMessage(), e); } return description; }
Source:
<code>public static File dumpQueueData(String data) throws IOException { <START> if (!isExternalStorageWritable()) { <END> throw new IllegalStateException("External storage is not writable!"); } String path = getExternalStoragePath() + "/" + "Local_changes_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".txt"; File file = new File(path); file.createNewFile(); try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) { writer.write(data); } return file; }</code><technical_language>this method throws IllegalStateException, added throws-List? react in dumpOfflineQueue()</technical_language>

Target:
public static File dumpQueueData(String data) throws IOException { if (!isExternalStorageWritable()) { throw new IllegalStateException("External storage is not writable!"); } String path = getExternalStoragePath() + "/" + "Local_changes_" + new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date()) + ".txt"; File file = new File(path); file.createNewFile(); try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) { writer.write(data); } return file; }
Source:
<code>private void processKey(final int keyCode, boolean shiftKeyPressed, final String value) { this.value = value; <START> if ((13 == keyCode) && (!shiftKeyPressed)) { <END> onSave(); } }</code><technical_language>Hmm, com.google.gwt.event.dom.client.KeyCodes.KEY_ENTER instead of 13, if do concern it</technical_language>

Target:
private void processKey(final int keyCode, boolean shiftKeyPressed, final String value) { this.value = value; if ((KeyCodes.KEY_ENTER == keyCode) && (!shiftKeyPressed)) { onSave(); } }
Source:
<code>protected void render(StringBuilder sb, int indent, boolean atRoot, ConfigRenderOptions options) { if (isEmpty()) { sb.append("{}"); } else { String[] keys = keySet().toArray(new String[size()]); Arrays.sort(keys, new com.typesafe.config.impl.AlphanumericComparator()); <START> <END> boolean outerBraces = options.getJson() || !atRoot; int innerIndent; if (outerBraces) { innerIndent = indent + 1; sb.append("{"); if (options.getFormatted()) sb.append('\n'); } else { innerIndent = indent; } int separatorCount = 0; for (String k : keys) { AbstractConfigValue v; v = value.get(k); if (options.getOriginComments()) { indent(sb, innerIndent, options); sb.append("# "); sb.append(v.origin().description()); sb.append("\n"); } if (options.getComments()) { for (String comment : v.origin().comments()) { indent(sb, innerIndent, options); sb.append("#"); if (!comment.startsWith(" ")) sb.append(' '); sb.append(comment); sb.append("\n"); } } indent(sb, innerIndent, options); v.render(sb, innerIndent, false , k, options); if (options.getFormatted()) { if (options.getJson()) { sb.append(","); separatorCount = 2; } else { separatorCount = 1; } sb.append('\n'); } else { sb.append(","); separatorCount = 1; } } sb.setLength(sb.length() - separatorCount); if (outerBraces) { if (options.getFormatted()) { sb.append('\n'); if (outerBraces) indent(sb, indent, options); } sb.append("}"); } } if (atRoot && options.getFormatted()) sb.append('\n'); }</code><technical_language>if reason move this block of code in file, diff more accurately shows change made</technical_language>

Target:
protected void render(StringBuilder sb, int indent, boolean atRoot, ConfigRenderOptions options) { if (isEmpty()) { sb.append("{}"); } else { boolean outerBraces = options.getJson() || !atRoot; int innerIndent; if (outerBraces) { innerIndent = indent + 1; sb.append("{"); if (options.getFormatted()) sb.append('\n'); } else { innerIndent = indent; } int separatorCount = 0; String[] keys = keySet().toArray(new String[size()]); Arrays.sort(keys, new com.typesafe.config.impl.AlphanumericComparator()); for (String k : keys) { AbstractConfigValue v; v = value.get(k); if (options.getOriginComments()) { indent(sb, innerIndent, options); sb.append("# "); sb.append(v.origin().description()); sb.append("\n"); } if (options.getComments()) { for (String comment : v.origin().comments()) { indent(sb, innerIndent, options); sb.append("#"); if (!comment.startsWith(" ")) sb.append(' '); sb.append(comment); sb.append("\n"); } } indent(sb, innerIndent, options); v.render(sb, innerIndent, false , k, options); if (options.getFormatted()) { if (options.getJson()) { sb.append(","); separatorCount = 2; } else { separatorCount = 1; } sb.append('\n'); } else { sb.append(","); separatorCount = 1; } } sb.setLength(sb.length() - separatorCount); if (outerBraces) { if (options.getFormatted()) { sb.append('\n'); if (outerBraces) indent(sb, indent, options); } sb.append("}"); } } if (atRoot && options.getFormatted()) sb.append('\n'); }
Source:
<code>public int markScheduledExecutionsTimedOut(int timeoutSecs) throws InvalidOperationException, MetaException { if (timeoutSecs < 0) { LOG.debug("scheduled executions - time_out mark is disabled"); return 0; } boolean committed = false; try (Query q = pm.newQuery(MScheduledExecution.class)) { openTransaction(); int maxLastUpdateTime = (int) (System.currentTimeMillis() / 1000) - timeoutSecs; q.setFilter("lastUpdateTime <= maxLastUpdateTime && (state == 'INITED' || state == 'EXECUTING')"); q.declareParameters("int maxLastUpdateTime"); List<MScheduledExecution> results = (List<MScheduledExecution>) q.execute(maxLastUpdateTime); for (MScheduledExecution e : results) { ScheduledQueryProgressInfo info = new ScheduledQueryProgressInfo(); info.setScheduledExecutionId(e.getScheduledExecutionId()); info.setState(QueryState.TIMED_OUT); info.setErrorMessage( "Query stuck in: " + e.getState() + " state for >" + timeoutSecs + " seconds. Execution timed out."); scheduledQueryProgress(info); } recoverInvalidScheduledQueryState(timeoutSecs); committed = commitTransaction(); return results.size(); <START> } catch (InvalidOperationException | MetaException e) { throw e; } catch (Exception e) { throw new MetaException(e.getMessage()); <END> } finally { if (!committed) { rollbackTransaction(); } } }</code><technical_language>catches needed</technical_language>

Target:
public int markScheduledExecutionsTimedOut(int timeoutSecs) throws InvalidOperationException, MetaException { if (timeoutSecs < 0) { LOG.debug("scheduled executions - time_out mark is disabled"); return 0; } boolean committed = false; Query q = null; try { openTransaction(); int maxLastUpdateTime = (int) (System.currentTimeMillis() / 1000) - timeoutSecs; q = pm.newQuery(MScheduledExecution.class); q.setFilter("lastUpdateTime <= maxLastUpdateTime && (state == 'INITED' || state == 'EXECUTING')"); q.declareParameters("int maxLastUpdateTime"); List<MScheduledExecution> results = (List<MScheduledExecution>) q.execute(maxLastUpdateTime); for (MScheduledExecution e : results) { ScheduledQueryProgressInfo info = new ScheduledQueryProgressInfo(); info.setScheduledExecutionId(e.getScheduledExecutionId()); info.setState(QueryState.TIMED_OUT); info.setErrorMessage( "Query stuck in: " + e.getState() + " state for >" + timeoutSecs + " seconds. Execution timed out."); scheduledQueryProgress(info); } recoverInvalidScheduledQueryState(timeoutSecs); committed = commitTransaction(); return results.size(); } finally { rollbackAndCleanup(committed, q); } }
Source:
<code>public void shouldNotRecordWhenRecorderIsDisabled() { String oldValue = System.getProperty("RECORDER_DISABLED"); System.setProperty("RECORDER_DISABLED", "true"); TestRecorderRule testRecorderRule = new TestRecorderRule(); Description shouldNotRecordSuccessTestExecutionByDefault = Description.createTestDescription("org.jenkinsci.test.acceptance.recorder.TestRecorderRuleTest", "shouldNotRecordWhenRecorderIsDisabled"); testRecorderRule.starting(shouldNotRecordSuccessTestExecutionByDefault); System.out.println("Hello World"); testRecorderRule.finished(shouldNotRecordSuccessTestExecutionByDefault); File outputFile = new File("target", "org.jenkinsci.test.acceptance.recorder.TestRecorderRuleTest-shouldNotRecordWhenRecorderIsDisabled.mov"); assertThat(outputFile.exists(), is(false)); <START> if(oldValue != null) { <END> System.setProperty("RECORDER_DISABLED", oldValue); } else { System.clearProperty("RECORDER_DISABLED"); } outputFile.delete(); }</code><technical_language>@lordofthejars Ditto</technical_language>

Target:
public void shouldNotRecordWhenRecorderIsDisabled() { TestRecorderRule.RECORDER_OPTION = TestRecorderRule.OFF; TestRecorderRule testRecorderRule = new TestRecorderRule(); Description shouldNotRecordSuccessTestExecutionByDefault = Description.createTestDescription("org.jenkinsci.test.acceptance.recorder.TestRecorderRuleTest", "shouldNotRecordWhenRecorderIsDisabled"); testRecorderRule.starting(shouldNotRecordSuccessTestExecutionByDefault); System.out.println("Hello World"); testRecorderRule.finished(shouldNotRecordSuccessTestExecutionByDefault); File outputFile = new File("target", "org.jenkinsci.test.acceptance.recorder.TestRecorderRuleTest-shouldNotRecordWhenRecorderIsDisabled.mov"); assertThat(outputFile.exists(), is(false)); TestRecorderRule.RECORDER_OPTION = TestRecorderRule.FAILURES; outputFile.delete(); }
Source:
<code>public void perform(GraphRewrite event, EvaluationContext context, WindupConfigurationModel payload) { WindupJavaConfigurationModel javaCfg = WindupJavaConfigurationService.getJavaConfigurationModel(event.getGraphContext()); for (FileModel ignoreDirectory : payload.getUserIgnorePaths()) { final List<Path> filesUrl = new ArrayList<>(); try { Files.walkFileTree(Paths.get(ignoreDirectory.getFilePath()), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (file.getFileName().toString().toLowerCase().endsWith(IGNORE_FILE_EXTENSION)) { filesUrl.add(file); } return FileVisitResult.CONTINUE; } }); for (Path filePath : filesUrl) { File file = filePath.toFile(); if (file.exists()) { try (BufferedReader reader = new BufferedReader(new FileReader(file));) { String line = null; while ((line = reader.readLine()) != null) { GraphService<IgnoredFileModel> graphService = new GraphService<IgnoredFileModel>( event.getGraphContext(), IgnoredFileModel.class); <START> IgnoredFileModel ignored = graphService.create(); <END> ignored.setRegex(line); javaCfg.addIgnoredFile(ignored); } } catch (FileNotFoundException e) { } catch (IOException e) { } } } } catch (IOException e1) { } } }</code><technical_language>In this context, IgnoredFileModel is name</technical_language>

Target:
public void perform(GraphRewrite event, EvaluationContext context, WindupConfigurationModel payload) { WindupJavaConfigurationModel javaCfg = WindupJavaConfigurationService.getJavaConfigurationModel(event .getGraphContext()); final List<Path> filesUrl = new ArrayList<>(); for (FileModel ignoredRegexesFileModel : payload.getUserIgnorePaths()) { if (ignoredRegexesFileModel.isDirectory()) { try { Files.walkFileTree(Paths.get(ignoredRegexesFileModel.getFilePath()), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (file.getFileName().toString().toLowerCase().endsWith(IGNORE_FILE_EXTENSION)) { filesUrl.add(file); } return FileVisitResult.CONTINUE; } }); } catch (IOException e1) { log.warning("IOException thrown when trying to access the ignored file regexes in " + ignoredRegexesFileModel.getFilePath()); } } else { filesUrl.add(Paths.get(ignoredRegexesFileModel.getFilePath())); } } for (Path filePath : filesUrl) { readAndAddFileRegexes(filePath, javaCfg, event.getGraphContext()); } }
Source:
<code>private Message<?> getMessageById(UUID messageId) { Message<?> theMessage = null; if (this.messageStore instanceof SimpleMessageStore) { synchronized (this.messageGroupId) { Collection<Message<?>> messages = this.messageStore.getMessageGroup(this.messageGroupId).getMessages(); for (Message<?> message : messages) { if (message.getHeaders().getId().equals(messageId)) { theMessage = message; break; } <START> } <END> } } else { theMessage = ((MessageStore) this.messageStore).getMessage(messageId); } if (theMessage == null) { if (logger.isDebugEnabled()) { logger.debug("No message in the Message Store for id: " + messageId + ". Likely another instance has already released it."); } return null; } else { return theMessage; } }</code><technical_language>This optimized a simple messages.get() if underlying Collection is a Set</technical_language>

Target:
private Message<?> getMessageById(UUID messageId) { Message<?> theMessage = ((MessageStore) this.messageStore).getMessage(messageId); if (theMessage == null) { if (logger.isDebugEnabled()) { logger.debug("No message in the Message Store for id: " + messageId + ". Likely another instance has already released it."); } return null; } else { return theMessage; } }
Source:
<code>public static JSITFunctionDefinition dmnFromWB(final FunctionDefinition wb, final Consumer<JSITComponentWidths> componentWidthsConsumer) { if (wb == null) { return null; } final JSITFunctionDefinition result = new JSITFunctionDefinition(); result.setId(wb.getId().getValue()); if (Objects.isNull(result.getFormalParameter())) { result.setFormalParameter(new ArrayList<>()); } final Optional<String> description = Optional.ofNullable(DescriptionPropertyConverter.dmnFromWB(wb.getDescription())); description.ifPresent(result::setDescription); QNamePropertyConverter.setDMNfromWB(wb.getTypeRef(), result::setTypeRef); result.setExpression(ExpressionPropertyConverter.dmnFromWB(wb.getExpression(), componentWidthsConsumer)); final Kind kind = wb.getKind(); <START> switch (kind) { case FEEL: result.setKind(Js.uncheckedCast(JSITFunctionKind.FEEL.value())); break; case JAVA: result.setKind(Js.uncheckedCast(JSITFunctionKind.JAVA.value())); break; case PMML: result.setKind(Js.uncheckedCast(JSITFunctionKind.PMML.value())); break; default: result.setKind(Js.uncheckedCast(JSITFunctionKind.FEEL.value())); break; } <END> for (InformationItem ii : wb.getFormalParameter()) { final JSITInformationItem iiConverted = InformationItemPropertyConverter.dmnFromWB(ii); result.addFormalParameter(iiConverted); } return result; }</code><technical_language>I similar question, possible, method for conversion function Kind, in original enum, toJSKind, toJSITFunctionKind</technical_language>

Target:
public static JSITFunctionDefinition dmnFromWB(final FunctionDefinition wb, final Consumer<JSITComponentWidths> componentWidthsConsumer) { if (Objects.isNull(wb)) { return null; } final JSITFunctionDefinition result = new JSITFunctionDefinition(); result.setId(wb.getId().getValue()); if (Objects.isNull(result.getFormalParameter())) { result.setFormalParameter(new ArrayList<>()); } final Optional<String> description = Optional.ofNullable(DescriptionPropertyConverter.dmnFromWB(wb.getDescription())); description.ifPresent(result::setDescription); QNamePropertyConverter.setDMNfromWB(wb.getTypeRef(), result::setTypeRef); result.setExpression(ExpressionPropertyConverter.dmnFromWB(wb.getExpression(), componentWidthsConsumer)); final Kind kind = wb.getKind(); switch (kind) { case FEEL: result.setKind(Js.uncheckedCast(JSITFunctionKind.FEEL.value())); break; case JAVA: result.setKind(Js.uncheckedCast(JSITFunctionKind.JAVA.value())); break; case PMML: result.setKind(Js.uncheckedCast(JSITFunctionKind.PMML.value())); break; default: result.setKind(Js.uncheckedCast(JSITFunctionKind.FEEL.value())); break; } for (InformationItem ii : wb.getFormalParameter()) { final JSITInformationItem iiConverted = InformationItemPropertyConverter.dmnFromWB(ii); result.addFormalParameter(iiConverted); } return result; }
Source:
<code>public void shouldCommitNextOffsetFromQueueIfAvailable() { <START> task = createStatelessTask(createConfig(false, "0"), StreamsConfig.METRICS_LATEST); <END> task.initializeIfNeeded(); task.completeRestoration(); task.addRecords(partition1, Arrays.asList(getConsumerRecord(partition1, 0L), getConsumerRecord(partition1, 5L))); task.process(0L); final Map<TopicPartition, OffsetAndMetadata> offsetsAndMetadata = task.prepareCommit(); assertThat(offsetsAndMetadata, equalTo(mkMap(mkEntry(partition1, new OffsetAndMetadata(5L, encodeTimestamp(5L)))))); }</code><technical_language>I need test assertFalse(task.commitNeeded() outcome is controlled task.markCommitted. need do once</technical_language>

Target:
public void shouldCommitNextOffsetFromQueueIfAvailable() { task = createStatelessTask(createConfig(false, "0"), StreamsConfig.METRICS_LATEST); task.initializeIfNeeded(); task.completeRestoration(); task.addRecords(partition1, Arrays.asList(getConsumerRecord(partition1, 0L), getConsumerRecord(partition1, 5L))); task.process(0L); task.prepareCommit(); final Map<TopicPartition, OffsetAndMetadata> offsetsAndMetadata = task.committableOffsetsAndMetadata(); assertThat(offsetsAndMetadata, equalTo(mkMap(mkEntry(partition1, new OffsetAndMetadata(5L, encodeTimestamp(5L)))))); }
Source:
<code>public Mask parseFromInput(String input, ParserContext context) throws InputParseException { if (!input.startsWith("^[") || !input.endsWith("]")) { return null; } Extent extent = Request.request().getEditSession(); String states = input.substring(2, input.length() - 1); try { <START> return new BlockStateMask(extent, Arrays.stream(states.split(",")).map(s -> s.split("=")) <END> .collect(Collectors.toMap(s -> s[0], s -> s[1]))); } catch (Exception e) { throw new InputParseException("Invalid states.", e); } }</code><technical_language>I Guava MapSplitter for this purpose</technical_language>

Target:
public Mask parseFromInput(String input, ParserContext context) throws InputParseException { if (!(input.startsWith("^[") || input.startsWith("^=[")) || !input.endsWith("]")) { return null; } Extent extent = Request.request().getEditSession(); boolean strict = input.charAt(1) == '='; String states = input.substring(2 + (strict ? 1 : 0), input.length() - 1); try { return new BlockStateMask(extent, Splitter.on(',').omitEmptyStrings().trimResults().withKeyValueSeparator('=').split(states), strict); } catch (Exception e) { throw new InputParseException("Invalid states.", e); } }
Source:
<code>public <T> T[] toArray(T[] array) { checkForParentModification(); if (array.length < size) { final Class<?> type = array.getClass().getComponentType(); array = (T[]) Array.newInstance(type, size); } if (size > 0) { <START> if(parent instanceof IonSequenceLite) { <END> System.arraycopy(IonSequenceLite.this._children, fromIndex, array, 0, size); } else { for(int i = 0; i < size; i++) { array[i] = (T) get(i); } } } if (size < array.length) { array[size] = null; } return array; }</code><technical_language>ditto...can System.arraycopy() for containers well</technical_language>

Target:
public <T> T[] toArray(T[] array) { checkForParentModification(); if (array.length < size) { final Class<?> type = array.getClass().getComponentType(); array = (T[]) Array.newInstance(type, size); } if (size > 0) { System.arraycopy(IonSequenceLite.this._children, fromIndex, array, 0, size); } if (size < array.length) { array[size] = null; } return array; }
Source:
<code>public CoreQueryManager( @Named("features") final Features features, final AsyncFramework async, final ClusterManager cluster, final QueryParser parser, final QueryCache queryCache, final AggregationFactory aggregations, @Named("groupLimit") final OptionalLimit groupLimit, @Named("smallQueryThreshold") final long smallQueryThreshold, final ApiReporter reporter ) { this.features = features; this.async = async; this.cluster = cluster; this.parser = parser; this.queryCache = queryCache; this.aggregations = aggregations; this.groupLimit = groupLimit; this.reporter = reporter; this.smallQueryThreshold = smallQueryThreshold; <START> log.info("smallQueryThreshold: " + smallQueryThreshold); <END> }</code><technical_language>rogue log statement</technical_language>

Target:
public CoreQueryManager( @Named("features") final Features features, final AsyncFramework async, final ClusterManager cluster, final QueryParser parser, final QueryCache queryCache, final AggregationFactory aggregations, @Named("groupLimit") final OptionalLimit groupLimit, @Named("smallQueryThreshold") final long smallQueryThreshold, final ApiReporter reporter ) { this.features = features; this.async = async; this.cluster = cluster; this.parser = parser; this.queryCache = queryCache; this.aggregations = aggregations; this.groupLimit = groupLimit; this.reporter = reporter; this.smallQueryThreshold = smallQueryThreshold; }
Source:
<code>public Row lockRow(Session session, Row row) { <START> syncLastModificationIdWithDatabase(); <END> return primaryIndex.lockRow(session, row); }</code><technical_language>a lock is a data modification, do need here? a lock prevent cached result of a previous query etc</technical_language>

Target:
public Row lockRow(Session session, Row row) { Row lockedRow = primaryIndex.lockRow(session, row); if (lockedRow == null || !row.hasSharedData(lockedRow)) { syncLastModificationIdWithDatabase(); } return lockedRow; }
Source:
<code>DesiredCapabilities getDriverCapabilities(Proxy proxy) { DesiredCapabilities capabilities = createCommonCapabilities(proxy); capabilities.setBrowserName(getBrowserNameForGrid()); if (headless) { capabilities.merge(getHeadlessCapabilities()); } if (!browserBinary.isEmpty()) { <START> log.info("Using browser binary: " + browserBinary); <END> if (isChrome()) { ChromeOptions options = new ChromeOptions(); options.setBinary(browserBinary); capabilities.merge(options); } else if (isFirefox()) { FirefoxOptions options = new FirefoxOptions(); options.setBinary(browserBinary); capabilities.merge(options); } else { log.warning("Changing browser binary on remote server is only supported for Chrome/Firefox, setting will be ignored."); } } return capabilities; }</code><technical_language>Consider extract this block separate method for getHeadlessCapabilities()</technical_language>

Target:
DesiredCapabilities getDriverCapabilities(Proxy proxy) { DesiredCapabilities capabilities = createCommonCapabilities(proxy); capabilities.setBrowserName(getBrowserNameForGrid()); if (headless) { capabilities.merge(getHeadlessCapabilities()); } if (!browserBinary.isEmpty()) { capabilities.merge(getBrowserBinaryCapabilites()); } return capabilities; }
Source:
<code>public CompletableFuture<Void> resolveConflicts(CacheTopology topology, Set<Address> preferredNodes) { if (!running) return CompletableFuture.completedFuture(null); LocalizedCacheTopology localizedTopology; if (topology instanceof LocalizedCacheTopology) { localizedTopology = (LocalizedCacheTopology) topology; } else { localizedTopology = distributionManager.createLocalizedCacheTopology(topology); } conflictFuture = resolutionExecutor.execute(() -> doResolveConflicts(localizedTopology, entryMergePolicy, preferredNodes), localizedTopology.getTopologyId()) .toCompletableFuture(); <START> return conflictFuture.whenComplete((Void, t) -> { <END> if (t != null) { log.errorf("Cache %s encountered exception whilst trying to resolve conflicts on merge: %s", cacheName, t); if (conflictSpliterator != null) { conflictSpliterator.stop(); conflictSpliterator = null; } } }); }</code><technical_language>resolveConflicts() is public API, changed return CompletionStage. I advantage in BlockingExecutor interface instead of more familiar Executor</technical_language>

Target:
public CompletionStage<Void> resolveConflicts(CacheTopology topology, Set<Address> preferredNodes) { if (!running) return CompletableFuture.completedFuture(null); LocalizedCacheTopology localizedTopology; if (topology instanceof LocalizedCacheTopology) { localizedTopology = (LocalizedCacheTopology) topology; } else { localizedTopology = distributionManager.createLocalizedCacheTopology(topology); } conflictFuture = resolutionExecutor.execute(() -> doResolveConflicts(localizedTopology, entryMergePolicy, preferredNodes), localizedTopology.getTopologyId()) .toCompletableFuture(); return conflictFuture.whenComplete((Void, t) -> { if (t != null) { log.errorf("Cache %s encountered exception whilst trying to resolve conflicts on merge: %s", cacheName, t); if (conflictSpliterator != null) { conflictSpliterator.stop(); conflictSpliterator = null; } } }); }
Source:
<code>protected static Integer convertToSenseVolumePercent(final Double maxDecibels, final Integer volumePercent) { <START> if (volumePercent > 100 || volumePercent <= 1) { <END> throw new IllegalArgumentException(String.format("volumePercent must be in the range (0, 100], not %s", volumePercent)); } final double decibelOffsetFromMaximum = 33.22 * Math.log10(volumePercent / 100.0); final double decibels = maxDecibels + decibelOffsetFromMaximum; return (int) Math.round((decibels / maxDecibels) * 100); }</code><technical_language>If volume percent is 1, illegal argument exception thrown</technical_language>

Target:
protected static Integer convertToSenseVolumePercent(final Double maxDecibels, final Integer volumePercent) { if (volumePercent > 100 || volumePercent < 0) { throw new IllegalArgumentException(String.format("volumePercent must be in the range [0, 100], not %s", volumePercent)); } else if (volumePercent <= 1) { return 0; } final double decibelOffsetFromMaximum = 33.22 * Math.log10(volumePercent / 100.0); final double decibels = maxDecibels + decibelOffsetFromMaximum; return (int) Math.round((decibels / maxDecibels) * 100); }
Source:
<code>public AdUserConditionFieldAutoCompleter() { mVerbs.put("NAME", "NAME"); mVerbs.put("USERNAME", "USERNAME"); if (StringHelper.EqOp(SyntaxCheckerFactory.getConfigAuthenticationMethod().toUpperCase(), "LDAP")) { mVerbs.put("LASTNAME", "LASTNAME"); mVerbs.put("DEPARTMENT", "DEPARTMENT"); mVerbs.put("TITLE", "TITLE"); } mVerbs.put("ALLNAMES", "ALLNAMES"); buildCompletions(); getTypeDictionary().put("NAME", String.class); getTypeDictionary().put("USERNAME", String.class); if (StringHelper.EqOp(SyntaxCheckerFactory.getConfigAuthenticationMethod().toUpperCase(), "LDAP")) { getTypeDictionary().put("LASTNAME", String.class); getTypeDictionary().put("DEPARTMENT", String.class); getTypeDictionary().put("TITLE", String.class); } mColumnNameDict.put("NAME", "$GIVENNAME"); mColumnNameDict.put("USERNAME", "$SAMACCOUNTNAME"); if (StringHelper.EqOp(SyntaxCheckerFactory.getConfigAuthenticationMethod().toUpperCase(), "LDAP")) { mColumnNameDict.put("LASTNAME", "$SN"); mColumnNameDict.put("DEPARTMENT", "$DEPARTMENT"); mColumnNameDict.put("TITLE", "$TITLE"); } ValueValidationFunction charValidation = validCahracters; for (String key : mVerbs.keySet()) { <START> java.util.ArrayList<ValueValidationFunction> curList = new java.util.ArrayList<ValueValidationFunction>(); <END> curList.add(charValidation); mValidationDict.put(key, curList); } }</code><technical_language>please remove teh java.util</technical_language>

Target:
public AdUserConditionFieldAutoCompleter() { mVerbs.put("NAME", "NAME"); mVerbs.put("USERNAME", "USERNAME"); if (StringHelper.EqOp(SyntaxCheckerFactory.getConfigAuthenticationMethod().toUpperCase(), "LDAP")) { mVerbs.put("LASTNAME", "LASTNAME"); mVerbs.put("DEPARTMENT", "DEPARTMENT"); mVerbs.put("TITLE", "TITLE"); } mVerbs.put("ALLNAMES", "ALLNAMES"); buildCompletions(); getTypeDictionary().put("NAME", String.class); getTypeDictionary().put("USERNAME", String.class); if (StringHelper.EqOp(SyntaxCheckerFactory.getConfigAuthenticationMethod().toUpperCase(), "LDAP")) { getTypeDictionary().put("LASTNAME", String.class); getTypeDictionary().put("DEPARTMENT", String.class); getTypeDictionary().put("TITLE", String.class); } mColumnNameDict.put("NAME", "$GIVENNAME"); mColumnNameDict.put("USERNAME", "$SAMACCOUNTNAME"); if (StringHelper.EqOp(SyntaxCheckerFactory.getConfigAuthenticationMethod().toUpperCase(), "LDAP")) { mColumnNameDict.put("LASTNAME", "$SN"); mColumnNameDict.put("DEPARTMENT", "$DEPARTMENT"); mColumnNameDict.put("TITLE", "$TITLE"); } ValueValidationFunction charValidation = validCahracters; for (String key : mVerbs.keySet()) { List<ValueValidationFunction> curList = new ArrayList<ValueValidationFunction>(1); curList.add(charValidation); mValidationDict.put(key, curList); } }
Source:
<code>public void resourceChanged(IResourceChangeEvent event) { IResourceDelta delta = event.getDelta(); if (delta != null) { ImageResourceDeltaVisitor visitor = getImageResourceDeltaVisitor(); try { delta.accept(visitor); <START> } catch (CoreException e) { <END> e.printStackTrace(); } for (String imageFileURI : visitor.changedImageFilesURI) { DiagramUIPlugin.getPlugin().removeImageFileStatusAndURIFromMaps(imageFileURI); } } }</code><technical_language>Sirius logger here</technical_language>

Target:
public void resourceChanged(IResourceChangeEvent event) { }
Source:
<code><START> public String cleanUp(String searchText) { <END> if(searchText.contains("@")) { return searchText.split("@")[0]; } return searchText; }</code><technical_language>I this method private</technical_language>

Target:
private String cleanUp(String searchText) { return searchText.split("@")[0]; }
Source:
<code>protected void buildAndValidateSaml( String samlRequest, String relayState, String signatureAlgorithm, String signature, SignableXMLObject xmlObject) throws ValidationException { String destination = request.getRequestURL().toString(); try { URL url = new URL(destination); if (url.getHost().equals(SystemBaseUrl.EXTERNAL.getHost()) <START> && String.valueOf(url.getPort()).equals(SystemBaseUrl.EXTERNAL.getPort())) { <END> destination = SystemBaseUrl.EXTERNAL.constructUrl(request.getRequestURI()); } } catch (MalformedURLException e) { LOGGER.error("Unable to convert request URL to URL object."); } new SamlValidator.Builder(simpleSign) .setRedirectParams( relayState, signature, signatureAlgorithm, samlRequest, idpMetadata.getSigningCertificate()) .buildAndValidate(destination, SamlProtocol.Binding.HTTP_REDIRECT, xmlObject); }</code><technical_language>additional check for external context put well</technical_language>

Target:
protected void buildAndValidateSaml( String samlRequest, String relayState, String signatureAlgorithm, String signature, SignableXMLObject xmlObject) throws ValidationException { String destination = request.getRequestURL().toString(); try { URL url = new URL(destination); if (url.getHost().equals(SystemBaseUrl.EXTERNAL.getHost()) && String.valueOf(url.getPort()).equals(SystemBaseUrl.EXTERNAL.getPort()) && !url.getPath().startsWith(SystemBaseUrl.EXTERNAL.getRootContext())) { destination = SystemBaseUrl.EXTERNAL.constructUrl(request.getRequestURI()); } } catch (MalformedURLException e) { LOGGER.error("Unable to convert request URL to URL object."); } new SamlValidator.Builder(simpleSign) .setRedirectParams( relayState, signature, signatureAlgorithm, samlRequest, idpMetadata.getSigningCertificate()) .buildAndValidate(destination, SamlProtocol.Binding.HTTP_REDIRECT, xmlObject); }
Source:
<code>private static SSLCustomizerInterceptor checkAndGetTlsInterceptor() { if (Misc.isRunningOnAndroid()) { System.out.println("RUNNING ON ANDROID"); try { String tlsv1_2 = "TLSv1.2"; int androidApiLevel = Class.forName("android.os.Build$VERSION").getField ("SDK_INT").getInt(null); if (androidApiLevel < 20) { SSLContext defSslCtx = SSLContext.getDefault(); if (!Arrays.asList(defSslCtx.getDefaultSSLParameters().getProtocols()) .contains(tlsv1_2) && Arrays.asList(defSslCtx.getSupportedSSLParameters().getProtocols()) .contains(tlsv1_2)) { SSLContext sc = SSLContext.getInstance(tlsv1_2); sc.init(null, null, null); SSLSocketFactory s = sc.getSocketFactory(); <START> return new Special(s); <END> } } } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (NoSuchFieldException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (KeyManagementException e) { throw new RuntimeException(e); } } return null; }</code><technical_language>remove Special class (see below), SSLCustomizerInterceptor directly</technical_language>

Target:
private static SSLCustomizerInterceptor checkAndGetTlsInterceptor() { if (Misc.isRunningOnAndroid()) { try { int androidApiLevel = Class.forName("android.os.Build$VERSION").getField ("SDK_INT").getInt(null); if (androidApiLevel < 20) { SSLContext defSslCtx = SSLContext.getDefault(); if (!Arrays.asList(defSslCtx.getDefaultSSLParameters().getProtocols()) .contains(TlsOnlySslSocketFactory.TLSv12) && Arrays.asList(defSslCtx.getSupportedSSLParameters().getProtocols()) .contains(TlsOnlySslSocketFactory.TLSv12)) { SSLContext sc = SSLContext.getInstance(TlsOnlySslSocketFactory.TLSv12); sc.init(null, null, null); SSLSocketFactory s = sc.getSocketFactory(); return new SSLCustomizerInterceptor(new TlsOnlySslSocketFactory(s)); } } } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (NoSuchFieldException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (KeyManagementException e) { throw new RuntimeException(e); } } return null; }
Source:
<code>public static boolean cacheProperty( Map<String, String> versionPropertyUpdateMap, String oldVersion, String newVersion, Object originalType ) throws ManipulationException { if (oldVersion == null) { return false; } <START> boolean result = false; <END> if ( oldVersion.startsWith( "${" ) ) { final int endIndex = oldVersion.indexOf( '}' ); final String oldProperty = oldVersion.substring( 2, endIndex ); if ( endIndex != oldVersion.length() - 1 ) { throw new ManipulationException( "NYI : handling for versions (" + oldVersion + ") with multiple embedded properties is NYI. " ); } else if ( "project.version".equals( oldProperty ) ) { logger.debug( "For ; original version was a property mapping. Not caching value as property is built-in ( -> )", originalType, oldProperty, newVersion ); } else { logger.debug( "For ; original version was a property mapping; caching new value for update -> {}", originalType, oldProperty, newVersion ); final String oldVersionProp = oldVersion.substring( 2, oldVersion.length() - 1 ); versionPropertyUpdateMap.put( oldVersionProp, newVersion ); } result = true; } return result; }</code><technical_language>inline comparison e.g. if ( oldVersion != null && oldVersion.startsWith.... is return path</technical_language>

Target:
public static boolean cacheProperty( Map<String, String> versionPropertyUpdateMap, String oldVersion, String newVersion, Object originalType ) throws ManipulationException { boolean result = false; if ( oldVersion != null && oldVersion.startsWith( "${" ) ) { final int endIndex = oldVersion.indexOf( '}' ); final String oldProperty = oldVersion.substring( 2, endIndex ); if ( endIndex != oldVersion.length() - 1 ) { throw new ManipulationException( "NYI : handling for versions (" + oldVersion + ") with multiple embedded properties is NYI. " ); } else if ( "project.version".equals( oldProperty ) ) { logger.debug( "For ; original version was a property mapping. Not caching value as property is built-in ( -> )", originalType, oldProperty, newVersion ); } else { logger.debug( "For ; original version was a property mapping; caching new value for update -> {}", originalType, oldProperty, newVersion ); final String oldVersionProp = oldVersion.substring( 2, oldVersion.length() - 1 ); versionPropertyUpdateMap.put( oldVersionProp, newVersion ); } result = true; } return result; }
Source:
<code>public void handleNewSession() { LOG.info("Got new session created event for processor=" + processorId); <START> debounceTimer.cancelAction(ZK_SESSION_ERROR); <END> LOG.info("register zk controller for the new session"); zkController.register(); }</code><technical_language>cleaner call cancelAll() here. expectation is clear state start afresh a new session</technical_language>

Target:
public void handleNewSession() { LOG.info("Got new session created event for processor=" + processorId); debounceTimer.cancelAllScheduledActions(); LOG.info("register zk controller for the new session"); zkController.register(); }