auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Object execute(final ExecutionEvent event) throws ExecutionException { final IEditorPart activeEditor = HandlerUtil.getActiveEditor(event); if (!(activeEditor instanceof AgeDiagramEditor)) { throw new RuntimeException("Unexpected editor: " + activeEditor); } final List<DiagramElement> selectedDiagramElements = AgeHandlerUtil.getSelectedDiagramElements(event); if (selectedDiagramElements.size() == 0) { throw new RuntimeException("No element selected"); } final DiagramElement selectedElement = selectedDiagramElements.get(0); final Object bo = selectedElement.getBusinessObject(); final DiagramService diagramService = Objects.requireNonNull(Adapters.adapt(activeEditor, DiagramService.class), "Unable to retrieve diagram service"); final ComponentImplementation ci = Objects.requireNonNull(getComponentImplementation(bo), "Unable to retrieve component implementation"); <START> ; <END> diagramService.openOrCreateDiagramForBusinessObject(ci); return null; }</code><technical_language>Extra semicolon</technical_language>

Target:
public Object execute(final ExecutionEvent event) throws ExecutionException { final IEditorPart activeEditor = HandlerUtil.getActiveEditor(event); if (!(activeEditor instanceof AgeDiagramEditor)) { throw new RuntimeException("Unexpected editor: " + activeEditor); } final List<DiagramElement> selectedDiagramElements = AgeHandlerUtil.getSelectedDiagramElements(event); if (selectedDiagramElements.size() == 0) { throw new RuntimeException("No element selected"); } final DiagramElement selectedElement = selectedDiagramElements.get(0); final Object bo = selectedElement.getBusinessObject(); final DiagramService diagramService = Objects.requireNonNull(Adapters.adapt(activeEditor, DiagramService.class), "Unable to retrieve diagram service"); final ComponentImplementation ci = Objects.requireNonNull(getComponentImplementation(bo), "Unable to retrieve component implementation"); diagramService.openOrCreateDiagramForBusinessObject(ci); return null; }
Source:
<code>private void checkPrivileges(Role role) { Collection<Privilege> privileges = role.getPrivileges(); Optional.ofNullable(role.getPrivileges()) .map(p -> p.stream().filter(pr -> !Context.hasPrivilege(pr.getPrivilege())).collect( Collectors.toSet())).ifPresent(missing -> { <START> throw new APIAuthenticationException("privileges required: " + missing.stream().map( <END> Privilege::getPrivilege).collect(Collectors.joining(", "))); }); }</code><technical_language>This "Privileges required", do this in a localisable for other ticket</technical_language>

Target:
private void checkPrivileges(Role role) { Collection<Privilege> privileges = role.getPrivileges(); Optional.ofNullable(role.getPrivileges()) .map(p -> p.stream().filter(pr -> !Context.hasPrivilege(pr.getPrivilege())).collect(Collectors.toSet())) .ifPresent(missing -> { throw new APIAuthenticationException("Privileges required: " + missing.stream().map(Privilege::getPrivilege).collect(Collectors.joining(", "))); }); }
Source:
<code>private LinkedBlockingQueue<ForceWriteRequest> enableForceWriteThreadSuspension( CountDownLatch forceWriteThreadSuspendedLatch, Journal journal) throws InterruptedException { LinkedBlockingQueue<ForceWriteRequest> supportQueue = new LinkedBlockingQueue<>(); BlockingQueue<ForceWriteRequest> forceWriteRequests = mock(BlockingQueue.class); doAnswer((Answer) (InvocationOnMock iom) -> { <START> log.error("something put " + iom.getArgument(0) + " on journal queue", <END> new Exception().fillInStackTrace()); supportQueue.put(iom.getArgument(0)); return null; }).when(forceWriteRequests).put(any(ForceWriteRequest.class)); when(forceWriteRequests.take()).thenAnswer(i -> { forceWriteThreadSuspendedLatch.await(); return supportQueue.take(); }); Whitebox.setInternalState(journal, "forceWriteRequests", forceWriteRequests); return supportQueue; }</code><technical_language>{}</technical_language>

Target:
private LinkedBlockingQueue<ForceWriteRequest> enableForceWriteThreadSuspension( CountDownLatch forceWriteThreadSuspendedLatch, Journal journal) throws InterruptedException { LinkedBlockingQueue<ForceWriteRequest> supportQueue = new LinkedBlockingQueue<>(); BlockingQueue<ForceWriteRequest> forceWriteRequests = mock(BlockingQueue.class); doAnswer((Answer) (InvocationOnMock iom) -> { log.error("something put on journal queue", iom.getArgument(0), new Exception().fillInStackTrace()); supportQueue.put(iom.getArgument(0)); return null; }).when(forceWriteRequests).put(any(ForceWriteRequest.class)); when(forceWriteRequests.take()).thenAnswer(i -> { forceWriteThreadSuspendedLatch.await(); return supportQueue.take(); }); Whitebox.setInternalState(journal, "forceWriteRequests", forceWriteRequests); return supportQueue; }
Source:
<code>public SeekableByteArrayInputStream(byte[] buf) { <START> this.buffer = buf; <END> this.cur = 0; this.max = buf.length; }</code><technical_language>Objects.requireNonNull(buf)</technical_language>

Target:
public SeekableByteArrayInputStream(byte[] buf) { Preconditions.checkNotNull(buf, "bug argument was null"); this.buffer = buf; this.cur = 0; this.max = buf.length; }
Source:
<code>public void sgeqrf(int M, int N, INDArray A, INDArray R, INDArray INFO) { INDArray tau = Nd4j.create( N ) ; int status = LAPACKE_sgeqrf(getColumnOrder(A), M, N, (FloatPointer)A.data().addressPointer(), getLda(A), (FloatPointer)tau.data().addressPointer() ); if( status != 0 ) { throw new BlasException( "Failed to execute sgeqrf", status ) ; } <START> if( R != null ) { <END> for( int ro=0 ; ro<M ; ro++ ) { for( int c=ro ; c<N ; c++ ) { R.putScalar( ro, c, A.getDouble(ro,c) ) ; } } } status = LAPACKE_sorgqr( getColumnOrder(A), M, N, N, (FloatPointer)A.data().addressPointer(), getLda(A), (FloatPointer)tau.data().addressPointer() ); if( status != 0 ) { throw new BlasException( "Failed to execute sorgqr", status ) ; } }</code><technical_language>want this happen ops indexing. significantly faster. looked put(INDArrayIndex[])</technical_language>

