auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public final Timestamp addMillis(long amount) { if (amount == 0 && _precision == Precision.SECOND && _fraction != null && _fraction.scale() >= 3) { return this; } long seconds = amount / 1000; BigDecimal millis = BigDecimal.valueOf(amount % 1000).movePointLeft(3); if (_fraction != null) { millis = _fraction.add(millis); } BigDecimal newFraction; if (BigDecimal.ONE.compareTo(millis) <= 0) { newFraction = millis.subtract(BigDecimal.ONE); seconds += 1; } else if (BigDecimal.ZERO.compareTo(millis) > 0) { newFraction = BigDecimal.ONE.add(millis); seconds -= 1; } else { newFraction = millis; } Timestamp ts = this; do { int incrementalSeconds; if (seconds > Integer.MAX_VALUE) { incrementalSeconds = Integer.MAX_VALUE; } else if (seconds < Integer.MIN_VALUE) { incrementalSeconds = Integer.MIN_VALUE; } else { incrementalSeconds = (int)seconds; } ts = ts.addSecond(incrementalSeconds); seconds -= incrementalSeconds; } while (seconds != 0); ts._fraction = newFraction; return ts; }

Target:
public final Timestamp addMillis(long amount) { if (amount == 0 && _precision == Precision.SECOND && _fraction != null && _fraction.scale() >= 3) { return this; } long seconds = amount / 1000; BigDecimal millis = BigDecimal.valueOf(amount % 1000).movePointLeft(3); if (_fraction != null) { millis = _fraction.add(millis); } BigDecimal newFraction; if (BigDecimal.ONE.compareTo(millis) <= 0) { newFraction = millis.subtract(BigDecimal.ONE); seconds += 1; } else if (BigDecimal.ZERO.compareTo(millis) > 0) { newFraction = BigDecimal.ONE.add(millis); seconds -= 1; } else { newFraction = millis; } Timestamp ts = addSecond(seconds); ts._fraction = newFraction; return ts; }
Source:
public void doOnTerminateError() { final AtomicBoolean atomicBoolean = new AtomicBoolean(); Single s = Single.error(new TestException()).doOnTerminate(new Action() { @Override public void run() { atomicBoolean.set(true); } }); try { s.blockingGet(); Assert.fail("Did dot throw exception"); } catch (TestException e) { } assertTrue(atomicBoolean.get()); }

Target:
public void doOnTerminateError() { final AtomicBoolean atomicBoolean = new AtomicBoolean(); Single.error(new TestException()).doOnTerminate(new Action() { @Override public void run() { atomicBoolean.set(true); } }) .test() .assertFailure(TestException.class); assertTrue(atomicBoolean.get()); }
Source:
public void authenticate_shouldThrowDisabledExceptionIfUserIsInactive() { final String shogun2UserName = "user"; final String correctPassword = "correctPassword"; final User userToAuth = createUserMock(shogun2UserName, correctPassword); Authentication authRequest = mock(Authentication.class); when(authRequest.getName()).thenReturn(shogun2UserName); when(authRequest.getCredentials()).thenReturn(correctPassword); when(userService.findByAccountName(shogun2UserName)).thenReturn(userToAuth); authProvider.authenticate(authRequest); }

Target:
public void authenticate_shouldThrowDisabledExceptionIfUserIsInactive() { final String shogun2UserName = "user"; final String correctPassword = "correctPassword"; final User userToAuth = createUserMock(shogun2UserName, correctPassword); userToAuth.setActive(false); Authentication authRequest = mock(Authentication.class); when(authRequest.getName()).thenReturn(shogun2UserName); when(authRequest.getCredentials()).thenReturn(correctPassword); when(userService.findByAccountName(shogun2UserName)).thenReturn(userToAuth); authProvider.authenticate(authRequest); }
Source:
public void run() { try { while (!Thread.interrupted() && !conn.isClosed()) { try { ResultSet resultSet = conn.createStatement().executeQuery( "SELECT * FROM " + PhoenixDatabaseMetaData.SYSTEM_MUTEX_NAME); if (resultSet.next()) { isSysMutexEmpty.getAndSet(false); break; } } catch (SQLException e) { if (conn.isClosed()) { Thread.currentThread().interrupt(); } else { LOGGER.error("Error while scanning , thread: {}", PhoenixDatabaseMetaData.SYSTEM_MUTEX_NAME, Thread.currentThread().getName(), e); } } } } catch (SQLException e) { LOGGER.error("Connection access error. Thread: {}", Thread.currentThread().getName(), e); } }

Target:
public void run() { try (Connection conn = DriverManager.getConnection(getUrl(), props)) { while (!Thread.interrupted() && !conn.isClosed()) { try { ResultSet resultSet = conn.createStatement().executeQuery( "SELECT * FROM " + PhoenixDatabaseMetaData.SYSTEM_MUTEX_NAME + " WHERE TENANT_ID IS NULL AND TABLE_SCHEM='" + schemaName + "' AND TABLE_NAME='" + tableName + "' AND COLUMN_NAME IS NULL AND COLUMN_FAMILY IS NULL"); if (resultSet.next()) { isSysMutexEmpty.set(false); break; } } catch (SQLException e) { if (conn.isClosed()) { Thread.currentThread().interrupt(); } else { LOGGER.error("Error while scanning , thread: {}", PhoenixDatabaseMetaData.SYSTEM_MUTEX_NAME, Thread.currentThread().getName(), e); } } } } catch (SQLException e) { LOGGER.error("Connection access error. Thread: {}", Thread.currentThread().getName(), e); } }
Source:
public static String cpu() { return Objects.requireNonNull(org.eclipse.tracecompass.tmf.core.event.aspect.Messages.AspectName_CPU); }

Target:
public static @NonNull String cpu() { return Objects.requireNonNull(org.eclipse.tracecompass.tmf.core.event.aspect.Messages.AspectName_CPU); }
Source:
protected void onRequestSuggestions(final Request req, final Callback callback) { RpcStatus.hide(new Runnable() { public void run() { SuggestUtil.SVC.suggestLabel(changeId, new GerritCallback<Set<ChangeLabel.LabelKey>>() { public void onSuccess(final Set<ChangeLabel.LabelKey> result) { final Set<StringSuggestion> r = new HashSet<StringSuggestion>(); for (ChangeLabel.LabelKey p : result) { if (!labelsToExclude.contains(p)) { r.add(new StringSuggestion(p.get())); } } callback.onSuggestionsReady(req, new Response(r)); } }); } }); }

