auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static Date parseDateString(String datetime) throws ParseException { Date result; try { result = new SimpleDateFormat(MarketoConstants.DATETIME_PATTERN_PARAM).parse(datetime); return result; } catch (ParseException e) { } try { result = new SimpleDateFormat(MarketoConstants.DATETIME_PATTERN_PARAM_ALT).parse(datetime); return result; } catch (ParseException e) { } try { result = new SimpleDateFormat(MarketoConstants.DATETIME_PATTERN_PARAM_UTC).parse(datetime); return result; } catch (ParseException e) { } try { result = new SimpleDateFormat(MarketoConstants.DATETIME_PATTERN_REST).parse(datetime); return result; } catch (ParseException e) { } try { result = new SimpleDateFormat(MarketoConstants.DATETIME_PATTERN_SOAP).parse(datetime); return result; } catch (ParseException e) { } throw new ParseException(datetime + " don't use a pattern allowed.", 0); }

Target:
public static Date parseDateString(String datetime) throws ParseException { Date result = null; for (SimpleDateFormat sdf : allowedDateFormats) { try { result = sdf.parse(datetime); break; } catch (ParseException e) { } } if (result == null) { throw new ParseException(datetime + " don't use a pattern allowed.", 0); } return result; }
Source:
public static String screenshot(String screenshotPath) { if (!Configuration.screenshots) { return ""; } if (Configuration.savePageSource) { if (screenshotPath == null || screenshotPath.isEmpty()) { return "\nScreenshot: " + screenshotPath; } return "\nScreenshot: " + screenshotPath + "\nHtml: " + screenshotPath.substring(0, screenshotPath.lastIndexOf('.')) + ".html"; } else { return "\nScreenshot: " + screenshotPath; } }

Target:
public static String screenshot(String screenshotPath) { if (!Configuration.screenshots) { return ""; } if (screenshotPath == null || screenshotPath.isEmpty()) { return "\nScreenshot: " + screenshotPath; } if (Configuration.savePageSource) { String htmlFilePath = getHtmlFilePath(screenshotPath); return "\nScreenshot: " + screenshotPath + "\nPage source: " + htmlFilePath; } else { return "\nScreenshot: " + screenshotPath; } }
Source:
public void createAlreadyExisting() throws Exception { ObjectMapper mapper = new ObjectMapper(); BitstreamFormatRest bitstreamFormatRest = this.createRandomMockBitstreamRest(true); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(post("/api/core/bitstreamformats/") .content(mapper.writeValueAsBytes(bitstreamFormatRest)).contentType(contentType)) .andExpect(status().isCreated()); getClient(token).perform(post("/api/core/bitstreamformats/") .content(mapper.writeValueAsBytes(bitstreamFormatRest)).contentType(contentType)) .andExpect(status().isInternalServerError()); }

Target:
public void createAlreadyExisting() throws Exception { ObjectMapper mapper = new ObjectMapper(); BitstreamFormatRest bitstreamFormatRest = this.createRandomMockBitstreamRest(true); AtomicReference<Integer> idRef = new AtomicReference<>(); try { String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(post("/api/core/bitstreamformats/") .content(mapper.writeValueAsBytes(bitstreamFormatRest)) .contentType(contentType)) .andExpect(status().isCreated()) .andDo(result -> idRef .set(read(result.getResponse().getContentAsString(), "$.id"))); getClient(token).perform(post("/api/core/bitstreamformats/") .content(mapper.writeValueAsBytes(bitstreamFormatRest)) .contentType(contentType)) .andExpect(status().isInternalServerError()); getClient().perform(get("/api/core/bitstreamformats/")) .andExpect(status().isOk()) .andExpect(jsonPath("$.page.totalElements", is(DEFAULT_AMOUNT_FORMATS + 1))); } finally { BitstreamFormatBuilder.deleteBitstreamFormat(idRef.get()); } }
Source:
public JoinFilterPreAnalysis computeJoinFilterPreAnalysisIfAbsent( Filter filter, List<JoinableClause> clauses, VirtualColumns virtualColumns ) { synchronized (analyses) { if (filter != null) { filter.hashCode(); } } JoinFilterPreAnalysisGroupKey key = new JoinFilterPreAnalysisGroupKey(filter, clauses, virtualColumns); return analyses.computeIfAbsent( key, (groupKey) -> { return JoinFilterAnalyzer.computeJoinFilterPreAnalysis( JoinableClauses.fromList(clauses), virtualColumns, filter, joinFilterRewriteConfig ); } ); }

Target:
public JoinFilterPreAnalysis computeJoinFilterPreAnalysisIfAbsent( Filter filter, List<JoinableClause> clauses, VirtualColumns virtualColumns ) { JoinFilterPreAnalysisGroupKey key = new JoinFilterPreAnalysisGroupKey(filter, clauses, virtualColumns); return analyses.computeIfAbsent( key, (groupKey) -> { return JoinFilterAnalyzer.computeJoinFilterPreAnalysis( JoinableClauses.fromList(clauses), virtualColumns, filter, joinFilterRewriteConfig ); } ); }
Source:
public Iterator<Chatter[]> getChatter(String fileJson) { Collection<Chatter[]> chattersArray = new ArrayList<Chatter[]>(); try { parser = new JSONParser(); Object jsonObject = parser.parse(new FileReader("src/test/resources/" + fileJson)); JSONArray jsonArray = (JSONArray) jsonObject; ObjectMapper objectMapper = new ObjectMapper(); List<Chatter> navigation = objectMapper.readValue(jsonArray.toJSONString(), objectMapper.getTypeFactory().constructCollectionType( List.class, Chatter.class)); for (Chatter chatter : navigation) chattersArray.add(new Chatter[]{chatter}); } catch (FileNotFoundException e) { LoggerManager.getInstance().addErrorLog(this.getClass().getName(), "File not found for chatter - Json file:", e);; } catch (IOException e) { LoggerManager.getInstance().addErrorLog(this.getClass().getName(), "Error on data for Chatter from Json file:", e); } catch (ParseException e) { LoggerManager.getInstance().addErrorLog(this.getClass().getName(), "Error on data for Chatter:", e); } return chattersArray.iterator(); }