Target:
public void sgeqrf(int M, int N, INDArray A, INDArray R, INDArray INFO) { INDArray tau = Nd4j.create( N ) ; int status = LAPACKE_sgeqrf(getColumnOrder(A), M, N, (FloatPointer)A.data().addressPointer(), getLda(A), (FloatPointer)tau.data().addressPointer() ); if( status != 0 ) { throw new BlasException( "Failed to execute sgeqrf", status ) ; } if( R != null ) { R.assign( A.get( NDArrayIndex.interval( 0, A.columns() ), NDArrayIndex.all() ) ) ; INDArrayIndex ix[] = new INDArrayIndex[ 2 ] ; for( int i=1 ; i<Math.min( A.rows(), A.columns() ) ; i++ ) { ix[0] = NDArrayIndex.point( i ) ; ix[1] = NDArrayIndex.interval( 0, i ) ; R.put(ix, 0) ; } } status = LAPACKE_sorgqr( getColumnOrder(A), M, N, N, (FloatPointer)A.data().addressPointer(), getLda(A), (FloatPointer)tau.data().addressPointer() ); if( status != 0 ) { throw new BlasException( "Failed to execute sorgqr", status ) ; } }
Source:
<code>static long applicationProc(long id, long sel, long arg0, long arg1) { Display display = getCurrent(); if (display == null && id != applicationDelegate.id) { objc_super super_struct = new objc_super (); super_struct.receiver = id; super_struct.super_class = OS.objc_msgSend (id, OS.sel_superclass); return OS.objc_msgSendSuper (super_struct, sel, arg0, arg1); } if (currAppDelegate != null) { if (currAppDelegate.respondsToSelector(sel)) OS.objc_msgSend(currAppDelegate.id, sel, arg0, arg1); } <START> if (sel == OS.sel_application_openFile_) { <END> String file = new NSString(arg1).getString(); Event event = new Event(); event.text = file; display.sendEvent(SWT.OpenDocument, event); return 1; } else if (sel == OS.sel_application_openFiles_) { NSArray files = new NSArray(arg1); long count = files.count(); for (int i=0; i<count; i++) { String file = new NSString(files.objectAtIndex(i)).getString(); Event event = new Event(); event.text = file; display.sendEvent(SWT.OpenDocument, event); } new NSApplication(arg0).replyToOpenOrPrint(OS.NSApplicationDelegateReplySuccess); } else if (sel == OS.sel_applicationShouldHandleReopen_hasVisibleWindows_) { final Event event = new Event(); display.sendEvent(SWT.Activate, event); return event.doit ? 1 : 0; } return 0; }</code><technical_language>Convert switch for consistency</technical_language>

Target:
static long applicationProc(long id, long sel, long arg0, long arg1) { Display display = getCurrent(); if (display == null && id != applicationDelegate.id) { objc_super super_struct = new objc_super (); super_struct.receiver = id; super_struct.super_class = OS.objc_msgSend (id, OS.sel_superclass); return OS.objc_msgSendSuper (super_struct, sel, arg0, arg1); } if (currAppDelegate != null) { if (currAppDelegate.respondsToSelector(sel)) OS.objc_msgSend(currAppDelegate.id, sel, arg0, arg1); } switch (Selector.valueOf(sel)) { case sel_application_openFile_: { String file = new NSString(arg1).getString(); Event event = new Event(); event.text = file; display.sendEvent(SWT.OpenDocument, event); return 1; } case sel_application_openFiles_: { NSArray files = new NSArray(arg1); long count = files.count(); for (int i=0; i<count; i++) { String file = new NSString(files.objectAtIndex(i)).getString(); Event event = new Event(); event.text = file; display.sendEvent(SWT.OpenDocument, event); } new NSApplication(arg0).replyToOpenOrPrint(OS.NSApplicationDelegateReplySuccess); return 0; } case sel_applicationShouldHandleReopen_hasVisibleWindows_: { final Event event = new Event(); display.sendEvent(SWT.Activate, event); return event.doit ? 1 : 0; } default: { return 0; } } }
Source:
<code>public Optional<IPageTypeCategoryRole> getTypeCategoryForCatName(String categoryName) { <START> loadTypeNameToCategoryMap(); <END> return Optional.fromNullable(getTypeNameToCategoryMapIncludeDeprecated().get(categoryName)); }</code><technical_language>additional loadTypeNameToCategoryMap needed</technical_language>

Target:
public Optional<IPageTypeCategoryRole> getTypeCategoryForCatName(String categoryName) { return Optional.fromNullable(getTypeNameToCategoryMapIncludeDeprecated().get(categoryName)); }
Source:
<code>public void testNonMatchingStream() throws Exception { RuleProcessorRuntime rpr = new RuleProcessorRuntime(mockBuilder); rpr.process(event3); new Verifications() {{ <START> mockRr1.evaluate(event1); <END> times=0; mockRr2.evaluate(event1); times=0; }}; }</code><technical_language>event1 -> event3</technical_language>

Target:
public void testNonMatchingStream() throws Exception { RuleProcessorRuntime rpr = new RuleProcessorRuntime(mockBuilder); rpr.process(event3); new Verifications() {{ mockRr1.evaluate(event3); times=0; mockRr2.evaluate(event3); times=0; }}; }
Source:
<code>public DRepresentationNotificationFilter(DRepresentation dRepresentation) { <START> super(); <END> this.dRepresentation = dRepresentation; }</code><technical_language>super() call is implicit. harm, needed</technical_language>

Target:
public DRepresentationNotificationFilter(DRepresentation dRepresentation) { this.dRepresentation = dRepresentation; }
Source:
<code>public void invoke(IN value, Context context) throws Exception { try { <START> bufferedResultsLock.lock(); <END> if (bufferedResults.size() >= maxResultsBuffered) { bufferNotFullCondition.await(); } bufferedResults.add(value); } finally { bufferedResultsLock.unlock(); } }</code><technical_language>put this try</technical_language>