Target:
protected void onRequestSuggestions(final Request req, final Callback callback) { RpcStatus.hide(new Runnable() { public void run() { SuggestUtil.SVC.suggestLabel(changeId, new GerritCallback<Set<ChangeLabel.LabelKey>>() { public void onSuccess(final Set<ChangeLabel.LabelKey> result) { result.removeAll(labelsToExclude); final Set<StringSuggestion> r = new HashSet<StringSuggestion>(result.size()); for (ChangeLabel.LabelKey l : result) { r.add(new StringSuggestion(l.get())); } callback.onSuggestionsReady(req, new Response(r)); } }); } }); }
Source:
protected Collection<Geocache> doImport() throws IOException, ParserException { Log.i("Import LOC from uri: " + uri); importStepHandler.sendMessage(importStepHandler.obtainMessage(GPXImporter.IMPORT_STEP_READ_FILE, R.string.gpx_import_loading_caches, -1)); final InputStream is = contentResolver.openInputStream(uri); final LocParser parser = new LocParser(listId); try { return parser.parse(is, progressHandler); } finally { if (is != null) { is.close(); } } }

Target:
protected Collection<Geocache> doImport() throws IOException, ParserException { Log.i("Import LOC from uri: " + uri); importStepHandler.sendMessage(importStepHandler.obtainMessage(GPXImporter.IMPORT_STEP_READ_FILE, R.string.gpx_import_loading_caches, -1)); final InputStream is = contentResolver.openInputStream(uri); final LocParser parser = new LocParser(listId); try { return parser.parse(is, progressHandler); } finally { IOUtils.closeQuietly(is); } }
Source:
protected static BibDatabaseContext createContext(Field field, String value, MetaData metaData) { BibEntry entry = new BibEntry(); entry.setField(field, value); BibDatabase bibDatabase = new BibDatabase(); bibDatabase.insertEntry(entry); return new BibDatabaseContext(bibDatabase, metaData); }

Target:
private BibDatabaseContext createContext(Field field, String value, MetaData metaData) { BibEntry entry = new BibEntry(); entry.setField(field, value); BibDatabase bibDatabase = new BibDatabase(); bibDatabase.insertEntry(entry); return new BibDatabaseContext(bibDatabase, metaData); }
Source:
public Iterable<Tuple> performEvaluation(final Tuple input) { final Object result = evaluateTerm(input); if (result != null) { if (this.isUnwinding) { if (result instanceof Set<?>) { return () -> { final Iterator<?> wrapped = ((Set<?>) result).iterator(); return new Iterator<Tuple>() { @Override public boolean hasNext() { return wrapped.hasNext(); } @Override public Tuple next() { final Object next = wrapped.next(); return Tuples.staticArityLeftInheritanceTupleOf(input, runtimeContext.wrapElement(next)); } }; }; } else { throw new IllegalStateException( "This is an unwinding evaluator, but the evaluation yielded " + result); } } else { return Collections.singleton( Tuples.staticArityLeftInheritanceTupleOf(input, runtimeContext.wrapElement(result))); } } else { return null; } }

Target:
public Iterable<Tuple> performEvaluation(final Tuple input) { final Object result = evaluateTerm(input); if (result != null) { if (this.isUnwinding) { final Set<?> resultAsSet = (result instanceof Set<?>) ? (Set<?>) result : (result instanceof Iterable<?>) ? Sets.newHashSet((Iterable<?>) result) : null; if (resultAsSet != null) { return () -> { final Iterator<?> wrapped = resultAsSet.iterator(); return new Iterator<Tuple>() { @Override public boolean hasNext() { return wrapped.hasNext(); } @Override public Tuple next() { final Object next = wrapped.next(); return Tuples.staticArityLeftInheritanceTupleOf(input, runtimeContext.wrapElement(next)); } }; }; } else { throw new IllegalStateException( "This is an unwinding evaluator, which expects the evaluation result to either be a set or an iterable, but it was " + result); } } else { return Collections.singleton( Tuples.staticArityLeftInheritanceTupleOf(input, runtimeContext.wrapElement(result))); } } else { return null; } }
Source:
protected OperationRequest makeOperationRequest(ReplicaId replicaId) { if(!sslEnabledColos.contains(replicaId.getDataNodeId().getDatacenterName())) { return new GetBlobOperationRequest(connectionPool, responseQueue, context, blobId, replicaId, makeGetRequest(), clusterMap, this, false); } else{ return new GetBlobOperationRequest(connectionPool, responseQueue, context, blobId, replicaId, makeGetRequest(), clusterMap, this, true); } }

Target:
protected OperationRequest makeOperationRequest(ReplicaId replicaId) { return new GetBlobOperationRequest(connectionPool, responseQueue, context, blobId, replicaId, makeGetRequest(), clusterMap, this); }
Source:
private static PRPAMT201306UV02LivingSubjectId createSubjectId(II subjectId) { PRPAMT201306UV02LivingSubjectId id = new PRPAMT201306UV02LivingSubjectId(); if (subjectId != null) { id.getValue().add(subjectId); } return id; }

Target:
private static PRPAMT201306UV02LivingSubjectId createSubjectId(II subjectId) { PRPAMT201306UV02LivingSubjectId id = new PRPAMT201306UV02LivingSubjectId(); id.getValue().add(subjectId); return id; }
Source:
public RetryPolicy(RetryPolicyOptions retryPolicyOptions) { this.retryPolicyOptions = Objects.requireNonNull(retryPolicyOptions, "'retryPolicyOptions' cannot be null."); }

Target:
public RetryPolicy(RetryPolicyOptions retryPolicyOptions) { this.retryPolicyOptions = Objects.requireNonNull(retryPolicyOptions, "'retryPolicyOptions' cannot be null."); Objects.requireNonNull(retryPolicyOptions.getRetryStrategy(), "'retryPolicyOptions.retryStrategy' cannot be null."); }
Source:
@Override public boolean onCreate() { Picasso.setSingletonInstance(new Picasso.Builder(getContext()).build()); return true; }

Target:
@Override public boolean onCreate() { context = getContext(); return true; }
Source:
public void onServerStarting(FMLServerStartingEvent event) { event.registerServerCommand(new MiningDimensionTest.DimensionTestCommand()); System.out.println("MiningDimensionTest Registered command /mining <int>"); for (File file : new File(event.getServer().isSinglePlayer() ? "saves" : ".").listFiles()) { if (file.isFile() || !file.getName().startsWith(savefoldername)) continue; String sint = file.getName().replace(savefoldername, ""); if (!sint.isEmpty() && isInteger(sint)) { miningid = Integer.valueOf(sint); DimensionManager.registerDimension(miningid, dimtypetest); System.out.println("Found OFFLINE mining dimension " + miningid); break; } } }

