auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void selectFindInItem(final MenuItem menuItem) { if (menuItem == allItem) selectFindInItem(menuItem, PREFS_FINDIN_ALL, allIcon, UIText.HistoryPage_findbar_changeto_comments); else if (menuItem == commentsItem) selectFindInItem(menuItem, PREFS_FINDIN_COMMENTS, commentsIcon, UIText.HistoryPage_findbar_changeto_author); else if (menuItem == authorItem) selectFindInItem(menuItem, PREFS_FINDIN_AUTHOR, authorIcon, UIText.HistoryPage_findbar_changeto_commit); else if (menuItem == commitIdItem) selectFindInItem(menuItem, PREFS_FINDIN_COMMITID, commitIdIcon, UIText.HistoryPage_findbar_changeto_committer); else if (menuItem == committerItem) selectFindInItem(menuItem, PREFS_FINDIN_COMMITTER, committerIcon, UIText.HistoryPage_findbar_changeto_all); else if (menuItem == referenceItem) selectFindInItem(menuItem, PREFS_FINDIN_REFERENCE, referenceIcon, UIText.HistoryPage_findbar_changeto_reference); }

Target:
private void selectFindInItem(final MenuItem menuItem) { if (menuItem == allItem) selectFindInItem(menuItem, PREFS_FINDIN_ALL, allIcon, UIText.HistoryPage_findbar_changeto_comments); else if (menuItem == commentsItem) selectFindInItem(menuItem, PREFS_FINDIN_COMMENTS, commentsIcon, UIText.HistoryPage_findbar_changeto_author); else if (menuItem == authorItem) selectFindInItem(menuItem, PREFS_FINDIN_AUTHOR, authorIcon, UIText.HistoryPage_findbar_changeto_commit); else if (menuItem == commitIdItem) selectFindInItem(menuItem, PREFS_FINDIN_COMMITID, commitIdIcon, UIText.HistoryPage_findbar_changeto_committer); else if (menuItem == committerItem) selectFindInItem(menuItem, PREFS_FINDIN_COMMITTER, committerIcon, UIText.HistoryPage_findbar_changeto_reference); else if (menuItem == referenceItem) selectFindInItem(menuItem, PREFS_FINDIN_REFERENCE, branchesIcon, UIText.HistoryPage_findbar_changeto_all); }
Source:
private void getApprovalNames() throws OrmException { SortedMap<Short, String> acvMap = new TreeMap<Short, String>(); optionList = new ArrayList<CmdOption>(); ResultSet<ApprovalCategory> rs = db.approvalCategories().all(); for (ApprovalCategory c : rs) { if (c.getFunctionName().equals("MaxWithBlock")) { ResultSet<ApprovalCategoryValue> acvrs = db.approvalCategoryValues().byCategory(c.getId()); short min = Short.MAX_VALUE; short max = Short.MIN_VALUE; String usage = ""; for (ApprovalCategoryValue acv : acvrs) { if (min > acv.getValue()) { min = acv.getValue(); } if (max < acv.getValue()) { max = acv.getValue(); } acvMap.put(acv.getValue(), acv.getName()); } usage += "Score for " + c.getName() + "\n"; Iterator<Short> i = acvMap.keySet().iterator(); while (i.hasNext()) { Short key = i.next(); usage += String.format("%4d", key) + " - " + acvMap.get(key) + "\n"; } optionList.add(new CmdOption("--" + c.getName().toLowerCase() .replace(' ', '-'), usage, c.getId().get(), min, max, c.getName())); usage = ""; acvMap.clear(); } } }

Target:
private void getApprovalNames() throws OrmException { optionList = new ArrayList<CmdOption>(); for (ApprovalType type : approvalTypes.getApprovalTypes()) { String usage = ""; final ApprovalCategory category = type.getCategory(); if (category.getFunctionName().equals("MaxWithBlock")) { usage = "Score for " + category.getName() + "\n"; for (ApprovalCategoryValue v : type.getValues()) { usage += String.format("%4d", v.getValue()) + " - " + v.getName() + "\n"; } } optionList.add( new CmdOption( "--" + category.getName().toLowerCase().replace(' ', '-'), usage, category.getId().get(), type.getMin().getValue(), type.getMax().getValue(), category.getName())); } }
Source:
public A create(I id) { final Constructor<A> entityConstructor = getEntityConstructor(); final AggregateRoot<I> root = createAggregateRootEntity(id, getBoundedContext(), rootClass); final A result = createAggregatePartEntity(entityConstructor, id, root); return result; }

Target:
public A create(I id) { final Constructor<A> entityConstructor = getEntityConstructor(); final Class<R> rootClass = getGenericParameterType(this.getClass(), 2); final AggregateRoot<I> root = createAggregateRoot(id, getBoundedContext(), rootClass); final A result = createAggregatePart(entityConstructor, root); return result; }
Source:
NettyPartitionRequestClient createPartitionRequestClient(ConnectionID connectionId) throws IOException, InterruptedException { while (true) { AtomicReference<Optional<CompletableFuture<NettyPartitionRequestClient>>> computeFuture = new AtomicReference<>(Optional.empty()); CompletableFuture<NettyPartitionRequestClient> waitFuture = clients.computeIfAbsent(connectionId, unused -> { CompletableFuture<NettyPartitionRequestClient> future = new CompletableFuture<>(); computeFuture.set(Optional.of(future)); return future; }); computeFuture.get().ifPresent(future -> future.complete(connectWithRetries(connectionId))); final NettyPartitionRequestClient client; try { client = waitFuture.get(); } catch (ExecutionException e) { throw new IOException(e); } if (client.incrementReferenceCounter()) { return client; } else { destroyPartitionRequestClient(connectionId, client); } } }

Target:
NettyPartitionRequestClient createPartitionRequestClient(ConnectionID connectionId) throws IOException, InterruptedException { while (true) { AtomicBoolean isTheFirstOne = new AtomicBoolean(false); CompletableFuture<NettyPartitionRequestClient> clientFuture = clients.computeIfAbsent(connectionId, unused -> { isTheFirstOne.set(true); return new CompletableFuture<>(); }); if (isTheFirstOne.get()) { clientFuture.complete(connectWithRetries(connectionId)); } final NettyPartitionRequestClient client; try { client = clientFuture.get(); } catch (ExecutionException e) { throw new IOException(e); } if (client.incrementReferenceCounter()) { return client; } else { destroyPartitionRequestClient(connectionId, client); } } }
Source:
private List<AuditEntry> fetchAuditHistoryLastEntries(final String key, final String type, int limit) throws IllegalArgumentException { final int theLimit = getLimit(limit); String queryString = "SELECT payload FROM %s WHERE type = :type"; if (key != null) { queryString += " and audit_key = :audit_key"; } queryString += " ORDER BY created_date DESC"; final String theQueryString = queryString; return dbi.withHandle( new HandleCallback<List<AuditEntry>>() { @Override public List<AuditEntry> withHandle(Handle handle) throws Exception { Query<Map<String, Object>> query = handle.createQuery(String.format(theQueryString, getAuditTable())); if (key != null) { query.bind("audit_key", key); } return query.bind("type", type) .setMaxRows(theLimit) .map( new ResultSetMapper<AuditEntry>() { @Override public AuditEntry map(int index, ResultSet r, StatementContext ctx) throws SQLException { try { return jsonMapper.readValue(r.getBytes("payload"), AuditEntry.class); } catch (IOException e) { throw new SQLException(e); } } } ) .list(); } } ); }