Target:
public Iterator<Chatter[]> getChatter(String fileJson) { Collection<Chatter[]> chattersArray = new ArrayList<Chatter[]>(); try { parser = new JSONParser(); Object jsonObject = parser.parse(new FileReader("src/test/resources/" + fileJson)); JSONArray jsonArray = (JSONArray) jsonObject; ObjectMapper objectMapper = new ObjectMapper(); List<Chatter> navigation = objectMapper.readValue(jsonArray.toJSONString(), objectMapper.getTypeFactory().constructCollectionType( List.class, Chatter.class)); for (Chatter chatter : navigation) chattersArray.add(new Chatter[]{chatter}); } catch (FileNotFoundException e) { LOGGER.addErrorLog("File not found for chatter - Json file:", e);; } catch (IOException e) { LOGGER.addErrorLog("Error on data for Chatter from Json file:", e); } catch (ParseException e) { LOGGER.addErrorLog( "Error on data for Chatter:", e); } return chattersArray.iterator(); }
Source:
public Redirect getRedirect(String siteId) { if (StringUtils.isNotBlank(siteId)) { Redirect redirect = new Redirect(); PortalNode node; String trimmedPath = ""; do{ node = portalHierarchyService.getNodeByUrl(siteId); if(node == null){ int index = siteId.lastIndexOf(PortalHierarchyService.SEPARATOR); if(index > 0){ String firstPart = siteId.substring(0, index); String tempString = PortalHierarchyService.SEPARATOR + siteId.substring(index + 1); trimmedPath = (StringUtils.isBlank(trimmedPath)) ? tempString : (tempString + trimmedPath) ; siteId = firstPart; } } else{ break; } }while(StringUtils.countMatches(siteId, PortalHierarchyService.SEPARATOR) > 1); if (node instanceof PortalNodeRedirect) { String redirectUrl = ((PortalNodeRedirect)node).getUrl(); boolean appendPath = ((PortalNodeRedirect)node).isAppendPath(); redirect.setAppendPath(appendPath); if(appendPath && StringUtils.isNotBlank(trimmedPath)){ redirect.setUrl(redirectUrl + trimmedPath); } else{ redirect.setUrl(redirectUrl); } return redirect; } Matcher matcher = trimTailingSeparators.matcher(siteId); if (matcher.matches()) { redirect.setUrl(serverConfigurationService.getString("portalPath")+ "/"+ "site"+ "/"+ matcher.group(1)); return redirect; } } return null; }

Target:
public Redirect getRedirect(String siteId) { if (StringUtils.isNotBlank(siteId)) { Redirect redirect = new Redirect(); Matcher matcher = trimTailingSeparators.matcher(siteId); if (matcher.matches()) { redirect.setUrl(serverConfigurationService.getString("portalPath")+ "/"+ "site"+ "/"+ matcher.group(1)); return redirect; } PortalNode node = null; String trimmedPath = ""; int length = StringUtils.countMatches(siteId, PortalHierarchyService.SEPARATOR); for(int i = length; i >= 1 ; i--){ node = portalHierarchyService.getNodeByUrl(siteId); if(node == null){ int index = siteId.lastIndexOf(PortalHierarchyService.SEPARATOR); if(index > 0){ String firstPart = siteId.substring(0, index); String tempString = PortalHierarchyService.SEPARATOR + siteId.substring(index + 1); trimmedPath = (StringUtils.isBlank(trimmedPath)) ? tempString : (tempString + trimmedPath) ; siteId = firstPart; } } else{ break; } } if (node instanceof PortalNodeRedirect) { String redirectUrl = ((PortalNodeRedirect)node).getUrl(); boolean appendPath = ((PortalNodeRedirect)node).isAppendPath(); redirect.setAppendPath(appendPath); if(appendPath && StringUtils.isNotBlank(trimmedPath)){ redirect.setUrl(redirectUrl + trimmedPath); } else{ redirect.setUrl(redirectUrl); } return redirect; } } return null; }
Source:
public static void verifyJvmRequirements() { String vendor = StandardSystemProperty.JAVA_VENDOR.value(); if (!JVM_VENDORS.contains(vendor)) { failRequirement("Presto requires an Oracle or OpenJDK JVM (found %s)", vendor); } verifyJavaVersion(); String dataModel = System.getProperty("sun.arch.data.model"); if (!"64".equals(dataModel)) { failRequirement("Presto requires a 64-bit JVM (found %s)", dataModel); } String osName = StandardSystemProperty.OS_NAME.value(); String osArch = StandardSystemProperty.OS_ARCH.value(); if ("Linux".equals(osName)) { if (!"amd64".equals(osArch)) { failRequirement("Presto requires x86-64 or amd64 on Linux (found %s)", osArch); } } else if ("Mac OS X".equals(osName)) { if (!"x86_64".equals(osArch)) { failRequirement("Presto requires x86_64 on Mac OS X (found %s)", osArch); } } else { failRequirement("Presto requires Linux or Mac OS X (found %s)", osName); } if (!ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) { failRequirement("Presto requires a little endian platform (found %s)", ByteOrder.nativeOrder()); } verifyUsingG1Gc(); verifyFileDescriptor(); verifySlice(); }

Target:
public static void verifyJvmRequirements() { String runtimeName = System.getProperty("java.runtime.name"); String vendor = StandardSystemProperty.JAVA_VENDOR.value(); if (!"Java(TM) SE Runtime Environment".equals(runtimeName)) { warnRequirement("Presto is running on an unsupported JVM runtime " + "(found %s) - only the Oracle(TM) runtime is supported", runtimeName); } else if (!"Oracle Corporation".equals(vendor)) { warnRequirement("Presto is running on a JVM from an unsupported " + "vendor (found %s) - the only supported vendor is " + "Oracle(TM)", vendor); } verifyJavaVersion(); String dataModel = System.getProperty("sun.arch.data.model"); if (!"64".equals(dataModel)) { failRequirement("Presto requires a 64-bit JVM (found %s)", dataModel); } String osName = StandardSystemProperty.OS_NAME.value(); String osArch = StandardSystemProperty.OS_ARCH.value(); if ("Linux".equals(osName)) { if (!"amd64".equals(osArch)) { failRequirement("Presto requires x86-64 or amd64 on Linux (found %s)", osArch); } } else if ("Mac OS X".equals(osName)) { if (!"x86_64".equals(osArch)) { failRequirement("Presto requires x86_64 on Mac OS X (found %s)", osArch); } } else { failRequirement("Presto requires Linux or Mac OS X (found %s)", osName); } if (!ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) { failRequirement("Presto requires a little endian platform (found %s)", ByteOrder.nativeOrder()); } verifyUsingG1Gc(); verifyFileDescriptor(); verifySlice(); }
Source:
private List<Thread> getThreadsWithLatchForFile(final CountDownLatch countDownLatch, int threadsCount) { List<Thread> result = new ArrayList<>(); String ballast = "" + System.currentTimeMillis(); for (int i = 0; i < threadsCount; i++) { final int curThreadNo = i; final File tmp = (i % 3 == 0 || i % 3 == 2) ? new File(tempDir.toAbsolutePath().toString() + "/cuce" + ballast + i + "/tmpFile.tmp") : new File(tempDir.toAbsolutePath().toString() + "/cuce" + ballast + (i - 1) + "/tmpFile.tmp"); tmpFiles.add(tmp); result.add(new Thread(() -> { try { countDownLatch.await(); URLOutputStream urlOutputStream = new URLOutputStream(tmp.toURI().toURL()); urlOutputStream.close(); } catch (IOException e) { threadErrors.add("Thread" + curThreadNo + ": parent dir not created. " + e.getMessage()); } catch (InterruptedException e) { threadErrors.add("Thread" + curThreadNo + ": not started on time. " + e.getMessage()); } })); } return result; }

