auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public CreateGlusterVolumeSnapshotCommand(CreateGlusterVolumeSnapshotParameters params) { super(params); this.snapshot = params.getSnapshot(); this.force = params.getForce(); if (this.snapshot != null) { setVdsGroupId(this.snapshot.getClusterId()); } <START> volumeId = snapshot.getVolumeId(); <END> }</code><technical_language>call setGlusterVolumeId(snapshot.getVolumeId() - if block</technical_language>

Target:
public CreateGlusterVolumeSnapshotCommand(CreateGlusterVolumeSnapshotParameters params) { super(params); this.snapshot = params.getSnapshot(); this.force = params.getForce(); if (this.snapshot != null) { setVdsGroupId(this.snapshot.getClusterId()); setGlusterVolumeId(snapshot.getVolumeId()); } }
Source:
<code>OneTimePasswordImpl(final String algorithm, final char[] password, final OneTimePasswordAlgorithmSpec spec) throws SaslException { this(algorithm, generateOTP(algorithm, getNormalizedPasswordBytes(password), <START> new String(spec.getSeed()).toLowerCase(Locale.ENGLISH).getBytes(StandardCharsets.US_ASCII), <END> spec.getSequenceNumber() ), spec.getSeed().clone(), spec.getSequenceNumber()); }</code><technical_language>This wrong. I consider making seed a String instead of a byte[]. RFC 2289: > seed consist of purely alphanumeric characters of 16 characters in length. seed is a string of characters blanks consist of strictly alphanumeric characters ISO-646 Invariant Code Set. seed case insensitive internally converted case is processed. this textual in nature, wrong represent a byte[]. @fjuma is a justification for this this field a String? A String a advantages immutability (one array copy) ease of manipulation</technical_language>

Target:
OneTimePasswordImpl(final String algorithm, final char[] password, final OneTimePasswordAlgorithmSpec spec) throws SaslException { this(algorithm, generateOTP(algorithm, getNormalizedPasswordBytes(password), spec.getSeed().toLowerCase(Locale.ENGLISH), spec.getSequenceNumber() ), spec.getSeed(), spec.getSequenceNumber()); }
Source:
<code>private Mono<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) { if(request.getOperationType() != OperationType.QueryPlan) { request.getHeaders().put(HttpConstants.HttpHeaders.IS_QUERY, "true"); } else { <START> request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); <END> } switch (this.queryCompatibilityMode) { case SqlQuery: request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.SQL); break; case Default: case Query: default: request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.QUERY_JSON); break; } return this.performRequest(request, HttpMethod.POST); }</code><technical_language>query plan is constructed session token, this is No-Op. please QueryPlanRetriever. I guess hurt safe</technical_language>

Target:
private Mono<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) { if(request.getOperationType() != OperationType.QueryPlan) { request.getHeaders().put(HttpConstants.HttpHeaders.IS_QUERY, "true"); } switch (this.queryCompatibilityMode) { case SqlQuery: request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.SQL); break; case Default: case Query: default: request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.QUERY_JSON); break; } return this.performRequest(request, HttpMethod.POST); }
Source:
<code>public <T> T getObject(int columnIndex, Class<T> type) throws SQLException { <START> return null; <END> }</code><technical_language>this implemented</technical_language>

Target:
public <T> T getObject(int columnIndex, Class<T> type) throws SQLException { throw new UnsupportedOperationException("HPCCResultSet: getPseudoColumns Not supported yet."); }
Source:
<code>private void buildProjectsTree(final List<ProjectData> result) { <START> treeContents = null; <END> treeContents = new ProjectsTreeContents(result, ProjectScreen.INFO); treeContents.addTreeNodeCheckHandler(new CheckBoxSelectionHandler() { @Override public void onValueChange(CheckBoxSelectionEvent checkBoxSelectionEvent) { final boolean isChecked = checkBoxSelectionEvent.isChecked(); final String projectName = checkBoxSelectionEvent.getProjectName(); hideOnSuccessPanel(); setSelectedProjectsTable(isChecked, projectName); } }); treeNodesMap = null; projectNodesMap = null; treeNodesMap = treeContents.getTreeNodesMap(); projectNodesMap = treeContents.getProjectNodesMap(); rootWildProject = treeContents.getRootWildProject(); projectsTree.addItem(rootWildProject); projectsTree.getItem(0).setState(true); }</code><technical_language>this line omitted in next line set this variable</technical_language>

Target:
private void buildProjectsTree(final List<ProjectData> result) { treeContents = new ProjectsTreeContents(result, ProjectScreen.INFO); treeContents.addTreeNodeCheckHandler(new CheckBoxSelectionHandler() { @Override public void onValueChange(CheckBoxSelectionEvent checkBoxSelectionEvent) { final boolean isChecked = checkBoxSelectionEvent.isChecked(); final String projectName = checkBoxSelectionEvent.getProjectName(); hideOnSuccessPanel(); setSelectedProjectsTable(isChecked, projectName); } }); treeNodesMap = treeContents.getTreeNodesMap(); projectNodesMap = treeContents.getProjectNodesMap(); rootWildProject = treeContents.getRootWildProject(); projectsTree.addItem(rootWildProject); projectsTree.getItem(0).setState(true); }
Source:
<code>protected IStatus run(IProgressMonitor monitor) { String contents = runStap(new String[] {"-v", "-p1", "-e"}, "probe begin{}", false); if (contents == null) { <START> return new Status(IStatus.ERROR, IDEPlugin.PLUGIN_ID, ""); END> } int firstTagIndex = contents.indexOf(TAG_FILE); if (firstTagIndex != -1) { int beginIndex = contents.indexOf(TAG_FILE, firstTagIndex + 1); if (beginIndex != -1) { tapsetContents = contents.substring(beginIndex); } } return new Status(IStatus.OK, IDEPlugin.PLUGIN_ID, ""); }</code><technical_language>Error status is good some message wrong</technical_language>