Target:
private List<AuditEntry> fetchAuditHistoryLastEntries(final String key, final String type, int limit) throws IllegalArgumentException { final int theLimit = getLimit(limit); String queryString = String.format("SELECT payload FROM %s WHERE type = :type", getAuditTable()); if (key != null) { queryString += " and audit_key = :audit_key"; } queryString += " ORDER BY created_date DESC"; final String theQueryString = queryString; return dbi.withHandle( new HandleCallback<List<AuditEntry>>() { @Override public List<AuditEntry> withHandle(Handle handle) throws Exception { Query<Map<String, Object>> query = handle.createQuery(theQueryString); if (key != null) { query.bind("audit_key", key); } return query.bind("type", type) .setMaxRows(theLimit) .map( new ResultSetMapper<AuditEntry>() { @Override public AuditEntry map(int index, ResultSet r, StatementContext ctx) throws SQLException { try { return jsonMapper.readValue(r.getBytes("payload"), AuditEntry.class); } catch (IOException e) { throw new SQLException(e); } } } ) .list(); } } ); }
Source:
private void writeCrlToFile(ByteSource byteSource, File crlFile) { try { AccessController.doPrivileged( (PrivilegedExceptionAction<Void>) () -> { try (OutputStream outStream = new FileOutputStream(crlFile); InputStream inputStream = byteSource.openStream()) { IOUtils.copy(inputStream, outStream); SecurityLogger.audit( "Copied the content of the CRl at to the local CRL at {}.", crlLocationUrl, crlFile.getPath()); setCrlFileLocationInPropertiesFile(crlFile.getPath()); } return null; }); } catch (PrivilegedActionException e) { LOGGER.warn("Unable to save the CRL. {}", e.getCause()); postErrorEvent("Unable to save the CRL."); } }

Target:
private void writeCrlToFile(ByteSource byteSource, File crlFile) { try { AccessController.doPrivileged( (PrivilegedExceptionAction<Void>) () -> { try (OutputStream outStream = new FileOutputStream(crlFile); InputStream inputStream = byteSource.openStream()) { IOUtils.copy(inputStream, outStream); SecurityLogger.audit( "Copied the content of the CRl at to the local CRL at {}.", crlLocationUrl, crlFile.getPath()); setCrlFileLocationInPropertiesFile(crlFile.getPath()); } return null; }); } catch (PrivilegedActionException e) { LOGGER.warn("Unable to save the CRL."); LOGGER.debug("Unable to save the CRL. {}", e.getCause()); postErrorEvent("Unable to save the CRL."); } }
Source:
public void run() { super.run(); EObject target; LineContainer lineContainer; if (getLine() != null) { target = getLine().getTarget(); lineContainer = (LineContainer) getLine().eContainer(); } else { target = table.getTarget(); lineContainer = table; } CompoundCommand compoundCommand = new CompoundCommand(getText()); Command cmd = tableCommandFactory.buildCreateLineCommandFromTool(lineContainer, target, getCreateTool()); compoundCommand.append(cmd); getEditingDomain().getCommandStack().execute(compoundCommand); }

Target:
public void run() { super.run(); EObject target; LineContainer lineContainer; DLine dLine = getLine(); if (dLine != null) { target = dLine.getTarget(); lineContainer = (LineContainer) dLine.eContainer(); } else { target = table.getTarget(); lineContainer = table; } Command cmd = tableCommandFactory.buildCreateLineCommandFromTool(lineContainer, target, getCreateTool()); String label = getText(); cmd = new CommandWrapper(label, label, cmd); getEditingDomain().getCommandStack().execute(cmd); }
Source:
public void testComputeBroadcast() throws Exception { latch = new CountDownLatch(1); try(IgniteEx g1 = startGrid(0)) { SystemView<ComputeTaskView> tasks = g1.context().metric().view(TASKS_VIEW); for (int i=0; i<5; i++) g1.compute().broadcastAsync(() -> { try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } }); assertEquals(5, tasks.size()); ComputeTaskView t = tasks.iterator().next(); assertFalse(t.internal()); assertNull(t.affinityCacheName()); assertEquals(-1, t.affinityPartitionId()); assertTrue(t.taskClassName().startsWith(getClass().getName())); assertTrue(t.taskName().startsWith(getClass().getName())); assertEquals(g1.localNode().id(), t.taskNodeId()); assertEquals("0", t.userVersion()); latch.countDown(); } }

Target:
public void testComputeBroadcast() throws Exception { CyclicBarrier barrier = new CyclicBarrier(6); try (IgniteEx g1 = startGrid(0)) { SystemView<ComputeTaskView> tasks = g1.context().systemView().view(TASKS_VIEW); for (int i = 0; i < 5; i++) { g1.compute().broadcastAsync(() -> { try { barrier.await(); barrier.await(); } catch (InterruptedException | BrokenBarrierException e) { throw new RuntimeException(e); } }); } barrier.await(); assertEquals(5, tasks.size()); ComputeTaskView t = tasks.iterator().next(); assertFalse(t.internal()); assertNull(t.affinityCacheName()); assertEquals(-1, t.affinityPartitionId()); assertTrue(t.taskClassName().startsWith(getClass().getName())); assertTrue(t.taskName().startsWith(getClass().getName())); assertEquals(g1.localNode().id(), t.taskNodeId()); assertEquals("0", t.userVersion()); barrier.await(); } }
Source:
public byte[] getCacheKey() { return new CacheKeyBuilder(DimFilterUtils.FALSE_CACHE_ID).build(); }

Target:
public byte[] getCacheKey() { return CACHE_KEY; }
Source:
public static boolean isNetworkConnectionPresent(Context ctx) { ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); return isConnected; }

