auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public SafeHtml getTooltip(GlusterBrickEntity brick) { GlusterStatus status = brick.getStatus(); String tooltip = null; switch (status) { case DOWN: tooltip = constants.down(); break; case UP: tooltip = constants.up(); break; case UNKNOWN: tooltip = constants.unknown(); break; default: tooltip = constants.down(); } if (brick.getStatus() != GlusterStatus.DOWN && brick.getUnSyncedEntries() != null && brick.getUnSyncedEntries() > 0) { tooltip += ", " + brick.getUnSyncedEntries() + constants.unSyncedEntriesPresent(); } return SafeHtmlUtils.fromSafeConstant(tooltip); }

Target:
public SafeHtml getTooltip(GlusterBrickEntity brick) { GlusterStatus status = brick.getStatus(); String tooltip = null; switch (status) { case DOWN: tooltip = constants.down(); break; case UP: tooltip = constants.up(); break; case UNKNOWN: tooltip = constants.unknown(); break; default: tooltip = constants.down(); } if (brick.getStatus() != GlusterStatus.DOWN && brick.getUnSyncedEntries() > 0) { tooltip = messages.brickStatusWithUnSyncedEntriesPresent(tooltip, brick.getUnSyncedEntries()); } return SafeHtmlUtils.fromSafeConstant(tooltip); }
Source:
protected Integer getIdentifierLengthLimit(JdbcEnvironment context) { String dialectName = context.getDialect().getClass().getSimpleName(); if (dialectName.startsWith("Oracle")) { return LENGTH_LIMIT_ORACLE; } if (context.getDialect() instanceof Shogun2OracleDialect) { return LENGTH_LIMIT_ORACLE; } else if (dialectName.startsWith("PostgreSQL")) { return LENGTH_LIMIT_POSTGRESQL; } return null; }

Target:
protected Integer getIdentifierLengthLimit(JdbcEnvironment context) { String dialectName = context.getDialect().getClass().getSimpleName(); if (dialectName.startsWith("Oracle")) { return LENGTH_LIMIT_ORACLE; } else if (context.getDialect() instanceof Shogun2OracleDialect) { return LENGTH_LIMIT_ORACLE; } else if (dialectName.startsWith("PostgreSQL")) { return LENGTH_LIMIT_POSTGRESQL; } return null; }
Source:
public static boolean updateDiskStats(HWDiskStore diskStore) { List<String> output = ExecutingCommand.runNative("iostat -Ix " + diskStore.getName()); long timeStamp = System.currentTimeMillis(); boolean diskFound = false; for (String line : output) { String[] split = ParseUtil.whitespaces.split(line); if (split.length < 7 || !split[0].equals(diskStore.getName())) { continue; } diskFound = true; diskStore.setReads((long) ParseUtil.parseDoubleOrDefault(split[1], 0d)); diskStore.setWrites((long) ParseUtil.parseDoubleOrDefault(split[2], 0d)); diskStore.setReadBytes((long) (ParseUtil.parseDoubleOrDefault(split[3], 0d) * 1024)); diskStore.setWriteBytes((long) (ParseUtil.parseDoubleOrDefault(split[4], 0d) * 1024)); diskStore.setQueueLength((long) (ParseUtil.parseDoubleOrDefault(split[5], 0d))); diskStore.setTransferTime((long) (ParseUtil.parseDoubleOrDefault(split[6], 0d) * 1000)); diskStore.setTimeStamp(timeStamp); } return diskFound; }

Target:
public static boolean updateDiskStats(HWDiskStore diskStore) { List<String> output = ExecutingCommand.runNative("iostat -Ix " + diskStore.getName()); long timeStamp = System.currentTimeMillis(); boolean diskFound = false; for (String line : output) { String[] split = ParseUtil.whitespaces.split(line); if (split.length < 7 || !split[0].equals(diskStore.getName())) { continue; } diskFound = true; diskStore.setReads((long) ParseUtil.parseDoubleOrDefault(split[1], 0d)); diskStore.setWrites((long) ParseUtil.parseDoubleOrDefault(split[2], 0d)); diskStore.setReadBytes((long) (ParseUtil.parseDoubleOrDefault(split[3], 0d) * 1024)); diskStore.setWriteBytes((long) (ParseUtil.parseDoubleOrDefault(split[4], 0d) * 1024)); diskStore.setCurrentQueueLength(ParseUtil.parseLongOrDefault(split[5], 0L)); diskStore.setTransferTime((long) (ParseUtil.parseDoubleOrDefault(split[6], 0d) * 1000)); diskStore.setTimeStamp(timeStamp); } return diskFound; }
Source:
private String getPropertiesFile(Path path) { return AccessUtils.doPrivileged( () -> { try { return new String(Files.readAllBytes(path)); } catch (IOException e) { throw new MigrationException(Messages.EXPORT_SYSTEM_PROPERTIES_ERROR, e); } }); }

Target:
private String getPropertiesFile(Path path) { return AccessUtils.doPrivileged( () -> { try { return new String(Files.readAllBytes(path), Charsets.UTF_8); } catch (IOException e) { throw new MigrationException(Messages.EXPORT_SYSTEM_PROPERTIES_ERROR, e); } }); }
Source:
private long getValue(CuratorFramework curatorClient, String basePath, String childrenPath) { Long sum = 0L; try { for (String child : curatorClient.getChildren().forPath(basePath)) { try { sum += Longs.fromByteArray(curatorClient.getData().forPath(basePath + "/" + child + childrenPath)); } catch (KeeperException.NoNodeException e) { logger.trace("Someone removed node " + basePath + "/" + child + childrenPath + " while we were iterating", e); } } } catch (Exception e) { logger.warn("Error while reading value for base path: and child path: {}; {}", basePath, childrenPath, getRootCauseMessage(e)); } finally { return sum; } }

Target:
private long getValue(CuratorFramework curatorClient, String basePath, String childrenPath) { try { return curatorClient.getChildren().forPath(basePath).stream() .map(child -> getValueForChild(curatorClient, basePath, childrenPath, child)) .reduce(0L, (a, b) -> a + b); } catch (Exception e) { logger.warn("Error while reading value for base path: and child path: {}; {}", basePath, childrenPath, getRootCauseMessage(e)); } return 0; }
Source:
public void unsubscribe(URL url, NotifyListener listener) { for (Registry registry : referenceRegistries.values()) { registry.unsubscribe(url, listener); } MultipleNotifyListenerWrapper notifyListener = multipleNotifyListenerMap.remove(listener); if (notifyListener != null) { super.unsubscribe(url, notifyListener); notifyListener.destroy(); } }

