auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void executeVmCommand() { ArrayList<String> errorMessages = new ArrayList<String>(); if (canAddVm(errorMessages, destStorages.values())) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { addVmStatic(); addVmDynamic(); addVmNetwork(); addVmStatistics(); addActiveSnapshot(); addVmPermission(); addVmWatchdog(); getCompensationContext().stateChanged(); return null; } }); if (addVmImages()) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { copyVmDevices(); addDiskPermissions(newDiskImages); addVmPayload(); updateSmartCardDevices(); setActionReturnValue(getVm().getId()); setSucceeded(true); return null; } }); } } else { log.errorFormat("Failed to add vm . The reasons are: {0}", StringUtils.join(errorMessages, ',')); } }

Target:
protected void executeVmCommand() { ArrayList<String> errorMessages = new ArrayList<String>(); if (canAddVm(errorMessages, destStorages.values())) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { addVmStatic(); addVmDynamic(); addVmNetwork(); addVmStatistics(); addActiveSnapshot(); addVmPermission(); getCompensationContext().stateChanged(); return null; } }); if (addVmImages()) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { copyVmDevices(); addDiskPermissions(newDiskImages); addVmPayload(); updateSmartCardDevices(); addVmWatchdog(); setActionReturnValue(getVm().getId()); setSucceeded(true); return null; } }); } } else { log.errorFormat("Failed to add vm . The reasons are: {0}", StringUtils.join(errorMessages, ',')); } }
Source:
private URL getResourceUrl(ServletContext context, String path) throws MalformedURLException { URL logo = context.getResource(path); if (logo == null) { String cpPath = path.startsWith("/") ? META_INF_RESOURCES + path : META_INF_RESOURCES + "/" + path; logo = PwaRegistry.class.getResource(cpPath); } return logo; }

Target:
private URL getResourceUrl(ServletContext context, String path) throws MalformedURLException { URL resourceUrl = context.getResource(path); if (resourceUrl == null) { String cpPath = path.startsWith("/") ? META_INF_RESOURCES + path : META_INF_RESOURCES + "/" + path; resourceUrl = PwaRegistry.class.getResource(cpPath); } return resourceUrl; }
Source:
public List<URI> getVxLanPorts() { if (vxLanPortIds == null) { return null; } List<URI> uris = new ArrayList<>(vxLanPortIds.size()); for (UUID id : vxLanPortIds) { uris.add(absoluteUri(PORTS, id)); } return uris; }

Target:
public List<URI> getVxLanPorts() { return absoluteUris(PORTS, vxLanPortIds); }
Source:
protected FactModelTree getSimpleClassFactModelTree(Class clazz) { String key = clazz.getSimpleName(); Map<String, String> simpleProperties = new HashMap<>(); String fullName = clazz.getCanonicalName(); simpleProperties.put("value", fullName); String packageName = fullName.substring(0, fullName.lastIndexOf(".")); return new FactModelTree(key, packageName, simpleProperties); }

Target:
protected static FactModelTree getSimpleClassFactModelTree(Class clazz) { String key = clazz.getSimpleName(); Map<String, String> simpleProperties = new HashMap<>(); String fullName = clazz.getCanonicalName(); simpleProperties.put("value", fullName); String packageName = fullName.substring(0, fullName.lastIndexOf(".")); return new FactModelTree(key, packageName, simpleProperties); }
Source:
public void start(ComponentContext context) { super.start(context); if (provider != null) { provider.close(); } List<PubSubProviderDescriptor> descs = getDescriptors(XP_CONFIG); PubSubProviderDescriptor providerDescriptor = descs.isEmpty() ? null : descs.get(descs.size() - 1); if (providerDescriptor == null) { provider = new MemPubSubProvider(); options = Collections.emptyMap(); } else { Class<? extends PubSubProvider> klass = providerDescriptor.klass; if (!PubSubProvider.class.isAssignableFrom(klass)) { throw new RuntimeException("Class does not implement PubSubServiceProvider: " + klass.getName()); } try { provider = klass.getDeclaredConstructor().newInstance(); options = providerDescriptor.options; } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } } if (provider != null) { provider.initialize(options, subscribers); } }