Target:
public void onServerStarting(FMLServerStartingEvent event) { event.registerServerCommand(new MiningDimensionTest.DimensionTestCommand()); logger.info("MiningDimensionTest Registered command /mining <int>"); for (File file : new File(event.getServer().isSinglePlayer() ? "saves" : ".").listFiles()) { if (file.isFile() || !file.getName().startsWith(savefoldername)) continue; String sint = file.getName().replace(savefoldername, ""); if (!sint.isEmpty() && isInteger(sint)) { miningid = Integer.valueOf(sint); DimensionManager.registerDimension(miningid, dimtypetest); logger.info("Found OFFLINE mining dimension " + miningid); break; } } }
Source:
private AuditLogableBase getLoggableQuotaStorageParams(String quotaName, double storageUsagePercentage, double storageRequestedPercentage) { AuditLogableBase logable = new AuditLogableBase(); logable.getUserName(); logable.AddCustomValue("QuotaName", quotaName); logable.AddCustomValue("CurrentStorage", String.valueOf((int)storageUsagePercentage)); logable.AddCustomValue("Requested", String.valueOf((int)storageRequestedPercentage)); return logable; }

Target:
private AuditLogableBase getLoggableQuotaStorageParams(String quotaName, double storageUsagePercentage, double storageRequestedPercentage) { AuditLogableBase logable = new AuditLogableBase(); logable.AddCustomValue("QuotaName", quotaName); logable.AddCustomValue("CurrentStorage", percentageFormatter.format(storageUsagePercentage)); logable.AddCustomValue("Requested", percentageFormatter.format(storageRequestedPercentage)); return logable; }
Source:
public Set<UsbSerialDeviceInformation> scan() throws IOException { Set<UsbSerialDeviceInformation> result = Sets.newHashSet(); for (SerialPortInfo serialPortInfo : getSerialPortInfos()) { try { UsbSerialDeviceInformation usbSerialDeviceInfo = tryGetUsbSerialDeviceInformation(serialPortInfo); if (usbSerialDeviceInfo != null) { result.add(usbSerialDeviceInfo); } } catch (IOException e) { logger.warn( "Could not extract usb device information for serial port due to an IOException; message: {}", serialPortInfo, e.getMessage()); } } return result; }

Target:
public Set<UsbSerialDeviceInformation> scan() throws IOException { Set<UsbSerialDeviceInformation> result = new HashSet<>(); for (SerialPortInfo serialPortInfo : getSerialPortInfos()) { try { UsbSerialDeviceInformation usbSerialDeviceInfo = tryGetUsbSerialDeviceInformation(serialPortInfo); if (usbSerialDeviceInfo != null) { result.add(usbSerialDeviceInfo); } } catch (IOException e) { logger.warn("Could not extract USB device information for serial port {}: {}", serialPortInfo, e.getMessage()); } } return result; }
Source:
public void cantOpenReadOnlyLogFiles() throws Exception { String serviceDir = PARAMETERS.TEST_TEMP_DIR; LogUnitServer s1 = new LogUnitServer(new ServerContextBuilder() .setLogPath(serviceDir) .setMemory(false) .build()); this.router.reset(); this.router.addServer(s1); final long LOW_ADDRESS = 0L; final String low_payload = "0"; final long MID_ADDRESS = 100L; final String mid_payload = "100"; final long HIGH_ADDRESS = 10000000L; final String high_payload = "100000"; final String streamName = "a"; rawWrite(LOW_ADDRESS, low_payload, streamName); rawWrite(MID_ADDRESS, mid_payload, streamName); rawWrite(HIGH_ADDRESS, high_payload, streamName); s1.shutdown(); String[] extension = {"log"}; File serviceDirectory = new File(serviceDir); Collection<File> files = FileUtils.listFiles(serviceDirectory, extension, true); for (File file : files) { try { boolean ok = file.setReadable(false); assertThat(ok).isEqualTo(true); } catch (SecurityException e) { assertThat("Should not hit security exception"+e.toString()); } } boolean readOnlyFailed = false; try { LogUnitServer s2 = new LogUnitServer(new ServerContextBuilder() .setLogPath(serviceDir) .setMemory(false) .build()); } catch (IllegalStateException e) { readOnlyFailed = true; } assertThat(readOnlyFailed).isEqualTo(true); }

Target:
public void cantOpenReadOnlyLogFiles() throws Exception { String serviceDir = PARAMETERS.TEST_TEMP_DIR; LogUnitServer s1 = new LogUnitServer(new ServerContextBuilder() .setLogPath(serviceDir) .setMemory(false) .build()); this.router.reset(); this.router.addServer(s1); final long LOW_ADDRESS = 0L; final String low_payload = "0"; final long MID_ADDRESS = 100L; final String mid_payload = "100"; final long HIGH_ADDRESS = 10000000L; final String high_payload = "100000"; final String streamName = "a"; rawWrite(LOW_ADDRESS, low_payload, streamName); rawWrite(MID_ADDRESS, mid_payload, streamName); rawWrite(HIGH_ADDRESS, high_payload, streamName); s1.shutdown(); try { File serviceDirectory = new File(serviceDir); serviceDirectory.setWritable(false); } catch(SecurityException e) { fail("Should not hit security exception"+e.toString()); } try { LogUnitServer s2 = new LogUnitServer(new ServerContextBuilder() .setLogPath(serviceDir) .setMemory(false) .build()); fail("Should have failed to startup in read-only mode"); } catch (UnrecoverableCorfuError e) { } File serviceDirectory = new File(serviceDir); serviceDirectory.setWritable(true); }
Source:
public synchronized void processJavaElementChange(final JavaElementDelta delta, final IProgressMonitor progressMonitor) throws CoreException { try { Logger.debug("Processing {}", delta); final IJavaElement element = delta.getElement(); final CompilationUnit ast = delta.getCompilationUnitAST(); final int deltaKind = delta.getKind(); if (element.getElementType() == IJavaElement.ANNOTATION) { processJavaAnnotationChange((IAnnotation) element, deltaKind, ast, progressMonitor); } else { processJavaElementChange(element, deltaKind, ast, progressMonitor); } } finally { progressMonitor.done(); setBuildStatus(Status.OK_STATUS); Logger.debug("Done processing Java changes."); } }