Target:
public void unsubscribe(URL url, NotifyListener listener) { MultipleNotifyListenerWrapper notifyListener = multipleNotifyListenerMap.remove(listener); for (Registry registry : referenceRegistries.values()) { SingleNotifyListener singleNotifyListener = notifyListener.registryMap.get(registry.getUrl()); registry.unsubscribe(url, singleNotifyListener); } if (notifyListener != null) { super.unsubscribe(url, notifyListener); notifyListener.destroy(); } }
Source:
private boolean isCompatibleWithDevice(int fps) { ArrayList<int[]> validValues = (ArrayList<int[]>) mCameraParameters.getSupportedPreviewFpsRange(); for(int[] row : validValues) { boolean is_included = fps >= row[0] && fps <= row[1]; if (is_included) return true; } Log.w("CAMERA_1::", "fps (framePerSecond) received an unsupported value and will be ignored."); return false; }

Target:
private boolean isCompatibleWithDevice(int fps) { ArrayList<int[]> validValues; validValues = getSupportedPreviewFpsRange(); int accurate_fps = fps * 1000; for(int[] row : validValues) { boolean is_included = accurate_fps >= row[0] && accurate_fps <= row[1]; boolean greater_then_zero = accurate_fps > 0; boolean compatible_with_device = is_included && greater_then_zero; if (compatible_with_device) return true; } Log.w("CAMERA_1::", "fps (framePerSecond) received an unsupported value and will be ignored."); return false; }
Source:
public static boolean canShare(Metacard metacard) { return metacard != null && metacard .getMetacardType() .getAttributeDescriptors() .stream() .map(AttributeDescriptor::getName) .anyMatch(attr -> Objects.equals(SecurityAttributes.ACCESS_GROUPS, attr)) && metacard .getMetacardType() .getAttributeDescriptors() .stream() .map(AttributeDescriptor::getName) .anyMatch(attr -> Objects.equals(SecurityAttributes.ACCESS_INDIVIDUALS, attr)); }

Target:
public static boolean canShare(Metacard metacard) { return metacard != null && isSharingCapable(metacard) && metacard .getMetacardType() .getAttributeDescriptors() .stream() .map(AttributeDescriptor::getName) .anyMatch(attr -> Objects.equals(SecurityAttributes.ACCESS_GROUPS, attr)) && metacard .getMetacardType() .getAttributeDescriptors() .stream() .map(AttributeDescriptor::getName) .anyMatch(attr -> Objects.equals(SecurityAttributes.ACCESS_INDIVIDUALS, attr)); }
Source:
public Builder ttl(int ttl) { checkArgument(ttl >= getInteger(TTL_MIN_IN_SEC), "ttl must be >= %s", getInteger(TTL_MIN_IN_SEC)); checkArgument(ttl <= getInteger(TTL_MAX_IN_SEC), "ttl must be <= %s", getInteger(TTL_MAX_IN_SEC)); this.ttl = ttl; return self(); }

Target:
public Builder ttl(int ttl) { this.ttl = ttl; return self(); }
Source:
public void loadGeppettoProject(String requestID, IGeppettoProject geppettoProject, long experimentId) { try { geppettoManager.loadProject(requestID, geppettoProject); Gson gson = new Gson(); String projectJSON = gson.toJson(geppettoProject); setConnectionProject(geppettoProject); websocketConnection.sendMessage(requestID, OutboundMessages.PROJECT_LOADED, projectJSON); boolean persisted = !geppettoProject.isVolatile(); String update = "{\"persisted\":" + persisted + ",\"projectId\":" + geppettoProject.getId() +"}"; websocketConnection.sendMessage(requestID, OutboundMessages.PROJECT_PERSISTENCE_STATE, update); String geppettoModelJSON = GeppettoSerializer.serializeToJSON(((GeppettoManager) geppettoManager).getRuntimeProject(geppettoProject).getGeppettoModel(), true); websocketConnection.sendMessage(requestID, OutboundMessages.GEPPETTO_MODEL_LOADED, geppettoModelJSON); if(experimentId != -1) { loadExperiment(requestID, experimentId, geppettoProject.getId()); } else if(geppettoProject.getActiveExperimentId() != -1) { loadExperiment(requestID, geppettoProject.getActiveExperimentId(), geppettoProject.getId()); } } catch(GeppettoInitializationException | GeppettoExecutionException | GeppettoAccessException | IOException e) { error(e, "Could not load geppetto project"); } }

Target:
public void loadGeppettoProject(String requestID, IGeppettoProject geppettoProject, long experimentId) { try { geppettoManager.loadProject(requestID, geppettoProject); Gson gson = new Gson(); String projectJSON = gson.toJson(geppettoProject); boolean persisted = geppettoProject.isVolatile(); String update = "{\"persisted\":" + !persisted + ",\"project\":" + projectJSON +"}"; setConnectionProject(geppettoProject); websocketConnection.sendMessage(requestID, OutboundMessages.PROJECT_LOADED, update); String geppettoModelJSON = GeppettoSerializer.serializeToJSON(((GeppettoManager) geppettoManager).getRuntimeProject(geppettoProject).getGeppettoModel(), true); websocketConnection.sendMessage(requestID, OutboundMessages.GEPPETTO_MODEL_LOADED, geppettoModelJSON); if(experimentId != -1) { loadExperiment(requestID, experimentId, geppettoProject.getId()); } else if(geppettoProject.getActiveExperimentId() != -1) { loadExperiment(requestID, geppettoProject.getActiveExperimentId(), geppettoProject.getId()); } } catch(GeppettoInitializationException | GeppettoExecutionException | GeppettoAccessException | IOException e) { error(e, "Could not load geppetto project"); } }
Source:
public List<ChooserTarget> onGetChooserTargets(ComponentName targetActivityName, IntentFilter matchedFilter) { final List<ChooserTarget> targets = new ArrayList<>(); HostManager hostManager = HostManager.getInstance(this); final Icon icon = Icon.createWithResource(this, R.mipmap.ic_launcher); final float score = 0; final ComponentName componentName = new ComponentName(getPackageName(), "org.xbmc.kore.ui.sections.remote.RemoteActivity"); for (HostInfo host : hostManager.getHosts()) { String title = host.getName(); Bundle intentExtras = new Bundle(); intentExtras.putString("host.name", title); targets.add(new ChooserTarget(title, icon, score, componentName, intentExtras)); } return targets; }