Target:
public void invoke(IN value, Context context) throws Exception { bufferedResultsLock.lock(); try { if (bufferedResults.size() >= maxResultsBuffered) { bufferNotFullCondition.await(); } bufferedResults.add(value); } finally { bufferedResultsLock.unlock(); } }
Source:
<code>public final MetricFunctionInvocation invoke(Set<Argument> arguments, AggregatedField field, String alias) { Set<String> requiredArguments = getArgumentNames(); <START> Map<String, Argument> providedArguments = arguments.stream() <END> .filter(arg -> requiredArguments.contains(arg.getName())) .collect(Collectors.toMap(Argument::getName, Function.identity())); Map<String, Argument> resolvedArguments = requiredArguments.stream() .map(argName -> { if (!providedArguments.containsKey(argName)) { throw new InvalidPredicateException("Argument Not Found " + getName() + "." + argName + "."); } Argument arg = providedArguments.get(argName); List<String> actualNames = getArgumentNameMapper().apply(argName); return actualNames.stream().map(name -> new AbstractMap.SimpleEntry<>(name, arg)); }) .reduce(Stream.empty(), Stream::concat) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); return invoke(resolvedArguments, field, alias); }</code><technical_language>simpler do Set equality provided argument names required argument names. If sets equal - throw exception</technical_language>

Target:
public final MetricFunctionInvocation invoke(Set<Argument> arguments, AggregatedField field, String alias) { Set<String> requiredArguments = getArgumentNames(); Set<String> providedArguments = arguments.stream() .map(Argument::getName) .collect(Collectors.toSet()); if (!requiredArguments.equals(providedArguments)) { throw new InvalidPredicateException( "Provided arguments doesn't match requirement for function " + getName() + "."); } Map<String, Argument> resolvedArguments = arguments.stream() .collect(Collectors.toMap(Argument::getName, Function.identity())); return invoke(resolvedArguments, field, alias); }
Source:
<code>private void initStreamLogDirectory() { try { if (!logDir.toFile().exists()) { Files.createDirectories(logDir); } String corfuDir = logDir.getParent().toString(); FileStore corfuDirBackend = Files.getFileStore(Paths.get(corfuDir)); if (corfuDirBackend.isReadOnly()) { throw new LogUnitException("Cannot start Corfu on a read-only filesystem:" + corfuDir); } <START> if (logSizeLimitPercentage < 0.0 || 100.0 < logSizeLimitPercentage) { <END> String msg = String.format("Invalid quota: quota(%d)% must be between 0-100%", logSizeLimitPercentage); throw new LogUnitException(msg); } logSizeLimit = (long)(corfuDirBackend.getTotalSpace() * logSizeLimitPercentage / 100); File corfuDirFile = new File(corfuDir); if (!corfuDirFile.canWrite()) { throw new LogUnitException("Corfu directory is not writable " + corfuDir); } File logDirectory = new File(logDir.toString()); if (!logDirectory.canWrite()) { throw new LogUnitException("Stream log directory not writable in " + corfuDir); } } catch (IOException ioe) { throw new LogUnitException(ioe); } log.info("initStreamLogDirectory: initialized {}", logDir); }</code><technical_language>need consider precision of double comparison here. Generally speaking, comparing double numbers, epsilon is used. <LINK_0></technical_language>

Target:
private long initStreamLogDirectory() { long fileSystemCapacity; try { if (!logDir.toFile().exists()) { Files.createDirectories(logDir); } String corfuDir = logDir.getParent().toString(); FileStore corfuDirBackend = Files.getFileStore(Paths.get(corfuDir)); if (corfuDirBackend.isReadOnly()) { throw new LogUnitException("Cannot start Corfu on a read-only filesystem:" + corfuDir); } File corfuDirFile = new File(corfuDir); if (!corfuDirFile.canWrite()) { throw new LogUnitException("Corfu directory is not writable " + corfuDir); } File logDirectory = new File(logDir.toString()); if (!logDirectory.canWrite()) { throw new LogUnitException("Stream log directory not writable in " + corfuDir); } fileSystemCapacity = corfuDirBackend.getTotalSpace(); } catch (IOException ioe) { throw new LogUnitException(ioe); } log.info("initStreamLogDirectory: initialized {}", logDir); return fileSystemCapacity; }
Source:
<code>private double[] getElevationRange(TargetDesc target) { double elMin = target.getElMin(); double elMax = target.getElMax(); Double startAlt = null; Double endAlt = null; switch(target.getElType()) { case AIRMASS: startAlt = ImprovedSkyCalcMethods.getAltitude(elMax); endAlt = ImprovedSkyCalcMethods.getAltitude(elMin); break; case HOUR_ANGLE: <START> final Option<WorldCoords> coords = target.getCoordinates(None.instance()); <END> if (coords.isDefined()) { double dec = coords.getValue().getDecDeg(); double lat = _site.latitude; startAlt = ImprovedSkyCalcMethods.altit(dec, elMin, lat); endAlt = ImprovedSkyCalcMethods.altit(dec, elMax, lat); } break; case NONE: startAlt = 0.0; endAlt = 0.0; } return new double[]{startAlt, endAlt}; }</code><technical_language>reading time scheduling block here</technical_language>

Target:
private double[] getElevationRange(TargetDesc target) { double elMin = target.getElMin(); double elMax = target.getElMax(); Double startAlt = null; Double endAlt = null; switch(target.getElType()) { case AIRMASS: startAlt = ImprovedSkyCalcMethods.getAltitude(elMax); endAlt = ImprovedSkyCalcMethods.getAltitude(elMin); break; case HOUR_ANGLE: startAlt = altit(target, _startDate, elMin, _site.latitude).getOrElse(startAlt); endAlt = altit(target, _endDate, elMax, _site.latitude).getOrElse(endAlt); break; case NONE: startAlt = 0.0; endAlt = 0.0; } return new double[]{startAlt, endAlt}; }
Source:
<code>static KeyspaceMetadata ensureExists(String keyspace, Session session) { KeyspaceMetadata result = session.getCluster().getMetadata().getKeyspace(keyspace); if (result == null || result.getTable("traces") == null) { LOG.info("Installing schema {}", SCHEMA_RESOURCE); applyCqlFile(keyspace, session, SCHEMA_RESOURCE); try { LOG.info("Installing index {}", INDEX_RESOURCE); applyCqlFile(keyspace, session, INDEX_RESOURCE); <START> } catch (InvalidConfigurationInQueryException e) { <END> if (e.getMessage().contains("org.apache.cassandra.index.sasi.SASIIndex")) { LOG.warn("Please upgrade to Cassandra 3.8+ in order to use SASIIndex {}", INDEX_RESOURCE); LOG.info("Installing index {}", INDEX_RESOURCE_3_0); } else { throw e; } } result = session.getCluster().getMetadata().getKeyspace(keyspace); } return result; }</code><technical_language>fallback SASI duration (when due version). indexes in a separate file, able more easily maintain manually created indexes of implementation</technical_language>