Target:
public void processJavaElementChange(final JavaElementDelta delta, final IProgressMonitor progressMonitor) throws CoreException { try { Logger.debug("Processing {}", delta); readWriteLock.writeLock().lock(); final IJavaElement element = delta.getElement(); final CompilationUnit ast = delta.getCompilationUnitAST(); final int deltaKind = delta.getKind(); if (element.getElementType() == IJavaElement.ANNOTATION) { processJavaAnnotationChange((IAnnotation) element, deltaKind, ast, progressMonitor); } else { processJavaElementChange(element, deltaKind, ast, progressMonitor); } } finally { progressMonitor.done(); readWriteLock.writeLock().unlock(); setBuildStatus(Status.OK_STATUS); Logger.debug("Done processing Java changes."); } }
Source:
public static String stripPathInformation(String osgiBundles) { StringBuilder result = new StringBuilder(); StringTokenizer tokenizer = new StringTokenizer(osgiBundles, ","); while (tokenizer.hasMoreElements()) { String token = tokenizer.nextToken(); token = token.replaceAll("\\\\:|/:", ":"); int atIndex = token.indexOf('@'); String bundle = atIndex > 0 ? token.substring(0, atIndex) : token; bundle = bundle.trim(); if (bundle.startsWith(REFERENCE_PREFIX) && bundle.length() > REFERENCE_PREFIX.length()) bundle = bundle.substring(REFERENCE_PREFIX.length()); if (bundle.startsWith(PLATFORM_PREFIX) && bundle.length() > PLATFORM_PREFIX.length()) bundle = bundle.substring(PLATFORM_PREFIX.length()); if (bundle.startsWith(FILE_URL_PREFIX) && bundle.length() > FILE_URL_PREFIX.length()) bundle = bundle.substring(FILE_URL_PREFIX.length()); IPath path = new Path(bundle); String id = null; if (path.isAbsolute()) { id = getSymbolicName(bundle); } if (id == null) { id = path.lastSegment(); } if (id != null) { int underscoreIndex = id.indexOf("_64"); underscoreIndex = id.indexOf('_', underscoreIndex + 1); if (underscoreIndex >= 0) { id = id.substring(0, underscoreIndex); } if (id.endsWith(JAR_EXTENSION)) { id = id.substring(0, id.length() - 4); } } if (result.length() > 0) result.append(","); result.append(id != null ? id : bundle); if (atIndex > -1) result.append(token.substring(atIndex).trim()); } return result.toString(); }

Target:
public static String stripPathInformation(String osgiBundles) { StringBuilder result = new StringBuilder(); StringTokenizer tokenizer = new StringTokenizer(osgiBundles, ","); while (tokenizer.hasMoreElements()) { String token = tokenizer.nextToken(); token = token.replaceAll("\\\\:|/:", ":"); int atIndex = token.indexOf('@'); String bundle = atIndex > 0 ? token.substring(0, atIndex) : token; bundle = bundle.trim(); if (bundle.startsWith(REFERENCE_PREFIX) && bundle.length() > REFERENCE_PREFIX.length()) bundle = bundle.substring(REFERENCE_PREFIX.length()); if (bundle.startsWith(PLATFORM_PREFIX) && bundle.length() > PLATFORM_PREFIX.length()) bundle = bundle.substring(PLATFORM_PREFIX.length()); if (bundle.startsWith(FILE_URL_PREFIX) && bundle.length() > FILE_URL_PREFIX.length()) bundle = bundle.substring(FILE_URL_PREFIX.length()); IPath path = new Path(bundle); String id = null; if (path.isAbsolute()) { id = getSymbolicName(bundle); } if (id == null) { id = path.lastSegment(); } if (id != null) { id = PATTERN_BUNDLE_VERSION.matcher(id).replaceFirst(""); if (id.endsWith(JAR_EXTENSION)) { id = id.substring(0, id.length() - 4); } } if (result.length() > 0) result.append(","); result.append(id != null ? id : bundle); if (atIndex > -1) result.append(token.substring(atIndex).trim()); } return result.toString(); }
Source:
public synchronized LeaderAndEpoch currentLeader(TopicPartition topicPartition) { Optional<MetadataResponse.PartitionMetadata> maybeMetadata = partitionMetadataIfCurrent(topicPartition); if (!maybeMetadata.isPresent()) return new LeaderAndEpoch(Optional.empty(), Optional.ofNullable(lastSeenLeaderEpochs.get(topicPartition))); MetadataResponse.PartitionMetadata partitionMetadata = maybeMetadata.get(); Optional<Integer> leaderEpoch = partitionMetadata.leaderEpoch; Optional<Node> leaderNodeOpt = cache.nodeById(partitionMetadata.leaderId); return new LeaderAndEpoch(leaderNodeOpt, leaderEpoch); }

Target:
public synchronized LeaderAndEpoch currentLeader(TopicPartition topicPartition) { Optional<MetadataResponse.PartitionMetadata> maybeMetadata = partitionMetadataIfCurrent(topicPartition); if (!maybeMetadata.isPresent()) return new LeaderAndEpoch(Optional.empty(), Optional.ofNullable(lastSeenLeaderEpochs.get(topicPartition))); MetadataResponse.PartitionMetadata partitionMetadata = maybeMetadata.get(); Optional<Integer> leaderEpochOpt = partitionMetadata.leaderEpoch; Optional<Node> leaderNodeOpt = partitionMetadata.leaderId.flatMap(cache::nodeById); return new LeaderAndEpoch(leaderNodeOpt, leaderEpochOpt); }
Source:
private void populateColumns(TreeItem item, ITmfStateInterval interval) { try { ITmfStateValue state = interval.getStateValue(); String value ; switch (state.getType()) { case INTEGER: value = String.valueOf(state.unboxInt()); item.setText(TYPE_COL, Messages.TypeInteger); break; case LONG: value = String.valueOf(state.unboxLong()); item.setText(TYPE_COL, Messages.TypeLong); break; case STRING: value = state.unboxStr(); item.setText(TYPE_COL, Messages.TypeString); break; case NULL: default: value = emptyString ; item.setText(TYPE_COL, emptyString); break; } TmfTimestamp startTime = new TmfTimestamp(interval.getStartTime(), ITmfTimestamp.NANOSECOND_SCALE); item.setText(START_TIME_COL, startTime.toString()); TmfTimestamp endTime = new TmfTimestamp(interval.getEndTime(), ITmfTimestamp.NANOSECOND_SCALE); item.setText(END_TIME_COL, endTime.toString()); item.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)) ; if ((!filterStatus) && !value.equals(item.getText(VALUE_COL)) || fCurrentTimestamp == startTime.getValue()) { item.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_YELLOW)); } item.setText(VALUE_COL, value) ; } catch (StateValueTypeException e) { throw new RuntimeException(); } }