Target:
public void start(ComponentContext context) { super.start(context); if (provider != null) { provider.close(); } List<PubSubProviderDescriptor> descs = getDescriptors(XP_CONFIG); PubSubProviderDescriptor providerDescriptor = descs.isEmpty() ? null : descs.get(descs.size() - 1); if (providerDescriptor == null) { provider = new MemPubSubProvider(); options = Collections.emptyMap(); } else { Class<? extends PubSubProvider> klass = providerDescriptor.klass; if (!PubSubProvider.class.isAssignableFrom(klass)) { throw new RuntimeException("Class does not implement PubSubServiceProvider: " + klass.getName()); } try { provider = klass.getDeclaredConstructor().newInstance(); options = providerDescriptor.options; } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } } provider.initialize(options, subscribers); }
Source:
public RoutingRequest clone() { try { RoutingRequest clone = (RoutingRequest) super.clone(); clone.bannedRoutes = bannedRoutes.clone(); clone.bannedTrips = (HashMap<AgencyAndId, BannedStopSet>) bannedTrips.clone(); clone.bannedStops = bannedStops.clone(); clone.bannedStopsHard = bannedStopsHard.clone(); clone.whiteListedAgencies = (HashSet<String>) whiteListedAgencies.clone(); clone.whiteListedRoutes = whiteListedRoutes.clone(); clone.preferredAgencies = (HashSet<String>) preferredAgencies.clone(); clone.preferredRoutes = preferredRoutes.clone(); if (this.bikeWalkingOptions != this) clone.bikeWalkingOptions = this.bikeWalkingOptions.clone(); else clone.bikeWalkingOptions = clone; return clone; } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } }

Target:
public RoutingRequest clone() { try { RoutingRequest clone = (RoutingRequest) super.clone(); clone.bannedRoutes = bannedRoutes.clone(); clone.bannedTrips = (HashMap<FeedScopedId, BannedStopSet>) bannedTrips.clone(); clone.bannedStops = bannedStops.clone(); clone.bannedStopsHard = bannedStopsHard.clone(); clone.whiteListedAgencies = (HashSet<String>) whiteListedAgencies.clone(); clone.whiteListedRoutes = whiteListedRoutes.clone(); clone.preferredAgencies = (HashSet<String>) preferredAgencies.clone(); clone.preferredRoutes = preferredRoutes.clone(); if (this.bikeWalkingOptions != this) clone.bikeWalkingOptions = this.bikeWalkingOptions.clone(); else clone.bikeWalkingOptions = clone; return clone; } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } }
Source:
public void testSelectorWidget() { final Button b1 = new Button("click-me"); RootPanel.get().add(b1); GQuery g = $(b1); assertEquals("inline-block", $(b1).css("display")); g.hide(); assertEquals("none", $(b1).css("display")); }

Target:
public void testSelectorWidget() { final Button b1 = new Button("Button click"); RootPanel.get().add(b1); GQuery g = $(b1); assertTrue(g.isVisible()); g.hide(); assertFalse(g.isVisible()); b1.removeFromParent(); }
Source:
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; }

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:
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(", "))); }); }

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:
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 " + iom.getArgument(0) + " on journal queue", 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; }

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:
public SeekableByteArrayInputStream(byte[] buf) { this.buffer = buf; this.cur = 0; this.max = buf.length; }