Target:
static KeyspaceMetadata ensureExists(String keyspace, Session session) { KeyspaceMetadata result = session.getCluster().getMetadata().getKeyspace(keyspace); if (result == null || result.getTable("traces") == null) { LOG.info("Installing schema {}", SCHEMA_RESOURCE); applyCqlFile(keyspace, session, SCHEMA_RESOURCE); result = session.getCluster().getMetadata().getKeyspace(keyspace); } return result; }
Source:
<code>public void testWrongPortConnection() throws Exception { BlockingChannel channel = new SSLBlockingChannel(hostName, sslPort + 1, new MetricRegistry(), 10000, 10000, 10000, 2000, sslSocketFactory, clientSSLConfig); try { channel.connect(); fail("should have thrown!"); } catch (IOException e) { <START> assertTrue(e.getMessage().contains("Connection refused")); <END> } }</code><technical_language>a bad idea checking for exception messages in place</technical_language>

Target:
public void testWrongPortConnection() throws Exception { BlockingChannel channel = new SSLBlockingChannel(hostName, sslPort + 1, new MetricRegistry(), 10000, 10000, 10000, 2000, sslSocketFactory, clientSSLConfig); try { channel.connect(); fail("should have thrown!"); } catch (IOException e) { } }
Source:
<code>private List<String> getPossibleGivers(FeedbackQuestionAttributes fqa, StudentAttributes studentRecipient) { FeedbackParticipantType giverType = fqa.giverType; FeedbackParticipantType recipientType = fqa.recipientType; List<String> possibleGivers = new ArrayList<String>(); switch (giverType) { case STUDENTS: possibleGivers = getSortedListOfStudentEmails(); break; case INSTRUCTORS: possibleGivers = getSortedListOfInstructorEmails(); break; case TEAMS: possibleGivers = getSortedListOfTeams(); break; case SELF: possibleGivers.add(fqa.creatorEmail); break; case CUSTOM: possibleGivers = fqa.getGiversFromFeedbackPathsForStudentRecipient(studentRecipient); break; default: log.severe("Invalid giver type specified"); break; } switch (recipientType) { case STUDENTS: case TEAMS: break; case SELF: possibleGivers = new ArrayList<String>(); possibleGivers.add(studentRecipient.email); break; case OWN_TEAM_MEMBERS: possibleGivers.retainAll(getSortedListOfTeamMembersEmailsExcludingSelf(studentRecipient)); break; case OWN_TEAM_MEMBERS_INCLUDING_SELF: possibleGivers.retainAll(getSortedListOfTeamMembersEmails(studentRecipient)); break; default: break; } return possibleGivers; <START> } <END></code><technical_language>shift methods (related finding givers/recipients) a new class</technical_language>

Target:
private List<String> getPossibleGivers(FeedbackQuestionAttributes fqa, StudentAttributes studentRecipient) { FeedbackParticipantType giverType = fqa.giverType; FeedbackParticipantType recipientType = fqa.recipientType; List<String> possibleGivers = new ArrayList<String>(); switch (giverType) { case STUDENTS: possibleGivers = getSortedListOfStudentEmails(); break; case INSTRUCTORS: possibleGivers = getSortedListOfInstructorEmails(); break; case TEAMS: possibleGivers = getSortedListOfTeams(); break; case SELF: possibleGivers.add(fqa.creatorEmail); break; case CUSTOM: possibleGivers = fqa.getGiversFromFeedbackPathsForStudentRecipient(studentRecipient.getEmail()); break; default: log.severe("Invalid giver type specified"); break; } switch (recipientType) { case STUDENTS: case TEAMS: break; case SELF: possibleGivers = new ArrayList<String>(); possibleGivers.add(studentRecipient.email); break; case OWN_TEAM_MEMBERS: possibleGivers.retainAll(getSortedListOfTeamMembersEmailsExcludingSelf(studentRecipient)); break; case OWN_TEAM_MEMBERS_INCLUDING_SELF: possibleGivers.retainAll(getSortedListOfTeamMembersEmails(studentRecipient)); break; default: break; } return possibleGivers; }
Source:
<code>public IProject[] getProjects() { Set<IProject> result= new HashSet<>(); for (IPackageFragment <START> fFragment : <END> fFragments) { result.add(fFragment.getJavaProject().getProject()); } return result.toArray(new IProject[result.size()]); }</code><technical_language>rename fragment</technical_language>

Target:
public IProject[] getProjects() { Set<IProject> result= new HashSet<>(); for (IPackageFragment fragment : fFragments) { result.add(fragment.getJavaProject().getProject()); } return result.toArray(new IProject[result.size()]); }
Source:
<code>protected String getVirtioIsoPath() { String virtioIsoName = getParameters().getVirtioIsoName(); if (virtioIsoName != null) { List<DiskImage> diskImageList; if (vmInfoBuildUtils.isValidUUID(virtioIsoName) && (diskImageList = diskImageDao.getDiskImageByDiskId(Guid.createGuidFromString(virtioIsoName))) != null && diskImageList.size() > 0 && diskImageList.get(0).getContentType() == DiskContentType.ISO) { resourceManager.setDiskList(diskImageList); DiskImage diskImage = diskImageList.get(0); if (diskImage.getStorageTypes().get(0).isBlockDomain()) { <START> resourceManager.setPrepareImageReturn(prepareImage(diskImage)); <END> } return vmInfoBuildUtils.getPathToImage(diskImage); } else { return new File(getIsoPrefix(getStoragePoolId(), getVdsId()), virtioIsoName).getPath(); } } return null; }</code><technical_language>ResourceManager is a singleton, storing a command specific state in a race condition. state visible multiple instances of this command time. state stored in command parameters. serialized DB, data of async methods is called, endWithFailure() endSuccessfully()</technical_language>