Target:
protected IStatus run(IProgressMonitor monitor) { String contents = runStap(STAP_OPTIONS, STAP_DUMMYPROBE, false); if (contents == null) { return new Status(IStatus.ERROR, IDEPlugin.PLUGIN_ID, Messages.SharedParser_NoOutput); } int firstTagIndex = contents.indexOf(TAG_FILE); if (firstTagIndex != -1) { int beginIndex = contents.indexOf(TAG_FILE, firstTagIndex + 1); if (beginIndex != -1) { tapsetContents = contents.substring(beginIndex); } } return new Status(IStatus.OK, IDEPlugin.PLUGIN_ID, ""); }
Source:
<code>public static IndexClient getInstance() { if (INSTANCE == null) { synchronized (IndexClient.class) { <START> INSTANCE = new IndexClient(); <END> } } return INSTANCE; }</code><technical_language>wrap INSTANCE = new IndexClient() in another if (INSTANCE == null) { check - this is double locking technique</technical_language>

Target:
public static IndexClient getInstance() { if (INSTANCE == null) { synchronized (IndexClient.class) { if (INSTANCE == null) { INSTANCE = new IndexClient(); } } } return INSTANCE; }
Source:
<code><START> public void shouldSetSecretParameter() <END> { Config config = Config.builder() .withSetting( MySettingsWithDefaults.password, "this should not be visible" ) .withSetting( MySettingsWithDefaults.hello, "ABC" ) .withConfigClasses( Arrays.asList( mySettingsWithDefaults, myMigratingSettings ) ) .build(); assertTrue( config.getConfigValues().get( MySettingsWithDefaults.password.name() ).isSecret() ); assertFalse( config.getConfigValues().get( MySettingsWithDefaults.hello.name() ).isSecret() ); String configText = config.toString(); assertTrue( configText.contains( Secret.OBSFUCATED ) ); assertFalse( configText.contains( "this should not be visible" ) ); assertFalse( configText.contains( config.get( MySettingsWithDefaults.password ) ) ); }</code><technical_language>test updateDynamicSetting properly obfuscate passwords</technical_language>

Target:
public void shouldSetSecretParameter() { Config config = Config.builder() .withSetting( MySettingsWithDefaults.password, "this should not be visible" ) .withSetting( MySettingsWithDefaults.hello, "ABC" ) .withConfigClasses( Arrays.asList( mySettingsWithDefaults, myMigratingSettings ) ) .build(); assertTrue( config.getConfigValues().get( MySettingsWithDefaults.password.name() ).secret() ); assertFalse( config.getConfigValues().get( MySettingsWithDefaults.hello.name() ).secret() ); String configText = config.toString(); assertTrue( configText.contains( Secret.OBSFUCATED ) ); assertFalse( configText.contains( "this should not be visible" ) ); assertFalse( configText.contains( config.get( MySettingsWithDefaults.password ) ) ); }
Source:
<code>private String ingestXmlWithProduct(String filename) throws IOException { Path path = Paths.get(filename); if (Files.exists(path)) { <START> Files.delete(Paths.get(filename)); <END> } Files.createFile(path); Files.write(path, Collections.singleton(SAMPLE_DATA)); String fileLocation = path.toUri().toURL().toString(); LOGGER.debug("File Location: {}", fileLocation); return ingest(getSimpleXml(fileLocation), "text/xml"); }</code><technical_language>Files.delete(path)</technical_language>

Target:
private String ingestXmlWithProduct(String filename) throws IOException { Path path = Paths.get(filename); if (Files.exists(path)) { Files.delete(path); } Files.createFile(path); Files.write(path, Collections.singleton(SAMPLE_DATA)); String fileLocation = path.toUri().toURL().toString(); LOGGER.debug("File Location: {}", fileLocation); return ingest(getSimpleXml(fileLocation), "text/xml"); }
Source:
<code>public static ImageLicense parseImageLicenseMetadata(JSONObject extmetadata) { try { String license = ""; String licenseShortName = ""; String licenseUrl = ""; Iterator<String> keys = extmetadata.keys(); while (keys.hasNext()) { String key = keys.next(); String value = extmetadata.getJSONObject(key).getString("value"); switch (key) { case "License": license = value; break; case "LicenseShortName": licenseShortName = value; break; case "LicenseUrl": licenseUrl = value; break; default: break; } } <START> Log.d(TAG, "Lead image license: " + license); <END> Log.d(TAG, "Lead image license short name: " + licenseShortName); Log.d(TAG, "Lead image license URL: " + licenseUrl); return new ImageLicense(license, licenseShortName, licenseUrl); } catch (Exception e) { Log.d(TAG, "Caught exception: " + e.getMessage()); return null; } }</code><technical_language>If checking this debug logging in, more sense put line? (It if line is super long felt worth asking.)</technical_language>

Target:
public static ImageLicense parseImageLicenseMetadata(JSONObject extmetadata) { Log.d(TAG, "extmetadata: " + extmetadata.toString()); try { String license = ""; String licenseShortName = ""; String licenseUrl = ""; Iterator<String> keys = extmetadata.keys(); while (keys.hasNext()) { String key = keys.next(); String value = extmetadata.getJSONObject(key).getString("value"); switch (key) { case "License": license = value; break; case "LicenseShortName": licenseShortName = value; break; case "LicenseUrl": licenseUrl = value; break; default: break; } } Log.d(TAG, "Found lead image license=" + license + ", short name=" + licenseShortName + ", url=" + licenseUrl); return new ImageLicense(license, licenseShortName, licenseUrl); } catch (JSONException e) { Log.d(TAG, "Caught exception: " + e.getMessage(), e); return null; } }
Source:
<code>List<TopicPartition> closeRevokedStandbyTasks(final Map<TaskId, Set<TopicPartition>> revokedTasks) { log.debug("Closing revoked standby tasks {}", revokedTasks); final List<TopicPartition> revokedChangelogs = new ArrayList<>(); for (final Map.Entry<TaskId, Set<TopicPartition>> entry : revokedTasks.entrySet()) { final TaskId taskId = entry.getKey(); final StandbyTask task; if (running.containsKey(taskId)) { task = running.get(taskId); } else if (created.containsKey(taskId)) { task = created.get(taskId); } else { log.error("Could not find the standby task while closing it", taskId); continue; } try { task.close(true, false); } catch (final RuntimeException e) { log.error("Closing the standby task failed due to the following error:", task.id(), e); } finally { <START> removeTaskFromAllOldMaps(task, null); <END> revokedChangelogs.addAll(task.changelogPartitions()); } } return revokedChangelogs; }</code><technical_language>minor suggestion - instead of null Collections.emptyMap()? This suggestion is subjective feel free ignore. Applies below</technical_language>

Target:
List<TopicPartition> closeRevokedStandbyTasks(final Map<TaskId, Set<TopicPartition>> revokedTasks) { log.debug("Closing revoked standby tasks {}", revokedTasks); final List<TopicPartition> revokedChangelogs = new ArrayList<>(); for (final Map.Entry<TaskId, Set<TopicPartition>> entry : revokedTasks.entrySet()) { final TaskId taskId = entry.getKey(); final StandbyTask task; if (running.containsKey(taskId)) { task = running.get(taskId); } else if (created.containsKey(taskId)) { task = created.get(taskId); } else { log.error("Could not find the standby task while closing it", taskId); continue; } try { task.close(true, false); } catch (final RuntimeException e) { log.error("Closing the standby task failed due to the following error:", task.id(), e); } finally { removeTaskFromAllStateMaps(task, Collections.emptyMap()); revokedChangelogs.addAll(task.changelogPartitions()); } } return revokedChangelogs; }
Source:
<code>private synchronized void updateTaggedMemoryAllocations(QueryId queryId, String allocationTag, long delta) { Map<String, Long> allocations = taggedMemoryAllocations.computeIfAbsent(queryId, ignored -> new HashMap<>()); Long value = allocations.get(allocationTag); if (value == null) { allocations.put(allocationTag, delta); return; } value = value + delta; <START> if (value <= 0) { <END> allocations.remove(allocationTag); } else { allocations.put(allocationTag, value); } }</code><technical_language>concerned this one. operators allowed freely tag things, bugs allocate tag match free tag. This end a huge positive for allocate a huge negative for free tag. I get error long total negative. change this == 0 allow for negative values for a tag, I enforce operator tag negative</technical_language>

Target:
private synchronized void updateTaggedMemoryAllocations(QueryId queryId, String allocationTag, long delta) { Map<String, Long> allocations = taggedMemoryAllocations.computeIfAbsent(queryId, ignored -> new HashMap<>()); allocations.compute(allocationTag, (ignored, oldValue) -> { if (oldValue == null) { return delta; } long newValue = oldValue.longValue() + delta; if (newValue == 0) { return null; } return newValue; }); }
Source:
<code>public void addWorkDefinition(IAtsWorkDefinition workDef) { WorkDefinitionFactory.get(); <START> WorkDefinitionFactory.instance.addWorkDefinition(workDef); <END> }</code><technical_language>Fix this - get other code -</technical_language>

Target:
public void addWorkDefinition(IAtsWorkDefinition workDef) { factory.addWorkDefinition(workDef); }
Source:
<code>public final int update(final String table, final String key, final HashMap<String, ByteIterator> values) { try { final MongoCollection collection = database.getCollection(table); final DocumentBuilder query = BuilderFactory.start().add("_id", key); final DocumentBuilder update = BuilderFactory.start(); final DocumentBuilder fieldsToSet = update.push("$set"); for (final Map.Entry<String, ByteIterator> entry : values.entrySet()) { fieldsToSet.add(entry.getKey(), entry.getValue().toArray()); } final long res = collection.update(query, update, false, false, writeConcern); <START> return res == 1 ? StatusCode.OK : StatusCode.ERROR; <END> } catch (final Exception e) { System.err.println(e.toString()); return StatusCode.ERROR; } }</code><technical_language>ERROR --> NOT_FOUND</technical_language>

Target:
public final Status update(final String table, final String key, final HashMap<String, ByteIterator> values) { try { final MongoCollection collection = database.getCollection(table); final DocumentBuilder query = BuilderFactory.start().add("_id", key); final DocumentBuilder update = BuilderFactory.start(); final DocumentBuilder fieldsToSet = update.push("$set"); for (final Map.Entry<String, ByteIterator> entry : values.entrySet()) { fieldsToSet.add(entry.getKey(), entry.getValue().toArray()); } final long res = collection.update(query, update, false, false, writeConcern); return res == 1 ? Status.OK : Status.NOT_FOUND; } catch (final Exception e) { System.err.println(e.toString()); return Status.ERROR; } }
Source:
<code>public void onRefreshButtonClicked() { <START> JavaFxUtil.assertBackgroundThread(); <END> mapService.evictCache(); switch (state.get()) { case SHOWROOM: displayShowroomMaps(); break; case SEARCH_RESULT: currentPage--; currentSupplier.get() .thenAccept(this::displayMaps) .exceptionally(throwable -> { notificationService.addNotification(new ImmediateErrorNotification( i18n.get("errorTitle"), i18n.get("vault.mods.searchError"), throwable, i18n, reportingService )); enterShowroomState(); return null; }); break; default: } }</code><technical_language>tis run Backgound thread</technical_language>

Target:
public void onRefreshButtonClicked() { mapService.evictCache(); switch (state.get()) { case SHOWROOM: displayShowroomMaps(); break; case SEARCH_RESULT: currentSupplier.get() .thenAccept(this::displayMaps) .exceptionally(throwable -> { notificationService.addNotification(new ImmediateErrorNotification( i18n.get("errorTitle"), i18n.get("vault.mods.searchError"), throwable, i18n, reportingService )); enterShowroomState(); return null; }); break; default: } }
Source:
<code>void addRamAttributes( Map<String, InternalMachineConfig> machines, Map<String, ComposeService> services) throws InfrastructureException { for (Entry<String, ComposeService> entry : services.entrySet()) { InternalMachineConfig machineConfig; if ((machineConfig = machines.get(entry.getKey())) == null) { machineConfig = new InternalMachineConfig(); machines.put(entry.getKey(), machineConfig); } initIfEmpty( () -> entry.getValue().getMemLimit(), machineConfig, MEMORY_LIMIT_ATTRIBUTE, <START> defaultMachineMaxMemorySizeAttribute); <END> initIfEmpty( () -> entry.getValue().getMemRequest(), machineConfig, MEMORY_REQUEST_ATTRIBUTE, defaultMachineRequestMemorySizeAttribute); } }</code><technical_language>Fix if I wrong Now, a user set a memory request attribute limit. is a case: user sets memory request attribute 2 GB, memory limit attribute is missing, set default 1 GB. unnatural memory request is memory limit. happen in this case? K8s/OS allows create this object? sense set for memory limit for memory request if memory request is memory limit is not</technical_language>

Target:
void addRamAttributes( Map<String, InternalMachineConfig> machines, Map<String, ComposeService> services) throws InfrastructureException { for (Entry<String, ComposeService> entry : services.entrySet()) { InternalMachineConfig machineConfig; if ((machineConfig = machines.get(entry.getKey())) == null) { machineConfig = new InternalMachineConfig(); machines.put(entry.getKey(), machineConfig); } memoryProvisioner.provision( machineConfig, entry.getValue().getMemLimit(), entry.getValue().getMemRequest()); } }
Source:
<code>public void testReadFromInserter() throws IOException { ObjectInserter ins = db.newObjectInserter(); ObjectId id1 = ins.insert(Constants.OBJ_BLOB, Constants.encode("foo")); ObjectId id2 = ins.insert(Constants.OBJ_BLOB, Constants.encode("bar")); assertEquals(0, db.getObjectDatabase().listPacks().size()); ObjectReader reader = ins.newReader(db); assertEquals("foo", readObject(reader.open(id1))); assertEquals("bar", readObject(reader.open(id2))); <START> assertEquals(0, db.getObjectDatabase().listPacks().size()); <END> ins.flush(); assertEquals(1, db.getObjectDatabase().listPacks().size()); }</code><technical_language>(optional) worth testing ins.release() (i.e., case pack is committed discarded instead)</technical_language>

Target:
public void testReadFromInserter() throws IOException { ObjectInserter ins = db.newObjectInserter(); ObjectId id1 = ins.insert(Constants.OBJ_BLOB, Constants.encode("foo")); ObjectId id2 = ins.insert(Constants.OBJ_BLOB, Constants.encode("bar")); assertEquals(0, db.getObjectDatabase().listPacks().size()); ObjectReader reader = ins.newReader(); assertEquals("foo", readObject(reader.open(id1))); assertEquals("bar", readObject(reader.open(id2))); assertEquals(0, db.getObjectDatabase().listPacks().size()); ins.flush(); assertEquals(1, db.getObjectDatabase().listPacks().size()); }
Source:
<code>private void prefetch() { while (this.inner.hasNext() && !Thread.currentThread().isInterrupted()) { final SAMRecord next = this.inner.peek(); final int bases = next.getReadLength(); try { synchronized (this.basesAllowed) { <START> while (this.basesAllowed.get() < bases && this.basesAllowed.get() < this.basePrefetchLimit) { <END> if (Thread.currentThread().isInterrupted()) { return; } this.basesAllowed.wait(); } this.basesAllowed.addAndGet(-bases); } synchronized (this) { this.inner.next(); this.queue.add(new Either(next)); } } catch (final InterruptedException e) { return; } catch (final Throwable t) { this.queue.add(new Either(t)); } } }</code><technical_language>this is a micro-optimization, I call basesAllowed.get() save in a variable</technical_language>

Target:
private void prefetch() { while (this.inner.hasNext() && !Thread.currentThread().isInterrupted()) { final SAMRecord next = this.inner.peek(); final int bases = next.getReadLength(); try { synchronized (this.basesAllowed) { int basesAllowed = this.basesAllowed.get(); while (basesAllowed < bases && basesAllowed < this.basePrefetchLimit) { if (Thread.currentThread().isInterrupted()) { return; } this.basesAllowed.wait(); basesAllowed = this.basesAllowed.get(); } this.basesAllowed.addAndGet(-bases); } synchronized (this) { this.inner.next(); this.queue.add(new Either(next)); } } catch (final InterruptedException e) { return; } catch (final Throwable t) { if (t instanceof Error) { t.printStackTrace(); } this.queue.add(new Either(t)); } } }
Source:
<code>public void testFtpUrlsHandledByFtpUrlConnection() throws Exception { URLConnection connection = fileUrl.openConnection(); <START> assertEquals(FtpURLConnection.class, <END> connection.getClass()); }</code><technical_language>Do need this</technical_language>

Target:
public void testFtpUrlsHandledByFtpUrlConnection() throws Exception { URL fileUrl = addFileEntry(FILE_PATH, fileContents); URLConnection connection = fileUrl.openConnection(); assertEquals("sun.net.www.protocol.ftp.FtpURLConnection", connection.getClass().getName()); }
Source:
<code>public Map<String, Class<?>> getTypeMap() throws SQLException { checkClosed(); <START> return new HashMap<String, Class<?>>(getTypeMapNoCopy()); <END> }</code><technical_language>point of adding a copy here</technical_language>

Target:
public Map<String, Class<?>> getTypeMap() throws SQLException { checkClosed(); return new LinkedHashMap<String, Class<?>>(udtMap.getTypeMap()); }
Source:
<code>private void reconstructMasterDomainNotInSync(final Guid storagePoolId, final Guid masterDomainId, final String exceptionMessage, final String logMessage) { ((EventQueue) EjbUtils.findBean(BeanType.EVENTQUEUE_MANAGER, BeanProxyType.LOCAL)).submitEventSync(new Event(_storagePoolId, masterDomainId, null, EventType.RECONSTRUCT), new Callable<EventResult>() { @Override public EventResult call() { EventResult result = null; log.warnFormat(logMessage); AuditLogableBase logable = new AuditLogableBase(mCurrentVdsId); logable.setStorageDomainId(masterDomainId); AuditLogDirector.log(logable, AuditLogType.SYSTEM_MASTER_DOMAIN_NOT_IN_SYNC); result = ResourceManager.getInstance() .getEventListener() .masterDomainNotOperational(masterDomainId, storagePoolId); <START> return result; <END> } }); throw new IRSNoMasterDomainException(exceptionMessage); }</code><technical_language>return inline, a matter of taste, I guess</technical_language>

Target:
private void reconstructMasterDomainNotInSync(final Guid storagePoolId, final Guid masterDomainId, final String exceptionMessage, final String logMessage) { ((EventQueue) EjbUtils.findBean(BeanType.EVENTQUEUE_MANAGER, BeanProxyType.LOCAL)).submitEventSync(new Event(_storagePoolId, masterDomainId, null, EventType.RECONSTRUCT), new Callable<EventResult>() { @Override public EventResult call() { log.warnFormat(logMessage); AuditLogableBase logable = new AuditLogableBase(mCurrentVdsId); logable.setStorageDomainId(masterDomainId); AuditLogDirector.log(logable, AuditLogType.SYSTEM_MASTER_DOMAIN_NOT_IN_SYNC); return ResourceManager.getInstance() .getEventListener() .masterDomainNotOperational(masterDomainId, storagePoolId); } }); throw new IRSNoMasterDomainException(exceptionMessage); }
Source:
<code><START> private String getImportText(DetailAST ast) { <END> final FullIdent imp; if (ast.getType() == TokenTypes.IMPORT) { imp = FullIdent.createFullIdentBelow(ast); } else { imp = FullIdent.createFullIdent(ast .getFirstChild().getNextSibling()); } return imp.getText(); }</code><technical_language>please static</technical_language>

Target:
private static String getImportText(DetailAST ast) { final FullIdent imp; if (ast.getType() == TokenTypes.IMPORT) { imp = FullIdent.createFullIdentBelow(ast); } else { imp = FullIdent.createFullIdent(ast .getFirstChild().getNextSibling()); } return imp.getText(); }
Source:
<code>private void deleteNoteAttachmentWithoutSourceOrTarget(Diagram gmfDiagram) { Iterable<Connector> noteAttachmentsToRemoveIter = Iterables.filter(Iterables.filter(gmfDiagram.getEdges(), Connector.class), new Predicate<Connector>() { @Override public boolean apply(Connector connector) { if (ViewType.NOTEATTACHMENT.equals(connector.getType())) { if (connector.getSource() == null || connector.getTarget() == null) { return true; } } return false; } }); Connector[] noteAttachmentsToRemove = Iterables.toArray(noteAttachmentsToRemoveIter, Connector.class); for (Connector connector : noteAttachmentsToRemove) { gmfDiagram.removeEdge(connector); } if (noteAttachmentsToRemove.length > 0) { <START> StringBuilder sb = new StringBuilder(Messages.NoteAttachmentWithoutSourceOrTargetMigrationParticipant_title); sb.append(MessageFormat.format(Messages.NoteAttachmentWithoutSourceOrTargetMigrationParticipant_edgesRemoved, noteAttachmentsToRemove.length)); DiagramPlugin.getDefault().logInfo(sb.toString()); <END> } }</code><technical_language>I important for end users diagrams impacted, 157 note attachment removed</technical_language>

Target:
private void deleteNoteAttachmentWithoutSourceOrTarget(Diagram gmfDiagram) { Iterable<Connector> noteAttachmentsToRemoveIter = Iterables.filter(Iterables.filter(gmfDiagram.getEdges(), Connector.class), new Predicate<Connector>() { @Override public boolean apply(Connector connector) { if (ViewType.NOTEATTACHMENT.equals(connector.getType())) { if (connector.getSource() == null || connector.getTarget() == null) { return true; } } return false; } }); Connector[] noteAttachmentsToRemove = Iterables.toArray(noteAttachmentsToRemoveIter, Connector.class); for (Connector connector : noteAttachmentsToRemove) { gmfDiagram.removeEdge(connector); } if (noteAttachmentsToRemove.length > 0) { sb.append(MessageFormat.format(Messages.NoteAttachmentWithoutSourceOrTargetMigrationParticipant_edgesRemoved, gmfDiagram.getName(), noteAttachmentsToRemove.length)); } }
Source:
<code>protected boolean mustBeRemoved(@Nonnull JDefinedClassOrInterface type) { if (type == stringDef || type == intDef) { return true; } if (type instanceof JDefinedAnnotationType) { if ((!type.getAnnotations(stringDef).isEmpty()) || !type.getAnnotations(intDef).isEmpty()) { JDefinedAnnotationType typeDef = (JDefinedAnnotationType) type; if (typeDef.getRetentionPolicy() != JRetentionPolicy.SOURCE) { <START> type.getSession().getReporter().report(Severity.NON_FATAL, <END> new InvalidRetentionForTypeDef(typeDef)); } return true; } } return false; }</code><technical_language>Bouhhh. Need discussion. related CL</technical_language>

Target:
protected boolean mustBeRemoved(@Nonnull JDefinedClassOrInterface type) { if (type == stringDef || type == intDef) { return true; } if (type instanceof JDefinedAnnotationType) { if ((!type.getAnnotations(stringDef).isEmpty()) || !type.getAnnotations(intDef).isEmpty()) { JDefinedAnnotationType typeDef = (JDefinedAnnotationType) type; if (typeDef.getRetentionPolicy() != JRetentionPolicy.SOURCE) { type.getSession().getReporter().report(Severity.NON_FATAL, new InvalidRetentionForTypeDef(typeDef)); } return true; } } else if ((!type.getAnnotations(stringDef).isEmpty()) || !type.getAnnotations(intDef).isEmpty()) { Jack.getSession().getReporter().report(Severity.NON_FATAL, new InvalidTypeDefTarget(type)); } return false; }
Source:
<code>private GoogleClientSecrets loadClientSecretFromJson() throws IOException { InputStream in; try { in = new FileInputStream(new File(TestProperties.TEST_GMAIL_API_FOLDER, "client_secret.json")); } catch (FileNotFoundException e) { <START> throw new RuntimeException("You need to setup your client_secret.json." + System.lineSeparator() <END> + "See <LINK_0>", e); } return GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in)); }</code><technical_language>Assumption.fail Const.EOL</technical_language>