Target:
public static boolean isNetworkConnectionPresent(Context ctx) { ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnected(); return isConnected; }
Source:
public void onStatusChanged(String provider, int status, Bundle extras) { String quality = ""; switch (status) { case IALocationManager.STATUS_CALIBRATION_CHANGED: if (extras != null) { switch (extras.getInt("quality")) { case IALocationManager.CALIBRATION_POOR: quality = "Poor"; break; case IALocationManager.CALIBRATION_GOOD: quality = "Good"; break; case IALocationManager.CALIBRATION_EXCELLENT: quality = "Excellent"; break; } log("Calibration change. Quality: " + quality); } break; case IALocationManager.STATUS_AVAILABLE: log("onStatusChanged: Available"); break; case IALocationManager.STATUS_LIMITED: log("onStatusChanged: Limited"); break; case IALocationManager.STATUS_OUT_OF_SERVICE: log("onStatusChanged: Out of service"); break; case IALocationManager.STATUS_TEMPORARILY_UNAVAILABLE: log("onStatusChanged: Temporarily unavailable"); } }

Target:
public void onStatusChanged(String provider, int status, Bundle extras) { switch (status) { case IALocationManager.STATUS_CALIBRATION_CHANGED: String quality = "unknown"; switch (extras.getInt("quality")) { case IALocationManager.CALIBRATION_POOR: quality = "Poor"; break; case IALocationManager.CALIBRATION_GOOD: quality = "Good"; break; case IALocationManager.CALIBRATION_EXCELLENT: quality = "Excellent"; break; } log("Calibration change. Quality: " + quality); break; case IALocationManager.STATUS_AVAILABLE: log("onStatusChanged: Available"); break; case IALocationManager.STATUS_LIMITED: log("onStatusChanged: Limited"); break; case IALocationManager.STATUS_OUT_OF_SERVICE: log("onStatusChanged: Out of service"); break; case IALocationManager.STATUS_TEMPORARILY_UNAVAILABLE: log("onStatusChanged: Temporarily unavailable"); } }
Source:
public Span startProcessor(@Nullable Chan channel, Msg message, boolean addConsumerSpan) { if (!addConsumerSpan) { Span result = tracer.nextSpan().start(); if (!result.isNoop()) { consumerHandler.parser.addMessageTags(adapter, channel, message, result.context(), result.customizer()); } return result; } C carrier = adapter.carrier(message); return consumerHandler.handleReceive(channel, message, carrier, adapter.brokerName(channel), consumerHandler.extractor.extract(carrier), true); }

Target:
public Span startProcessor(@Nullable Chan channel, Msg message, boolean addConsumerSpan) { C carrier = adapter.carrier(message); TraceContextOrSamplingFlags extracted = consumerHandler.extractor.extract(carrier); if (!addConsumerSpan) { Span result = tracer.nextSpan(extracted).start(); if (!result.isNoop() && extracted.equals(TraceContextOrSamplingFlags.EMPTY)) { consumerHandler.parser .addMessageTags(adapter, channel, message, result.context(), result.customizer()); } return result; } return consumerHandler.handleReceive(channel, message, carrier, adapter.brokerName(channel), extracted, true); }
Source:
private void generateFileList(File localDir, String remotePath, List<BlobDetail> blobDetails) { for (File localFile: localDir.listFiles()) { if (localFile.isFile()) { String remoteBlobName = remotePath + localFile.getName(); blobDetails.add(new BlobDetail(remoteBlobName, localFile)); } else { generateFileList(localFile, remotePath + localFile.getName() + "/", blobDetails); } } }

Target:
private void generateFileList(File localDir, String remotePath, List<BlobDetail> blobDetails) { for (File localFile: localDir.listFiles()) { String remoteBlobName = remotePath + localFile.getName(); if (localFile.isFile()) { blobDetails.add(new BlobDetail(remoteBlobName, localFile)); } else { generateFileList(localFile, remoteBlobName + "/", blobDetails); } } }
Source:
public final int parseArguments(final Parameters params) throws CmdLineException { final String token = params.getParameter(0); final String[] tokens = token.split(","); if (tokens.length != 3) { throw new CmdLineException(owner, "change should be specified as " + "<project>,<branch>,<change-id>"); } try { final Change.Key key = Change.Key.parse(tokens[2]); final Project.NameKey project = new Project.NameKey(tokens[0]); final Branch.NameKey branch = new Branch.NameKey(project, "refs/heads/" + tokens[1]); for (final Change change : db.changes().byBranchKey(branch, key)) { setter.addValue(change.getId()); return 1; } } catch (IllegalArgumentException e) { throw new CmdLineException(owner, "Change-Id is not valid"); } catch (OrmException e) { throw new CmdLineException(owner, "Database error: " + e.getMessage()); } throw new CmdLineException(owner, "\"" + token + "\": change not found"); }

Target:
public final int parseArguments(final Parameters params) throws CmdLineException { final String token = params.getParameter(0); final String[] tokens = token.split(","); if (tokens.length != 3) { throw new CmdLineException(owner, "change should be specified as " + "<project>,<branch>,<change-id>"); } try { final Change.Key key = Change.Key.parse(tokens[2]); final Project.NameKey project = new Project.NameKey(tokens[0]); final Branch.NameKey branch = new Branch.NameKey(project, tokens[1]); for (final Change change : db.changes().byBranchKey(branch, key)) { setter.addValue(change.getId()); return 1; } } catch (IllegalArgumentException e) { throw new CmdLineException(owner, "Change-Id is not valid"); } catch (OrmException e) { throw new CmdLineException(owner, "Database error: " + e.getMessage()); } throw new CmdLineException(owner, "\"" + token + "\": change not found"); }
Source:
} catch (Throwable t) { }

Target:
} catch (Throwable t) { if (log.isDebugEnabled()) { log.debug("Unable to use 'onSpinWait' from JVM", t); } }
Source:
protected static String pad(final String in, final int length) { final StringBuilder inBuilder = new StringBuilder(Math.max(length, in.length())); while (inBuilder.length() < length - in.length()) { inBuilder.append(" "); } return inBuilder.append(in).toString(); }

Target:
static String pad(final String in, final int length) { final StringBuilder inBuilder = new StringBuilder(Math.max(length, in.length())); while (inBuilder.length() < length - in.length()) { inBuilder.append(" "); } return inBuilder.append(in).toString(); }
Source:
protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Wootric.with(this) .user(CLIENT_ID, CLIENT_SECRET, ACCOUNT_TOKEN) .endUser("junkuits@gmail.com", "ORIGIN URL") .survey(); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Wootric.with(this) .user(CLIENT_ID, CLIENT_SECRET, ACCOUNT_TOKEN) .endUser("END USER EMAIL", "ORIGIN URL") .survey(); }
Source:
boolean isHealthy() { boolean scriptHealthStatus = nodeHealthScriptRunner == null || nodeHealthScriptRunner.isHealthy(); return nodeHealthException == null && scriptHealthStatus && dirsHandler.areDisksHealthy(); }