Target:
protected String getVirtioIsoPath() { String virtioIsoName = getParameters().getVirtioIsoName(); if (virtioIsoName != null) { List<DiskImage> diskImageList; if (vmInfoBuildUtils.isValidUUID(virtioIsoName) && (diskImageList = diskImageDao.getDiskImageByDiskId(Guid.createGuidFromString(virtioIsoName))) != null && diskImageList.size() > 0 && diskImageList.get(0).getContentType() == DiskContentType.ISO) { getParameters().setDiskList(diskImageList); DiskImage diskImage = diskImageList.get(0); if (diskImage.getStorageTypes().get(0).isBlockDomain()) { PrepareImageReturn prepareImageReturn = prepareImage(diskImage); getParameters().setPrepareImageReturn(prepareImageReturn != null && prepareImageReturn.getStatus().message.equals("Done")); } return vmInfoBuildUtils.getPathToImage(diskImage); } else { return new File(getIsoPrefix(getStoragePoolId(), getVdsId()), virtioIsoName).getPath(); } } return null; }
Source:
<code>private void validateInstanceGroups(List<InstanceGroupV4Request> instanceGroups) { assertNotNull(instanceGroups); assertEquals("The result instance group list has " + instanceGroups.size() + " items instead of 2", 2, instanceGroups.size()); <START> assertTrue(instanceGroups.stream().anyMatch(ig -> ig.getName().equals(MASTER_INSTANCE_GROUP) || ig.getName().equals(IDBROKER_INSTANCE_GROUP))); <END> }</code><technical_language>I test MASTER IDBROKER instance groups time</technical_language>

Target:
private void validateInstanceGroups(List<InstanceGroupV4Request> instanceGroups) { assertNotNull(instanceGroups); assertEquals("The result instance group list has " + instanceGroups.size() + " items instead of 2", 2, instanceGroups.size()); Set<String> groups = instanceGroups.stream() .map(InstanceGroupV4Request::getName) .collect(Collectors.toSet()); assertTrue(groups.contains(MASTER_INSTANCE_GROUP) && groups.contains(IDBROKER_INSTANCE_GROUP)); }
Source:
<code>protected GenericRecord readEntity() throws IOException { <START> return readRecord(); <END> }</code><technical_language>another level method redirection if else is in it</technical_language>

Target:
protected GenericRecord readEntity() throws IOException { GenericRecord record = null; record = null; try { if (avroDataStream != null && avroDataStream.hasNext()) { offset++; record = avroDataStream.next(); recordCount++; return record; } } catch (AvroRuntimeException are) { LOG.error("Exception in parsing record for file - " + super.currentFile + " at offset - " + offset, are); if (errorRecordsPort.isConnected()) { errorRecordsPort.emit("FileName:" + super.currentFile + ", Offset:" + offset); } errorCount++; throw new AvroRuntimeException(are); } return record; }
Source:
<code>private String handleResponse( double latitude, double longitude, JsonObject json, ReverseGeocoderCallback callback) { Address address = parseAddress(json); if (address != null) { String formattedAddress = addressFormat.format(address); if (cache != null) { cache.put(new AbstractMap.SimpleImmutableEntry<>(latitude, longitude), formattedAddress); } if (callback != null) { callback.onSuccess(formattedAddress); } return formattedAddress; } else { if (callback != null) { <START> callback.onFailure(new GeocoderException("Empty address. " + json.getString("error_message"))); <END> } else { LOGGER.warn("Empty address"); } } return null; }</code><technical_language>I this is correct. geocoder key</technical_language>

Target:
private String handleResponse( double latitude, double longitude, JsonObject json, ReverseGeocoderCallback callback) { Address address = parseAddress(json); if (address != null) { String formattedAddress = addressFormat.format(address); if (cache != null) { cache.put(new AbstractMap.SimpleImmutableEntry<>(latitude, longitude), formattedAddress); } if (callback != null) { callback.onSuccess(formattedAddress); } return formattedAddress; } else { String msg = "Empty address. Error: " + parseError(json); if (callback != null) { callback.onFailure(new GeocoderException(msg)); } else { LOGGER.warn(msg); } } return null; }
Source:
<code>public ClusteringServiceConfiguration(URI clusterUri, Timeouts timeouts, boolean autoCreate, ServerSideConfiguration serverConfig, Properties properties) { this.clusterUri = Objects.requireNonNull(clusterUri, "Cluster URI cannot be null"); this.autoCreate = autoCreate; this.serverConfiguration = serverConfig; this.timeouts = Objects.requireNonNull(timeouts, "Operation timeouts cannot be null"); <START> this.properties = cloneProperties(Objects.requireNonNull(properties, "Properties cannot be null")); <END> }</code><technical_language>do (Properties) Objects.requireNonNull(properties, "Properties null").clone(); done it</technical_language>

Target:
public ClusteringServiceConfiguration(URI clusterUri, Timeouts timeouts, boolean autoCreate, ServerSideConfiguration serverConfig, Properties properties) { this.clusterUri = Objects.requireNonNull(clusterUri, "Cluster URI cannot be null"); this.autoCreate = autoCreate; this.serverConfiguration = serverConfig; this.timeouts = Objects.requireNonNull(timeouts, "Operation timeouts cannot be null"); this.properties = (Properties) Objects.requireNonNull(properties, "Properties cannot be null").clone(); }
Source:
<code>protected PipelineTemplateConfig findAddedTemplate(CruiseConfig cruiseConfig) { if (templateConfig == null || templateConfig.name() == null) { result.unprocessableEntity(LocalizedMessage.string("TEMPLATE_INVALID")); throw new NullPointerException("Template name cannot be null."); } else { PipelineTemplateConfig pipelineTemplateConfig = cruiseConfig.findTemplate(templateConfig.name()); if (pipelineTemplateConfig == null) { result.notFound(LocalizedMessage.string("RESOURCE_NOT_FOUND"), HealthStateType.notFound()); <START> throw new NullPointerException(String.format("The template with name '%s' is not found.", templateConfig.name())); <END> } return pipelineTemplateConfig; } }</code><technical_language>throw a specific exception throw new NoSuchTemplateException(templateName); do for invalid agent <LINK_0></technical_language>