Target:
private void populateColumns(TreeItem item, ITmfStateInterval interval) { try { ITmfStateValue state = interval.getStateValue(); String value ; switch (state.getType()) { case INTEGER: value = String.valueOf(state.unboxInt()); item.setText(TYPE_COL, Messages.TypeInteger); break; case LONG: value = String.valueOf(state.unboxLong()); item.setText(TYPE_COL, Messages.TypeLong); break; case STRING: value = state.unboxStr(); item.setText(TYPE_COL, Messages.TypeString); break; case NULL: default: value = emptyString ; item.setText(TYPE_COL, emptyString); break; } TmfTimestamp startTime = new TmfTimestamp(interval.getStartTime(), ITmfTimestamp.NANOSECOND_SCALE); item.setText(START_TIME_COL, startTime.toString()); TmfTimestamp endTime = new TmfTimestamp(interval.getEndTime(), ITmfTimestamp.NANOSECOND_SCALE); item.setText(END_TIME_COL, endTime.toString()); item.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)) ; if (!filterStatus && (!value.equals(item.getText(VALUE_COL)) || fCurrentTimestamp == startTime.getValue())) { item.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_YELLOW)); } item.setText(VALUE_COL, value) ; } catch (StateValueTypeException e) { throw new RuntimeException(); } }
Source:
private String getSortValue() { if (account != null) { if (account.email != null) { return account.email; } return Strings.nullToEmpty(account.name); } return Strings.nullToEmpty(group.name); }

Target:
private String getSortValue() { return account != null ? Objects.firstNonNull(account.email, Strings.nullToEmpty(account.name)) : Strings.nullToEmpty(group.name); }
Source:
private HttpEntity<String> getSampleSheetForRun(Run run, SampleSheet casavaVersion, HttpServletResponse response) throws IOException { if (run == null) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } User user = securityManager.getUserByLoginName(SecurityContextHolder.getContext().getAuthentication().getName()); if (run.getSequencerPartitionContainers().size() != 1) { throw new RestException( "Expected 1 sequencing container for run " + run.getAlias() + ", but found " + run.getSequencerPartitionContainers().size()); } HttpHeaders headers = new HttpHeaders(); headers.setContentType(new MediaType("text", "csv")); response.setHeader("Content-Disposition", "attachment; filename=" + String.format("RUN%d-%s-SampleSheet.csv", run.getId(), casavaVersion.name())); return new HttpEntity<>(casavaVersion.createSampleSheet(run, user), headers); }

Target:
private HttpEntity<String> getSampleSheetForRun(Run run, SampleSheet casavaVersion, HttpServletResponse response) throws IOException { if (run == null) { throw new RestException("Run does not exist.", Status.NOT_FOUND); } User user = securityManager.getUserByLoginName(SecurityContextHolder.getContext().getAuthentication().getName()); if (run.getSequencerPartitionContainers().size() != 1) { throw new RestException( "Expected 1 sequencing container for run " + run.getAlias() + ", but found " + run.getSequencerPartitionContainers().size()); } HttpHeaders headers = new HttpHeaders(); headers.setContentType(new MediaType("text", "csv")); response.setHeader("Content-Disposition", "attachment; filename=" + String.format("RUN%d-%s-SampleSheet.csv", run.getId(), casavaVersion.name())); return new HttpEntity<>(casavaVersion.createSampleSheet(run, user), headers); }
Source:
public void testNullRequestHeader () throws Exception { final List<String> headers = new ArrayList<>(); doReturn(headers).when(request).getRequestHeader("X-Cloud-Trace-Context"); textFormat.extract(request, textFormatGetter); }

Target:
public void testNullRequestHeader () throws Exception { doReturn(null).when(request).getRequestHeader(Mockito.anyString()); textFormat.extract(request, textFormatGetter); }
Source:
private boolean isCompareToDeclaration(MethodTree tree) { Tree returnType = tree.returnType(); return "compareTo".equals(tree.simpleName().name()) && returnType.is(Kind.PRIMITIVE_TYPE) && "int".equals(((PrimitiveTypeTree) returnType).keyword().text()); }

Target:
private boolean isCompareToDeclaration(MethodTree tree) { return isNamedCompareTo(tree) && hasOneNonPrimitiveParameter(tree) && returnsInt(tree); }
Source:
static TabData getTabData(ApplicationConstants applicationConstants, DetailModelProvider<HostListModel, StorageDeviceListModel> modelProvider) { return new ModelBoundTabData(applicationConstants.disksLabel(), 4, modelProvider); }

Target:
static TabData getTabData(ApplicationConstants applicationConstants, DetailModelProvider<HostListModel, StorageDeviceListModel> modelProvider) { return new ModelBoundTabData(applicationConstants.logicalVolumes(), 4, modelProvider); }
Source:
public void setHealth(double health) { if (health < 0) health = 0; if (health > getMaxHealth()) health = getMaxHealth(); this.health = health; metadata.set(MetadataIndex.HEALTH, (float) health); for (Objective objective : getServer().getScoreboardManager().getMainScoreboard().getObjectivesByCriteria(Criterias.HEALTH)) { objective.getScore(this.getName()).setScore((int) health); } if (health == 0) { active = false; Sound deathSound = getDeathSound(); if (deathSound != null) { world.playSound(location, deathSound, 1.0f, 1.0f); } playEffect(EntityEffect.DEATH); } }

Target:
public void setHealth(double health) { if (health < 0) health = 0; if (health > getMaxHealth()) health = getMaxHealth(); this.health = health; metadata.set(MetadataIndex.HEALTH, (float) health); for (Objective objective : getServer().getScoreboardManager().getMainScoreboard().getObjectivesByCriteria(Criterias.HEALTH)) { objective.getScore(this.getName()).setScore((int) health); } if (health <= 0) { active = false; Sound deathSound = getDeathSound(); if (deathSound != null) { world.playSound(location, deathSound, 1.0f, 1.0f); } playEffect(EntityEffect.DEATH); } }
Source:
public void onDownloadComplete(LoadRequest request, boolean wasCancelled){ Log.d("ImageLoader", "Download complete: " + request.mUrl); if (!wasCancelled && request.mResult != null){ MemoryCache.instance().addBitmapToMemoryCache(request.mUrl, request.mResult); completeLodRequest(request); queueWriteRequest(new WriteRequest(request.mResult, request.mUrl)); } closeRequest(); }