Target:
boolean isHealthy() { boolean scriptHealthy = nodeHealthScriptRunner == null || nodeHealthScriptRunner.isHealthy(); return nodeHealthException == null && scriptHealthy && dirsHandler.areDisksHealthy(); }
Source:
static void addConditionParams(NewAction action) { action .createParam(PARAM_METRIC) .setDescription("Condition metric") .setRequired(true) .setExampleValue("blocker_violations"); action.createParam(PARAM_OPERATOR) .setDescription("Condition operator:<br/>" + "<ul>" + "<li>EQ = equals</li>" + "<li>NE = is not</li>" + "<li>LT = is lower than</li>" + "<li>GT = is greater than</li>" + "</ui>") .setExampleValue(QualityGateConditionDto.OPERATOR_EQUALS) .setPossibleValues(QualityGateConditionDto.ALL_OPERATORS); action.createParam(PARAM_PERIOD) .setDescription("Condition period. If not set, the absolute value is considered.") .setPossibleValues("1"); action.createParam(PARAM_WARNING) .setMaximumLength(VALUE_LENGTH) .setDescription("Condition warning threshold") .setExampleValue("5"); action.createParam(PARAM_ERROR) .setMaximumLength(VALUE_LENGTH) .setDescription("Condition error threshold") .setExampleValue("10"); }

Target:
static void addConditionParams(NewAction action) { action .createParam(PARAM_METRIC) .setDescription("Condition metric") .setRequired(true) .setExampleValue("blocker_violations"); action.createParam(PARAM_OPERATOR) .setDescription("Condition operator:<br/>" + "<ul>" + "<li>EQ = equals</li>" + "<li>NE = is not</li>" + "<li>LT = is lower than</li>" + "<li>GT = is greater than</li>" + "</ui>") .setExampleValue(QualityGateConditionDto.OPERATOR_EQUALS) .setPossibleValues(QualityGateConditionDto.ALL_OPERATORS); action.createParam(PARAM_PERIOD) .setDescription("Condition period. If not set, the absolute value is considered.") .setPossibleValues("1"); action.createParam(PARAM_WARNING) .setMaximumLength(CONDITION_MAX_LENGTH) .setDescription("Condition warning threshold") .setExampleValue("5"); action.createParam(PARAM_ERROR) .setMaximumLength(CONDITION_MAX_LENGTH) .setDescription("Condition error threshold") .setExampleValue("10"); }
Source:
public void removeNode(Node node) { String nodeName = node.getNodeInformation().getName(); String nodeUrl = node.getNodeInformation().getURL(); InetAddress nodeHost = node.getVMInformation().getInetAddress(); String parsedHost = nodeNameBuilder.extractHostFromNodeName(nodeName); putRemovedNodeUrlForHostWithLockAndPersist(parsedHost, node.getNodeInformation().getURL()); logger.info("Removed node " + nodeUrl + " on host " + nodeHost); if (!getHostHasAliveNodesWithLock(parsedHost)) { killNodeProcess(node, nodeHost); setHostNeedsNodesWithLockAndPersist(parsedHost); logger.info("Host " + nodeHost + " has no more alive nodes. Need nodes flag is set."); } }

Target:
public void removeNode(Node node) { String nodeName = node.getNodeInformation().getName(); String nodeUrl = node.getNodeInformation().getURL(); InetAddress nodeHost = node.getVMInformation().getInetAddress(); String parsedHost = nodeNameBuilder.extractHostFromNodeName(nodeName); putRemovedNodeUrlWithLockAndPersist(parsedHost, node.getNodeInformation().getURL()); logger.info("Removed node " + nodeUrl + " on host " + nodeHost); if (!hasAliveNodes(parsedHost)) { killNodeProcess(node, nodeHost); setNeedsNodesWithLockAndPersist(parsedHost, true); logger.info("Host " + nodeHost + " has no more alive nodes. Need nodes flag is set."); } }
Source:
static Type getParameterLowerBound(int index, ParameterizedType type) { Type[] types = type.getActualTypeArguments(); if (index < 0 || index >= types.length) { throw new IllegalArgumentException( "Index " + index + " not in range [0," + types.length + ") for " + type); } Type paramType = types[index]; if (paramType instanceof WildcardType) { return ((WildcardType) paramType).getLowerBounds()[0]; } return paramType; }

Target:
static Type getParameterLowerBound(int index, ParameterizedType type) { Type paramType = type.getActualTypeArguments()[index]; if (paramType instanceof WildcardType) { return ((WildcardType) paramType).getLowerBounds()[0]; } return paramType; }
Source:
private <T> void runParallelInBatchAndWait( Collection<Collection<T>> batches, Closure closure, Logger logger ) { ThreadContext ctx = ThreadContext.getContext( true ); AtomicInteger depth = (AtomicInteger) ctx.computeIfAbsent( ITERATION_DEPTH, k -> new AtomicInteger( -1 ) ); depth.incrementAndGet(); try { final CountDownLatch latch = new CountDownLatch( batches.size() ); batches.forEach( batch -> ruleParallelExecutor.execute( () -> { try { logger.trace( "The paralleled exe on batch {}", batch ); batch.forEach( e -> { MDC.put( ITERATION_ITEM, String.valueOf( e ) ); closure.call( e ); } ); } finally { latch.countDown(); } } ) ); waitForCompletion( latch ); } finally { depth.decrementAndGet(); } }