Target:
protected PipelineTemplateConfig findAddedTemplate(CruiseConfig cruiseConfig) { if (templateConfig == null || templateConfig.name() == null || templateConfig.name().isBlank()) { result.unprocessableEntity(LocalizedMessage.string("TEMPLATE_NAME_CANNOT_BE_NULL")); throw new IllegalArgumentException("Template name cannot be null."); } else { PipelineTemplateConfig pipelineTemplateConfig = cruiseConfig.findTemplate(templateConfig.name()); if (pipelineTemplateConfig == null) { result.notFound(LocalizedMessage.string("RESOURCE_NOT_FOUND"), HealthStateType.notFound()); throw new NoSuchTemplateException(templateConfig.name()); } return pipelineTemplateConfig; } }
Source:
<code>public void enter() { if (mMostRecentState == BluetoothProfile.STATE_CONNECTING) { onConnectionStateChanged(BluetoothProfile.STATE_CONNECTED); BluetoothMediaBrowserService.addressedPlayerChanged(mSessionCallbacks); } else { <START> Log.d(STATE_TAG, <END> "ReEnteringConnecting"); } super.enter(); }</code><technical_language>logD? for else</technical_language>

Target:
public void enter() { if (mMostRecentState == BluetoothProfile.STATE_CONNECTING) { broadcastConnectionStateChanged(BluetoothProfile.STATE_CONNECTED); BluetoothMediaBrowserService.addressedPlayerChanged(mSessionCallbacks); } else { logD(STATE_TAG, "ReEnteringConnected"); } super.enter(); }
Source:
<code>public Login() { message = new Span(); message.setVisible(false); login = new TextField("Login"); password = new PasswordField("Password"); Button submit = new Button("Submit", this::handeLogin); VerticalLayout usage = new VerticalLayout(); usage.add(new Span("Login with user [admin|user] with any password.")); usage.add(new Span("- admin will always navigate to root url")); usage.add(new Span("- user will reload and navigate to set url")); <START> add(message, login, password, submit, usage); <END> if (ApplicationRouteRegistry .getInstance(VaadinServlet.getCurrent().getServletContext()) .getNavigationTarget("global").isPresent()) { add(new RouterLink("global", GlobalView.class)); } }</code><technical_language>![MAJOR](<LINK_0> 'Severity: MAJOR') Remove this call a constructor overridable "add" method. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
public Login() { message = new Span(); message.setVisible(false); login = new TextField("Login"); login.setId("login-field"); password = new PasswordField("Password"); password.setId("password-field"); Button submit = new Button("Submit", this::handeLogin); submit.setId("submit"); VerticalLayout usage = new VerticalLayout(); usage.add(new Span("Login with user [admin|user] with any password.")); usage.add(new Span("- admin will always navigate to root url")); usage.add(new Span("- user will reload and navigate to set url")); add(message, login, password, submit, usage); if (RouteConfiguration.forApplicationScope() .isRouteRegistered(GlobalView.class)) { RouterLink global = new RouterLink("global", GlobalView.class); global.setId("global-link"); add(global); } }
Source:
<code>private <T, R> R calculateConfirmedVolume(GlusterVolumeEntity volume, Function<BrickProperties, T> field, Function<List<Stream<T>>, R> reduce) { List<BrickProperties> bricks = volume.getBricks().stream() .map(GlusterBrickEntity::getId) .map(b -> brickDao.getById(b)) .filter(Objects::nonNull) .map(GlusterBrickEntity::getBrickProperties) .collect(Collectors.toList()); if (bricks.stream().map(field).anyMatch(Objects::isNull)) { log.info("Volume have non-thin bricks, skipping confirmed free size calculation", volume.getName()); return null; } List<Stream<T>> replicaSets = new ArrayList<>(); switch (volume.getVolumeType()) { case REPLICATE: case DISTRIBUTED_REPLICATE: int replicaSize = bricks.size()/volume.getReplicaCount(); <START> while (!bricks.isEmpty()) { <END> int replicaCounter = 0; List<BrickProperties> set = new ArrayList<>(); while(replicaCounter < replicaSize) { set.add(bricks.get(0)); replicaCounter++; } replicaSets.add(set.stream().map(field)); } break; default: replicaSets = Collections.singletonList(bricks.stream().map(field)); break; } return reduce.apply(replicaSets); }</code><technical_language>for (int i=0; i< bricks.size() ; i=i+volume.getReplicaCount()) { List<BrickProperties> set = new ArrayList<>(); int replicaCounter = 0; while (replicaCounter <volume.getReplicaCount()) { if (!brick.isArbiter) { set.add(bricks.get(i+replicaCounter)) } replicaCounter++; } replicaSets.add(set.stream().map(field)); }</technical_language>

Target:
private <T, R> R calculateConfirmedVolume(GlusterVolumeEntity volume, Function<BrickProperties, T> field, Function<List<Stream<T>>, R> reduce) { List<BrickProperties> bricks = volume.getBricks().stream() .map(GlusterBrickEntity::getId) .map(b -> brickDao.getById(b)) .filter(Objects::nonNull) .map(GlusterBrickEntity::getBrickProperties) .collect(Collectors.toList()); if (bricks.stream().map(field).anyMatch(Objects::isNull)) { log.info("Volume have non-thin bricks, skipping confirmed free size calculation", volume.getName()); return null; } List<Stream<T>> replicaSets = new ArrayList<>(); switch (volume.getVolumeType()) { case REPLICATE: case DISTRIBUTED_REPLICATE: int replicaSize = bricks.size()/volume.getReplicaCount(); while (!bricks.isEmpty()) { int replicaCounter = 0; List<BrickProperties> set = new ArrayList<>(); while(replicaCounter < replicaSize) { set.add(bricks.get(0)); bricks.remove(0); replicaCounter++; } replicaSets.add(set.stream().map(field)); } break; default: replicaSets = Collections.singletonList(bricks.stream().map(field)); break; } return reduce.apply(replicaSets); }
Source:
<code>protected boolean isValidConnection(StorageServerConnections conn) { StorageType storageType = conn.getStorageType(); if (storageType == StorageType.NFS && !new NfsMountPointConstraint().isValid(conn.getConnection(), null)) { return failValidation(EngineMessage.VALIDATION_STORAGE_CONNECTION_INVALID); } if (storageType == StorageType.POSIXFS && StringUtils.isEmpty(conn.getVfsType())) { return failValidation(EngineMessage.VALIDATION_STORAGE_CONNECTION_EMPTY_VFSTYPE); } if ((storageType == StorageType.POSIXFS || storageType == StorageType.NFS) && !validate(validateMountOptions())) { return false; } if (storageType == StorageType.ISCSI) { if (StringUtils.isEmpty(conn.getIqn())) { return failValidation(EngineMessage.VALIDATION_STORAGE_CONNECTION_EMPTY_IQN); } if (!isValidStorageConnectionPort(conn.getPort())) { return failValidation(EngineMessage.VALIDATION_STORAGE_CONNECTION_INVALID_PORT); } } if (storageType == StorageType.GLUSTERFS) { StorageConnectionValidator validator = new StorageConnectionValidator(conn); if (!validate(validateVolumeIdAndUpdatePath(conn)) <START> && !validate(validator.canVDSConnectToGlusterfs(getVds()))) { <END> return false; } } if (checkIsConnectionFieldEmpty(conn)) { return false; } return true; }</code><technical_language>||</technical_language>