Target:
public List<ChooserTarget> onGetChooserTargets(ComponentName targetActivityName, IntentFilter matchedFilter) { final List<ChooserTarget> targets = new ArrayList<>(); HostManager hostManager = HostManager.getInstance(this); final Icon icon = Icon.createWithResource(this, R.mipmap.ic_launcher); final float score = 0; final ComponentName componentName = new ComponentName(getPackageName(), "org.xbmc.kore.ui.sections.remote.RemoteActivity"); for (HostInfo host : hostManager.getHosts()) { Bundle intentExtras = new Bundle(); intentExtras.putInt("hostId", host.getId()); targets.add(new ChooserTarget(host.getName(), icon, score, componentName, intentExtras)); } return targets; }
Source:
public File generateMultipleDockets(Collection<DocketData> docketData, URI xslFileUri) throws IOException { ExportDocket exportDocket = new ExportDocket(); File file = new File("docket_multipage.pdf"); FileOutputStream fileOutputStream = new FileOutputStream(file); try { exportDocket.startExport(docketData, fileOutputStream, new File(xslFileUri)); } catch (IOException e) { throw new IOException(e.getMessage()); } finally { fileOutputStream.flush(); fileOutputStream.close(); } return file; }

Target:
public File generateMultipleDockets(Collection<DocketData> docketData, URI xslFileUri) throws IOException { ExportDocket exportDocket = new ExportDocket(); File file = new File("docket_multipage.pdf"); try (FileOutputStream fileOutputStream = new FileOutputStream(file)) { exportDocket.startExport(docketData, fileOutputStream, new File(xslFileUri)); } catch (IOException e) { throw new IOException(e.getMessage()); } return file; }
Source:
public LiveMigrateDiskCommand(T parameters) { super(parameters); if (VMStatus.Up != getVm().getstatus()) { internalEndFailure(); return; } setVdsId(getVm().getrun_on_vds().getValue()); getParameters().setVdsId(getVdsId()); setStoragePoolId(getVm().getstorage_pool_id()); getParameters().setStoragePoolId(getStoragePoolId().getValue()); getParameters().setDiskAlias(getDiskAlias()); getParameters().setImageGroupID(getImageGroupId()); getParameters().setCommandType(getActionType()); }

Target:
public LiveMigrateDiskCommand(T parameters) { super(parameters); if (VMStatus.Up != getVm().getstatus()) { log.infoFormat("Rollback LiveMigrateDiskCommand - VM {0} is not UP", getVm().getvm_name()); handleVmNotUp(); return; } setVdsId(getVm().getrun_on_vds().getValue()); getParameters().setVdsId(getVdsId()); setStoragePoolId(getVm().getstorage_pool_id()); getParameters().setStoragePoolId(getStoragePoolId().getValue()); getParameters().setDiskAlias(getDiskAlias()); getParameters().setImageGroupID(getImageGroupId()); getParameters().setCommandType(getActionType()); }
Source:
public void testAddFolder() throws Exception { assertTrue(new File(db.getWorkTree(), "sub").mkdir()); File file = new File(db.getWorkTree(), "sub/a.txt"); FileUtils.createNewFile(file); PrintWriter writer = new PrintWriter(file); writer.print("content"); writer.close(); File file2 = new File(db.getWorkTree(), "sub/b.txt"); FileUtils.createNewFile(file2); writer = new PrintWriter(file2); writer.print("content b"); writer.close(); Git git = new Git(db); git.add().addFilepattern("sub").call(); assertEquals( "[sub/a.txt, mode:100644, content:content]" + "[sub/b.txt, mode:100644, content:content b]", indexState(CONTENT)); }

Target:
public void testAddFolder() throws Exception { FileUtils.mkdir(new File(db.getWorkTree(), "sub")); File file = new File(db.getWorkTree(), "sub/a.txt"); FileUtils.createNewFile(file); PrintWriter writer = new PrintWriter(file); writer.print("content"); writer.close(); File file2 = new File(db.getWorkTree(), "sub/b.txt"); FileUtils.createNewFile(file2); writer = new PrintWriter(file2); writer.print("content b"); writer.close(); Git git = new Git(db); git.add().addFilepattern("sub").call(); assertEquals( "[sub/a.txt, mode:100644, content:content]" + "[sub/b.txt, mode:100644, content:content b]", indexState(CONTENT)); }
Source:
protected Class<? extends BiFunction<Key,Value,String>> getFormatter(String formatterClazz) { try { if (formatterClazz != null) { return (Class<? extends BiFunction<Key,Value,String>>) this.getClass().getClassLoader() .loadClass(formatterClazz).asSubclass(BiFunction.class); } } catch (ClassNotFoundException e) { System.err.println("Could not find formatter class: " + formatterClazz); } return null; }

Target:
protected Class<? extends BiFunction<Key,Value,String>> getFormatter(String formatterClazz) throws ClassNotFoundException { @SuppressWarnings("unchecked") Class<? extends BiFunction<Key,Value,String>> clazz = (Class<? extends BiFunction<Key,Value,String>>) this.getClass().getClassLoader() .loadClass(formatterClazz).asSubclass(BiFunction.class); return clazz; }
Source:
public void scan(String resource, Path filePath, Charset encoding) throws IOException { LOG.debug("Scanning {}", resource); init(); int lineIndex = 0; try (BufferedReader br = Files.newBufferedReader(filePath)) { String line; while ((line = br.readLine()) != null) { lineIndex++; if (line.trim().length() == 0) { continue; } for (java.util.regex.Pattern pattern : allFilePatterns) { if (pattern.matcher(line).find()) { exclusionPatternInitializer.getPatternMatcher().addPatternToExcludeResource(resource); LOG.debug("- Exclusion pattern '{}': every violation in this file will be ignored.", pattern); return; } } checkDoubleRegexps(line, lineIndex); } } if (currentMatcher != null && !currentMatcher.hasSecondPattern()) { endExclusion(lineIndex + 1); } fileLength = lineIndex; if (!lineExclusions.isEmpty()) { Set<LineRange> lineRanges = convertLineExclusionsToLineRanges(); LOG.debug("- Line exclusions found: {}", lineRanges); exclusionPatternInitializer.getPatternMatcher().addPatternToExcludeLines(resource, lineRanges); } }