Target:
private <T> void runParallelInBatchAndWait( Collection<Collection<T>> batches, Closure closure, Logger logger ) { ThreadContext ctx = ThreadContext.getContext( true ); AtomicInteger depth = (AtomicInteger) ctx.computeIfAbsent( ITERATION_DEPTH, k -> new AtomicInteger( -1 ) ); int nextDepth = depth.incrementAndGet(); if ( nextDepth > 0 ) { logger.warn( "Nested parallel iteration detected in promotion validation rule!!" ); } try { final CountDownLatch latch = new CountDownLatch( batches.size() ); batches.forEach( batch -> ruleParallelExecutor.execute( () -> { try { logger.trace( "The paralleled exe on batch {}", batch ); batch.forEach( e -> { MDC.put( ITERATION_ITEM, String.valueOf( e ) ); MDC.put( ITERATION_DEPTH, String.valueOf( depth.get() ) ); try { closure.call( e ); } finally { MDC.remove( ITERATION_ITEM ); MDC.remove( ITERATION_DEPTH ); } } ); } finally { latch.countDown(); } } ) ); waitForCompletion( latch ); } finally { depth.decrementAndGet(); } }
Source:
public void verifyMovingImageAfterZoomingToDirection (PerformTouchAction touchAction, String direction) { Shooter shooter = new Shooter(); ImageComparison ic = new ImageComparison(); File beforeZooming = shooter.capturePage(driver); touchAction.tapOnPointXY(50, 50, 140, 0); touchAction.tapOnPointXY(50, 50, 140, 2000); File afterZooming = shooter.capturePage(driver); if (!ic.areFilesTheSame(beforeZooming, afterZooming)) { PageObjectLogging.log("verifyZoomingByGesture", "Zoom in works", true); } else { PageObjectLogging.log("verifyZoomingByGesture", "Zoom in doesn't work", false); } touchAction.swipeFromCenterToDirection(direction, 200, 200, 2000); File afterMoving = shooter.capturePage(driver); if (!ic.areFilesTheSame(afterZooming, afterMoving)) { PageObjectLogging.log("verifyZoomingByGesture", "Move to " + direction + " works", true); } else { PageObjectLogging.log("verifyZoomingByGesture", "Move to " + direction + " doesn't work", false); } }

Target:
public void verifyMovingImageAfterZoomingToDirection (PerformTouchAction touchAction, String direction) { Shooter shooter = new Shooter(); ImageComparison ic = new ImageComparison(); File beforeZooming = shooter.capturePage(driver); touchAction.tapOnPointXY(50, 50, 140, 0); touchAction.tapOnPointXY(50, 50, 140, 2000); File afterZooming = shooter.capturePage(driver); if (ic.areFilesTheSame(beforeZooming, afterZooming)) { PageObjectLogging.log("verifyZoomingByGesture", "Zoom in doesn't work", false); } else { PageObjectLogging.log("verifyZoomingByGesture", "Zoom in works", true); } touchAction.swipeFromCenterToDirection(direction, 200, 200, 2000); File afterMoving = shooter.capturePage(driver); if (ic.areFilesTheSame(afterZooming, afterMoving)) { PageObjectLogging.log("verifyZoomingByGesture", "Move to " + direction + " doesn't work", false); } else { PageObjectLogging.log("verifyZoomingByGesture", "Move to " + direction + " works", true); } }
Source:
public REVERSE_DEBUG_ACTIONS_ENUM getOperation() { String item = combo.getItem(combo.getSelectionIndex()); return REVERSE_DEBUG_ACTIONS_ENUM.valueOf(item.toUpperCase()); }

Target:
public REVERSE_DEBUG_ACTIONS_ENUM getOperation() { int index = combo.getSelectionIndex(); return REVERSE_DEBUG_ACTIONS_ENUM.getValue(index); }
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof AbstractMatcher)) { return false; } return pattern.equals(((AbstractMatcher) obj).pattern); }

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof AbstractMatcher)) return false; AbstractMatcher other = (AbstractMatcher) obj; return dirOnly == other.dirOnly && pattern.equals(other.pattern); }
Source:
public void different_statements() { verifyBlockCfg("" + "block( succ = [END], elem = 2 ); ;"); verifyBlockCfg("" + "block( succ = [END], elem = 2 ); yield 42;"); verifyBlockCfg("" + "block( succ = [END], elem = 2 ); global $x;"); verifyBlockCfg("" + "block( succ = [END], elem = 2 ); static $x;"); verifyBlockCfg("" + "block( succ = [END], elem = 2 ); echo($x);"); verifyBlockCfg("" + "block( succ = [END], elem = 2 ); echo($x);"); verifyBlockCfg("" + "block( succ = [END], elem = 2 ); declare (x);"); verifyBlockCfg("" + "block( succ = [END], elem = 1 ); ?> <html> <?php"); verifyBlockCfg("" + "block( succ = [END], elem = 2 ); unset($x);"); verifyBlockCfg("" + "block( succ = [END], elem = 2 ); 1, 2;"); verifyBlockCfg("" + "block( succ = [END], elem = 2 ); function foo(){}"); verifyBlockCfg("" + "block( succ = [END], elem = 2 ); class Foo{}"); verifyBlockCfg("" + "block( succ = [END], elem = 2 ); interface Foo{}"); verifyBlockCfg("" + "block( succ = [END], elem = 2 ); trait Foo{}"); }

Target:
public void different_statements() { verifyBlockCfg("" + "block( succ = [END], elem = 2 ); ;"); verifyBlockCfg("" + "block( succ = [END], elem = 2 ); yield 42;"); verifyBlockCfg("" + "block( succ = [END], elem = 2 ); global $x;"); verifyBlockCfg("" + "block( succ = [END], elem = 2 ); static $x;"); verifyBlockCfg("" + "block( succ = [END], elem = 2 ); echo($x);"); verifyBlockCfg("" + "block( succ = [END], elem = 2 ); declare (x);"); verifyBlockCfg("" + "block( succ = [END], elem = 1 ); ?> <html> <?php"); verifyBlockCfg("" + "block( succ = [END], elem = 2 ); unset($x);"); verifyBlockCfg("" + "block( succ = [END], elem = 2 ); 1, 2;"); verifyBlockCfg("" + "block( succ = [END], elem = 2 ); function foo(){}"); verifyBlockCfg("" + "block( succ = [END], elem = 2 ); class Foo{}"); verifyBlockCfg("" + "block( succ = [END], elem = 2 ); interface Foo{}"); verifyBlockCfg("" + "block( succ = [END], elem = 2 ); trait Foo{}"); }
Source:
public static <K, V> List<Pair<K, V>> fetchData(final HdfsSplitInfo hdfsSplitInfo) throws IOException { final ExternalConstructor<JobConf> jobConfExternalConstructor = new JobConfExternalConstructor(hdfsSplitInfo.getInputFormatClassName(), hdfsSplitInfo.getInputPath()); final JobConf jobConf = jobConfExternalConstructor.newInstance(); final RecordReader<K, V> newRecordReader = jobConf.getInputFormat().getRecordReader( hdfsSplitInfo.getInputSplit(), jobConfExternalConstructor.newInstance(), DUMMY_REPORTER); final List<Pair<K, V>> recordList = new ArrayList<>(); while (true) { final Pair<K, V> record = new Pair<>(newRecordReader.createKey(), newRecordReader.createValue()); if (newRecordReader.next(record.getFirst(), record.getSecond())) { recordList.add(record); } else { break; } } return recordList; }