Target:
private GoogleClientSecrets loadClientSecretFromJson() throws IOException { InputStream in; try { in = new FileInputStream(new File(TestProperties.TEST_GMAIL_API_FOLDER, "client_secret.json")); } catch (FileNotFoundException e) { throw new RuntimeException("You need to set up your Gmail API credentials." + Const.EOL + "See docs/development.md section \"Deploying to a staging server\".", e); } return GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in)); }
Source:
<code>public void testSliceSamplingOfNormalDistribution() { final double mean = 5.; final double standardDeviation = 0.75; final NormalDistribution normalDistribution = new NormalDistribution(mean, standardDeviation); final Function<Double, Double> normalLogPDF = x -> normalDistribution.logDensity(x); <START> final double xInitial = 4.5; <END> final double xMin = Double.NEGATIVE_INFINITY; final double xMax = Double.POSITIVE_INFINITY; final double width = 0.5; final int numSamples = 20000; final SliceSampler normalSampler = new SliceSampler(rng, normalLogPDF, xInitial, xMin, xMax, width); final List<Double> samples = normalSampler.sample(numSamples); final double sampleMean = new Mean().evaluate(Doubles.toArray(samples)); final double sampleStandardDeviation = new StandardDeviation().evaluate(Doubles.toArray(samples)); Assert.assertEquals(relativeError(sampleMean, mean), 0., 0.0005); Assert.assertEquals(relativeError(sampleStandardDeviation, standardDeviation), 0., 0.02); }</code><technical_language>xInitial standard deviations a slice sampler robust bad initial guesses. honest I of coding error fail in this failing in general, right stack test code</technical_language>