Target:
public void scan(String resource, Path filePath, Charset encoding) throws IOException { LOG.debug("Scanning {}", resource); init(); int lineIndex = 0; try (BufferedReader br = Files.newBufferedReader(filePath, encoding)) { String line; while ((line = br.readLine()) != null) { lineIndex++; if (line.trim().length() == 0) { continue; } for (java.util.regex.Pattern pattern : allFilePatterns) { if (pattern.matcher(line).find()) { exclusionPatternInitializer.getPatternMatcher().addPatternToExcludeResource(resource); LOG.debug("- Exclusion pattern '{}': every issue in this file will be ignored.", pattern); return; } } checkDoubleRegexps(line, lineIndex); } } if (currentMatcher != null && !currentMatcher.hasSecondPattern()) { endExclusion(lineIndex + 1); } fileLength = lineIndex; if (!lineExclusions.isEmpty()) { Set<LineRange> lineRanges = convertLineExclusionsToLineRanges(); LOG.debug("- Line exclusions found: {}", lineRanges); exclusionPatternInitializer.getPatternMatcher().addPatternToExcludeLines(resource, lineRanges); } }
Source:
public void save(Table table) throws TableManagerException { validateTableParams(table); try { if (metadataManager.exists(table.getName())) { throw new TableManagerException(TableManagerException.ErrorCode.BAD_REQUEST, "table already exists"); } queryStore.init(table.getName()); dataStore.init(table); metadataManager.save(table); } catch (DataStoreException e) { switch (e.getErrorCode()) { case TABLE_NOT_FOUND: throw new TableManagerException(TableManagerException.ErrorCode.BAD_REQUEST, e); case STORE_CONNECTION: throw new TableManagerException(TableManagerException.ErrorCode.INTERNAL_ERROR, e); default: throw new TableManagerException(TableManagerException.ErrorCode.INTERNAL_ERROR, e); } } catch (TableManagerException e) { throw e; } catch (Exception e) { throw new TableManagerException(TableManagerException.ErrorCode.INTERNAL_ERROR, e); } }

Target:
public void save(Table table) throws TableManagerException { validateTableParams(table); try { if (metadataManager.exists(table.getName())) { throw new TableManagerException(TableManagerException.ErrorCode.BAD_REQUEST, "table already exists"); } queryStore.initializeTable(table.getName()); dataStore.initializeTable(table); metadataManager.save(table); } catch (DataStoreException e) { switch (e.getErrorCode()) { case TABLE_NOT_FOUND: throw new TableManagerException(TableManagerException.ErrorCode.BAD_REQUEST, e); default: throw new TableManagerException(TableManagerException.ErrorCode.INTERNAL_ERROR, e); } } catch (TableManagerException e) { throw e; } catch (Exception e) { throw new TableManagerException(TableManagerException.ErrorCode.INTERNAL_ERROR, e); } }
Source:
public void testStackUnstack() { SymbolicValue sv1 = new SymbolicValue(1); ProgramState state = ProgramState.EMPTY_STATE.stackValue(sv1); assertThat(state.peekValue()).isSameAs(sv1); SymbolicValue sv2 = new SymbolicValue(2); state = state.stackValue(sv2); List<SymbolicValue> values = state.peekValues(2); assertThat(values).hasSize(2); assertThat(values.get(0)).isSameAs(sv2); assertThat(values.get(1)).isSameAs(sv1); try { state.peekValues(3); Assert.fail("Able to retrieve more values than there are actually on the stack!"); } catch (IllegalStateException e) { } Pop unstack = state.unstackValue(1); state = unstack.state; values = unstack.values; assertThat(values).hasSize(1); assertThat(values.get(0)).isSameAs(sv2); assertThat(state.peekValue()).isSameAs(sv1); }

Target:
public void testStackUnstack() { SymbolicValue sv1 = new SymbolicValue(1); ProgramState state = ProgramState.EMPTY_STATE.stackValue(sv1); assertThat(state.peekValue()).isSameAs(sv1); SymbolicValue sv2 = new SymbolicValue(2); state = state.stackValue(sv2); List<SymbolicValue> values = state.peekValues(2); assertThat(values).hasSize(2).containsSequence(sv2, sv1); try { state.peekValues(3); Assert.fail("Able to retrieve more values than there are actually on the stack!"); } catch (IllegalStateException e) { } Pop unstack = state.unstackValue(1); state = unstack.state; values = unstack.values; assertThat(values).hasSize(1); assertThat(values.get(0)).isSameAs(sv2); assertThat(state.peekValue()).isSameAs(sv1); }
Source:
public void addMethodSelector(String className, int priority) { if (className != null && !className.trim().isEmpty()) { m_methodDescriptors.put(className, priority); } }

Target:
public void addMethodSelector(String className, int priority) { if (Strings.isNotNullAndNotEmpty(className)) { m_methodDescriptors.put(className, priority); } }
Source:
private void animate() { final AnimationTimer timer = new AnimationTimer() { @Override public void handle(long nowInNanoSeconds) { if (texts!=null && !texts.isEmpty()) { for(Text text: texts) { shapesGroup.getChildren().add(text); } texts=null; } gradientFactor = Math.pow(2,slider.getValue()); for(GradientParamShape input: allGradientParamShapes) { input.applyUpdatesToShapesAndRefresh(); } shapesGroup.requestLayout(); if (captureScreenImages && nowInNanoSeconds-startTime> FIVE_SECOND_IN_NANO_SECONDS && frameCount<FRAME_COUNT_TO_COLLECT) { if (frameCount==0) { initializeCapture(); System.out.println("Starting capture"); } capture(); if (frameCount==100) { System.out.println("Ending capture"); } } if (selectedGradientParamShape!=null) { String g=numberFormatLonger.format(selectedGradientParamShape.getGradient()); String p=numberFormatLonger.format(selectedGradientParamShape.getParam()); textForSelectedGradientParam.setText("param = " + p + ", gradient = " + g); } } }; timer.start(); }