Target:
private List<Thread> getThreadsWithLatchForFile(final CountDownLatch countDownLatch, int threadsCount) { List<Thread> result = new ArrayList<>(); String ballast = "" + System.currentTimeMillis(); for (int i = 0; i < threadsCount; i++) { final int curThreadNo = i; final File tmp = (i % 3 == 0 || i % 3 == 2) ? new File(tempDir.toAbsolutePath().toString() + "/cuce" + ballast + i + "/tmpFile.tmp") : new File(tempDir.toAbsolutePath().toString() + "/cuce" + ballast + (i - 1) + "/tmpFile.tmp"); tmpFiles.add(tmp); result.add(new Thread(() -> { try { countDownLatch.await(); try (URLOutputStream urlOutputStream = new URLOutputStream(tmp.toURI().toURL())) { } } catch (IOException e) { threadErrors.add("Thread" + curThreadNo + ": parent dir not created. " + e.getMessage()); } catch (InterruptedException e) { threadErrors.add("Thread" + curThreadNo + ": not started on time. " + e.getMessage()); } })); } return result; }
Source:
public Future<Optional<String>> sendPaymentConfirmedEmail(ChargeEntity chargeEntity, GatewayAccountEntity gatewayAccountEntity) { return sendEmail(EmailNotificationType.PAYMENT_CONFIRMED, chargeEntity, gatewayAccountEntity, buildConfirmationEmailPersonalisationFrom(chargeEntity)); }

Target:
public Future<Optional<String>> sendPaymentConfirmedEmail(ChargeEntity chargeEntity, GatewayAccountEntity gatewayAccountEntity) { return sendEmail(EmailNotificationType.PAYMENT_CONFIRMED, Charge.from(chargeEntity), gatewayAccountEntity, buildConfirmationEmailPersonalisationFrom(chargeEntity)); }
Source:
public void close() { for (StreamReader structField : structFields) { structField.close(); } }

Target:
public void close() { try (Closer closer = Closer.create()) { for (StreamReader structField : structFields) { closer.register(() -> structField.close()); } } catch (IOException e) { throw new UncheckedIOException(e); } }
Source:
public PropertyCursor( Read read ) { super( -1 ); this.read = read; }

Target:
public PropertyCursor( Read read ) { super( NO_ID ); this.read = read; }
Source:
private void handleDeleteFile(final DeleteFile deleteFile) { final String messageId = deleteFile.getId(); log.debug("Received file delete message in job {}", messageId, this.jobId); if (this.waitingForBeginMessage) { log.debug( "Haven't received a message. Ignoring file delete message {}.", BeginSync.class.getCanonicalName(), messageId ); this.sendResetMessageIfNecessary(); } else { try { this.jobFileService.deleteJobFile(this.jobId, deleteFile.getPath()); synchronized (this.messagesLock) { this.successfulSyncIds.add(messageId); } } catch (final Exception e) { log.error( "Deleting for job failed due to {}", deleteFile.getPath(), this.jobId, e.getMessage(), e ); synchronized (this.messagesLock) { this.failedSyncIds.add(messageId); } } } this.checkIfShouldSendAck(); }

Target:
private void handleDeleteFile(final DeleteFile deleteFile) { final String messageId = deleteFile.getId(); log.debug("Received file delete message in job {}", messageId, this.jobId); if (this.waitingForBeginMessage) { log.debug( "Haven't received a message. Ignoring file delete message {}.", BeginSync.class.getCanonicalName(), messageId ); this.sendResetMessageIfNecessary(); } else { try { this.jobFileService.deleteJobFile(this.jobId, deleteFile.getPath()); synchronized (this.messagesLock) { this.requestResults.add(this.createRequestResult(messageId, true)); } } catch (final Exception e) { log.error( "Deleting for job failed due to {}", deleteFile.getPath(), this.jobId, e.getMessage(), e ); synchronized (this.messagesLock) { this.requestResults.add(this.createRequestResult(messageId, false)); } } } this.checkIfShouldSendAck(); }
Source:
private static CamelReactiveStreamsService resolveReactiveStreamsService(CamelContext context, String serviceName) { CamelReactiveStreamsService service = null; if (serviceName != null) { service = context.getRegistry().lookupByNameAndType(serviceName, CamelReactiveStreamsService.class); } if (service == null) { LOG.info("Using default reactive stream service"); service = new CamelReactiveStreamsServiceImpl(); } return service; }

Target:
private static CamelReactiveStreamsService resolveReactiveStreamsService(CamelContext context, String serviceName) { CamelReactiveStreamsService service = null; if (serviceName != null) { service = context.getRegistry().lookupByNameAndType(serviceName, CamelReactiveStreamsService.class); if (service == null) { service = resolveServiceUsingFactory(context, serviceName); } } else { Set<CamelReactiveStreamsService> set = context.getRegistry().findByType(CamelReactiveStreamsService.class); if (set.size() == 1) { service = set.iterator().next(); } if (service == null) { LOG.info("Using default reactive stream service"); service = resolveServiceUsingFactory(context, null); } } return service; }
Source:
public void dialogOnAddButtonPressed(String time, String date, String reading, String type, String notes) { if (validateDate(date) && validateTime(time) && validateGlucose(reading) && validateType(type)) { Date finalDateTime = getReadingTime(); Number number = parseReading(reading); if (number == null) { activity.showErrorMessage(); return; } boolean isReadingAdded; if ("mg/dL".equals(getUnitMeasuerement())) { int finalReading = number.intValue(); GlucoseReading gReading = new GlucoseReading(finalReading, type, finalDateTime, notes); isReadingAdded = dB.addGlucoseReading(gReading); } else { converter = new GlucosioConverter(); int convertedReading = converter.glucoseToMgDl(number.doubleValue()); GlucoseReading gReading = new GlucoseReading(convertedReading, type, finalDateTime, notes); isReadingAdded = dB.addGlucoseReading(gReading); } if (!isReadingAdded) { activity.showDuplicateErrorMessage(); } else { activity.finishActivity(); } } else { activity.showErrorMessage(); } }