Target:
public void onDownloadComplete(LoadRequest request, boolean wasCancelled){ Log.d("ImageLoader", "Download complete: " + request.mUrl); if (!wasCancelled && request.mResult != null){ MemoryCache.instance().addBitmapToMemoryCache(request.mUrl, request.mResult); completeLoadRequest(request); queueWriteRequest(new WriteRequest(request.mResult, request.mUrl)); } closeRequest(); }
Source:
public Account validate(TaskRepository repository, IProgressMonitor monitor) throws CoreException { if (!Boolean.parseBoolean(repository.getProperty(GerritConnector.KEY_REPOSITORY_OPEN_ID_ENABLED))) { monitor = Policy.backgroundMonitorFor(monitor); } try { return ((GerritClient) createReviewClient(repository, false)).getAccountAndRefreshConfig(monitor); } catch (UnsupportedClassVersionError e) { throw toCoreException(repository, e); } catch (GerritException e) { throw toCoreException(repository, "Invalid repository", e); } }

Target:
public GerritSystemInfo validate(TaskRepository repository, IProgressMonitor monitor) throws CoreException { if (!Boolean.parseBoolean(repository.getProperty(GerritConnector.KEY_REPOSITORY_OPEN_ID_ENABLED))) { monitor = Policy.backgroundMonitorFor(monitor); } try { return ((GerritClient) createReviewClient(repository, false)).getInfo(monitor); } catch (UnsupportedClassVersionError e) { throw toCoreException(repository, e); } catch (GerritException e) { throw toCoreException(repository, "Invalid repository", e); } }
Source:
public String removePlayerFromTeam( HttpSession session, @PathVariable int id) { Member me = (Member) session.getAttribute("member"); if (me == null) { return "redirect:/denied"; } TeamDao teamDao = new TeamDao(); Team team = teamDao.getTeamById(id, false, true, false); if (team == null || me.equals(team.getTeamLeader())) { return "redirect:/denied"; } team.removePlayer(me); new MessageDao().notify(me, "You were removed from " + team.getName()); new MessageDao().notify(team.getTeamLeader(), me.getName() + " was removed from " + team.getName()); teamDao.saveTeam(team); return "redirect:/profile"; }

Target:
public String removePlayerFromTeam( HttpSession session, @PathVariable int id) { Member me = (Member) session.getAttribute("member"); MemberDao memberDao = new MemberDao(); me = memberDao.getMemberById(me.getId()); if (me == null) { return "redirect:/denied"; } TeamDao teamDao = new TeamDao(); Team team = teamDao.getTeamById(id, false, true, false); if (team == null || me.equals(team.getTeamLeader())) { return "redirect:/denied"; } team.removePlayer(me); new MessageDao().notify(me, "You were removed from " + team.getName()); new MessageDao().notify(team.getTeamLeader(), me.getName() + " was removed from " + team.getName()); teamDao.saveTeam(team); return "redirect:/profile"; }
Source:
public ResponseEntity<?> getSchemaVersion(@PathVariable("name") final String name, @PathVariable("version") final String version, final NativeWebRequest request) { if (version.equals("latest")) { final EventType eventType = eventTypeService.get(name); return ResponseEntity.status(HttpStatus.OK).body(eventType.getSchema()); } final EventTypeSchema result = schemaService.getSchemaVersion(name, version); return ResponseEntity.status(HttpStatus.OK).body(result); }

Target:
public ResponseEntity<?> getSchemaVersion(@PathVariable("name") final String name, @PathVariable("version") final String version, final NativeWebRequest request) throws NoSuchEventTypeException, InternalNakadiException, NoSuchSchemaException, InvalidVersionNumberException { if (version.equals("latest")) { final EventType eventType = eventTypeService.get(name); return ResponseEntity.status(HttpStatus.OK).body(eventType.getSchema()); } final EventTypeSchema result = schemaService.getSchemaVersion(name, version); return ResponseEntity.status(HttpStatus.OK).body(result); }
Source:
public boolean updateLiveInAndOut(ControlFlowGraph cfg, Map<CfgBlock, BlockLiveness> livenessPerBlock) { liveOut.clear(); for (CfgBlock successor : block.successors()) { if (successor != cfg.end()) { liveOut.addAll(livenessPerBlock.get(successor).liveIn); } } Set<Symbol> oldIn = liveIn; liveIn = new HashSet<>(liveOut); for (Tree element : Lists.reverse(block.elements())) { Usage usage = usageByElement.get(element); if (isWrite(usage)) { liveIn.remove(symbol(usage)); } else if (isRead(usage)) { liveIn.add(symbol(usage)); } } return !oldIn.equals(liveIn); }

Target:
public boolean updateLiveInAndOut(ControlFlowGraph cfg, Map<CfgBlock, BlockLiveness> livenessPerBlock) { liveOut.clear(); for (CfgBlock successor : block.successors()) { liveOut.addAll(livenessPerBlock.get(successor).liveIn); } Set<Symbol> oldIn = liveIn; liveIn = new HashSet<>(liveOut); for (Tree element : Lists.reverse(block.elements())) { Usage usage = usageByElement.get(element); if (isWrite(usage)) { liveIn.remove(symbol(usage)); } else if (isRead(usage)) { liveIn.add(symbol(usage)); } } return !oldIn.equals(liveIn); }
Source:
private static Object getAvroValue(Object input, Schema schema) { if (input instanceof byte[]) { return new GenericData.Fixed(schema, (byte[]) input); } else if (input instanceof Map && !((Map) input).isEmpty()) { return getAvroGenericRecord((StreamlineEvent) input, schema.toString()); } else if (input instanceof List && !((List) input).isEmpty()) { return new GenericData.Array<Object>(schema, (Collection<Object>) input); } else { return input; } }

Target:
private static Object getAvroValue(Object input, Schema schema) { if (input instanceof byte[] && Schema.Type.FIXED.equals(schema.getType())) { return new GenericData.Fixed(schema, (byte[]) input); } else if (input instanceof Map && !((Map) input).isEmpty()) { GenericRecord result; result = new GenericData.Record(schema); for (Map.Entry<String, Object> entry: ((Map<String, Object>) input).entrySet()) { result.put(entry.getKey(), getAvroValue(entry.getValue(), schema.getField(entry.getKey()).schema())); } return result; } else if (input instanceof Collection && !((Collection) input).isEmpty()) { List<Object> values = new ArrayList<>(((Collection) input).size()); for (Object value: (Collection) input) { values.add(getAvroValue(value, schema.getElementType())); } return new GenericData.Array<Object>(schema, values); } else { return input; } }
Source:
protected void onCreate(Bundle savedInstanceState) { supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); super.onCreate(savedInstanceState); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } setTitle(getString(R.string.navdrawer_item_send_feedback)); setContentView(R.layout.report); if (savedInstanceState == null) { ObaRegion currentRegion = Application.get().getCurrentRegion(); if (showValidateRegionDialog(currentRegion)) { mRegionId = currentRegion.getId(); RegionValidateDialog rvd = new RegionValidateDialog(); rvd.show(getSupportFragmentManager(), ReportConstants.TAG_REGION_VALIDATE_DIALOG); } else { createIssueTypeListFragment(); } } setUpProgressBar(); }