Target:
private void animate() { final AnimationTimer timer = new AnimationTimer() { @Override public void handle(long nowInNanoSeconds) { doPauseLogicInUIThread(); if (texts != null && !texts.isEmpty()) { for (Text text : texts) { shapesGroup.getChildren().add(text); } texts = null; } gradientFactor = Math.pow(2, slider.getValue()); for (GradientParamShape input : allGradientParamShapes) { input.applyUpdatesToShapesAndRefresh(); } shapesGroup.requestLayout(); if (captureScreenImages && nowInNanoSeconds - startTime > FIVE_SECOND_IN_NANO_SECONDS && frameCount < FRAME_COUNT_TO_COLLECT) { if (frameCount == 0) { initializeCapture(); System.out.println("Starting capture"); } capture(); if (frameCount == 100) { System.out.println("Ending capture"); } } if (selectedGradientParamShape != null) { String g = format(selectedGradientParamShape.getGradient()); String p = format(selectedGradientParamShape.getParam()); textForSelectedGradientParam.setText("param = " + p + ", gradient = " + g); } } }; timer.start(); }
Source:
private void logOpenLocks(LockWatchRequest request) { RangeSet<LockDescriptor> requestAsRangeSet = TreeRangeSet.create(toRanges(request)); heldLocksCollection.locksHeld().forEach(locksHeld -> { Set<LockDescriptor> descriptors = locksHeld.getLocks().stream() .map(AsyncLock::getDescriptor) .filter(requestAsRangeSet::contains) .collect(Collectors.toSet()); lockEventLog.logOpenLocks(descriptors); } ); }

Target:
private void logOpenLocks(LockWatchRequest request) { RangeSet<LockDescriptor> requestAsRangeSet = TreeRangeSet.create(toRanges(request)); Set<LockDescriptor> openLocks = heldLocksCollection.locksHeld().stream() .flatMap(locksHeld -> locksHeld.getLocks().stream().map(AsyncLock::getDescriptor)) .filter(requestAsRangeSet::contains) .collect(Collectors.toSet()); lockEventLog.logOpenLocks(openLocks); }
Source:
public void testDeleteByIdAndPartitionKey() { final Mono<Void> deleteMono = repository.deleteById(DOMAIN_1.getNumber(), new PartitionKey(entityInformation.getPartitionKeyFieldValue(DOMAIN_1))); StepVerifier.create(deleteMono).verifyComplete(); Mono<LongIdDomainPartition> findIdMono = this.repository.findById(ID_1, new PartitionKey(entityInformation.getPartitionKeyFieldValue(DOMAIN_1))); StepVerifier.create(findIdMono).verifyComplete(); }

Target:
public void testDeleteByIdAndPartitionKey() { final Mono<Void> deleteMono = repository.deleteById(DOMAIN_1.getNumber(), new PartitionKey(entityInformation.getPartitionKeyFieldValue(DOMAIN_1))); StepVerifier.create(deleteMono).verifyComplete(); Mono<LongIdDomainPartition> findIdMono = this.repository.findById(ID_1, new PartitionKey(entityInformation.getPartitionKeyFieldValue(DOMAIN_1))); StepVerifier.create(findIdMono).expectNextCount(0).verifyComplete(); }
Source:
GetAllSupportedNetworkFiltersByVersionQuery(VersionQueryParameters parameters) { super(parameters); }

Target:
public GetAllSupportedNetworkFiltersByVersionQuery(VersionQueryParameters parameters) { super(parameters); }
Source:
public double getPercent() { final double extent = this.max - (double) this.min; if (extent == 0.) { return 0.; } return (this.current - this.min) * 100. / extent; }

Target:
public double getPercent() { final int extent = this.max - this.min; if (extent == 0.) { return 0.; } return (this.current - this.min) * 100. / extent; }
Source:
public T build() { return builderFunction.build(this); }

Target:
public T build() { return builderFunction.apply(this); }
Source:
public GraphInfo<?> getGraphInfo() { final DefaultGraphInfo graphInfo = new DefaultGraphInfo(TOPOLOGY_NAMESPACE, SimpleVertex.class); graphInfo.setLabel("Application Graph"); graphInfo.setDescription("This Topology Provider displays the hierarchy of TODO."); return graphInfo; }

Target:
public GraphInfo<?> getGraphInfo() { final DefaultGraphInfo graphInfo = new DefaultGraphInfo(TOPOLOGY_NAMESPACE, ApplicationVertex.class); graphInfo.setLabel(GRAPH_LABEL); graphInfo.setDescription(GRAPH_DESCRIPTION); return graphInfo; }
Source:
public static ByteBuffer map(FileChannel fc, FileChannel.MapMode mode, long position, long size) throws IOException { ByteBuffer byteBuffer; if (Platform.OS_WIN32.equals(Platform.getOS())) { byteBuffer = ByteBuffer.allocate((int) size); fc.read(byteBuffer, position); } else { byteBuffer = fc.map(mode, position, size); } return byteBuffer; }

Target:
public static ByteBuffer map(FileChannel fc, FileChannel.MapMode mode, long position, long size) throws IOException { ByteBuffer byteBuffer; if (IS_WIN32) { byteBuffer = ByteBuffer.allocate((int) size); fc.read(byteBuffer, position); } else { byteBuffer = fc.map(mode, position, size); } return byteBuffer; }
Source:
public List<ArticleRelationship> getRelationshipsTo(ArticleIdentifier targetId) { return (List<ArticleRelationship>) hibernateTemplate.execute(session -> { Query query = session.createQuery("" + "SELECT ar " + "FROM VersionedArticleRelationship ar " + "WHERE ar.targetArticle.doi = :doi "); query.setParameter("doi", targetId.getDoiName()); return query.list(); }); }

Target:
public List<ArticleRelationship> getRelationshipsTo(ArticleIdentifier targetId) { return (List<ArticleRelationship>) hibernateTemplate.execute(session -> { Query query = session.createQuery("" + "SELECT ar " + "FROM ArticleRelationship ar " + "WHERE ar.targetArticle.doi = :doi "); query.setParameter("doi", targetId.getDoiName()); return query.list(); }); }
Source:
public Stat forPath(String path) throws Exception { path = client.fixForNamespace(path); client.getSchemaSet().getSchema(path).validateWatch(path, watching.isWatched() || watching.hasWatcher()); Stat returnStat = null; if ( backgrounding.inBackground() ) { OperationAndData<String> operationAndData = new OperationAndData<String>(this, path, backgrounding.getCallback(), null, backgrounding.getContext(), watching); if ( createParentContainersIfNeeded || createParentsIfNeeded ) { CreateBuilderImpl.backgroundCreateParentsThenNode(client, operationAndData, operationAndData.getData(), backgrounding, client.getAclProvider(), createParentContainersIfNeeded); } else { client.processBackgroundOperation(operationAndData, null); } } else { returnStat = pathInForeground(path); } return returnStat; }