Target:
public void dialogOnAddButtonPressed(String time, String date, String reading, String type, String notes) { dialogOnAddButtonPressed(time, date, reading, type, notes, UNKNOWN_ID); }
Source:
private void isAreaLoadedInject(int xStart, int yStart, int zStart, int xEnd, int yEnd, int zEnd, boolean allowEmpty, @Nonnull CallbackInfoReturnable<Boolean> cbi) { if (!this.isCubicWorld()) { return; } boolean ret = (this.isRemote() && allowEmpty) || this.testForCubes( xStart, yStart, zStart, xEnd, yEnd, zEnd, Objects::nonNull, Requirement.GET_WATCHED); cbi.cancel(); cbi.setReturnValue(ret); }

Target:
private void isAreaLoadedInject(int xStart, int yStart, int zStart, int xEnd, int yEnd, int zEnd, boolean allowEmpty, @Nonnull CallbackInfoReturnable<Boolean> cbi) { if (!this.isCubicWorld()) { return; } boolean ret = (this.isRemote() && allowEmpty) || this.testForCubes( xStart, yStart, zStart, xEnd, yEnd, zEnd, Objects::nonNull); cbi.cancel(); cbi.setReturnValue(ret); }
Source:
public void testFindTaskEventsForNotExistingTask() { try { taskClient.findTaskEvents(-9999l, 0, 10); fail("KieServicesException should be thrown complaining about task not found."); } catch (KieServicesException e) { KieServerAssert.assertResultContainsString(e.getMessage(), "No task found with id"); } }

Target:
public void testFindTaskEventsForNotExistingTask() { try { taskClient.findTaskEvents(-9999l, 0, 10); fail("KieServicesException should be thrown complaining about task not found."); } catch (KieServicesException e) { KieServerAssert.assertResultContainsString(e.getMessage(), "No task found with id"); if(configuration.isRest()) { KieServicesHttpException httpEx = (KieServicesHttpException) e; assertEquals("Exception has wrong HTTP Response code.", Integer.valueOf(404), httpEx.getHttpCode()); } } }
Source:
public File getDatabasePath(String name) { File dir; if (name.charAt(0) == File.separatorChar) { String dirPath = name.substring(0, name.lastIndexOf(File.separatorChar)); dir = new File(dirPath); name = name.substring(name.lastIndexOf(File.separatorChar)); } else { DATABASE_DIR.mkdirs(); dir = DATABASE_DIR; } return new File(dir, name); }

Target:
public File getDatabasePath(String name) { File file = new File(name); if (file.isAbsolute()) { return file; } else { DATABASE_DIR.mkdirs(); return new File(DATABASE_DIR, name); } }
Source:
private Function<Cursor, Result<TopNResultValue>> getMapFn(TopNQuery query, final StorageAdapter adapter) { final Capabilities capabilities = adapter.getCapabilities(); final String dimension = query.getDimensionSpec().getDimension(); final ColumnCapabilities columnCapabilities = adapter.getColumnCapabilities(dimension); final int cardinality = adapter.getDimensionCardinality(dimension); int numBytesPerRecord = 0; for (AggregatorFactory aggregatorFactory : query.getAggregatorSpecs()) { numBytesPerRecord += aggregatorFactory.getMaxIntermediateSize(); } final TopNAlgorithmSelector selector = new TopNAlgorithmSelector(cardinality, numBytesPerRecord); query.initTopNAlgorithmSelector(selector); final TopNAlgorithm topNAlgorithm; if ( selector.isHasExtractionFn() && dimension.equals(Column.TIME_COLUMN_NAME) ) { topNAlgorithm = new TimeExtractionTopNAlgorithm(capabilities, query); } else if (selector.isHasExtractionFn()) { topNAlgorithm = new DimExtractionTopNAlgorithm(capabilities, query); } else if (selector.isAggregateAllMetrics()) { topNAlgorithm = new PooledTopNAlgorithm(capabilities, query, bufferPool); } else if (selector.isAggregateTopNMetricFirst() || query.getContextBoolean("doAggregateTopNMetricFirst", false)) { topNAlgorithm = new AggregateTopNMetricFirstAlgorithm(capabilities, query, bufferPool); } else { topNAlgorithm = new PooledTopNAlgorithm(capabilities, query, bufferPool); } return new TopNMapFn(query, topNAlgorithm); }

Target:
private Function<Cursor, Result<TopNResultValue>> getMapFn(TopNQuery query, final StorageAdapter adapter) { final Capabilities capabilities = adapter.getCapabilities(); final String dimension = query.getDimensionSpec().getDimension(); final int cardinality = adapter.getDimensionCardinality(dimension); int numBytesPerRecord = 0; for (AggregatorFactory aggregatorFactory : query.getAggregatorSpecs()) { numBytesPerRecord += aggregatorFactory.getMaxIntermediateSize(); } final TopNAlgorithmSelector selector = new TopNAlgorithmSelector(cardinality, numBytesPerRecord); query.initTopNAlgorithmSelector(selector); final TopNAlgorithm topNAlgorithm; if ( selector.isHasExtractionFn() && dimension.equals(Column.TIME_COLUMN_NAME) ) { topNAlgorithm = new TimeExtractionTopNAlgorithm(capabilities, query); } else if (selector.isHasExtractionFn()) { topNAlgorithm = new DimExtractionTopNAlgorithm(capabilities, query); } else if (selector.isAggregateAllMetrics()) { topNAlgorithm = new PooledTopNAlgorithm(capabilities, query, bufferPool); } else if (selector.isAggregateTopNMetricFirst() || query.getContextBoolean("doAggregateTopNMetricFirst", false)) { topNAlgorithm = new AggregateTopNMetricFirstAlgorithm(capabilities, query, bufferPool); } else { topNAlgorithm = new PooledTopNAlgorithm(capabilities, query, bufferPool); } return new TopNMapFn(query, topNAlgorithm); }
Source:
public void update(Observable o, Object arg) { final String arg1 = OoyalaNotification.getNameOrUnknown(arg); if (arg1.equals(OoyalaPlayer.TIME_CHANGED_NOTIFICATION_NAME)) { if(TAG.toString().equalsIgnoreCase("class com.ooyala.sample.players.ProgrammaticVolumePlayerActivity")) { player.setVolume(player.getVolume() + .025f); return; } return; } String text = "Notification Received: " + arg1 + " - state: " + player.getState(); Log.d(TAG, text); if (writePermission) { Log.d(TAG, "Writing log to SD card"); log.writeToSdcardLog(text); } }

Target:
public void update(Observable o, Object arg) { final String arg1 = OoyalaNotification.getNameOrUnknown(arg); if (arg1.equals(OoyalaPlayer.TIME_CHANGED_NOTIFICATION_NAME)) { if(TAG.equalsIgnoreCase("class com.ooyala.sample.players.ProgrammaticVolumePlayerActivity")) { player.setVolume(player.getVolume() + .025f); return; } return; } String text = "Notification Received: " + arg1 + " - state: " + player.getState(); Log.d(TAG, text); if (writePermission) { Log.d(TAG, "Writing log to SD card"); log.writeToSdcardLog(text); } }
Source:
private static File getConfigDirectory() throws Exception { File dir = Paths.get(LOADER_RESOURCES_DIR.toURI()).toFile(); if (!dir.exists()) { fail("Invalid setup parameter 'target', the directory does not exist"); } return dir; }