Target:
public void testSliceSamplingOfNormalDistribution() { final double mean = 5.; final double standardDeviation = 0.75; final NormalDistribution normalDistribution = new NormalDistribution(mean, standardDeviation); final Function<Double, Double> normalLogPDF = normalDistribution::logDensity; final double xInitial = 1.; final double xMin = Double.NEGATIVE_INFINITY; final double xMax = Double.POSITIVE_INFINITY; final double width = 0.5; final int numSamples = 20000; final SliceSampler normalSampler = new SliceSampler(rng, normalLogPDF, xInitial, xMin, xMax, width); final List<Double> samples = normalSampler.sample(numSamples); final double sampleMean = new Mean().evaluate(Doubles.toArray(samples)); final double sampleStandardDeviation = new StandardDeviation().evaluate(Doubles.toArray(samples)); Assert.assertEquals(relativeError(sampleMean, mean), 0., 0.0005); Assert.assertEquals(relativeError(sampleStandardDeviation, standardDeviation), 0., 0.02); }
Source:
<code>private boolean addCertificateToTrustStore(Certificate cert) throws CertificateManagerException, Exception { ImportCertificateRequestMessageType requestMessage = createImportCertRequest(cert); <START> ImportCertificateResponseMessageType response = (ImportCertificateResponseMessageType) getClient().invokePort(EntityConfigAdminPortType.class, "importCertificate", requestMessage); <END> return response.isStatus(); }</code><technical_language>If possible, catch Exception re-throw CertificateManagerException need throw general Exception caller class</technical_language>