Target:
public Stat forPath(String path) throws Exception { path = client.fixForNamespace(path); client.getSchemaSet().getSchema(path).validateWatch(path, watching.isWatched() || watching.hasWatcher()); Stat returnStat = null; if ( backgrounding.inBackground() ) { OperationAndData<String> operationAndData = new OperationAndData<String>(this, path, backgrounding.getCallback(), null, backgrounding.getContext(), watching); if ( createParentContainersIfNeeded || createParentsIfNeeded ) { CreateBuilderImpl.backgroundCreateParentsThenNode(client, operationAndData, operationAndData.getData(), backgrounding, acling.getACLProviderForParents(), createParentContainersIfNeeded); } else { client.processBackgroundOperation(operationAndData, null); } } else { returnStat = pathInForeground(path); } return returnStat; }
Source:
public void releaseSlotFor(LocalAssignment assignment, int port) throws IOException { PortAndAssignment pna = new PortAndAssignmentImpl(port, assignment); final String topologyId = assignment.get_topology_id(); LOG.debug("Releasing slot for {}", topologyId, port); String topoJarKey = ConfigUtils.masterStormJarKey(topologyId); String topoCodeKey = ConfigUtils.masterStormCodeKey(topologyId); String topoConfKey = ConfigUtils.masterStormConfKey(topologyId); LocallyCachedBlob topoJar = topologyBlobs.get(topoJarKey); if (topoJar != null) { topoJar.removeReference(pna); } LocallyCachedBlob topoCode = topologyBlobs.get(topoCodeKey); if (topoCode != null) { topoCode.removeReference(pna); } LocallyCachedBlob topoConfBlob = topologyBlobs.get(topoConfKey); if (topoConfBlob != null) { topoConfBlob.removeReference(pna); } List<LocalResource> localResources = null; try { localResources = getLocalResources(pna); } catch (FileNotFoundException fnfException) { LOG.warn("Local base blobs have not been downloaded yet. " + "DownloadExecService is too busy", fnfException); return; } catch (IOException ioException) { LOG.error("Unable to read local conf file. ", ioException); throw ioException; } for (LocalResource lr : localResources) { try { removeBlobReference(lr.getBlobName(), pna, lr.shouldUncompress()); } catch (Exception e) { throw new IOException(e); } } }

Target:
public void releaseSlotFor(LocalAssignment assignment, int port) throws IOException { PortAndAssignment pna = new PortAndAssignmentImpl(port, assignment); final String topologyId = assignment.get_topology_id(); LOG.debug("Releasing slot for {}", topologyId, port); String topoJarKey = ConfigUtils.masterStormJarKey(topologyId); String topoCodeKey = ConfigUtils.masterStormCodeKey(topologyId); String topoConfKey = ConfigUtils.masterStormConfKey(topologyId); LocallyCachedBlob topoJar = topologyBlobs.get(topoJarKey); if (topoJar != null) { topoJar.removeReference(pna); } LocallyCachedBlob topoCode = topologyBlobs.get(topoCodeKey); if (topoCode != null) { topoCode.removeReference(pna); } LocallyCachedBlob topoConfBlob = topologyBlobs.get(topoConfKey); if (topoConfBlob != null) { topoConfBlob.removeReference(pna); } List<LocalResource> localResources; try { localResources = getLocalResources(pna); } catch (IOException e) { LOG.info("Port and assignment info: {}", pna); if (e instanceof FileNotFoundException) { localResourceFileNotFoundWhenReleasingSlot.mark(); LOG.warn("Local base blobs have not been downloaded yet. ", e); return; } else { LOG.error("Unable to read local file. ", e); throw e; } } for (LocalResource lr : localResources) { removeBlobReference(lr.getBlobName(), pna, lr.shouldUncompress()); } }
Source:
public void test_named_parameters() throws Throwable { Class<?> moduleClass = compileAndLoadGoloModule(SRC, "namedparameters-function-calls.golo"); Method createPost = moduleClass.getMethod("create_post", Object.class, Object.class, Object.class); GoloFunction annotatation = createPost.getAnnotation(GoloFunction.class); assertThat(annotatation, is(notNullValue())); assertThat(Arrays.asList(annotatation.parameters()), containsInAnyOrder("author", "title", "content")); Method createPostOk = moduleClass.getMethod("create_post_ok"); String result = (String) createPostOk.invoke(null); assertThat(result, is("John Awesome Post Lorem Ipsum")); Method createPostWithInvalidArgumentName = moduleClass.getMethod("create_post_with_invalid_argument_name"); try { createPostWithInvalidArgumentName.invoke(null); fail("Exception should have been thrown"); } catch (InvocationTargetException e) { assertThat(e.getCause(), instanceOf(IllegalArgumentException.class)); IllegalArgumentException iae = (IllegalArgumentException) e.getCause(); assertThat(iae.getMessage(), is("Argument name foo not in parameter names used in declaration: create_post[author, title, content]")); } Method csvBuilder = moduleClass.getMethod("csv_builder"); result = (String) csvBuilder.invoke(null); assertThat(result, is("a,b,c")); }

Target:
public void test_named_parameters() throws Throwable { Class<?> moduleClass = compileAndLoadGoloModule(SRC, "namedparameters-function-calls.golo"); Method createPostOk = moduleClass.getMethod("create_post_ok"); String result = (String) createPostOk.invoke(null); assertThat(result, is("John Awesome Post Lorem Ipsum")); Method createPostWithInvalidArgumentName = moduleClass.getMethod("create_post_with_invalid_argument_name"); try { createPostWithInvalidArgumentName.invoke(null); fail("Exception should have been thrown"); } catch (InvocationTargetException e) { assertThat(e.getCause(), instanceOf(IllegalArgumentException.class)); IllegalArgumentException iae = (IllegalArgumentException) e.getCause(); assertThat(iae.getMessage(), is("Argument name foo not in parameter names used in declaration: create_post[author, title, content]")); } Method csvBuilder = moduleClass.getMethod("csv_builder"); result = (String) csvBuilder.invoke(null); assertThat(result, is("a,b,c")); try { compileAndLoadGoloModule(SRC, "failure-function-call-with-named-and-unamed-args.golo"); fail("A GoloCompilationException was expected"); } catch (GoloCompilationException e) { assertThat(e.getProblems().size(), is(1)); Problem problem = e.getProblems().get(0); assertThat(problem.getType(), is(INCOMPLETE_NAMED_ARGUMENTS_USAGE)); } Method golo_decoratored = moduleClass.getMethod("golo_decoratored"); result = (String) golo_decoratored.invoke(null); assertThat(result, is("<Golo>")); Method golo_augmentation_varargs = moduleClass.getMethod("golo_augmentation_varargs"); result = (String) golo_augmentation_varargs.invoke(null); assertThat(result, is("abc")); }
Source:
protected void handleError(final Exception e, final String correlationUid, final String organisationIdentification, final String deviceIdentification, final String messageType) { LOGGER.info("handeling error: for message type: {}", e.getMessage(), messageType); OsgpException osgpException = null; if (e instanceof OsgpException) { osgpException = (OsgpException) e; } else { osgpException = new TechnicalException(ComponentType.DOMAIN_PUBLIC_LIGHTING, "An unknown error occurred", e); } this.webServiceResponseMessageSender.send(ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(correlationUid).withOrganisationIdentification(organisationIdentification) .withDeviceIdentification(deviceIdentification).withResult(ResponseMessageResultType.NOT_OK) .withOsgpException(osgpException).withDataObject(e).build()); }