Target:
private static File getConfigDirectory() throws Exception { File dir = Paths.get(LOADER_RESOURCES_DIR.toURI()).toFile(); if (!dir.exists()) { fail( format( "Invalid setup parameter 'target', the directory [%s] does not exist", dir.getAbsolutePath())); } return dir; }
Source:
public void run() { try { while (_running) { Frame frame = _frameHandler.readFrame(); if (frame != null) { _missedHeartbeats = 0; if (frame.type == AMQP.FRAME_HEARTBEAT) { } else { if (frame.channel == 0) { _channel0.handleFrame(frame); } else { if (isOpen()) { ChannelManager cm = _channelManager; if (cm != null) { ChannelN channel; try { channel = cm.getChannel(frame.channel); } catch(UnknownChannelException e) { LOGGER.info("Channel is unknown, ignoring frame", frame.channel); continue; } channel.handleFrame(frame); } } } } } else { handleSocketTimeout(); } } } catch (EOFException ex) { if (!_brokerInitiatedShutdown) shutdown(null, false, ex, true); } catch (Throwable ex) { _exceptionHandler.handleUnexpectedConnectionDriverException(AMQConnection.this, ex); shutdown(null, false, ex, true); } finally { _frameHandler.close(); _appContinuation.set(null); notifyListeners(); notifyRecoveryCanBeginListeners(); } }

Target:
public void run() { try { while (_running) { Frame frame = _frameHandler.readFrame(); if (frame != null) { _missedHeartbeats = 0; if (frame.type == AMQP.FRAME_HEARTBEAT) { } else { if (frame.channel == 0) { _channel0.handleFrame(frame); } else { if (isOpen()) { ChannelManager cm = _channelManager; if (cm != null) { ChannelN channel; try { channel = cm.getChannel(frame.channel); } catch(UnknownChannelException e) { LOGGER.info("Received a frame on an unknown channel, ignoring it"); continue; } channel.handleFrame(frame); } } } } } else { handleSocketTimeout(); } } } catch (EOFException ex) { if (!_brokerInitiatedShutdown) shutdown(null, false, ex, true); } catch (Throwable ex) { _exceptionHandler.handleUnexpectedConnectionDriverException(AMQConnection.this, ex); shutdown(null, false, ex, true); } finally { _frameHandler.close(); _appContinuation.set(null); notifyListeners(); notifyRecoveryCanBeginListeners(); } }
Source:
public java.io.File cache(IFileStore source, IProgressMonitor monitor) throws CoreException { try { SubMonitor subMonitor = SubMonitor.convert(monitor, NLS.bind(Messages.copying, toString()), 100); IFileInfo myInfo = source.fetchInfo(EFS.NONE, subMonitor.newChild(25)); if (!myInfo.exists()) return new File(cacheDir, "Non-Existent-" + System.currentTimeMillis()); File result; if (myInfo.isDirectory()) { result = getUniqueDirectory(cacheDir, false); } else { result = File.createTempFile(source.getFileSystem().getScheme(), "efs", cacheDir); } subMonitor.worked(25); IFileStore resultStore = new LocalFile(result); source.copy(resultStore, EFS.OVERWRITE, subMonitor.newChild(25)); result.deleteOnExit(); return result; } catch (IOException e) { Policy.error(EFS.ERROR_WRITE, NLS.bind(Messages.couldNotWrite, toString())); return null; } }

Target:
public java.io.File cache(IFileStore source, IProgressMonitor monitor) throws CoreException { try { SubMonitor subMonitor = SubMonitor.convert(monitor, NLS.bind(Messages.copying, toString()), 3); IFileInfo myInfo = source.fetchInfo(EFS.NONE, subMonitor.newChild(1)); if (!myInfo.exists()) return new File(cacheDir, "Non-Existent-" + System.currentTimeMillis()); File result; if (myInfo.isDirectory()) { result = getUniqueDirectory(cacheDir, false); } else { result = File.createTempFile(source.getFileSystem().getScheme(), "efs", cacheDir); } subMonitor.worked(1); IFileStore resultStore = new LocalFile(result); source.copy(resultStore, EFS.OVERWRITE, subMonitor.newChild(1)); result.deleteOnExit(); return result; } catch (IOException e) { Policy.error(EFS.ERROR_WRITE, NLS.bind(Messages.couldNotWrite, toString())); return null; } }
Source:
public void testGenerate() throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, URISyntaxException, JSONException { Assert.assertNotNull("CrudResource was not injected by the container", cutCrudResource); String metadata = readFile("generator-md.json"); EntityMetadata em = RestConfiguration.getFactory().getJSONParser().parseEntityMetadata(JsonUtils.json(metadata)); RestConfiguration.getFactory().getMetadata().createNewMetadata(em); String result=cutCrudResource.generate("generate","1.0.0","number",1).getEntity().toString(); System.out.println("Generated:"+result); JSONAssert.assertEquals("{\"processed\":[\"50000000\"]}",result,false); result=cutCrudResource.generate("generate","1.0.0","number",3).getEntity().toString(); System.out.println("Generated:"+result); JSONAssert.assertEquals("{\"processed\":[\"50000001\",\"50000002\",\"50000003\"]}",result,false); }

Target:
public void testGenerate() throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, URISyntaxException, JSONException { Assert.assertNotNull("CrudResource was not injected by the container", cutCrudResource); String metadata = readFile("generator-md.json"); EntityMetadata em = RestConfiguration.getFactory().getJSONParser().parseEntityMetadata(JsonUtils.json(metadata)); RestConfiguration.getFactory().getMetadata().createNewMetadata(em); String result=cutCrudResource.generate("generate","1.0.0","number",1).getEntity().toString(); System.out.println("Generated:"+result); JSONAssert.assertEquals("{\"processed\":[\"50000000\"]}",result,false); result=cutCrudResource.generate("generate","number",3).getEntity().toString(); System.out.println("Generated:"+result); JSONAssert.assertEquals("{\"processed\":[\"50000001\",\"50000002\",\"50000003\"]}",result,false); }
Source:
public ITmfTimestamp readEnd() { try { Long pos = fFile.length() - 1; while (pos > 0) { while (pos > 0) { fFile.seek(pos - 1); if (fFile.read() == '\n') { break; } pos--; } ITmfLocation location = new TmfLongLocation(pos); TmfContext context = new TmfContext(location, ITmfContext.UNKNOWN_RANK); CustomTxtEvent event = parseEvent(context); if (event != null) { return event.getTimestamp(); } pos--; } } catch (IOException e) { return null; } return null; }