Target:
protected void onCreate(Bundle savedInstanceState) { supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); super.onCreate(savedInstanceState); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } setTitle(getString(R.string.navdrawer_item_send_feedback)); setContentView(R.layout.report); if (savedInstanceState == null) { ObaRegion currentRegion = Application.get().getCurrentRegion(); if (showValidateRegionDialog(currentRegion)) { RegionValidateDialog rvd = new RegionValidateDialog(); rvd.show(getSupportFragmentManager(), ReportConstants.TAG_REGION_VALIDATE_DIALOG); } else { createIssueTypeListFragment(); } } setUpProgressBar(); }
Source:
static Set<String> getYarnApiAddresses(Configuration conf) { String emptyString = ""; String rmIdsConf = conf.get("yarn.resourcemanager.ha.rm-ids", emptyString); if (rmIdsConf.isEmpty()) { String yarnApiAddress = conf.get("yarn.resourcemanager.webapp.address", emptyString); return yarnApiAddress.isEmpty() ? Sets.newHashSet() : Sets.newHashSet(yarnApiAddress); } String[] allRmIds = rmIdsConf.split(","); return Arrays.stream(allRmIds) .map(rmId -> conf.get("yarn.resourcemanager.webapp.address." + rmId, emptyString)) .filter(address -> !address.isEmpty()) .collect(Collectors.toSet()); }

Target:
static Set<String> getYarnApiAddresses(Configuration conf) { String[] rmIds = conf.getStrings("yarn.resourcemanager.ha.rm-ids"); if (rmIds == null) { String yarnApiAddress = conf.get("yarn.resourcemanager.webapp.address"); return yarnApiAddress == null ? Sets.newHashSet() : Sets.newHashSet(yarnApiAddress); } return Arrays.stream(rmIds) .map(rmId -> conf.get("yarn.resourcemanager.webapp.address." + rmId)) .filter(Objects::nonNull) .collect(Collectors.toSet()); }
Source:
public LockResource(Lock lock, long tryMs, long sleepMs, long timeoutMs) throws InterruptedException, TimeoutException { mLock = lock; long deadlineMs = System.currentTimeMillis() + timeoutMs; boolean lockAcquired = false; while (System.currentTimeMillis() < deadlineMs) { if (mLock.tryLock(tryMs, TimeUnit.MILLISECONDS)) { lockAcquired = true; break; } else { long remainingWaitMs = deadlineMs = System.currentTimeMillis(); if (remainingWaitMs > 0) { Thread.sleep(Math.min(sleepMs, remainingWaitMs)); } } } if (!lockAcquired) { throw new TimeoutException( String.format("Failed to acquire the lock:%s, after %dms", mLock, timeoutMs)); } }

Target:
public LockResource(Lock lock, long tryMs, long sleepMs, long timeoutMs) throws InterruptedException, TimeoutException { mLock = lock; long deadlineMs = System.currentTimeMillis() + timeoutMs; boolean lockAcquired = false; while (System.currentTimeMillis() < deadlineMs) { if (mLock.tryLock(tryMs, TimeUnit.MILLISECONDS)) { lockAcquired = true; break; } else { long remainingWaitMs = deadlineMs - System.currentTimeMillis(); if (remainingWaitMs > 0) { Thread.sleep(Math.min(sleepMs, remainingWaitMs)); } } } if (!lockAcquired) { throw new TimeoutException(ExceptionMessage.STATE_LOCK_TIMED_OUT.getMessage(timeoutMs)); } }
Source:
private void testDownloadAction() { homePage.verifyDownloadResultButtonExists(feedbackSessionClosed.getCourseId(), feedbackSessionClosed.getSessionName()); ______TS("Typical case: download report"); AppUrl reportUrl = createUrl(Const.ActionURIs.INSTRUCTOR_FEEDBACK_RESULTS_DOWNLOAD) .withUserId("CHomeUiT.instructor.tmms") .withCourseId(feedbackSessionClosed.getCourseId()) .withSessionName(feedbackSessionClosed.getSessionName()); homePage.verifyDownloadLink(reportUrl); ______TS("Typical case: download report unsuccessfully"); reportUrl = createUrl(Const.ActionURIs.INSTRUCTOR_FEEDBACK_RESULTS_DOWNLOAD) .withUserId("CHomeUiT.instructor.tmms"); browser.driver.get(reportUrl.toAbsoluteString()); String afterReportDownloadUrl = browser.driver.getCurrentUrl(); assertFalse(reportUrl.toString().equals(afterReportDownloadUrl)); assertTrue("Expected url is InstructorHomePage or Unauthorised page, but is " + afterReportDownloadUrl, afterReportDownloadUrl.contains(Const.ActionURIs.INSTRUCTOR_HOME_PAGE) || afterReportDownloadUrl.contains(Const.ViewURIs.UNAUTHORIZED)); loginAsCommonInstructor(); }