Target:
protected boolean isValidConnection(StorageServerConnections conn) { StorageType storageType = conn.getStorageType(); if (storageType == StorageType.NFS && !new NfsMountPointConstraint().isValid(conn.getConnection(), null)) { return failValidation(EngineMessage.VALIDATION_STORAGE_CONNECTION_INVALID); } if (storageType == StorageType.POSIXFS && StringUtils.isEmpty(conn.getVfsType())) { return failValidation(EngineMessage.VALIDATION_STORAGE_CONNECTION_EMPTY_VFSTYPE); } if ((storageType == StorageType.POSIXFS || storageType == StorageType.NFS) && !validate(validateMountOptions())) { return false; } if (storageType == StorageType.ISCSI) { if (StringUtils.isEmpty(conn.getIqn())) { return failValidation(EngineMessage.VALIDATION_STORAGE_CONNECTION_EMPTY_IQN); } if (!isValidStorageConnectionPort(conn.getPort())) { return failValidation(EngineMessage.VALIDATION_STORAGE_CONNECTION_INVALID_PORT); } } if (storageType == StorageType.GLUSTERFS) { StorageConnectionValidator validator = new StorageConnectionValidator(conn); if (!validate(validateVolumeIdAndUpdatePath(conn)) || !validate(validator.canVDSConnectToGlusterfs(getVds()))) { return false; } } if (checkIsConnectionFieldEmpty(conn)) { return false; } return true; }
Source:
<code>protected void bindParameters() throws StandardException { if (leftOperand.requiresTypeFromContext()) { if (rightOperand.requiresTypeFromContext()) { DataTypeDescriptor dtd = DataTypeDescriptor.getBuiltInDataTypeDescriptor(Types.VARCHAR, false, 254); leftOperand.setType(dtd); rightOperand.setType(dtd); return; } else { leftOperand.setType(rightOperand.getTypeServices()); } } <START> if (rightOperand.requiresTypeFromContext()) { <END> rightOperand.setType(leftOperand.getTypeServices()); } }</code><technical_language>Change this 'else if'</technical_language>

Target:
protected void bindParameters() throws StandardException { if (leftOperand.requiresTypeFromContext()) { if (rightOperand.requiresTypeFromContext()) { DataTypeDescriptor dtd = DataTypeDescriptor.getBuiltInDataTypeDescriptor(Types.VARCHAR, false, 254); leftOperand.setType(dtd); rightOperand.setType(dtd); } else { leftOperand.setType(rightOperand.getTypeServices()); } } else if (rightOperand.requiresTypeFromContext()) { rightOperand.setType(leftOperand.getTypeServices()); } }
Source:
<code>private KItem(Term kLabel, Term kList, TermContext termContext, Tool tool, Source source, Location location) { super(Kind.KITEM, source, location); this.kLabel = kLabel; this.kList = kList; Definition definition = termContext.definition(); if (kLabel instanceof KLabelConstant && kList instanceof KList && !((KList) kList).hasFrame()) { KLabelConstant kLabelConstant = (KLabelConstant) kLabel; CacheTableColKey cacheTabColKey = null; CacheTableValue cacheTabVal = null; enableCache = (tool != Tool.KOMPILE) && definition.sortPredicateRulesOn(kLabelConstant).isEmpty(); if (enableCache) { cacheTabColKey = new CacheTableColKey(kLabelConstant, (KList) kList); <START> synchronized(definition.getSortCacheTable()) { <END> cacheTabVal = definition.getSortCacheTable().get(cacheTabColKey); } if (cacheTabVal != null) { sort = cacheTabVal.sort; isExactSort = cacheTabVal.isExactSort; possibleSorts = cacheTabVal.possibleSorts; this.termContext = null; return; } } sort = null; isExactSort = false; possibleSorts = null; this.termContext = termContext; } else { if (kLabel instanceof KLabelInjection) { assert kList.equals(KList.EMPTY); isExactSort = true; } else { isExactSort = false; } sort = kind.asSort(); possibleSorts = Collections.singleton(sort); this.termContext = null; enableCache = false; } }</code><technical_language>Is reason need expose sortCacheTable in Definition a getter? If not, providing methods put/get key/value of cache table do synchronization methods</technical_language>