Target:
public SeekableByteArrayInputStream(byte[] buf) { Preconditions.checkNotNull(buf, "bug argument was null"); this.buffer = buf; this.cur = 0; this.max = buf.length; }
Source:
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 ) { 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 ) ; } }

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:
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); } if (sel == OS.sel_application_openFile_) { 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; }

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:
public Optional<IPageTypeCategoryRole> getTypeCategoryForCatName(String categoryName) { loadTypeNameToCategoryMap(); return Optional.fromNullable(getTypeNameToCategoryMapIncludeDeprecated().get(categoryName)); }

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

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:
public DRepresentationNotificationFilter(DRepresentation dRepresentation) { super(); this.dRepresentation = dRepresentation; }

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

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:
public final MetricFunctionInvocation invoke(Set<Argument> arguments, AggregatedField field, String alias) { Set<String> requiredArguments = getArgumentNames(); Map<String, Argument> providedArguments = arguments.stream() .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); }

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:
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); } if (logSizeLimitPercentage < 0.0 || 100.0 < logSizeLimitPercentage) { 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); }

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:
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: final Option<WorldCoords> coords = target.getCoordinates(None.instance()); 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}; }

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:
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); } catch (InvalidConfigurationInQueryException e) { 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; }

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:
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) { assertTrue(e.getMessage().contains("Connection refused")); } }

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:
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; }

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:
public IProject[] getProjects() { Set<IProject> result= new HashSet<>(); for (IPackageFragment fFragment : fFragments) { result.add(fFragment.getJavaProject().getProject()); } return result.toArray(new IProject[result.size()]); }

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:
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()) { resourceManager.setPrepareImageReturn(prepareImage(diskImage)); } return vmInfoBuildUtils.getPathToImage(diskImage); } else { return new File(getIsoPrefix(getStoragePoolId(), getVdsId()), virtioIsoName).getPath(); } } return null; }

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:
private void validateInstanceGroups(List<InstanceGroupV4Request> instanceGroups) { assertNotNull(instanceGroups); assertEquals("The result instance group list has " + instanceGroups.size() + " items instead of 2", 2, instanceGroups.size()); assertTrue(instanceGroups.stream().anyMatch(ig -> ig.getName().equals(MASTER_INSTANCE_GROUP) || ig.getName().equals(IDBROKER_INSTANCE_GROUP))); }

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:
protected GenericRecord readEntity() throws IOException { return readRecord(); }

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:
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) { callback.onFailure(new GeocoderException("Empty address. " + json.getString("error_message"))); } else { LOGGER.warn("Empty address"); } } return null; }

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:
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 = cloneProperties(Objects.requireNonNull(properties, "Properties cannot be null")); }

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:
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()); throw new NullPointerException(String.format("The template with name '%s' is not found.", templateConfig.name())); } return pipelineTemplateConfig; } }

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:
public void enter() { if (mMostRecentState == BluetoothProfile.STATE_CONNECTING) { onConnectionStateChanged(BluetoothProfile.STATE_CONNECTED); BluetoothMediaBrowserService.addressedPlayerChanged(mSessionCallbacks); } else { Log.d(STATE_TAG, "ReEnteringConnecting"); } super.enter(); }

Target:
public void enter() { if (mMostRecentState == BluetoothProfile.STATE_CONNECTING) { broadcastConnectionStateChanged(BluetoothProfile.STATE_CONNECTED); BluetoothMediaBrowserService.addressedPlayerChanged(mSessionCallbacks); } else { logD(STATE_TAG, "ReEnteringConnected"); } super.enter(); }
Source:
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")); add(message, login, password, submit, usage); if (ApplicationRouteRegistry .getInstance(VaadinServlet.getCurrent().getServletContext()) .getNavigationTarget("global").isPresent()) { add(new RouterLink("global", GlobalView.class)); } }

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:
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)); replicaCounter++; } replicaSets.add(set.stream().map(field)); } break; default: replicaSets = Collections.singletonList(bricks.stream().map(field)); break; } return reduce.apply(replicaSets); }

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:
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; }

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:
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()); } } if (rightOperand.requiresTypeFromContext()) { rightOperand.setType(leftOperand.getTypeServices()); } }

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:
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); synchronized(definition.getSortCacheTable()) { 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; } }

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:
public void close() { if (details == null) { return; } FunctionResult result = new FunctionResult(); stopWatch(details, result); details = null; if (result.isFailed()) { throw new NativeException("Failed to stop watch. Reason: " + result.getMessage()); } }

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:
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(); 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; }

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:
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 { progress.worked(1); } }

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

Target:
private String getFileExt(String name) { int i = name.lastIndexOf('.'); if (i < 0 || i + 1 == name.length()) { return null; } return name.substring(i + 1); }