Target:
private boolean addCertificateToTrustStore(Certificate cert) throws CertificateManagerException { try { ImportCertificateRequestMessageType requestMessage = createImportCertRequest(cert); ImportCertificateResponseMessageType response = (ImportCertificateResponseMessageType) getClient().invokePort(EntityConfigAdminPortType.class, "importCertificate", requestMessage); return response.isStatus(); } catch (Exception ex) { throw new CertificateManagerException("Error sending import request message.", ex); } }
Source:
<code>public PlanNode visitSemiJoin(SemiJoinNode node, RewriteContext<Void> context) { PlanNode sourceRewritten = context.rewrite(node.getSource(), context.get()); PlanNode filteringSourceRewritten = context.rewrite(node.getFilteringSource(), context.get()); SemiJoinNode rewrittenNode = new SemiJoinNode( node.getId(), sourceRewritten, filteringSourceRewritten, node.getSourceJoinSymbol(), node.getFilteringSourceJoinSymbol(), node.getSemiJoinOutput(), node.getSourceHashSymbol(), node.getFilteringSourceHashSymbol(), <START> Optional.empty()); <END> if (isDeleteQuery) { return rewrittenNode.withDistributionType(REPLICATED); } return rewrittenNode; }</code><technical_language>if ! isDeleteQuery, optimizer change anything; empties distribution type</technical_language>