Target:
public synchronized ITmfTimestamp readEnd() { try { Long pos = fFile.length() - 1; while (pos > 0) { while (pos > 0) { fFile.seek(pos - 1); if (fFile.read() == '\n') { break; } pos--; } ITmfLocation location = new TmfLongLocation(pos); ITmfContext context = seekEvent(location); ITmfEvent event = parseEvent(context); context.dispose(); if (event != null) { return event.getTimestamp(); } pos--; } } catch (IOException e) { return null; } return null; }
Source:
public static Thread pipe(InputStream in, OutputStream out) { Runnable run = () -> { try (in; out) { IOUtils.copy(in, out); out.flush(); } catch (IOException e) { throw new RuntimeException(e); } }; Thread thread = new Thread(run, "Nuxeo-pipe-" + PIPE_COUNT.incrementAndGet()); thread.setDaemon(true); thread.start(); return thread; }

Target:
public static Thread pipe(InputStream in, OutputStream out) { Runnable run = () -> { try (in; out) { IOUtils.copy(in, out); out.flush(); } catch (IOException e) { throw new RuntimeServiceException(e); } }; Thread thread = new Thread(run, "Nuxeo-pipe-" + PIPE_COUNT.incrementAndGet()); thread.setDaemon(true); thread.start(); return thread; }
Source:
public Boolean isSHREnabled(){ boolean enableSHR = true; try { MuzimaSetting muzimaSHRStatus = getSettingByProperty(SHR_STATUS_SETTING); enableSHR = muzimaSHRStatus.getValueBoolean(); } catch (MuzimaSettingFetchException e){ Log.e(getClass().getSimpleName(), "Could not fetch requireMedicalRecordNumber setting. ", e); } return enableSHR; }

Target:
public Boolean isSHREnabled(){ boolean enableSHR = false; try { MuzimaSetting muzimaSHRStatus = getSettingByProperty(SHR_STATUS_SETTING); enableSHR = muzimaSHRStatus.getValueBoolean(); } catch (MuzimaSettingFetchException e){ Log.e(getClass().getSimpleName(), "Could not fetch requireMedicalRecordNumber setting. ", e); } return enableSHR; }
Source:
public static Iterable<Object[]> data() { Field[] fields = Look.class.getDeclaredFields(); ArrayList<Object[]> parameterList = new ArrayList<>(); for (Field field : fields) { if (!field.getName().equals("scheduler")) { parameterList.add(new Object[] {field.getName(), field}); } } return parameterList; }

Target:
public static Iterable<Object[]> data() { Field[] fields = Look.class.getDeclaredFields(); ArrayList<Object[]> parameterList = new ArrayList<>(); for (Field field : fields) { if (!field.getName().equals("scheduler") && !field.getName().startsWith("$")) { parameterList.add(new Object[] {field.getName(), field}); } } return parameterList; }
Source:
public void bakeNewCake(CakeInfo cakeInfo) throws CakeBakingException { List<CakeTopping> allToppings = getAvailableToppingEntities(); List<CakeTopping> matchingToppings = allToppings.stream().filter(t -> t.getName().equals(cakeInfo.cakeToppingInfo.name)) .collect(Collectors.toList()); if (matchingToppings.isEmpty()) { throw new CakeBakingException(String.format("Topping %s is not available", cakeInfo.cakeToppingInfo.name)); } List<CakeLayer> allLayers = getAvailableLayerEntities(); Set<CakeLayer> foundLayers = new HashSet<>(); for (CakeLayerInfo info : cakeInfo.cakeLayerInfos) { Optional<CakeLayer> found = allLayers.stream().filter(layer -> layer.getName().equals(info.name)).findFirst(); if (!found.isPresent()) { throw new CakeBakingException(String.format("Layer %s is not available", info.name)); } else { foundLayers.add(found.get()); } } CakeToppingDao toppingBean = context.getBean(CakeToppingDao.class); Optional<CakeTopping> topping = toppingBean.findById(matchingToppings.iterator().next().getId()); CakeDao cakeBean = context.getBean(CakeDao.class); if (topping.isPresent()) { Cake cake = new Cake(); cake.setTopping(topping.get()); cake.setLayers(foundLayers); cakeBean.save(cake); topping.get().setCake(cake); toppingBean.save(topping.get()); CakeLayerDao layerBean = context.getBean(CakeLayerDao.class); for (CakeLayer layer : foundLayers) { layer.setCake(cake); layerBean.save(layer); } } }

Target:
public void bakeNewCake(CakeInfo cakeInfo) throws CakeBakingException { List<CakeTopping> allToppings = getAvailableToppingEntities(); List<CakeTopping> matchingToppings = allToppings.stream().filter(t -> t.getName().equals(cakeInfo.cakeToppingInfo.name)) .collect(Collectors.toList()); if (matchingToppings.isEmpty()) { throw new CakeBakingException(String.format("Topping %s is not available", cakeInfo.cakeToppingInfo.name)); } List<CakeLayer> allLayers = getAvailableLayerEntities(); Set<CakeLayer> foundLayers = new HashSet<>(); for (CakeLayerInfo info : cakeInfo.cakeLayerInfos) { Optional<CakeLayer> found = allLayers.stream().filter(layer -> layer.getName().equals(info.name)).findFirst(); if (!found.isPresent()) { throw new CakeBakingException(String.format("Layer %s is not available", info.name)); } else { foundLayers.add(found.get()); } } CakeToppingDao toppingBean = context.getBean(CakeToppingDao.class); Optional<CakeTopping> topping = toppingBean.findById(matchingToppings.iterator().next().getId()); CakeDao cakeBean = context.getBean(CakeDao.class); if (topping.isPresent()) { Cake cake = new Cake(); cake.setTopping(topping.get()); cake.setLayers(foundLayers); cakeBean.save(cake); topping.get().setCake(cake); toppingBean.save(topping.get()); CakeLayerDao layerBean = context.getBean(CakeLayerDao.class); for (CakeLayer layer : foundLayers) { layer.setCake(cake); layerBean.save(layer); } } else { throw new CakeBakingException(String.format("Topping %s is not available", cakeInfo.cakeToppingInfo.name)); } }
Source:
public Path(String fullPath, boolean windows) { String devicePart = null; if (windows) { fullPath = fullPath.indexOf('\\') == -1 ? fullPath : fullPath.replace('\\', SEPARATOR); int i = fullPath.indexOf(DEVICE_SEPARATOR); if (i != -1) { int start = fullPath.charAt(0) == SEPARATOR ? 1 : 0; devicePart = fullPath.substring(start, i + 1); fullPath = fullPath.substring(i + 1, fullPath.length()); } } initialize(devicePart, fullPath, windows); }