Target:
public static <K, V> Iterator<Pair<K, V>> fetchData(final HdfsSplitInfo hdfsSplitInfo) throws IOException { final JobConf jobConf; try { final Tang tang = Tang.Factory.getTang(); jobConf = tang.newInjector(tang.newConfigurationBuilder() .bindNamedParameter(JobConfExternalConstructor.InputFormatClass.class, hdfsSplitInfo.getInputFormatClassName()) .bindNamedParameter(JobConfExternalConstructor.InputPath.class, hdfsSplitInfo.getInputPath()) .bindConstructor(JobConf.class, JobConfExternalConstructor.class) .build()) .getInstance(JobConf.class); } catch (final InjectionException e) { throw new RuntimeException("Exception while injecting JobConf", e); } final InputFormat<K, V> inputFormat = jobConf.getInputFormat(); final RecordReader<K, V> recordReader = inputFormat.getRecordReader( hdfsSplitInfo.getInputSplit(), jobConf, DUMMY_REPORTER); final class RecordReaderIterator implements Iterator<Pair<K, V>> { private final RecordReader<K, V> recordReader; private Pair<K, V> recordPair; private boolean hasNext; private RecordReaderIterator(final RecordReader<K, V> recordReader) { this.recordReader = recordReader; fetchRecord(); } @Override public boolean hasNext() { return this.hasNext; } @Override public Pair<K, V> next() { final Pair<K, V> prevRecordPair = this.recordPair; fetchRecord(); return prevRecordPair; } private void fetchRecord() { this.recordPair = Pair.of(this.recordReader.createKey(), this.recordReader.createValue()); try { this.hasNext = this.recordReader.next(this.recordPair.getKey(), this.recordPair.getValue()); } catch (final IOException ex) { throw new RuntimeException("Unable to get InputSplits using the specified InputFormat", ex); } } } return new RecordReaderIterator(recordReader); }
Source:
public Set<AccountGroup.Id> getAllOwners() { final HashSet<AccountGroup.Id> owners = new HashSet<AccountGroup.Id>(); for (final RefRight right : getAllRights(ApprovalCategory.OWN, true)) { if (right.getMaxValue() > 0) { owners.add(right.getAccountGroupId()); } } return Collections.unmodifiableSet(owners); }

Target:
public Set<AccountGroup.Id> getAllOwners() { final HashSet<AccountGroup.Id> owners = new HashSet<AccountGroup.Id>(); for (final RefRight right : getAllRights(ApprovalCategory.OWN, true)) { if (right.getMaxValue() > 0 && right.getRefPattern().equals(RefRight.ALL)) { owners.add(right.getAccountGroupId()); } } return Collections.unmodifiableSet(owners); }
Source:
public void testCheckAttributeSyntaxVo() throws Exception { attributesManagerBl = getTargetObject(perun.getAttributesManagerBl()); Attribute attribute = setAttributeInNamespace(AttributesManager.NS_VO_ATTR_DEF); attributesManagerBl.checkAttributeSyntax(sess, vo1, attribute); }

Target:
public void testCheckAttributeSyntaxVo() throws Exception { Attribute attribute = setAttributeInNamespace(AttributesManager.NS_VO_ATTR_DEF); attributesManager.checkAttributeSyntax(sess, vo1, attribute); }
Source:
protected static void disableSourceLookup() { ShellLookup.getInstance().getActiveShell(); String originalShellText = new DefaultShell().getText(); WorkbenchPreferenceDialog preferenceDialog = new WorkbenchPreferenceDialog(); preferenceDialog.open(); SourceLookupPreferencePage sourceLookupPreferencePage = new SourceLookupPreferencePage(preferenceDialog); preferenceDialog.select(sourceLookupPreferencePage); sourceLookupPreferencePage.setSourceAttachment(SourceLookupPreferencePage.SourceAttachmentEnum.NEVER); preferenceDialog.ok(); new WaitUntil(new ShellIsActive(originalShellText)); }

Target:
protected static void disableSourceLookup() { ShellLookup.getInstance().getActiveShell(); String originalShellText = new DefaultShell().getText(); WorkbenchPreferenceDialog preferenceDialog = new WorkbenchPreferenceDialog(); preferenceDialog.open(); SourceLookupPreferencePage sourceLookupPreferencePage = new SourceLookupPreferencePage(preferenceDialog); preferenceDialog.select(sourceLookupPreferencePage); sourceLookupPreferencePage.setSourceAttachment(SourceLookupPreferencePage.SourceAttachmentEnum.NEVER); preferenceDialog.ok(); new WaitUntil(new ShellIsAvailable(originalShellText)); }
Source:
protected void setInstanceHeader(ScenarioSimulationContext context, ScenarioGridColumn selectedColumn, String alias, String fullClassName) { int columnIndex = context.getModel().getColumns().indexOf(selectedColumn); final FactIdentifier factIdentifier = setEditableHeadersAndGetFactIdentifier(context, selectedColumn, alias, fullClassName); setInstanceHeaderMetaData(selectedColumn, alias, factIdentifier); final ScenarioHeaderMetaData propertyHeaderMetaData = selectedColumn.getPropertyHeaderMetaData(); final boolean isDMNScenario = Objects.equals(context.getModel().getSimulation().orElseThrow(IllegalStateException::new).getSimulationDescriptor().getType(), ScenarioSimulationModel.Type.DMN); if (isDMNScenario || ScenarioSimulationUtils.isSimpleJavaType(factIdentifier.getClassName())) { setPropertyMetaData(propertyHeaderMetaData, getPropertyPlaceHolder(columnIndex), false, selectedColumn, ScenarioSimulationEditorConstants.INSTANCE.defineValidType()); context.getModel().updateColumnInstance(columnIndex, selectedColumn); } else { propertyHeaderMetaData.setColumnGroup(getColumnSubGroup(selectedColumn.getInformationHeaderMetaData().getColumnGroup())); setPropertyMetaData(propertyHeaderMetaData, ConstantHolder.EXPRESSION_INSTANCE_PLACEHOLDER, false, selectedColumn, ScenarioSimulationEditorConstants.INSTANCE.insertExpression()); selectedColumn.setPropertyAssigned(true); context.getModel().updateColumnProperty(columnIndex, selectedColumn, Arrays.asList(alias), fullClassName, context.getStatus().isKeepData()); selectedColumn.setFactory(context.getScenarioExpressionCellTextAreaSingletonDOMElementFactory()); } if (context.getScenarioSimulationEditorPresenter() != null) { context.getScenarioSimulationEditorPresenter().reloadTestTools(false); } }