Target:
public PlanNode visitSemiJoin(SemiJoinNode node, RewriteContext<Void> context) { PlanNode sourceRewritten = context.rewrite(node.getSource(), context.get()); PlanNode filteringSourceRewritten = context.rewrite(node.getFilteringSource(), context.get()); SemiJoinNode rewrittenNode = new SemiJoinNode( node.getId(), sourceRewritten, filteringSourceRewritten, node.getSourceJoinSymbol(), node.getFilteringSourceJoinSymbol(), node.getSemiJoinOutput(), node.getSourceHashSymbol(), node.getFilteringSourceHashSymbol(), node.getDistributionType()); if (isDeleteQuery) { return rewrittenNode.withDistributionType(REPLICATED); } return rewrittenNode; }
Source:
<code>public void rendersPage() throws Exception { final Base base = new MkBase(); final String alias = "test"; final String urn = "urn:test:1"; base.user(URN.create(urn)).aliases().add(alias); MatcherAssert.assertThat( new RsPrint( new TkIndex(base).act( new RqWithHeader( new RqWithAuth(urn), "Accept", "text/xml" ) <START> )).printBody(), <END> XhtmlMatchers.hasXPaths( "/page/alias/email", "/page/links/link[@rel='save-email']/@href" ) ); }</code><technical_language>@exper0 move final ).printBody(), next line maintain correct indentation</technical_language>

Target:
public void rendersPage() throws Exception { final Base base = new MkBase(); final String alias = "test"; final String urn = "urn:test:1"; base.user(URN.create(urn)).aliases().add(alias); MatcherAssert.assertThat( new RsPrint( new TkIndex(base).act(new RqWithAuth(urn)) ).printBody(), XhtmlMatchers.hasXPaths( "/page/alias/email", "/page/links/link[@rel='save-email']/@href" ) ); }
Source:
<code>public boolean matches(ITmfEvent event) { for (ITmfFilterTreeNode node : getChildren()) { if (! node.matches(event)) { return false ^ fNot; } } <START> return false ^ fNot; <END> }</code><technical_language>Empty children needs a special case loop, this fall-through executes children match (expect true)</technical_language>

Target:
public boolean matches(ITmfEvent event) { if (getChildren().length == 0) { return false ^ fNot; } for (ITmfFilterTreeNode node : getChildren()) { if (! node.matches(event)) { return false ^ fNot; } } return true ^ fNot; }
Source:
<code>public static DiscoveryStrategy create(ResourceLoader resourceLoader, Bootstrap bootstrap, Set<Class<? extends Annotation>> initialBeanDefiningAnnotations, boolean jandexStrategyDisabled) { <START> if (jandexStrategyDisabled) { <END> CommonLogger.LOG.jandexDiscoveryStrategyDisabled(); } else { if (Jandex.isJandexAvailable(resourceLoader)) { CommonLogger.LOG.usingJandex(); try { return Jandex.createJandexDiscoveryStrategy(resourceLoader, bootstrap, initialBeanDefiningAnnotations); } catch (Exception e) { throw CommonLogger.LOG.unableToInstantiate(Jandex.JANDEX_DISCOVERY_STRATEGY_CLASS_NAME, Arrays.toString(new Object[] { resourceLoader, bootstrap, initialBeanDefiningAnnotations }), e); } } } return new ReflectionDiscoveryStrategy(resourceLoader, bootstrap, initialBeanDefiningAnnotations); }</code><technical_language>I move this check if (Jandex.isJandexAvailable(resourceLoader)) block. more sense show log message if jandex is classpath. WDYT</technical_language>