Target:
private void testDownloadAction() throws Exception { homePage.verifyDownloadResultButtonExists(feedbackSessionClosed.getCourseId(), feedbackSessionClosed.getSessionName()); ______TS("Typical case: download report"); AppUrl reportUrl = createUrl(Const.ActionURIs.INSTRUCTOR_FEEDBACK_RESULTS_DOWNLOAD) .withUserId("CHomeUiT.instructor.tmms") .withCourseId(feedbackSessionClosed.getCourseId()) .withSessionName(feedbackSessionClosed.getSessionName()); homePage.verifyDownloadLink(reportUrl); ______TS("Typical case: download report unsuccessfully due to missing parameters"); reportUrl = createUrl(Const.ActionURIs.INSTRUCTOR_FEEDBACK_RESULTS_DOWNLOAD) .withUserId("CHomeUiT.instructor.tmms"); browser.driver.get(reportUrl.toAbsoluteString()); String afterReportDownloadUrl = browser.driver.getCurrentUrl(); assertFalse(reportUrl.toString().equals(afterReportDownloadUrl)); assertTrue("Expected url is Unauthorised page, but is " + afterReportDownloadUrl, afterReportDownloadUrl.contains(Const.ViewURIs.UNAUTHORIZED)); loginAsCommonInstructor(); }
Source:
private void assertScoreAndConstraintMatches(SolverFactory<Solution_> solverFactory, Solution_ bestSolution, String bestScoreLimitString) { assertThat(bestSolution).isNotNull(); InnerScoreDirectorFactory<Solution_> scoreDirectorFactory = (InnerScoreDirectorFactory<Solution_>) solverFactory .getScoreDirectorFactory(); Score bestScore = scoreDirectorFactory.getSolutionDescriptor().getScore(bestSolution); ScoreDefinition scoreDefinition = scoreDirectorFactory.getScoreDefinition(); Score bestScoreLimit = scoreDefinition.parseScore(bestScoreLimitString); assertThat(bestScore) .isGreaterThanOrEqualTo(bestScoreLimit) .as("The bestScore (" + bestScore + ") must be at least the bestScoreLimit (" + bestScoreLimit + ")."); try (ScoreDirector<Solution_> scoreDirector = scoreDirectorFactory.buildScoreDirector()) { scoreDirector.setWorkingSolution(bestSolution); Score score = scoreDirector.calculateScore(); assertThat(bestScore).isEqualTo(score); if (scoreDirector.isConstraintMatchEnabled()) { Collection<ConstraintMatchTotal> constraintMatchTotals = scoreDirector.getConstraintMatchTotals(); assertThat(constraintMatchTotals).isNotNull(); assertThat(constraintMatchTotals.stream() .map(ConstraintMatchTotal::getScore) .reduce(Score::add) .orElse(scoreDefinition.getZeroScore())).isEqualTo(score); assertThat(scoreDirector.getIndictmentMap()).isNotNull(); } } }

Target:
private void assertScoreAndConstraintMatches(SolverFactory<Solution_> solverFactory, Solution_ bestSolution, String bestScoreLimitString) { assertThat(bestSolution).isNotNull(); InnerScoreDirectorFactory<Solution_> scoreDirectorFactory = (InnerScoreDirectorFactory<Solution_>) solverFactory .getScoreDirectorFactory(); Score bestScore = scoreDirectorFactory.getSolutionDescriptor().getScore(bestSolution); ScoreDefinition scoreDefinition = scoreDirectorFactory.getScoreDefinition(); Score bestScoreLimit = scoreDefinition.parseScore(bestScoreLimitString); assertThat(bestScore.compareTo(bestScoreLimit)) .as("The bestScore (" + bestScore + ") must be at least the bestScoreLimit (" + bestScoreLimit + ").") .isGreaterThanOrEqualTo(0); try (ScoreDirector<Solution_> scoreDirector = scoreDirectorFactory.buildScoreDirector()) { scoreDirector.setWorkingSolution(bestSolution); Score score = scoreDirector.calculateScore(); assertThat(bestScore).isEqualTo(score); if (scoreDirector.isConstraintMatchEnabled()) { Collection<ConstraintMatchTotal> constraintMatchTotals = scoreDirector.getConstraintMatchTotals(); assertThat(constraintMatchTotals).isNotNull(); assertThat(constraintMatchTotals.stream() .map(ConstraintMatchTotal::getScore) .reduce(Score::add) .orElse(scoreDefinition.getZeroScore())).isEqualTo(score); assertThat(scoreDirector.getIndictmentMap()).isNotNull(); } } }
Source:
public static Double lineLocatePoint(@SqlType(GEOMETRY_TYPE_NAME) Slice lineSlice, @SqlType(GEOMETRY_TYPE_NAME) Slice pointSlice) { Geometry line = JtsGeometrySerde.deserialize(lineSlice); Geometry point = JtsGeometrySerde.deserialize(pointSlice); if (line.isEmpty() || point.isEmpty()) { return null; } GeometryType lineType = GeometryType.getForJtsGeometryType(line.getGeometryType()); if (lineType != GeometryType.LINE_STRING && lineType != GeometryType.MULTI_LINE_STRING) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("First argument to line_locate_point must be a LineString or a MultiLineString. Got: %s", line.getGeometryType())); } GeometryType pointType = GeometryType.getForJtsGeometryType(point.getGeometryType()); if (pointType != POINT) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("Second argument to line_locate_point must be a Point. Got: %s", point.getGeometryType())); } return new LengthIndexedLine(line).indexOf(point.getCoordinate()); }

Target:
public static Double lineLocatePoint(@SqlType(GEOMETRY_TYPE_NAME) Slice lineSlice, @SqlType(GEOMETRY_TYPE_NAME) Slice pointSlice) { Geometry line = JtsGeometrySerde.deserialize(lineSlice); Geometry point = JtsGeometrySerde.deserialize(pointSlice); if (line.isEmpty() || point.isEmpty()) { return null; } GeometryType lineType = GeometryType.getForJtsGeometryType(line.getGeometryType()); if (lineType != GeometryType.LINE_STRING && lineType != GeometryType.MULTI_LINE_STRING) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("First argument to line_locate_point must be a LineString or a MultiLineString. Got: %s", line.getGeometryType())); } GeometryType pointType = GeometryType.getForJtsGeometryType(point.getGeometryType()); if (pointType != GeometryType.POINT) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("Second argument to line_locate_point must be a Point. Got: %s", point.getGeometryType())); } return new LengthIndexedLine(line).indexOf(point.getCoordinate()); }
Source:
public Object[] getElements(Object inputElement) { List<IBrowserDescriptor> list = new ArrayList<IBrowserDescriptor>(); Iterator<IBrowserDescriptor> iterator = BrowserManager.getInstance().getWebBrowsers() .iterator(); while (iterator.hasNext()) { IBrowserDescriptor browser = iterator .next(); list.add(browser); } return list.toArray(); }

Target:
public Object[] getElements(Object inputElement) { List<IBrowserDescriptor> list = new ArrayList<>(); Iterator<IBrowserDescriptor> iterator = BrowserManager.getInstance().getWebBrowsers() .iterator(); while (iterator.hasNext()) { IBrowserDescriptor browser = iterator .next(); list.add(browser); } return list.toArray(); }
Source:
public void connect(String url) throws Exception { System.out.println("[SchedulerNodeClient] Connecting to scheduler at url " + url); CredData userCreds = decrypter.decrypt(); client.init(new ConnectionInfo(url, userCreds.getLogin(), userCreds.getPassword(), null, true)); System.out.println("[SchedulerNodeClient] Connected"); }

Target:
public void connect(String url) throws Exception { CredData userCreds = decrypter.decrypt(); client.init(new ConnectionInfo(url, userCreds.getLogin(), userCreds.getPassword(), null, true)); }