Target:
private Path(String fullPath, boolean windows) { String devicePart = null; if (windows) { fullPath = fullPath.indexOf('\\') == -1 ? fullPath : fullPath.replace('\\', SEPARATOR); int i = fullPath.indexOf(DEVICE_SEPARATOR); if (i != -1) { int start = fullPath.charAt(0) == SEPARATOR ? 1 : 0; devicePart = fullPath.substring(start, i + 1); fullPath = fullPath.substring(i + 1, fullPath.length()); } } initialize(devicePart, fullPath, windows); }
Source:
public String getGitServerHost() { if (isNullOrEmpty(host)) { return nullToEmpty(host); } StringBuilder gitServerHosts = new StringBuilder(" \""); if (!host.startsWith(HTTPS)) { gitServerHosts.append(HTTPS); } gitServerHosts.append(host); gitServerHosts.append("\""); return gitServerHosts.toString(); }

Target:
public String getGitServerHost() { return host; }
Source:
@Override public void onCreate(Bundle savedInstanceState) { assertNotDead(); latestSavedInstanceState = savedInstanceState; toloadThisTime.addAll(bundlers); duringOnCreate = true; doLoading(); duringOnCreate = false; for (RealMortarScope child : children.values()) { if (!(child instanceof RealActivityScope)) continue; ((RealActivityScope) child).onCreate(getChildBundle(child, savedInstanceState, false)); } }

Target:
@Override public void onCreate(Bundle savedInstanceState) { assertNotDead(); latestSavedInstanceState = savedInstanceState; toloadThisTime.addAll(bundlers); loadingFromOnCreate = true; doLoading(); loadingFromOnCreate = false; for (RealMortarScope child : children.values()) { if (!(child instanceof RealActivityScope)) continue; ((RealActivityScope) child).onCreate(getChildBundle(child, savedInstanceState, false)); } }
Source:
private static byte[] toByteArray(final SAMFileHeader samFileHeader) { final ByteArrayOutputStream headerBodyOS = new ByteArrayOutputStream(); final OutputStreamWriter outStreamWriter = new OutputStreamWriter(headerBodyOS); new SAMTextHeaderCodec().encode(outStreamWriter, samFileHeader); try { outStreamWriter.close(); } catch (final IOException e) { throw new RuntimeException(e); } final ByteBuffer buf = ByteBuffer.allocate(4); buf.order(ByteOrder.LITTLE_ENDIAN); buf.putInt(headerBodyOS.size()); buf.flip(); final byte[] bytes = new byte[buf.limit()]; buf.get(bytes); final ByteArrayOutputStream headerOS = new ByteArrayOutputStream(); try { headerOS.write(bytes); headerOS.write(headerBodyOS.toByteArray(), 0, headerBodyOS.size()); } catch (final IOException e) { throw new RuntimeException(e); } return headerOS.toByteArray(); }

Target:
private static byte[] toByteArray(final SAMFileHeader samFileHeader) { final ByteArrayOutputStream headerBodyOS = new ByteArrayOutputStream(); final OutputStreamWriter outStreamWriter = new OutputStreamWriter(headerBodyOS); new SAMTextHeaderCodec().encode(outStreamWriter, samFileHeader); try { outStreamWriter.close(); } catch (final IOException e) { throw new RuntimeIOException(e); } final ByteBuffer buf = ByteBuffer.allocate(4); buf.order(ByteOrder.LITTLE_ENDIAN); buf.putInt(headerBodyOS.size()); buf.flip(); final byte[] bytes = new byte[buf.limit()]; buf.get(bytes); final ByteArrayOutputStream headerOS = new ByteArrayOutputStream(); try { headerOS.write(bytes); headerOS.write(headerBodyOS.toByteArray(), 0, headerBodyOS.size()); } catch (final IOException e) { throw new RuntimeIOException(e); } return headerOS.toByteArray(); }
Source:
protected boolean canDoAction() { boolean result = validateVM(); List<DiskImage> disksList = getDisksList(); if (result && disksList.size() > 0) { VmValidator vmValidator = new VmValidator(getVm()); SnapshotsValidator snapshotValidator = new SnapshotsValidator(); result = validate(snapshotValidator.vmNotDuringSnapshot(getVmId())) && validate(snapshotValidator.vmNotInPreview(getVmId())) && validate(vmValidator.vmNotDuringMigration()) && validate(vmValidator.vmNotRunningStateless()) && validate(vmValidator.vmNotIlegal()) && ImagesHandler.PerformImagesChecks( getReturnValue().getCanDoActionMessages(), getVm().getStoragePoolId(), Guid.Empty, true, true, true, true, true, true, disksList) && validate(vmValidator.vmNotLocked()); } return result; }

Target:
protected boolean canDoAction() { VmValidator vmValidator = new VmValidator(getVm()); boolean result = validateVM(vmValidator); List<DiskImage> disksList = getDisksList(); if (result && disksList.size() > 0) { SnapshotsValidator snapshotValidator = new SnapshotsValidator(); result = validate(snapshotValidator.vmNotDuringSnapshot(getVmId())) && validate(snapshotValidator.vmNotInPreview(getVmId())) && validate(vmValidator.vmNotDuringMigration()) && validate(vmValidator.vmNotRunningStateless()) && validate(vmValidator.vmNotIlegal()) && ImagesHandler.PerformImagesChecks( getReturnValue().getCanDoActionMessages(), getVm().getStoragePoolId(), Guid.Empty, true, true, true, true, true, true, disksList) && validate(vmValidator.vmNotLocked()); } return result; }
Source:
public Iterator<T> iterator() { return new Iterator<T>() { @Override public boolean hasNext() { return true; } @Override public synchronized T next() { return items.get(random.nextInt(numItems)); } @Override public void remove() { throw new IllegalArgumentException("Cannot remove from " + RandomIterator.class); } }; }

Target:
public Iterator<T> iterator() { return new Iterator<T>() { @Override public boolean hasNext() { return true; } @Override public synchronized T next() { return items.get(random.nextInt(items.size())); } @Override public void remove() { throw new UnsupportedOperationException("Cannot remove from " + RandomIterator.class); } }; }
Source:
protected CoordinateReferenceSystem getCrsForCoverage( String coverageName ) { CoordinateReferenceSystem crs = crsCache.get(coverageName); if (crs != null) { return crs; } AdapterToIndexMapping adapterMapping = geowaveAdapterIndexMappingStore.getIndicesForAdapter(new ByteArrayId( coverageName)); PrimaryIndex[] indices = adapterMapping.getIndices(geowaveIndexStore); if (indices != null && indices.length > 0) { if (indices[0].getIndexModel() instanceof CustomCrsIndexModel) { crs = ((CustomCrsIndexModel) indices[0].getIndexModel()).getCrs(); } else { crs = GeometryUtils.DEFAULT_CRS; } crsCache.put( coverageName, crs); } return crs; }