Target:
public static DiscoveryStrategy create(ResourceLoader resourceLoader, Bootstrap bootstrap, Set<Class<? extends Annotation>> initialBeanDefiningAnnotations, boolean jandexStrategyDisabled) { if (Jandex.isJandexAvailable(resourceLoader)) { if (jandexStrategyDisabled) { CommonLogger.LOG.jandexDiscoveryStrategyDisabled(); } else { CommonLogger.LOG.usingJandex(); try { return Jandex.createJandexDiscoveryStrategy(resourceLoader, bootstrap, initialBeanDefiningAnnotations); } catch (Exception e) { throw CommonLogger.LOG.unableToInstantiate(Jandex.JANDEX_DISCOVERY_STRATEGY_CLASS_NAME, Arrays.toString(new Object[] { resourceLoader, bootstrap, initialBeanDefiningAnnotations }), e); } } } return new ReflectionDiscoveryStrategy(resourceLoader, bootstrap, initialBeanDefiningAnnotations); }
Source:
<code>public void addTo(DSeries series) { final HistogramStatistics statistics = histogram.getStatistics(); series.add(new StaticDMetric(statistics.getMean(), withMetricNameSuffix(metaData, "avg"))); series.add(new StaticDMetric(histogram.getCount(), withMetricNameSuffix(metaData, "count"))); series.add(new StaticDMetric(statistics.getQuantile(.5), withMetricNameSuffix(metaData, "median"))); series.add(new StaticDMetric(statistics.getQuantile(.95), withMetricNameSuffix(metaData, "95percentile"))); series.add(new StaticDMetric(statistics.getMin(), withMetricNameSuffix(metaData, "min"))); <START> series.add(new StaticDMetric(statistics.getMax(), withMetricNameSuffix(metaData, "max"))); <END> }</code><technical_language>This runs in a separate thread, expensive string concat MetricsMetaData allocation time send metric. sense initialize MetaData name suffixes in constructor</technical_language>

Target:
public void addTo(DSeries series) { final HistogramStatistics statistics = histogram.getStatistics(); series.add(new StaticDMetric(statistics.getMean(), metaDataAvg)); series.add(new StaticDMetric(histogram.getCount(), metaDataCount)); series.add(new StaticDMetric(statistics.getQuantile(.5), metaDataMedian)); series.add(new StaticDMetric(statistics.getQuantile(.95), metaData95Percentile)); series.add(new StaticDMetric(statistics.getMin(), metaDataMin)); series.add(new StaticDMetric(statistics.getMax(), metaDataMax)); }
Source:
<code>public OutputStream openOutputStream(String filePath) throws IOException { try { DistributedLogManager dlm = namespace.openLog( filePath); LedgerMetadata metadata = new LedgerMetadata(); metadata.setApplication(Constants.LEDGER_METADATA_APPLICATION_STREAM_STORAGE); <START> metadata.setComponent("checkpoint-store"); <END> AsyncLogWriter writer = Utils.ioResult(dlm.openAsyncLogWriter()); return new BufferedOutputStream( new DLOutputStream(dlm, writer), 128 * 1024); } catch (LogNotFoundException le) { throw new FileNotFoundException(filePath); } }</code><technical_language>this a dead store, this variable</technical_language>

Target:
public OutputStream openOutputStream(String filePath) throws IOException { try { DistributedLogManager dlm = namespace.openLog( filePath); LedgerMetadata metadata = new LedgerMetadata(); metadata.setApplication(Constants.LEDGER_METADATA_APPLICATION_STREAM_STORAGE); metadata.setComponent("checkpoint-store"); AsyncLogWriter writer = Utils.ioResult(dlm.openAsyncLogWriter(metadata)); return new BufferedOutputStream( new DLOutputStream(dlm, writer), 128 * 1024); } catch (LogNotFoundException le) { throw new FileNotFoundException(filePath); } }
Source:
<code>public Optional<String> getGroupId() { <START> return Optional.of("org.junit.platform.suite"); <END> }</code><technical_language>suggestion return Optional.of("org.junit.platform");</technical_language>

Target:
public Optional<String> getGroupId() { return Optional.of("org.junit.platform"); }
Source:
<code>@Test public void testBitOrFunc() { tester.setFor(SqlStdOperatorTable.BIT_OR, VM_FENNEL, VM_JAVA); tester.checkFails("bit_or(^*^)", "Unknown identifier '\\*'", false); tester.checkType("bit_or(1)", "INTEGER"); tester.checkType("bit_or(CAST(2 AS TINYINT))", "TINYINT"); tester.checkType("bit_or(CAST(2 AS SMALLINT))", "SMALLINT"); tester.checkType("bit_or(distinct CAST(2 AS BIGINT))", "BIGINT"); tester.checkType("bit_or(CAST(x'02' AS BINARY(1)))", "BINARY(1)"); tester.checkFails("^bit_or(1.2)^", "Cannot apply 'BIT_OR' to arguments of type 'BIT_OR\\(<DECIMAL\\(2, 1\\)>\\)'\\. Supported form\\(s\\): 'BIT_OR\\(<INTEGER>\\)'\n" + "'BIT_OR\\(<BINARY>\\)'", false); tester.checkFails( "^bit_or()^", "Invalid number of arguments to function 'BIT_OR'. Was expecting 1 arguments", false); tester.checkFails( "^bit_or(1, 2)^", "Invalid number of arguments to function 'BIT_OR'. Was expecting 1 arguments", false); final String[] values = {"1", "2", "2"}; tester.checkAgg("bit_or(x)", values, 3, 0); final String[] binaryValues = { "CAST(x'01' AS BINARY)", "cast(x'02' as BINARY)", <START> "cast(x'02' AS BINARY)"}; <END> tester.checkAgg("bit_or(x)", binaryValues, "03", 0); }</code><technical_language>need update reference.md for function signatures change</technical_language>