Target:
protected void handleError(final Exception e, final String correlationUid, final String organisationIdentification, final String deviceIdentification, final String messageType) { LOGGER.info("handeling error: for message type: {}", e.getMessage(), messageType); OsgpException osgpException = null; if (e instanceof OsgpException) { osgpException = (OsgpException) e; } else { osgpException = new TechnicalException(ComponentType.DOMAIN_PUBLIC_LIGHTING, "An unknown error occurred", e); } ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(correlationUid).withOrganisationIdentification(organisationIdentification) .withDeviceIdentification(deviceIdentification).withResult(ResponseMessageResultType.NOT_OK) .withOsgpException(osgpException).withDataObject(e).build(); this.webServiceResponseMessageSender.send(responseMessage); }
Source:
public void setPriority(int priority) { if (NICE_VALUES.length != (1 + Thread.MAX_PRIORITY - Thread.MIN_PRIORITY)) { throw new AssertionError("NICE_VALUES[] length is not correct"); } if (priority < Thread.MIN_PRIORITY || priority > Thread.MAX_PRIORITY) { throw new IllegalArgumentException("Priority out of range: " + priority); } Process.setThreadPriority(NICE_VALUES[priority - Thread.MIN_PRIORITY]); }

Target:
public void setPriority(int priority) { if (NICE_VALUES.length != (1 + Thread.MAX_PRIORITY - Thread.MIN_PRIORITY)) { throw new AssertionError("Unexpected NICE_VALUES.length=" + NICE_VALUES.length); } if (priority < Thread.MIN_PRIORITY || priority > Thread.MAX_PRIORITY) { throw new IllegalArgumentException("Priority out of range: " + priority); } Process.setThreadPriority(NICE_VALUES[priority - Thread.MIN_PRIORITY]); }
Source:
private static List<Policy> parse(String policyString) { List<Policy> list = new LinkedList<Policy>(); String[] policies = policyString.split(" and "); for (String policy : policies) { policy = policy.trim(); String name; String[] args = null; int i = policy.indexOf('('); if (i == -1) { name = policy.trim(); } else { name = policy.substring(0, i).trim(); args = policy.substring(i + 1, policy.length() - 1).split(","); for (int j = 0; j < args.length; j++) { args[j] = args[j].trim(); } } if (name.equals(Length.NAME)) { list.add(new Length(args)); } else if (name.equals(Digits.NAME)) { list.add(new Digits(args)); } else if (name.equals(LowerCase.NAME)) { list.add(new LowerCase(args)); } else if (name.equals(UpperCase.NAME)) { list.add(new UpperCase(args)); } else if (name.equals(SpecialChars.NAME)) { list.add(new SpecialChars(args)); } else if (name.equals(NotUsername.NAME)) { list.add(new NotUsername(args)); } else if (name.equals(HashIterations.NAME)) { list.add(new HashIterations(args)); } else if (name.equals(RegexPatterns.NAME)) { for (String regexPattern : args) { Pattern.compile(regexPattern); } list.add(new RegexPatterns(args)); } else if (name.equals(ExpiredPasswords.NAME)) { list.add(new ExpiredPasswords(args)); } } return list; }

Target:
private static List<Policy> parse(String policyString) { List<Policy> list = new LinkedList<Policy>(); String[] policies = policyString.split(" and "); for (String policy : policies) { policy = policy.trim(); String name; String[] args = null; int i = policy.indexOf('('); if (i == -1) { name = policy.trim(); } else { name = policy.substring(0, i).trim(); args = policy.substring(i + 1, policy.length() - 1).split(","); for (int j = 0; j < args.length; j++) { args[j] = args[j].trim(); } } if (name.equals(Length.NAME)) { list.add(new Length(args)); } else if (name.equals(Digits.NAME)) { list.add(new Digits(args)); } else if (name.equals(LowerCase.NAME)) { list.add(new LowerCase(args)); } else if (name.equals(UpperCase.NAME)) { list.add(new UpperCase(args)); } else if (name.equals(SpecialChars.NAME)) { list.add(new SpecialChars(args)); } else if (name.equals(NotUsername.NAME)) { list.add(new NotUsername(args)); } else if (name.equals(HashIterations.NAME)) { list.add(new HashIterations(args)); } else if (name.equals(RegexPatterns.NAME)) { for (String regexPattern : args) { Pattern.compile(regexPattern); } list.add(new RegexPatterns(args)); } else if (name.equals(PasswordHistory.NAME)) { list.add(new PasswordHistory(args)); } } return list; }
Source:
protected OperatingMode determineOperatingMode() { try { operatingMode = OperatingMode.API; dataReader.setXBeeReaderMode(operatingMode); ATCommandResponse response = sendATCommand(new ATCommand("AP")); if (response.getResponse() != null && response.getResponse().length > 0) { if (response.getResponse()[0] == OperatingMode.API.getID()) return OperatingMode.API; else return OperatingMode.API_ESCAPE; } } catch (XBeeException e) { operatingMode = OperatingMode.AT; dataReader.setXBeeReaderMode(operatingMode); try { Thread.sleep(1200); boolean success = enterATCommandMode(); if (success) return OperatingMode.AT; } catch (InvalidOperatingModeException e1) { } catch (XBeeException e1) { } catch (InterruptedException e2) { } } catch (InvalidOperatingModeException e) { } return OperatingMode.UNKNOWN; }