Target:
protected void setInstanceHeader(ScenarioSimulationContext context, ScenarioGridColumn selectedColumn, String alias, String fullClassName) { int columnIndex = context.getSelectedScenarioGridModel().getColumns().indexOf(selectedColumn); final FactIdentifier factIdentifier = setEditableHeadersAndGetFactIdentifier(context, selectedColumn, alias, fullClassName); setInstanceHeaderMetaData(selectedColumn, alias, factIdentifier); final ScenarioHeaderMetaData propertyHeaderMetaData = selectedColumn.getPropertyHeaderMetaData(); setPropertyMetaData(propertyHeaderMetaData, getPropertyPlaceHolder(columnIndex), false, selectedColumn, ScenarioSimulationUtils.getPlaceHolder(selectedColumn.isInstanceAssigned(), selectedColumn.isPropertyAssigned(), factMappingValueType, fullClassName)); context.getSelectedScenarioGridModel().updateColumnInstance(columnIndex, selectedColumn); if (context.getScenarioSimulationEditorPresenter() != null) { context.getScenarioSimulationEditorPresenter().reloadTestTools(false); } }
Source:
public static String settingsAsJSON(Index i) { if (i.tokenize == null) { return "{}"; } return "{\"tokenize\":\""+i.tokenize+"\"}"; }

Target:
static String settingsAsJSON(Index i) { if (i.tokenize == null) { return "{}"; } return "{\"tokenize\":\""+i.tokenize+"\"}"; }
Source:
public StorIOSQLiteDbImpl build() { Checks.checkNotNull(db, "Please specify SQLiteDatabase instance"); return new StorIOSQLiteDbImpl(db); }

Target:
public StorIOSQLiteDbImpl build() { checkNotNull(db, "Please specify SQLiteDatabase instance"); return new StorIOSQLiteDbImpl(db); }
Source:
public static TenantAwareLoggingEvent getTenantAwareLogEvent(List<Pattern> maskingPatterns, LoggingEvent loggingEvent, int tenantId, String serviceName) { Logger logger = Logger.getLogger(loggingEvent.getLoggerName()); TenantAwareLoggingEvent tenantAwareLoggingEvent; ThrowableInformation throwableInformation = loggingEvent.getThrowableInformation(); Throwable throwable; if (null == throwableInformation) { throwable = null; } else { throwable = throwableInformation.getThrowable(); } String logMessage = loggingEvent.getMessage().toString(); if (maskingPatterns != null && maskingPatterns.size() > 0) { Matcher matcher; for (Pattern pattern : maskingPatterns) { matcher = pattern.matcher(logMessage); StringBuffer stringBuffer = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(stringBuffer, REPLACEMENT_STRING); } matcher.appendTail(stringBuffer); logMessage = stringBuffer.toString(); } } tenantAwareLoggingEvent = new TenantAwareLoggingEvent(loggingEvent.fqnOfCategoryClass, logger, loggingEvent.timeStamp, loggingEvent.getLevel(), logMessage, throwable); tenantAwareLoggingEvent.setTenantId(Integer.toString(tenantId)); tenantAwareLoggingEvent.setServiceName(serviceName); return tenantAwareLoggingEvent; }

Target:
public static TenantAwareLoggingEvent getTenantAwareLogEvent(List<Pattern> maskingPatterns, LoggingEvent loggingEvent, int tenantId, String serviceName) { Logger logger = Logger.getLogger(loggingEvent.getLoggerName()); TenantAwareLoggingEvent tenantAwareLoggingEvent; ThrowableInformation throwableInformation = loggingEvent.getThrowableInformation(); Throwable throwable; if (null == throwableInformation) { throwable = null; } else { throwable = throwableInformation.getThrowable(); } String logMessage = loggingEvent.getMessage().toString(); if (maskingPatterns != null && maskingPatterns.size() > 0) { for (Pattern pattern : maskingPatterns) { Matcher matcher = pattern.matcher(logMessage); StringBuffer stringBuffer = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(stringBuffer, REPLACEMENT_STRING); } matcher.appendTail(stringBuffer); logMessage = stringBuffer.toString(); } } tenantAwareLoggingEvent = new TenantAwareLoggingEvent(loggingEvent.fqnOfCategoryClass, logger, loggingEvent.timeStamp, loggingEvent.getLevel(), logMessage, throwable); tenantAwareLoggingEvent.setTenantId(Integer.toString(tenantId)); tenantAwareLoggingEvent.setServiceName(serviceName); return tenantAwareLoggingEvent; }
Source:
private void getAndTestApiCall(FiveUpdater.TimeFrame timeFrame, String startDateTime, String endDateTime) { FiveUpdater fiveUpdater = fiveUpdaterBuilder .withTimeFrame(timeFrame) .build(); DateTimeFormatter formatter = DateTimeFormat.forPattern("y-M-d'T'hh:mm:ss'Z'"); DateTime testDate = formatter.parseDateTime("1973-11-03T02:02:02Z"); String foundApiCall = fiveUpdater.getApiCall(0, "channelId", testDate); String predictedBaseUri = "<LINK_0>" + "expand=watchable&from_time=%s&until_time=%s"; String predictedUri = String.format( predictedBaseUri, startDateTime, endDateTime ); assertEquals(predictedUri, foundApiCall); }

Target:
private void getAndTestApiCall( FiveUpdater.TimeFrame timeFrame, String startDateTime, String endDateTime ) { FiveUpdater fiveUpdater = fiveUpdaterBuilder .withTimeFrame(timeFrame) .build(); DateTimeFormatter formatter = DateTimeFormat.forPattern("y-M-d'T'hh:mm:ss'Z'"); DateTime testDate = formatter .parseDateTime("1973-11-03T02:02:02Z") .withZone(DateTimeZone.UTC); String foundApiCall = fiveUpdater.getApiCall(0, "channelId", testDate); String predictedBaseUri = "<LINK_0>" + "expand=watchable&from_time=%s&until_time=%s"; String predictedUri = String.format( predictedBaseUri, startDateTime, endDateTime ); assertEquals(predictedUri, foundApiCall); }
Source:
public void expandAll(IProgressMonitor monitor) { expand(monitor); for (DTreeItem child : item.getOwnedTreeItems()) { new DTreeItemUserInteraction(child, ctx).expandAll(monitor); } }