Target:
@Test void testBitOrFunc() { tester.setFor(SqlStdOperatorTable.BIT_OR, VM_FENNEL, VM_JAVA); tester.checkFails("bit_or(^*^)", "Unknown identifier '\\*'", false); tester.checkType("bit_or(1)", "INTEGER"); tester.checkType("bit_or(CAST(2 AS TINYINT))", "TINYINT"); tester.checkType("bit_or(CAST(2 AS SMALLINT))", "SMALLINT"); tester.checkType("bit_or(distinct CAST(2 AS BIGINT))", "BIGINT"); tester.checkType("bit_or(CAST(x'02' AS BINARY(1)))", "BINARY(1)"); tester.checkFails("^bit_or(1.2)^", "Cannot apply 'BIT_OR' to arguments of type 'BIT_OR\\(<DECIMAL\\(2, 1\\)>\\)'\\. Supported form\\(s\\): 'BIT_OR\\(<INTEGER>\\)'\n" + "'BIT_OR\\(<BINARY>\\)'", false); tester.checkFails( "^bit_or()^", "Invalid number of arguments to function 'BIT_OR'. Was expecting 1 arguments", false); tester.checkFails( "^bit_or(1, 2)^", "Invalid number of arguments to function 'BIT_OR'. Was expecting 1 arguments", false); final String[] values = {"1", "2", "2"}; tester.checkAgg("bit_or(x)", values, 3, 0); final String[] binaryValues = { "CAST(x'01' AS BINARY)", "cast(x'02' as BINARY)", "cast(x'02' AS BINARY)", "cast(null AS BINARY)"}; tester.checkAgg("bit_or(x)", binaryValues, "03", 0); tester.checkAgg("bit_or(x)", new String[]{"CAST(x'02' AS BINARY)"}, "02", 0); }
Source:
<code>public List<PhpIniIssue> analyze(PhpIniFile phpIniFile) { List<PhpIniIssue> issues = new ArrayList<>(); List<Directive> directives = phpIniFile.directivesForName("open_basedir"); if (directives.isEmpty()) { <START> issues.add(newIssue("Set \"open_basedir\".")); <END> } for (Directive directive : directives) { String value = directive.value().text(); if (value.startsWith("\"")) { value = value.substring(1); } if (value.endsWith("\"")) { value = value.substring(0, value.length() - 1); } for (String path : value.split(":|;")) { if (".".equals(path) || "/".equals(path)) { String message = "Limit \"open_basedir\" to a narrower path than \"" + path + "\"."; int line = directive.name().line(); issues.add(newIssue(message).line(line)); break; } } } return issues; }</code><technical_language>@pynicolas extract messages class fields</technical_language>

Target:
public List<PhpIniIssue> analyze(PhpIniFile phpIniFile) { List<PhpIniIssue> issues = new ArrayList<>(); List<Directive> directives = phpIniFile.directivesForName("open_basedir"); if (directives.isEmpty()) { issues.add(newIssue(FILE_MESSAGE)); } for (Directive directive : directives) { String value = directive.value().text(); if (value.startsWith("\"")) { value = value.substring(1); } if (value.endsWith("\"")) { value = value.substring(0, value.length() - 1); } for (String path : value.split(":|;")) { if (".".equals(path) || "/".equals(path)) { String message = String.format(DIRECTIVE_MESSAGE, path); int line = directive.name().line(); issues.add(newIssue(message).line(line)); break; } } } return issues; }
Source:
<code>public void compareVersion_shouldTreatSNAPSHOTAsEarliestVersion() throws Exception { <START> String olderVersion = "1.8.4~SNAPSHOT"; <END> String newerVersion = "1.8.4"; Assert.assertTrue(ModuleUtil.compareVersion(newerVersion, olderVersion) > 0); Assert.assertTrue(ModuleUtil.compareVersion(olderVersion, newerVersion) < 0); }</code><technical_language>intend remove -</technical_language>

Target:
public void compareVersion_shouldTreatSNAPSHOTAsEarliestVersion() throws Exception { String olderVersion = "1.8.4-SNAPSHOT"; String newerVersion = "1.8.4"; Assert.assertTrue(ModuleUtil.compareVersion(newerVersion, olderVersion) > 0); Assert.assertTrue(ModuleUtil.compareVersion(olderVersion, newerVersion) < 0); }
Source:
<code>private void updateWidgetOffsets(int fromOffset) { <START> if (document != null) { <END> final int docLines = document.getNumberOfLines(); if (isFixedWidth()) { try { final int offset = Math.max(fromOffset, 0); int docLineIndex = Math.max(document.getLineOfOffset(offset), 0); final int docLineOffset = document.getLineOffset(docLineIndex); int widgetLineIndex; if (docLineOffset > 0) { widgetLineIndex = getLineOfOffset(docLineOffset); } else { widgetLineIndex = 0; ensureOffsetsCapacity(widgetLineIndex + 1); widgetLineOffsets[widgetLineIndex] = 0; } for (; docLineIndex < docLines; docLineIndex++) { int lineLength = document.getLineInformation(docLineIndex).getLength(); for (; lineLength > consoleWidth; lineLength -= consoleWidth) { widgetLineIndex++; ensureOffsetsCapacity(widgetLineIndex + 1); widgetLineOffsets[widgetLineIndex] = widgetLineOffsets[widgetLineIndex - 1] + consoleWidth; } final String docLineDelimiter = document.getLineDelimiter(docLineIndex); if (docLineDelimiter != null) { widgetLineIndex++; ensureOffsetsCapacity(widgetLineIndex + 1); widgetLineOffsets[widgetLineIndex] = widgetLineOffsets[widgetLineIndex - 1] + lineLength + docLineDelimiter.length(); } } widgetLines = widgetLineIndex + 1; } catch (BadLocationException e) { ConsolePlugin.log(e); } } else { widgetLines = docLines; } } else { widgetLines = 0; } }</code><technical_language>I personally prefer "fast return" style, "if" branches do match ends a return. This avoids "deep" nesting</technical_language>

Target:
private void updateWidgetOffsets(int fromOffset) { if (document == null) { widgetLines = 0; return; } final int docLines = document.getNumberOfLines(); if (!isFixedWidth()) { widgetLines = docLines; } else { try { final int offset = Math.max(fromOffset, 0); int docLineIndex = Math.max(document.getLineOfOffset(offset), 0); final int docLineOffset = document.getLineOffset(docLineIndex); int widgetLineIndex; if (docLineOffset > 0) { widgetLineIndex = getLineOfOffset(docLineOffset); } else { widgetLineIndex = 0; ensureOffsetsCapacity(widgetLineIndex + 1); widgetLineOffsets[widgetLineIndex] = 0; } for (; docLineIndex < docLines; docLineIndex++) { int lineLength = document.getLineInformation(docLineIndex).getLength(); for (; lineLength > consoleWidth; lineLength -= consoleWidth) { widgetLineIndex++; ensureOffsetsCapacity(widgetLineIndex + 1); widgetLineOffsets[widgetLineIndex] = widgetLineOffsets[widgetLineIndex - 1] + consoleWidth; } final String docLineDelimiter = document.getLineDelimiter(docLineIndex); if (docLineDelimiter != null) { widgetLineIndex++; ensureOffsetsCapacity(widgetLineIndex + 1); widgetLineOffsets[widgetLineIndex] = widgetLineOffsets[widgetLineIndex - 1] + lineLength + docLineDelimiter.length(); } } widgetLines = widgetLineIndex + 1; } catch (BadLocationException e) { ConsolePlugin.log(e); } } }