Target:
protected OperatingMode determineOperatingMode() { try { operatingMode = OperatingMode.API; dataReader.setXBeeReaderMode(operatingMode); ATCommandResponse response = sendATCommand(new ATCommand("AP")); if (response.getResponse() != null && response.getResponse().length > 0) { if (response.getResponse()[0] == OperatingMode.API.getID()) return OperatingMode.API; else return OperatingMode.API_ESCAPE; } } catch (XBeeException e) { if (e.getErrorCode() == XBeeException.CONNECTION_TIMEOUT) { operatingMode = OperatingMode.AT; dataReader.setXBeeReaderMode(operatingMode); try { Thread.sleep(TIMEOUT_BEFORE_COMMAND_MODE); boolean success = enterATCommandMode(); if (success) return OperatingMode.AT; } catch (InvalidOperatingModeException e1) { } catch (XBeeException e1) { } catch (InterruptedException e2) { } } } catch (InvalidOperatingModeException e) { } return OperatingMode.UNKNOWN; }
Source:
public ZkCoordinator( SegmentLoadDropHandler loadDropHandler, ObjectMapper jsonMapper, ZkPathsConfig zkPaths, DruidServerMetadata me, CuratorFramework curator, SegmentLoaderConfig config ) { this.dataSegmentChangeHandler = loadDropHandler; this.jsonMapper = jsonMapper; this.zkPaths = zkPaths; this.me = me; this.curator = curator; this.loadSegmentService = Executors.newFixedThreadPool( config.getNumLoadingThreads(), new ThreadFactoryBuilder().setNameFormat( "ZKCoordinator-LoadSegment--%d").build() ); }

Target:
public ZkCoordinator( SegmentLoadDropHandler loadDropHandler, ObjectMapper jsonMapper, ZkPathsConfig zkPaths, DruidServerMetadata me, CuratorFramework curator, SegmentLoaderConfig config ) { this.dataSegmentChangeHandler = loadDropHandler; this.jsonMapper = jsonMapper; this.zkPaths = zkPaths; this.me = me; this.curator = curator; this.segmentLoadUnloadService = Execs.multiThreaded( config.getNumLoadingThreads(), "ZKCoordinator--%d" ); }
Source:
private static Object readArrayTillTheEnd(final StringTokenizer tokenizer) { final JSONArray result = new JSONArray(); final char possibleEnd = tokenizer.nextUnskippable(); if (possibleEnd == ']') { return result; } tokenizer.back(); boolean finished = false; while (!finished) { result.put(parse(tokenizer)); final char separator = tokenizer.nextUnskippable(); if (separator == ']') { finished = true; } else if (separator != ',') { throw syntaxError("Unexpected separator " + separator, tokenizer); } } return result; }

Target:
private static Object readArrayTillTheEnd(final StringTokenizer tokenizer) { final JSONArray result = new JSONArray(); final char possibleEnd = tokenizer.nextUnskippable(); if (possibleEnd == ']') { return result; } tokenizer.back(); boolean finished = false; while (!finished) { result.put(parse(tokenizer)); final char separator = tokenizer.nextUnskippable(); if (separator == ']') { finished = true; } else if (separator != ',') { throw syntaxError("Unexpected separator '" + separator + "'", tokenizer); } } return result; }
Source:
public Iterable<SingleServerAppliance> listImages() { GenericQueryOptions options = new GenericQueryOptions(); options.options(0, 0, null, Types.OSImageType.Minimal.toString(), null); List<ServerAppliance> list = api.serverApplianceApi().list(options); List<SingleServerAppliance> results = new ArrayList<SingleServerAppliance>(); for (ServerAppliance appliance : list) { List<SingleServerAppliance.AvailableDataCenters> availableDatacenters = new ArrayList<SingleServerAppliance.AvailableDataCenters>(); for (String dcId : appliance.availableDataCenters()) { availableDatacenters.add(SingleServerAppliance.AvailableDataCenters.create(dcId, "")); } results.add(SingleServerAppliance.create(appliance.id(), appliance.name(), availableDatacenters, appliance.osInstallationBase(), appliance.osFamily(), appliance.os(), appliance.osVersion(), appliance.osArchitecture(), appliance.osImageType(), appliance.minHddSize(), appliance.type(), appliance.state(), appliance.version(), appliance.categories(), appliance.eulaUrl())); } return results; }

Target:
public Iterable<SingleServerAppliance> listImages() { GenericQueryOptions options = new GenericQueryOptions(); options.options(0, 0, null, null, null); List<ServerAppliance> list = api.serverApplianceApi().list(options); List<SingleServerAppliance> results = new ArrayList<SingleServerAppliance>(); for (ServerAppliance appliance : list) { List<SingleServerAppliance.AvailableDataCenters> availableDatacenters = new ArrayList<SingleServerAppliance.AvailableDataCenters>(); for (String dcId : appliance.availableDataCenters()) { availableDatacenters.add(SingleServerAppliance.AvailableDataCenters.create(dcId, "")); } results.add(SingleServerAppliance.builder() .id(appliance.id()) .name(appliance.name()) .availableDataCenters(availableDatacenters) .osInstallationBase(appliance.osInstallationBase()) .osFamily(appliance.osFamily()) .os(appliance.os()) .osVersion(appliance.osVersion()) .osArchitecture(appliance.osArchitecture()) .osImageType(appliance.osImageType()) .minHddSize(appliance.minHddSize()) .type(appliance.type()) .state(appliance.state()) .version(appliance.version()) .categories(appliance.categories()) .eulaUrl(appliance.eulaUrl()) .build()); } return results; }
Source:
private Optional<PinotExpression> handleDateOrTimestampBinaryExpression(String operator, List<RowExpression> arguments, Function<VariableReferenceExpression, Selection> context) { String leftDefinition = arguments.get(0).accept(this, context).getDefinition(); String rightDefinition = arguments.get(1).accept(this, context).getDefinition(); Optional<String> left = handleTimeValueCast(arguments.get(1), arguments.get(0), leftDefinition); Optional<String> right = handleTimeValueCast(arguments.get(0), arguments.get(1), rightDefinition); if (left.isPresent() && right.isPresent()) { return Optional.of(derived(format("(%s %s %s)", left.get(), operator, right.get()))); } else { return Optional.empty(); } }

Target:
private Optional<PinotExpression> handleDateOrTimestampBinaryExpression(String operator, List<RowExpression> arguments, Function<VariableReferenceExpression, Selection> context) { Optional<String> left = handleTimeValueCast(context, arguments.get(1), arguments.get(0)); Optional<String> right = handleTimeValueCast(context, arguments.get(0), arguments.get(1)); if (left.isPresent() && right.isPresent()) { return Optional.of(derived(format("(%s %s %s)", left.get(), operator, right.get()))); } else { return Optional.empty(); } }