Target:
private KItem(Term kLabel, Term kList, TermContext termContext, Tool tool, Source source, Location location) { super(Kind.KITEM, source, location); this.kLabel = kLabel; this.kList = kList; Definition definition = termContext.definition(); if (kLabel instanceof KLabelConstant && kList instanceof KList && !((KList) kList).hasFrame()) { KLabelConstant kLabelConstant = (KLabelConstant) kLabel; CacheTableColKey cacheTabColKey = null; CacheTableValue cacheTabVal = null; enableCache = (tool != Tool.KOMPILE) && definition.sortPredicateRulesOn(kLabelConstant).isEmpty(); if (enableCache) { cacheTabColKey = new CacheTableColKey(kLabelConstant, (KList) kList); cacheTabVal = definition.getSortCacheValue(cacheTabColKey); if (cacheTabVal != null) { sort = cacheTabVal.sort; isExactSort = cacheTabVal.isExactSort; possibleSorts = cacheTabVal.possibleSorts; this.termContext = null; return; } } sort = null; isExactSort = false; possibleSorts = null; this.termContext = termContext; } else { if (kLabel instanceof KLabelInjection) { assert kList.equals(KList.EMPTY); isExactSort = true; } else { isExactSort = false; } sort = kind.asSort(); possibleSorts = Collections.singleton(sort); this.termContext = null; enableCache = false; } }
Source:
<code>public void close() { if (details == null) { return; } FunctionResult result = new FunctionResult(); stopWatch(details, result); details = null; if (result.isFailed()) { <START> throw new NativeException("Failed to stop watch. Reason: " + result.getMessage()); <END> } }</code><technical_language>suggestion throw new NativeException("Failed stop watching. Reason: " + result.getMessage());</technical_language>

Target:
public void close() { if (details == null) { return; } FunctionResult result = new FunctionResult(); stopWatching(details, result); details = null; if (result.isFailed()) { throw new NativeException("Failed to stop watching. Reason: " + result.getMessage()); } }
Source:
<code>public List<Metric> transform(List<Metric> metrics, List<String> constants) { SystemAssert.requireArgument(metrics != null, "Cannot transform null metric/metrics"); SystemAssert.requireState(metrics.size() == 1, "Anomaly Detection Transform can only be used on one metric."); SystemAssert.requireState(metrics.get(0) != null, "Anomaly Detection Transform cannot be used with a null " + "metric."); SystemAssert.requireState(constants.size() == 1, "Anomaly Detection RPCA Transform can only be used with " + "one constant for the length of a season"); <START> <END> Map<Long, String> completeDatapoints = metrics.get(0).getDatapoints(); timestamps = completeDatapoints.keySet().toArray(new Long[completeDatapoints.size()]); Arrays.sort(timestamps); long seasonLengthInMilliseconds = getTimePeriodInSeconds(constants.get(0)) * 1000; frequency = getFrequency(seasonLengthInMilliseconds); metricValues = new double[completeDatapoints.size()]; for (int i = 0; i < metricValues.length; i++) { String value = completeDatapoints.get(timestamps[i]); metricValues[i] = Double.parseDouble(value); } standardize(metricValues); trainModel(); Metric predictions = predictAnomalies(); Metric predictionsNormalized = normalizePredictions(predictions); List<Metric> resultMetrics = new ArrayList<>(); resultMetrics.add(predictionsNormalized); return resultMetrics; }</code><technical_language>combine 3 asserts above? I a compelling reason of asserts runtime? Do asserts semantics asserts in test frameworks? In case want halt execution instead do exception handling</technical_language>

Target:
public List<Metric> transform(List<Metric> metrics, List<String> constants) { SystemAssert.requireArgument(metrics != null, "Cannot transform null metric/metrics"); SystemAssert.requireState(metrics.size() == 1, "Anomaly Detection Transform can only be used on one metric."); SystemAssert.requireState(metrics.get(0) != null, "Anomaly Detection Transform cannot be used with a null " + "metric."); SystemAssert.requireState(constants.size() == 1, "Anomaly Detection RPCA Transform can only be used with " + "one constant for the length of a season"); Map<Long, String> completeDatapoints = metrics.get(0).getDatapoints(); SystemAssert.requireState(completeDatapoints.size() != 0, "Cannot transform metric with no data points."); timestamps = completeDatapoints.keySet().toArray(new Long[completeDatapoints.size()]); Arrays.sort(timestamps); String seasonLengthInput = constants.get(0); long seasonLengthInMilliseconds = super.getTimePeriodInSeconds(seasonLengthInput) * 1000; frequency = calculateFrequency(seasonLengthInMilliseconds); metricValues = new double[completeDatapoints.size()]; for (int i = 0; i < metricValues.length; i++) { String value = completeDatapoints.get(timestamps[i]); metricValues[i] = Double.parseDouble(value); } standardize(metricValues); trainModel(); Metric predictions = predictAnomalies(); Metric predictionsNormalized = normalizePredictions(predictions); List<Metric> resultMetrics = new ArrayList<>(); resultMetrics.add(predictionsNormalized); return resultMetrics; }
Source:
<code>protected void doRun(IProgressMonitor monitor) throws CoreException { SubMonitor progress = SubMonitor.convert(monitor, MakeUIPlugin.getResourceString("WizardMakeProjectConversion.monitor.convertingToMakeProject"), 1); try { super.doRun(progress.split(1)); } finally { <START> progress.worked(1); <END> } }</code><technical_language>I get this. If progress tick, this consumes now. anyway, if operation monitor, simply pass though: super.doRun(progress);</technical_language>

Target:
protected void doRun(IProgressMonitor monitor) throws CoreException { super.doRun(SubMonitor.convert(monitor, MakeUIPlugin.getResourceString("WizardMakeProjectConversion.monitor.convertingToMakeProject"), 1)); }
Source:
<code>private String getFileExt(String name) { int i = name.lastIndexOf('.'); <START> if (i < 0 || i > name.length() - 1) { <END> return null; } return name.substring(i + 1); }</code><technical_language>This i == -1</technical_language>

Target:
private String getFileExt(String name) { int i = name.lastIndexOf('.'); if (i < 0 || i + 1 == name.length()) { return null; } return name.substring(i + 1); }
Source:
<code>private Response copy(Action action) { GlusterHookManageParameters params = new GlusterHookManageParameters(guid); <START> if (action.getHost() != null) { <END> validateParameters(action.getHost(),"host.id|name"); Guid hostId = getHostId(action); if (hostId == null) { return handleError(new EntityNotFoundException(action.getHost().getId() != null ? id : action.getHost().getName()), false); } params.setSourceServerId(hostId); } return doAction(VdcActionType.UpdateGlusterHook, params, action); }</code><technical_language>action.isSetHost()</technical_language>

Target:
private Response copy(Action action) { GlusterHookManageParameters params = new GlusterHookManageParameters(guid); if (action.isSetHost()) { validateParameters(action.getHost(),"host.id|name"); Guid hostId = getHostId(action); params.setSourceServerId(hostId); } return doAction(VdcActionType.UpdateGlusterHook, params, action); }