Target:
protected CoordinateReferenceSystem getCrsForCoverage( String coverageName ) { CoordinateReferenceSystem crs = crsCache.get(coverageName); if (crs != null) { return crs; } AdapterToIndexMapping adapterMapping = geowaveAdapterIndexMappingStore.getIndicesForAdapter(new ByteArrayId( coverageName)); PrimaryIndex[] indices = adapterMapping.getIndices(geowaveIndexStore); if (indices != null && indices.length > 0) { crs = GeometryUtils.getIndexCrs(indices[0]); crsCache.put( coverageName, crs); } return crs; }
Source:
public void saveCondition_shouldSaveNewCondition(){ Integer patientId = 2; String uuid = "08002000-4469-12q3-551f-0339000c9a76"; CodedOrFreeText codedOrFreeText = new CodedOrFreeText(); Condition condition = new Condition(); condition.setCondition(codedOrFreeText); condition.setClinicalStatus(ConditionClinicalStatus.ACTIVE); condition.setUuid(uuid); condition.setPatient(new Patient(patientId)); condition.setEncounter(new Encounter(2039)); conditionService.saveCondition(condition); Condition savedCondition = conditionService.getConditionByUuid(uuid); Assert.assertEquals(patientId, savedCondition.getPatient().getPatientId()); Assert.assertEquals(uuid, savedCondition.getUuid()); Assert.assertEquals(codedOrFreeText, savedCondition.getCondition()); Assert.assertEquals(ConditionClinicalStatus.ACTIVE, savedCondition.getClinicalStatus()); Assert.assertNotNull(savedCondition.getConditionId()); Assert.assertEquals(Integer.valueOf(2039), savedCondition.getEncounter().getId()); }

Target:
public void saveCondition_shouldSaveNewCondition(){ Integer patientId = 2; String uuid = "08002000-4469-12q3-551f-0339000c9a76"; CodedOrFreeText codedOrFreeText = new CodedOrFreeText(); Condition condition = new Condition(); condition.setCondition(codedOrFreeText); condition.setClinicalStatus(ConditionClinicalStatus.ACTIVE); condition.setUuid(uuid); condition.setPatient(new Patient(patientId)); conditionService.saveCondition(condition); Condition savedCondition = conditionService.getConditionByUuid(uuid); Assert.assertEquals(patientId, savedCondition.getPatient().getPatientId()); Assert.assertEquals(uuid, savedCondition.getUuid()); Assert.assertEquals(codedOrFreeText, savedCondition.getCondition()); Assert.assertEquals(ConditionClinicalStatus.ACTIVE, savedCondition.getClinicalStatus()); Assert.assertNotNull(savedCondition.getConditionId()); }
Source:
private static Map<DereferenceExpression, VariableReferenceExpression> getDereferenceSymbolMap(Collection<RowExpression> expressions, Context context, Metadata metadata, SqlParser sqlParser) { Set<DereferenceExpression> dereferences = expressions.stream() .filter(OriginalExpressionUtils::isExpression) .map(OriginalExpressionUtils::castToExpression) .flatMap(expression -> extractDereferenceExpressions(expression).stream()) .filter(PushDownDereferences::validPushDown) .collect(toImmutableSet()); if (dereferences.stream().anyMatch(exp -> baseExists(exp, dereferences))) { return ImmutableMap.of(); } return dereferences.stream() .collect(toImmutableMap(Function.identity(), expression -> newSymbol(expression, context, metadata, sqlParser))); }

Target:
private static Map<DereferenceExpression, VariableReferenceExpression> getDereferenceSymbolMap(Collection<RowExpression> expressions, Context context, Metadata metadata, SqlParser sqlParser) { Set<DereferenceExpression> dereferences = expressions.stream() .filter(OriginalExpressionUtils::isExpression) .map(OriginalExpressionUtils::castToExpression) .flatMap(expression -> extractDereferenceExpressions(expression).stream()) .collect(toImmutableSet()); if (dereferences.stream().anyMatch(expression -> baseExists(expression, dereferences))) { return ImmutableMap.of(); } return dereferences.stream() .collect(toImmutableMap(Function.identity(), expression -> newSymbol(expression, context, metadata, sqlParser))); }
Source:
public void testSTTouches() throws Exception { assertQuery("select ST_Touches(ST_GeometryFromText('Point(1 2)'), ST_GeometryFromText('Polygon ((1 1, 1 4, 4 4, 4 1))'))", "select true"); }

Target:
public void testSTTouches() throws Exception { assertFunction("ST_Touches(ST_GeometryFromText('POINT (50 100)'), ST_GeometryFromText('POINT (150 150)'))", BOOLEAN, false); assertFunction("ST_Touches(ST_GeometryFromText('MULTIPOINT (50 100, 50 200)'), ST_GeometryFromText('POINT (50 100)'))", BOOLEAN, false); assertFunction("ST_Touches(ST_GeometryFromText('LINESTRING (50 100, 50 200)'), ST_GeometryFromText('LINESTRING (20 150, 100 150)'))", BOOLEAN, false); assertFunction("ST_Touches(ST_GeometryFromText('MULTILINESTRING ((1 1, 5 1), (2 4, 4 4))'), ST_GeometryFromText('MULTILINESTRING ((3 4, 6 4), (5 0, 5 4))'))", BOOLEAN, false); assertFunction("ST_Touches(ST_GeometryFromText('POINT (1 2)'), ST_GeometryFromText('POLYGON ((1 1, 1 4, 4 4, 4 1))'))", BOOLEAN, true); assertFunction("ST_Touches(ST_GeometryFromText('POLYGON ((1 1, 1 3, 3 3, 3 1))'), ST_GeometryFromText('POLYGON ((4 4, 4 5, 5 5, 5 4))'))", BOOLEAN, false); assertFunction("ST_Touches(ST_GeometryFromText('POLYGON ((1 1, 1 3, 3 3, 3 1))'), ST_GeometryFromText('LINESTRING (0 0, 1 1)'))", BOOLEAN, true); assertFunction("ST_Touches(ST_GeometryFromText('POLYGON ((1 1, 1 3, 3 3, 3 1))'), ST_GeometryFromText('POLYGON ((3 3, 3 5, 5 5, 5 3))'))", BOOLEAN, true); assertFunction("ST_Touches(ST_GeometryFromText('MULTIPOLYGON (((1 1, 1 3, 3 3, 3 1)), ((0 0, 0 2, 2 2, 2 0)))'), ST_GeometryFromText('POLYGON ((0 1, 3 1, 3 3, 0 3))'))", BOOLEAN, false); }