Target:
public void expandAll(IProgressMonitor monitor) { try { monitor.beginTask("Tree item expandion", item.getOwnedTreeItems().size() + 1); expand(new SubProgressMonitor(monitor, 1)); for (DTreeItem child : item.getOwnedTreeItems()) { new DTreeItemUserInteraction(child, ctx).expandAll(new SubProgressMonitor(monitor, 1)); } } finally { monitor.done(); } }
Source:
private void appendDefinitions(StringBuilder out, String indent) { if (toolName == ToolName.CONFIG_TOOL) { out.append(indent).append(lineSeparator()).append("Definitions:").append(lineSeparator()); out.append(indent).append(" ").append("namespace").append(lineSeparator()); Map<String, String> nameSpaces = new LinkedHashMap<>(); nameSpaces.put("stripe.<stripeId>.node.<nodeId>", "to apply a change only on a specific node"); nameSpaces.put("stripe.<stripeId>", "to apply a change only on a specific stripe"); nameSpaces.put("'' (empty namespace)", "to apply a change only on all nodes of the cluster"); int maxNamespaceLength = Integer.MIN_VALUE; for (String nameSpace : nameSpaces.keySet()) { if (nameSpace.length() > maxNamespaceLength) { maxNamespaceLength = nameSpace.length(); } } for (Map.Entry<String, String> entry : nameSpaces.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); out.append(indent).append(" ").append(key); for (int i = 0; i < maxNamespaceLength - key.length() + 4; i++) { out.append(" "); } out.append(value).append(lineSeparator()); } } }

Target:
protected void appendDefinitions(StringBuilder out, String indent) { }
Source:
public PdpFeedAccountingEntry buildPdpFeedAccountingEntry(ConcurStandardAccountingExtractDetailLine line) { PdpFeedAccountingEntry currentAccountingEntry = new PdpFeedAccountingEntry(); currentAccountingEntry.setCoaCd(line.getChartOfAccountsCode()); currentAccountingEntry.setAccountNbr(line.getAccountNumber()); currentAccountingEntry.setObjectCd(line.getJournalAccountCode()); currentAccountingEntry.setSubObjectCd(line.getSubObjectCode()); currentAccountingEntry.setOrgRefId(line.getOrgRefId()); currentAccountingEntry.setProjectCd(line.getProjectCode()); currentAccountingEntry.setAmount(KualiDecimal.ZERO.toString()); return currentAccountingEntry; }

Target:
public PdpFeedAccountingEntry buildPdpFeedAccountingEntry(ConcurStandardAccountingExtractDetailLine line) { PdpFeedAccountingEntry currentAccountingEntry = new PdpFeedAccountingEntry(); currentAccountingEntry.setCoaCd(line.getChartOfAccountsCode()); currentAccountingEntry.setAccountNbr(line.getAccountNumber()); currentAccountingEntry.setSubAccountNbr(line.getSubAccountNumber()); currentAccountingEntry.setObjectCd(line.getJournalAccountCode()); currentAccountingEntry.setSubObjectCd(line.getSubObjectCode()); currentAccountingEntry.setOrgRefId(line.getOrgRefId()); currentAccountingEntry.setProjectCd(line.getProjectCode()); currentAccountingEntry.setAmount(KualiDecimal.ZERO); return currentAccountingEntry; }
Source:
protected Control createDialogArea(Composite parent) { Composite main = new Composite(parent, SWT.NONE); GridLayoutFactory.fillDefaults().applyTo(main); GridDataFactory.fillDefaults().grab(true, true).applyTo(main); TableViewer tv = new TableViewer(main, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION); GridDataFactory.fillDefaults().grab(true, true) .applyTo(tv.getControl()); tv.setContentProvider(ArrayContentProvider.getInstance()); tv.setLabelProvider(new GraphLabelProvider()); Table table = tv.getTable(); TableColumn c1 = new TableColumn(table, SWT.NONE); c1.setWidth(200); c1.setText(UIText.CommitSelectDialog_MessageColumn); TableColumn c2 = new TableColumn(table, SWT.NONE); c2.setWidth(200); c2.setText(UIText.CommitSelectDialog_AuthoColumn); TableColumn c3 = new TableColumn(table, SWT.NONE); c3.setWidth(150); c3.setText(UIText.CommitSelectDialog_DateColumn); TableColumn c4 = new TableColumn(table, SWT.NONE); c4.setWidth(100); c4.setText(UIText.CommitSelectDialog_IdColumn); tv.setInput(commits); table.setHeaderVisible(true); table.setLinesVisible(true); tv.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { if (!event.getSelection().isEmpty()) selected = (RevCommit) ((IStructuredSelection) event .getSelection()).getFirstElement(); else selected = null; getButton(OK).setEnabled(selected != null); } }); return main; }

Target:
protected Control createDialogArea(Composite parent) { Composite main = new Composite(parent, SWT.NONE); GridLayoutFactory.fillDefaults().applyTo(main); GridDataFactory.fillDefaults().grab(true, true).applyTo(main); TableViewer tv = new TableViewer(main, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION); GridDataFactory.fillDefaults().grab(true, true) .applyTo(tv.getControl()); tv.setContentProvider(ArrayContentProvider.getInstance()); tv.setLabelProvider(new GraphLabelProvider()); Table table = tv.getTable(); TableColumn c1 = new TableColumn(table, SWT.NONE); c1.setWidth(200); c1.setText(UIText.CommitSelectDialog_MessageColumn); TableColumn c2 = new TableColumn(table, SWT.NONE); c2.setWidth(200); c2.setText(UIText.CommitSelectDialog_AuthoColumn); TableColumn c3 = new TableColumn(table, SWT.NONE); c3.setWidth(150); c3.setText(UIText.CommitSelectDialog_DateColumn); TableColumn c4 = new TableColumn(table, SWT.NONE); c4.setWidth(100); c4.setText(UIText.CommitSelectDialog_IdColumn); tv.setInput(commits); table.setHeaderVisible(true); table.setLinesVisible(true); tv.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { if (!event.getSelection().isEmpty()) selected = (RevCommit) ((IStructuredSelection) event .getSelection()).getFirstElement(); else selected = null; getButton(OK).setEnabled(selected != null); } }); tv.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { okPressed(); } }); return main; }
Source:
private boolean matchExpressionAndColumnRef(AbstractExpression statementExpr, ColumnRef indexColRef, StmtTableScan tableScan) { if (statementExpr instanceof TupleValueExpression) { TupleValueExpression tve = (TupleValueExpression)statementExpr; if (tve.getTableAlias().equals(tableScan.getTableAlias()) && tve.getColumnName().equals(indexColRef.getColumn().getTypeName())) { return true; } } return false; }

Target:
private static boolean matchExpressionAndColumnRef(AbstractExpression statementExpr, ColumnRef indexColRef, StmtTableScan tableScan) { if (statementExpr instanceof TupleValueExpression) { TupleValueExpression tve = (TupleValueExpression)statementExpr; if (tve.getTableAlias().equals(tableScan.getTableAlias()) && tve.getColumnName().equals(indexColRef.getColumn().getTypeName())) { return true; } } return false; }