auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private CalculationTasks(List<CalculationTask> tasks, List<Column> columns) { this.columns = ImmutableList.copyOf(columns); this.tasks = ImmutableList.copyOf(tasks); <START> long taskCount = tasks.stream() <END> .flatMap(task -> task.getCells().stream()) .count(); int columnCount = columns.size(); if (taskCount != 0) { if (columnCount == 0) { throw new IllegalArgumentException("There must be at least one column"); } if (taskCount % columnCount != 0) { throw new IllegalArgumentException( Messages.format( "Number of tasks ({}) must be exactly divisible by the number of columns ({})", taskCount, columnCount)); } } int targetCount = (int) taskCount / columnCount; CalculationTarget[] targets = new CalculationTarget[targetCount]; for (CalculationTask task : tasks) { int rowIndex = task.getRowIndex(); if (targets[rowIndex] == null) { targets[rowIndex] = task.getTarget(); } else if (targets[rowIndex] != task.getTarget()) { throw new IllegalArgumentException("Tasks define two different targets for the same row"); } } this.targets = ImmutableList.copyOf(targets); }</code><technical_language>worth renaming taskCount cellCount a 1-1 relationship tasks cells</technical_language>

Target:
private CalculationTasks(List<CalculationTask> tasks, List<Column> columns) { this.columns = ImmutableList.copyOf(columns); this.tasks = ImmutableList.copyOf(tasks); long cellCount = tasks.stream() .flatMap(task -> task.getCells().stream()) .count(); int columnCount = columns.size(); if (cellCount != 0) { if (columnCount == 0) { throw new IllegalArgumentException("There must be at least one column"); } if (cellCount % columnCount != 0) { throw new IllegalArgumentException( Messages.format( "Number of cells ({}) must be exactly divisible by the number of columns ({})", cellCount, columnCount)); } } int targetCount = (int) cellCount / columnCount; CalculationTarget[] targets = new CalculationTarget[targetCount]; for (CalculationTask task : tasks) { int rowIdx = task.getRowIndex(); if (targets[rowIdx] == null) { targets[rowIdx] = task.getTarget(); } else if (targets[rowIdx] != task.getTarget()) { throw new IllegalArgumentException(Messages.format( "Tasks define two different targets for row {}: and {}", rowIdx, targets[rowIdx], task.getTarget())); } } this.targets = ImmutableList.copyOf(targets); }
Source:
<code>public Response addCustomizedStateAggregationConfig(@PathParam("clusterId") String clusterId, String content) { HelixZkClient zkClient = getHelixZkClient(); if (!ZKUtil.isClusterSetup(clusterId, zkClient)) { return notFound("Cluster is not properly setup!"); } HelixAdmin admin = getHelixAdmin(); ZNRecord record; try { record = toZNRecord(content); } catch (IOException e) { _logger.error("Failed to deserialize user's input " + content + ", Exception: " + e); return badRequest("Input is not a vaild ZNRecord!"); } try { CustomizedStateAggregationConfig customizedStateAggregationConfig = new CustomizedStateAggregationConfig.Builder(record).build(); admin.addCustomizedStateAggregationConfig(clusterId, customizedStateAggregationConfig); <START> } catch (HelixException ex) { _logger.error("Error in adding a CustomizedStateAggregationConfig to cluster: " + clusterId, ex); return badRequest(ex.getMessage()); <END> } catch (Exception ex) { _logger.error("Cannot add CustomizedStateAggregationConfig to cluster: " + clusterId, ex); return serverError(ex); } return OK(); }</code><technical_language>For this exception, is caused a server error a client error? is good response status code is appropriate</technical_language>

Target:
public Response addCustomizedStateAggregationConfig(@PathParam("clusterId") String clusterId, String content) { if (!doesClusterExist(clusterId)) { return notFound(String.format("Cluster %s does not exist", clusterId)); } HelixAdmin admin = getHelixAdmin(); ZNRecord record; try { record = toZNRecord(content); } catch (IOException e) { return badRequest("Input is not a vaild ZNRecord!"); } try { CustomizedStateAggregationConfig customizedStateAggregationConfig = new CustomizedStateAggregationConfig.Builder(record).build(); admin.addCustomizedStateAggregationConfig(clusterId, customizedStateAggregationConfig); } catch (Exception ex) { _logger.error("Cannot add CustomizedStateAggregationConfig to cluster: Exception: {}", clusterId, ex); return serverError(ex); } return OK(); }
Source:
<code>public void updateDevicesHashes(List<Pair<Guid, String>> vmHashes) { getCallsHandler().executeStoredProcAsBatch("SetHashByVmGuid", vmHashes, pair -> getCustomMapSqlParameterSource() <START> .addValue("v_vm_guid", <END> pair.getFirst()) .addValue("v_hash", pair.getSecond())); }</code><technical_language>convention is 'v_' prefix in java code</technical_language>

Target:
public void updateDevicesHashes(List<Pair<Guid, String>> vmHashes) { getCallsHandler().executeStoredProcAsBatch("SetHashByVmGuid", vmHashes, pair -> getCustomMapSqlParameterSource() .addValue("vm_guid", pair.getFirst()) .addValue("hash", pair.getSecond())); }
Source:
<code>protected void processRecord(ComputationContext context, Record record) { KeyValueStore kvStore = Framework.getService(KeyValueService.class).getKeyValueStore(BULK_KV_STORE_NAME); try { String bulkActionId = record.getKey(); BulkCommand command = BulkCommandHelper.getBulkCommandJson(record.getData()); <START> if (!kvStore.compareAndSet(bulkActionId + STATE, SCHEDULED.toString(), BUILDING.toString())) { <END> log.error("Discard record: " + record + " because it's already building"); return; } try (CloseableCoreSession session = CoreInstance.openCoreSession(command.getRepository(), command.getUsername())) { ScrollResult<String> scroll = session.scroll(command.getQuery(), scrollBatchSize, scrollKeepAliveSeconds); long documentCount = 0; while (scroll.hasResults()) { List<String> docIds = scroll.getResults(); documentIds.addAll(docIds); if (documentIds.size() >= recordBatchSize) { produceRecord(context, command.getAction(), bulkActionId, record.getData()); } documentCount += docIds.size(); scroll = session.scroll(scroll.getScrollId()); TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); } while (!documentIds.isEmpty()) { produceRecord(context, command.getAction(), bulkActionId, record.getData()); } kvStore.put(bulkActionId + STATE, COMPLETED.toString()); kvStore.put(bulkActionId + SCROLLED_DOCUMENT_COUNT, documentCount); } } catch (NuxeoException e) { log.error("Discard invalid record: " + record, e); } }</code><technical_language>This happen, 2 consumers of group read partition. this check useful for handling cancellation, if skip record need call context.askForCompletion</technical_language>

Target:
protected void processRecord(ComputationContext context, Record record) { KeyValueStore kvStore = Framework.getService(KeyValueService.class).getKeyValueStore(BULK_KV_STORE_NAME); try { String bulkId = record.getKey(); BulkCommand command = BulkCommands.fromBytes(record.getData()); if (!kvStore.compareAndSet(bulkId + STATE, SCHEDULED.toString(), SCROLLING_RUNNING.toString())) { log.error("Discard record: " + record + " because it's already building"); context.askForCheckpoint(); return; } try (CloseableCoreSession session = CoreInstance.openCoreSession(command.getRepository(), command.getUsername())) { ScrollResult<String> scroll = session.scroll(command.getQuery(), scrollBatchSize, scrollKeepAliveSeconds); long documentCount = 0; long bucketNumber = 0; while (scroll.hasResults()) { List<String> docIds = scroll.getResults(); documentIds.addAll(docIds); while (documentIds.size() >= bucketSize) { bucketNumber++; produceBucket(context, command.getAction(), bulkId, bucketNumber * bucketSize); } documentCount += docIds.size(); scroll = session.scroll(scroll.getScrollId()); TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); } if (!documentIds.isEmpty()) { produceBucket(context, command.getAction(), bulkId, documentCount); } kvStore.put(bulkId + STATE, RUNNING.toString()); kvStore.put(bulkId + SCROLLED_DOCUMENT_COUNT, documentCount); } } catch (NuxeoException e) { log.error("Discard invalid record: " + record, e); } }
Source:
<code>public void concatenates() { final List<String> alist = new ArrayList<String>(2); final String aone = "a1"; final String atwo = "a2"; alist.add(aone); alist.add(atwo); final List<String> blist = new ArrayList<String>(2); final String bone = "b1"; final String btwo = "b2"; blist.add(bone); blist.add(btwo); MatcherAssert.assertThat( <START> new Concat<String>(alist, blist), <END> Matchers.hasItems(aone, atwo, bone, btwo) ); }</code><technical_language>I do this: assertThat( Joiner.on(" ").join( new Concat<String>( Arrays.asList("one", "two"), Arrays.asList("three", "four") ) ) Matchers.equalTo("one four") ); more readable, it</technical_language>

Target:
public void concatenates() { MatcherAssert.assertThat( Joiner.on(" ").join( new Concat<String>( Arrays.asList("one", "two"), Arrays.asList("three", "four") ) ), Matchers.equalTo("one two three four") ); }
Source:
<code>public RefUpdate.Result save(CommitBuilder cb) throws IOException { if (added.isEmpty()) { return RefUpdate.Result.NO_CHANGE; } if (reader == null) { load(); } DirCache dc = newDirCache(); DirCacheEditor editor = dc.editor(); try (ObjectInserter inserter = db.newObjectInserter()) { for (Map.Entry<String, List<PushCertificate>> e : added.entrySet()) { String refName = e.getKey(); List<InputStream> streams = new ArrayList<>(e.getValue().size() + 1); long len = readExisting(refName, streams); len += joinCertificates(e.getValue(), streams); final ObjectId blobId = inserter.insert( OBJ_BLOB, len, new UnionInputStream(streams.toArray(new InputStream[0]))); editor.add(new PathEdit(pathName(refName)) { @Override public void apply(DirCacheEntry ent) { ent.setFileMode(FileMode.REGULAR_FILE); ent.setObjectId(blobId); } }); } editor.finish(); cb.setTreeId(dc.writeTree(inserter)); if (commit != null) { cb.setParentId(commit); } else { cb.setParentIds(Collections.<ObjectId> emptyList()); } ObjectId newCommit = inserter.insert(OBJ_COMMIT, cb.build()); inserter.flush(); RefUpdate ru = db.updateRef(REF_NAME); ru.setExpectedOldObjectId(commit); ru.setNewObjectId(newCommit); ru.setRefLogIdent(cb.getCommitter()); RefUpdate.Result result = ru.update(new <START> RevWalk(inserter.newReader())); <END> if (result == RefUpdate.Result.NEW || result == RefUpdate.Result.FAST_FORWARD) { added.clear(); } return result; } finally { close(); } }</code><technical_language>leaked</technical_language>

Target:
public RefUpdate.Result save(CommitBuilder cb) throws IOException { if (added.isEmpty()) { return RefUpdate.Result.NO_CHANGE; } if (reader == null) { load(); } DirCache dc = newDirCache(); DirCacheEditor editor = dc.editor(); try (ObjectInserter inserter = db.newObjectInserter()) { for (Map.Entry<String, List<PushCertificate>> e : added.entrySet()) { String refName = e.getKey(); List<InputStream> streams = new ArrayList<>(e.getValue().size() + 1); long len = readExisting(refName, streams); len += joinCertificates(e.getValue(), streams); final ObjectId blobId = inserter.insert( OBJ_BLOB, len, new UnionInputStream(streams.toArray(new InputStream[0]))); editor.add(new PathEdit(pathName(refName)) { @Override public void apply(DirCacheEntry ent) { ent.setFileMode(FileMode.REGULAR_FILE); ent.setObjectId(blobId); } }); } editor.finish(); cb.setTreeId(dc.writeTree(inserter)); if (commit != null) { cb.setParentId(commit); } else { cb.setParentIds(Collections.<ObjectId> emptyList()); } ObjectId newCommit = inserter.insert(OBJ_COMMIT, cb.build()); inserter.flush(); RefUpdate ru = db.updateRef(REF_NAME); ru.setExpectedOldObjectId(commit); ru.setNewObjectId(newCommit); ru.setRefLogIdent(cb.getCommitter()); RefUpdate.Result result; try (ObjectReader insReader = inserter.newReader(); RevWalk rw = new RevWalk(insReader)) { result = ru.update(rw); } if (result == RefUpdate.Result.NEW || result == RefUpdate.Result.FAST_FORWARD) { added.clear(); } return result; } finally { close(); } }
Source:
<code>public Iterator<Object[]> init() { if (isClosed()) return Collections.emptyIterator(); cctx = ectx.parent().kernal().cache().context().cacheContext(cacheId = desc.cacheId()); if (!cctx.group().sharedGroup()) cacheId = UNDEFINED_CACHE_ID; GridDhtPartitionTopology top = cctx.topology(); <START> top.readLock(); <END> try { GridDhtTopologyFuture fut = top.topologyVersionFuture(); AffinityTopologyVersion topVer = ectx.parent().topologyVersion(); if (!fut.isDone() || fut.topologyVersion().compareTo(topVer) != 0) throw new ClusterTopologyException("Failed to execute query. Retry on stable topology."); if (cctx.isPartitioned()) reservePartitioned(top); else reserveReplicated(top); } catch (Throwable e) { U.closeQuiet(this); throw e; } finally { top.readUnlock(); } return this; }</code><technical_language>Do need lock topology in order reserve partitions</technical_language>

Target:
public Iterator<Object[]> init() throws IgniteCheckedException { if (isClosed()) return Collections.emptyIterator(); GridCacheContext<?, ?> cctx = desc.cacheContext(); if (!cctx.gate().enterIfNotStopped()) { close(); throw new CacheStoppedException(cctx.name()); } try { GridDhtPartitionTopology top = cctx.topology(); top.readLock(); try { GridDhtTopologyFuture fut = top.topologyVersionFuture(); AffinityTopologyVersion topVer = ectx.parent().topologyVersion(); if (!fut.isDone() || fut.topologyVersion().compareTo(topVer) != 0) throw new ClusterTopologyCheckedException("Failed to execute query. Retry on stable topology."); if (cctx.isPartitioned()) reservePartitioned(top); else reserveReplicated(top); } finally { top.readUnlock(); } cacheId = cctx.cacheId(); return this; } catch (Exception e) { Commons.close(this, e); throw e; } finally { cctx.gate().leave(); } }
Source:
<code><START> public SecurityGroupExtensionProvider(NeutronSecurityGroupExtension neutronSecurityGroupExtension, <END> NovaSecurityGroupExtension novaSecurityGroupExtension) { this.neutronSecurityGroupExtension = neutronSecurityGroupExtension; this.novaSecurityGroupExtension = novaSecurityGroupExtension; }</code><technical_language>Remove public modifier</technical_language>

Target:
SecurityGroupExtensionProvider(NeutronSecurityGroupExtension neutronSecurityGroupExtension, NovaSecurityGroupExtension novaSecurityGroupExtension) { this.neutronSecurityGroupExtension = neutronSecurityGroupExtension; this.novaSecurityGroupExtension = novaSecurityGroupExtension; }
Source:
<code>public void returnsBlockingTimeoutWithConnectorWithIdleTimeouts() throws IOException { assertThat(BlockingTimeouts.getBlockingTimeout(OBJECT_MAPPER, getConfigurationFromResource( "lock/one-specified-timeout.yml"))) <START> .isEqualTo(BlockingTimeouts.scaleForErrorMargin(86400 * MILLIS_PER_SECOND)); <END> }</code><technical_language>nit: SECONDS_IN_ONE_DAY</technical_language>

Target:
public void returnsBlockingTimeoutWithConnectorWithIdleTimeouts() throws IOException { assertThat(BlockingTimeouts.getBlockingTimeout(OBJECT_MAPPER, getConfigurationFromResource( "lock/one-specified-timeout.yml"))) .isEqualTo(BlockingTimeouts.scaleForErrorMargin(SECONDS_IN_ONE_DAY * MILLIS_PER_SECOND, ERROR_MARGIN)); }
Source:
<code>public ExecutorSelector(List<String> filterList, Map<String,Integer> comparatorList) { <START> super(null == filterList || filterList.size() == 0 ? null : new ExecutorFilter(filterList), <END> null == comparatorList || comparatorList.size() == 0 ? null : new ExecutorComparator(comparatorList)); }</code><technical_language>small - filterList.isEmpty() is shorter</technical_language>

Target:
public ExecutorSelector(List<String> filterList, Map<String,Integer> comparatorList) { super(null == filterList || filterList.isEmpty() ? null : new ExecutorFilter(filterList), null == comparatorList || comparatorList.isEmpty() ? null : new ExecutorComparator(comparatorList)); }
Source:
<code>public static Iterable<Object[]> constructorFeeder() { return ImmutableList.of( <START> new Object[]{LockGranularity.TIME_CHUNK, false}, new Object[]{LockGranularity.TIME_CHUNK, true}, new Object[]{LockGranularity.SEGMENT, false}, new Object[]{LockGranularity.SEGMENT, true} <END> ); }</code><technical_language>This is a slow test (~15 seconds parameterized run), permutations overkill. remove (SEGMENT, false), give coverage of lock granularities with/without input format API</technical_language>

Target:
public static Iterable<Object[]> constructorFeeder() { return ImmutableList.of( new Object[]{LockGranularity.TIME_CHUNK, false}, new Object[]{LockGranularity.TIME_CHUNK, true}, new Object[]{LockGranularity.SEGMENT, true} ); }
Source:
<code>public void nodesRemoved(Collection<DiscoveryDruidNode> nodesDisappeared) { synchronized (lock) { List<DiscoveryDruidNode> nodesRemoved = new ArrayList<>(); for (DiscoveryDruidNode node : nodesDisappeared) { DiscoveryDruidNode prev = nodes.remove(node.getDruidNode().getHostAndPortToUse()); if (prev != null) { nodesRemoved.add(node); } else { log.warn("Node[%s] disappeared but was unknown for service listener [%s].", node, service); } } <START> if (!nodesRemoved.isEmpty()) { <END> Collection<DiscoveryDruidNode> unmodifiableNodesRemoved = Collections.unmodifiableCollection(nodesRemoved); for (Listener listener : listeners) { try { listener.nodesRemoved(unmodifiableNodesRemoved); } catch (Exception ex) { log.error(ex, "Listener[%s].nodesRemoved(%s) threw exception. Ignored.", listener, nodesRemoved); } } } } }</code><technical_language>notified removed nodes types of nodes initialized, ignore</technical_language>

Target:
public void nodesRemoved(Collection<DiscoveryDruidNode> nodesDisappeared) { synchronized (lock) { List<DiscoveryDruidNode> nodesRemoved = new ArrayList<>(); for (DiscoveryDruidNode node : nodesDisappeared) { DiscoveryDruidNode prev = nodes.remove(node.getDruidNode().getHostAndPortToUse()); if (prev != null) { nodesRemoved.add(node); } else { log.warn("Node[%s] disappeared but was unknown for service listener [%s].", node, service); } } if (nodesRemoved.isEmpty()) { return; } Collection<DiscoveryDruidNode> unmodifiableNodesRemoved = Collections.unmodifiableCollection(nodesRemoved); for (Listener listener : listeners) { try { listener.nodesRemoved(unmodifiableNodesRemoved); } catch (Exception ex) { log.error(ex, "Listener[%s].nodesRemoved(%s) threw exception. Ignored.", listener, nodesRemoved); } } } }
Source:
<code>public String toString() { return "KafkaTuningConfig{" + "maxRowsInMemory=" + maxRowsInMemory + ", maxRowsPerSegment=" + maxRowsPerSegment + <START> ",maxBytesInMemory=" + maxBytesInMemory + <END> ", intermediatePersistPeriod=" + intermediatePersistPeriod + ", basePersistDirectory=" + basePersistDirectory + ", maxPendingPersists=" + maxPendingPersists + ", indexSpec=" + indexSpec + ", reportParseExceptions=" + reportParseExceptions + ", handoffConditionTimeout=" + handoffConditionTimeout + ", resetOffsetAutomatically=" + resetOffsetAutomatically + ", segmentWriteOutMediumFactory=" + segmentWriteOutMediumFactory + ", intermediateHandoffPeriod=" + intermediateHandoffPeriod + '}'; }</code><technical_language>nit: ", maxBytesInMemory=" other variables</technical_language>

Target:
public String toString() { return "KafkaTuningConfig{" + "maxRowsInMemory=" + maxRowsInMemory + ", maxRowsPerSegment=" + maxRowsPerSegment + ", maxBytesInMemory=" + maxBytesInMemory + ", intermediatePersistPeriod=" + intermediatePersistPeriod + ", basePersistDirectory=" + basePersistDirectory + ", maxPendingPersists=" + maxPendingPersists + ", indexSpec=" + indexSpec + ", reportParseExceptions=" + reportParseExceptions + ", handoffConditionTimeout=" + handoffConditionTimeout + ", resetOffsetAutomatically=" + resetOffsetAutomatically + ", segmentWriteOutMediumFactory=" + segmentWriteOutMediumFactory + ", intermediateHandoffPeriod=" + intermediateHandoffPeriod + ", logParseExceptions=" + logParseExceptions + ", maxParseExceptions=" + maxParseExceptions + ", maxSavedParseExceptions=" + maxSavedParseExceptions + '}'; }
Source:
<code>public static String listUsers(final IEssentials ess, final List<User> users, final String seperator) { final StringBuilder groupString = new StringBuilder(); Collections.sort(users); boolean needComma = false; for (User user : users) { if (needComma) { groupString.append(seperator); } needComma = true; if (user.isAfk()) { groupString.append(tl("listAfkTag")); } if (user.isHidden()) { groupString.append(tl("listHiddenTag")); } user.setDisplayNick(); if (ess.getSettings().realNamesOnList() && !ChatColor.stripColor(user.getDisplayName()).equals(user.getName())) { groupString.append(user.getDisplayName() + " (" + user.getName() + ")"); } else { <START> groupString.append(user.getDisplayName()); <END> } groupString.append("\u00a7f"); } return groupString.toString(); }</code><technical_language>Better: append this unconditionally, append other part based condition</technical_language>

Target:
public static String listUsers(final IEssentials ess, final List<User> users, final String seperator) { final StringBuilder groupString = new StringBuilder(); Collections.sort(users); boolean needComma = false; for (User user : users) { if (needComma) { groupString.append(seperator); } needComma = true; if (user.isAfk()) { groupString.append(tl("listAfkTag")); } if (user.isHidden()) { groupString.append(tl("listHiddenTag")); } user.setDisplayNick(); groupString.append(user.getDisplayName()); if (ess.getSettings().realNamesOnList() && !ChatColor.stripColor(user.getDisplayName()).equals(user.getName())) { groupString.append(" (").append(user.getName()).append(")"); } groupString.append("\u00a7f"); } return groupString.toString(); }
Source:
<code>public void terminate() { <START> initializer.terminate("ws-master"); <END> }</code><technical_language>I guess this "ws-master-output", no</technical_language>

Target:
public void terminate() { initializer.terminate("workspace/output"); }
Source:
<code>public void shouldSequenceEmpty() { <START> final Seq<Lazy<Integer>> testee = Stream.empty(); <END> final Lazy<Seq<Integer>> sequence = Lazy.sequence(testee); assertThat(sequence.get()).isEqualTo(Stream.empty()); }</code><technical_language>I this remain a List</technical_language>

Target:
public void shouldSequenceEmpty() { final List<Lazy<Integer>> testee = List.empty(); final Lazy<Seq<Integer>> sequence = Lazy.sequence(testee); assertThat(sequence.get()).isEqualTo(Vector.empty()); }
Source:
<code>public static void initSessionAndResetTestSchema() throws Exception { String testFolder = CassPersistenceTest.class.getResource("/").getPath(); System.setProperty(JBOSS_DATA_DIR, testFolder); externalCassandra = (null != System.getProperty(EXTERNAL_CASSANDRA)); if (!externalCassandra) { System.out.print("Starting embedded Cassandra for unit testing..."); EmbeddedCassandra.start(); } else { System.out.print("Using External Cassandra for unit testing..."); } keyspace = AlertProperties.getProperty("hawkular-alerts.cassandra-keyspace", "hawkular_alerts_test"); <START> Session session = CassCluster.getSession(true); <END> definitionsService = StandaloneAlerts.getDefinitionsService(); alertsService = StandaloneAlerts.getAlertsService(); actionsService = StandaloneAlerts.getActionsService(); }</code><technical_language>drop hawkular_alerts_test keyspace default, is true? hawkular-alerts.cassandra-keyspace set "hawkular_alerts_test". is done? want CassCluster.getCleanSession(String keyspace) that</technical_language>

Target:
public static void initSessionAndResetTestSchema() throws Exception { String testFolder = CassPersistenceTest.class.getResource("/").getPath(); System.setProperty(JBOSS_DATA_DIR, testFolder); externalCassandra = (null != System.getProperty(EXTERNAL_CASSANDRA)); if (!externalCassandra) { System.out.print("Starting embedded Cassandra for unit testing..."); EmbeddedCassandra.start(); } else { System.out.print("Using External Cassandra for unit testing..."); } keyspace = "hawkular_alerts_test"; System.setProperty("hawkular-alerts.cassandra-keyspace", keyspace); CassCluster.getSession(true); definitionsService = StandaloneAlerts.getDefinitionsService(); alertsService = StandaloneAlerts.getAlertsService(); actionsService = StandaloneAlerts.getActionsService(); }
Source:
<code>public synchronized long getTimestamp(final int offset) { HistogramScaledData scaledData = fScaledData; if (scaledData != null) { return <START> fScaledData.fFirstBucketTime <END> + Math.round(scaledData.fBucketDuration * offset); } return 0; }</code><technical_language>scaledData, thread safety</technical_language>

Target:
public synchronized long getTimestamp(final int offset) { HistogramScaledData scaledData = fScaledData; if (scaledData != null) { return scaledData.fFirstBucketTime + Math.round(scaledData.fBucketDuration * offset); } return 0; }
Source:
<code>public void write(Object object) throws IOException { result.totalCount++; commitCount++; if (null == factory) { factory = (IndexedRecordConverter<Object, ? extends IndexedRecord>) SnowflakeAvroRegistry.get() .createIndexedRecordConverter(object.getClass()); <START> } <END> IndexedRecord input = factory.convertToAvro(object); try { if (usePreparedStatement) { PreparedStatement pstmt = (PreparedStatement) statement; SnowflakePreparedStatementUtils.fillPreparedStatement(pstmt, rowProperties.preparedStatementTable); pstmt.execute(); rs = pstmt.getResultSet(); pstmt.clearParameters(); } else { rs = statement.executeQuery(rowProperties.query.getValue()); } handleSuccess(input); } catch (SQLException e) { if (dieOnError) { throw new IOException(e); } LOGGER.error(I18N_MESSAGES.getMessage("error.queryExecution"), e); handleReject(input, e); } try { if (rowProperties.connection.getReferencedComponentId() == null && commitCount == commitEvery) { connection.commit(); commitCount = 0; } } catch (SQLException e) { if (dieOnError) { throw new IOException(e); } LOGGER.error(I18N_MESSAGES.getMessage("error.performCommit"), e); } }</code><technical_language>I suggest rename factory converter extract this code method: getConverter()</technical_language>

Target:
public void write(Object object) throws IOException { commitCount++; IndexedRecord input = (IndexedRecord) object; try { if (rowProperties.usePreparedStatement()) { PreparedStatement pstmt = (PreparedStatement) statement; SnowflakePreparedStatementUtils.fillPreparedStatement(pstmt, rowProperties.preparedStatementTable); if (rowProperties.propagateQueryResultSet()) { pstmt.execute(); rs = pstmt.getResultSet(); } else { pstmt.addBatch(); } pstmt.clearParameters(); } else { if (rowProperties.propagateQueryResultSet()) { rs = statement.executeQuery(sink.getQuery()); } else { statement.addBatch(sink.getQuery()); } } handleSuccess(input); } catch (SQLException e) { if (rowProperties.dieOnError.getValue()) { throw new IOException(e); } LOGGER.error(I18N_MESSAGES.getMessage("error.queryExecution"), e); handleReject(input, e); } try { if (rowProperties.connection.getReferencedComponentId() == null && commitCount == rowProperties.commitCount.getValue()) { statement.executeBatch(); connection.commit(); commitCount = 0; } } catch (SQLException e) { if (rowProperties.dieOnError.getValue()) { throw new IOException(e); } LOGGER.error(I18N_MESSAGES.getMessage("error.performCommit"), e); } }
Source:
<code><START> public void onApproachGround(PlayerMoveEvent e) { <END> Player player = e.getPlayer(); ItemStack helmet = e.getPlayer().getInventory().getChestplate(); if (!SlimefunUtils.isItemSimilar(helmet, SlimefunItems.BEE_WINGS, true) && !Slimefun.hasUnlocked(e.getPlayer(), helmet, true)) return; if (!player.isGliding()) return; if (getDistanceToGround(player) == 0) return; if (getDistanceToGround(player) <= 6) player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW_FALLING, 30, 0)); }</code><technical_language>PlayerMoveEvent is risky a ton of lag</technical_language>

Target:
public void onApproachGround(PlayerMoveEvent e) { Player player = e.getPlayer(); if (e.getTo().getBlockY() == e.getFrom().getBlockY()) { return; } if (!player.isGliding()) return; if (player.isOnGround()) return; if (player.hasPotionEffect(PotionEffectType.SLOW_FALLING)) return; ItemStack chestplate = player.getInventory().getChestplate(); if (!SlimefunUtils.isItemSimilar(chestplate, SlimefunItems.BEE_WINGS, true) || !Slimefun.hasUnlocked(player, chestplate, true)) { return; } Location loc = player.getLocation(); int distanceToHighestBlock = (loc.getBlockY() - player.getWorld().getHighestBlockYAt(loc, HeightMap.WORLD_SURFACE)); if (distanceToHighestBlock < 0) { int distanceToGround = getDistanceToGround(loc.getBlock(), 6); if (distanceToGround < 1) return; player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW_FALLING, 40, 0)); return; } else if (distanceToHighestBlock <= 6) { player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW_FALLING, 40, 0)); } }
Source:
<code>public synchronized Collection<MetaAnnotation> getAnnotations() { final Annotation[] array; <START> if (_annotationsCache != null) { <END> array = _annotationsCache; } else { array = _annotationsCache = method.getAnnotations(); } return Arrays.stream(array).map(JavaReflectionAnnotation::new).collect(Collectors.toList()); }</code><technical_language>note for previous caches</technical_language>

Target:
public Collection<MetaAnnotation> getAnnotations() { return Arrays.stream(method.getAnnotations()).map(JavaReflectionAnnotation::new).collect(toList()); }
Source:
<code>public void checkPreviewUpdatedAfterRotateDeviceAndStopResume() { <START> mActivityRule.getActivity().setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); <END> pressHomeButton(); mActivityRule.getActivity().resetViewIdlingResource(); IdlingRegistry.getInstance().register(mActivityRule.getActivity().getViewIdlingResource()); mIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); mActivityRule.getActivity().startActivity(mIntent); onView(withId(R.id.textureView)).check(matches(isDisplayed())); IdlingRegistry.getInstance().unregister( mActivityRule.getActivity().getViewIdlingResource()); }</code><technical_language>test Preview ready rotation? wait for Preview result press home key directly, Preview switching rotation test yet</technical_language>

Target:
public void checkPreviewUpdatedAfterRotateDeviceAndStopResume() { mActivityRule.getActivity().setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); onView(withId(R.id.textureView)).check(matches(isDisplayed())); pressHomeButton(); mActivityRule.getActivity().resetViewIdlingResource(); IdlingRegistry.getInstance().register(mActivityRule.getActivity().getViewIdlingResource()); mIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); mActivityRule.getActivity().startActivity(mIntent); onView(withId(R.id.textureView)).check(matches(isDisplayed())); IdlingRegistry.getInstance().unregister( mActivityRule.getActivity().getViewIdlingResource()); }
Source:
<code>public void testCountMessagesPropertyExist() throws Exception { String key = new String("key_group"); String valueGroup1 = "group_1"; String valueGroup2 = "group_2"; SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); session.createQueue(address, queue, null, false); ClientProducer producer = session.createProducer(address); for (int i = 0; i < 100; i++) { ClientMessage msg = session.createMessage(false); <START> if(i % 3 == 0){ <END> msg.putStringProperty(key, valueGroup1); } else { msg.putStringProperty(key, valueGroup2); } producer.send(msg); } for (int i = 0; i < 20; i++) { ClientMessage msg = session.createMessage(false); producer.send(msg); } QueueControl queueControl = createManagementControl(address, queue); Assert.assertEquals(120, getMessageCount(queueControl)); String result = queueControl.countMessagesProperty(key); JsonObject jsonObject = JsonUtil.readJsonObject(result); Assert.assertEquals(34, jsonObject.getInt(valueGroup1)); Assert.assertEquals(66, jsonObject.getInt(valueGroup2)); Assert.assertEquals(20, jsonObject.getInt("*_UNDEFINED_*")); session.deleteQueue(queue); }</code><technical_language>checkstyle , need space if curly</technical_language>

Target:
public void testCountMessagesPropertyExist() throws Exception { String key = new String("key_group"); String valueGroup1 = "group_1"; String valueGroup2 = "group_2"; SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); session.createQueue(address, queue, null, false); ClientProducer producer = session.createProducer(address); for (int i = 0; i < 100; i++) { ClientMessage msg = session.createMessage(false); if (i % 3 == 0) { msg.putStringProperty(key, valueGroup1); } else { msg.putStringProperty(key, valueGroup2); } producer.send(msg); } for (int i = 0; i < 20; i++) { ClientMessage msg = session.createMessage(false); producer.send(msg); } QueueControl queueControl = createManagementControl(address, queue); Assert.assertEquals(120, getMessageCount(queueControl)); String result = queueControl.countMessages(null, key); JsonObject jsonObject = JsonUtil.readJsonObject(result); Assert.assertEquals(34, jsonObject.getInt(valueGroup1)); Assert.assertEquals(66, jsonObject.getInt(valueGroup2)); Assert.assertEquals(20, jsonObject.getInt("null")); session.deleteQueue(queue); }
Source:
<code>public boolean isRecoveryRequiredAt( File dataDir ) throws IOException { File neoStore = new File( dataDir, MetaDataStore.DEFAULT_NAME ); boolean noStoreFound = !NeoStores.isStorePresent( pageCache, dataDir ); if ( noStoreFound ) { return false; } long logVersion = MetaDataStore.getRecord( pageCache, neoStore, MetaDataStore.Position.LOG_VERSION ); <START> MetaDataStore.setRecord( pageCache, neoStore, MetaDataStore.Position.LOG_VERSION, logVersion ); <END> PhysicalLogFiles logFiles = new PhysicalLogFiles( dataDir, fs ); LogEntryReader<ReadableClosablePositionAwareChannel> reader = new VersionAwareLogEntryReader<>(); LogTailScanner tailScanner = new LogTailScanner( logFiles, fs, reader ); return new PositionToRecoverFrom( tailScanner, NO_MONITOR ).get() != LogPosition.UNSPECIFIED; }</code><technical_language>set a new for record here? this a "checker" only</technical_language>

Target:
public boolean isRecoveryRequiredAt( File dataDir ) throws IOException { File neoStore = new File( dataDir, MetaDataStore.DEFAULT_NAME ); boolean noStoreFound = !NeoStores.isStorePresent( pageCache, dataDir ); if ( noStoreFound ) { return false; } PhysicalLogFiles logFiles = new PhysicalLogFiles( dataDir, fs ); LogEntryReader<ReadableClosablePositionAwareChannel> reader = new VersionAwareLogEntryReader<>(); LogTailScanner tailScanner = new LogTailScanner( logFiles, fs, reader ); return new PositionToRecoverFrom( tailScanner, NO_MONITOR ).get() != LogPosition.UNSPECIFIED; }
Source:
<code>public boolean validate() { getLvName().validateEntity(new IValidation[] { new NotEmptyValidation(), new LengthValidation(50), new AsciiNameValidation() }); if (!getLvName().getIsValid()) { return false; } getMountPoint().validateEntity(new IValidation[] { new NotEmptyValidation(), new BrickMountPointValidation() }); if (!getMountPoint().getIsValid()) { return false; } IntegerValidation noOfPhysicalDiscsValidation = new IntegerValidation(); noOfPhysicalDiscsValidation.setMinimum(1); getNoOfPhysicalDisksInRaidVolume().validateEntity(new IValidation[] { new NotEmptyValidation(), <START> noOfPhysicalDiscsValidation }); <END> IntegerValidation stripSizeValidation = new IntegerValidation(); stripSizeValidation.setMinimum(1); getStripeSize().validateEntity(new IValidation[] { new NotEmptyValidation(), stripSizeValidation }); if (!getStripeSize().getIsValid()) { return false; } if (getStorageDevices().getSelectedItems() == null || getStorageDevices().getSelectedItems().isEmpty()) { setMessage(ConstantsManager.getInstance().getConstants().selectStorageDevice()); return false; } return true; }</code><technical_language>Missing? noOfPhysicalDiscsValidation().getIsValid()</technical_language>

Target:
public boolean validate() { getLvName().validateEntity(new IValidation[] { new NotEmptyValidation(), new LengthValidation(50), new AsciiNameValidation() }); if (!getLvName().getIsValid()) { return false; } getMountPoint().validateEntity(new IValidation[] { new NotEmptyValidation(), new BrickMountPointValidation() }); if (!getMountPoint().getIsValid()) { return false; } IntegerValidation noOfPhysicalDiscsValidation = new IntegerValidation(); noOfPhysicalDiscsValidation.setMinimum(1); getNoOfPhysicalDisksInRaidVolume().validateEntity(new IValidation[] { new NotEmptyValidation(), noOfPhysicalDiscsValidation }); if (!getNoOfPhysicalDisksInRaidVolume().getIsValid()) { return false; } IntegerValidation stripSizeValidation = new IntegerValidation(); stripSizeValidation.setMinimum(1); getStripeSize().validateEntity(new IValidation[] { new NotEmptyValidation(), stripSizeValidation }); if (!getStripeSize().getIsValid()) { return false; } if (getStorageDevices().getSelectedItems() == null || getStorageDevices().getSelectedItems().isEmpty()) { setMessage(ConstantsManager.getInstance().getConstants().selectStorageDevice()); return false; } return true; }
Source:
<code>public static String buildPayload(Map<String, String> params) { <START> if (params == null) { <END> return null; } StringBuilder bodyBuilder = new StringBuilder(); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, String> param = iterator.next(); bodyBuilder.append(param.getKey()).append('=').append(param.getValue()); if (iterator.hasNext()) { bodyBuilder.append('&'); } } return bodyBuilder.toString(); }</code><technical_language>This null check is get rid of, I believe</technical_language>

Target:
public static String buildPayload(Map<String, String> params) { StringBuilder bodyBuilder = new StringBuilder(); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, String> param = iterator.next(); bodyBuilder.append(param.getKey()).append('=').append(param.getValue()); if (iterator.hasNext()) { bodyBuilder.append('&'); } } return bodyBuilder.toString(); }
Source:
<code>public void testPerformHandshakeWithoutOriginHeader() { EmbeddedChannel ch = new EmbeddedChannel( new HttpObjectAggregator(42), new HttpRequestDecoder(), new HttpResponseEncoder()); FullHttpRequest req = new DefaultFullHttpRequest( HTTP_1_1, HttpMethod.GET, "/chat", Unpooled.copiedBuffer("^n:ds[4U", CharsetUtil.US_ASCII)); req.headers().set(HttpHeaderNames.HOST, "server.example.com"); req.headers().set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET); req.headers().set(HttpHeaderNames.CONNECTION, "Upgrade"); req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_KEY1, "4 @1 46546xW%0l 1 5"); req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, "chat, superchat"); WebSocketServerHandshaker00 handshaker00 = new WebSocketServerHandshaker00( "ws://example.com/chat", "chat", Integer.MAX_VALUE); try { handshaker00.handshake(ch, req); fail("Expecting WebSocketHandshakeException"); } catch (WebSocketHandshakeException e) { assertEquals("Missing origin header, got only " + "[host, upgrade, connection, sec-websocket-key1, sec-websocket-protocol]", e.getMessage()); <START> } <END> }</code><technical_language>need release req. Add like: java } finally { req.release(); }</technical_language>

Target:
public void testPerformHandshakeWithoutOriginHeader() { EmbeddedChannel ch = new EmbeddedChannel( new HttpObjectAggregator(42), new HttpRequestDecoder(), new HttpResponseEncoder()); FullHttpRequest req = new DefaultFullHttpRequest( HTTP_1_1, HttpMethod.GET, "/chat", Unpooled.copiedBuffer("^n:ds[4U", CharsetUtil.US_ASCII)); req.headers().set(HttpHeaderNames.HOST, "server.example.com"); req.headers().set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET); req.headers().set(HttpHeaderNames.CONNECTION, "Upgrade"); req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_KEY1, "4 @1 46546xW%0l 1 5"); req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, "chat, superchat"); WebSocketServerHandshaker00 handshaker00 = new WebSocketServerHandshaker00( "ws://example.com/chat", "chat", Integer.MAX_VALUE); try { handshaker00.handshake(ch, req); fail("Expecting WebSocketHandshakeException"); } catch (WebSocketHandshakeException e) { assertEquals("Missing origin header, got only " + "[host, upgrade, connection, sec-websocket-key1, sec-websocket-protocol]", e.getMessage()); } finally { req.release(); } }
Source:
<code>public Map<Long, ILogData> readAll(RuntimeLayout runtimeLayout, List<Long> addresses, boolean waitForWrite) { long startAddress = Collections.min(addresses); <START> long endAddress = Collections.max(addresses); <END> int numUnits = runtimeLayout.getLayout().getSegmentLength(startAddress); log.trace("readAll[{}-{}]: chain {}/{}", startAddress, endAddress, numUnits, numUnits); Map<Long, LogData> logResult = CFUtils.getUninterruptibly(runtimeLayout .getLogUnitClient(startAddress, numUnits - 1) .readAll(addresses)).getAddresses(); return readOrHoleFill(runtimeLayout, logResult, startAddress, numUnits, waitForWrite); }</code><technical_language>This lose data if addresses span a segment</technical_language>

Target:
public Map<Long, ILogData> readAll(RuntimeLayout runtimeLayout, List<Long> addresses, boolean waitForWrite) { Map<String, List<Long>> serverAddressMap = new HashMap<>(); for (Long address : addresses) { List<String> logServers = runtimeLayout.getLayout().getStripe(address).getLogServers(); String logServer = logServers.get(logServers.size() - 1); List<Long> addressList = serverAddressMap.computeIfAbsent(logServer, s -> new ArrayList<>()); addressList.add(address); } List<CompletableFuture<ReadResponse>> futures = serverAddressMap.entrySet().stream() .map(entry -> runtimeLayout.getLogUnitClient(entry.getKey()).readAll(entry.getValue())) .collect(Collectors.toList()); Map<Long, LogData> readResult = futures.stream() .map(future -> CFUtils.getUninterruptibly(future).getAddresses()) .reduce(new HashMap<>(), (map1, map2) -> { map1.putAll(map2); return map1; }); return waitOrHoleFill(runtimeLayout, readResult, waitForWrite); }
Source:
<code>public void onPluginLoad() { <START> Plugin.get().screen("create-service-user", new CreateServiceUserScreen.Factory()); <END> }</code><technical_language>plugin is called service-user, OK calling screen create. URL is "/#/x/service-user/create"</technical_language>

Target:
public void onPluginLoad() { Plugin.get().screen("create", new CreateServiceUserScreen.Factory()); }
Source:
<code>public void progressUpdatedNotification(String scriptId, int progress) { Map<Event.WorkflowProgressField, String> eventData = Maps.newHashMap(); eventData.put(Event.WorkflowProgressField.workflowProgress, Integer.toString(progress)); pushEvent(scriptId, new Event.WorkflowProgressEvent(eventData)); <START> LOG.info("pushed event , progress={}", progress); <END> for (DAGNode<PigJob> node : dagNodeNameMap.values()) { if (node.getJob().getId() == null) { continue; } addMapReduceJobState(node.getJob()); if (node.getJob().getMapReduceJobState() != null && !completedJobIds.contains(node.getJob().getId())) { pushEvent(scriptId, new Event.JobProgressEvent(node)); if (node.getJob().getMapReduceJobState().isComplete()) { completedJobIds.add(node.getJob().getId()); } } } }</code><technical_language>LOG.debug</technical_language>

Target:
public void progressUpdatedNotification(String scriptId, int progress) { Map<Event.WorkflowProgressField, String> eventData = Maps.newHashMap(); eventData.put(Event.WorkflowProgressField.workflowProgress, Integer.toString(progress)); pushEvent(scriptId, new Event.WorkflowProgressEvent(eventData)); for (DAGNode<PigJob> node : dagNodeNameMap.values()) { if (node.getJob().getId() == null) { continue; } addMapReduceJobState(node.getJob()); if (node.getJob().getMapReduceJobState() != null && !completedJobIds.contains(node.getJob().getId())) { pushEvent(scriptId, new Event.JobProgressEvent(node)); if (node.getJob().getMapReduceJobState().isComplete()) { completedJobIds.add(node.getJob().getId()); } } } }
Source:
<code>public RestGatewayLink(final GatewayBean gateway) { try { this.gateway = gateway; String cfg = gateway.getConfiguration(); cfg = CurrentDataEncrypter.instance.decrypt(cfg, new DataEncryptionContext()); cfg = PROPERTY_SUBSTITUTOR.replace(cfg); setConfig((RestGatewayConfigBean) mapper.reader(RestGatewayConfigBean.class).readValue(cfg)); getConfig().setPassword( PROPERTY_SUBSTITUTOR.replace( <START> CurrentDataEncrypter.instance.decrypt(getConfig().getPassword(), new DataEncryptionContext()))); <END> httpClient = HttpClientBuilder.create() .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE) .setSSLSocketFactory(sslConnectionFactory) .addInterceptorFirst(new HttpRequestInterceptor() { @Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { configureBasicAuth(request); } }).build(); } catch (JsonProcessingException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } }</code><technical_language>spend a new variable for config call getConfig()</technical_language>

Target:
public RestGatewayLink(final GatewayBean gateway) { try { this.gateway = gateway; String cfg = gateway.getConfiguration(); cfg = CurrentDataEncrypter.instance.decrypt(cfg, new DataEncryptionContext()); cfg = PROPERTY_SUBSTITUTOR.replace(cfg); this.config = (RestGatewayConfigBean) mapper.reader(RestGatewayConfigBean.class).readValue(cfg); this.config.setPassword( PROPERTY_SUBSTITUTOR.replace( CurrentDataEncrypter.instance.decrypt(this.config.getPassword(), new DataEncryptionContext()))); httpClient = HttpClientBuilder.create() .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE) .setSSLSocketFactory(sslConnectionFactory) .addInterceptorFirst(new HttpRequestInterceptor() { @Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { configureBasicAuth(request); } }).build(); } catch (JsonProcessingException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } }
Source:
<code>public void controlResized(ControlEvent e) { for (final Entry<Control, Integer> entry : controlsToAlign.entrySet()) { final int availableWidth = entry.getKey().getParent().getSize().x; if (availableWidth == 0) { continue; } <START> final double prefWidth = entry.getValue(); <END> int widthHint = computePreferedWidthBasedOnStep(prefWidth, step); if (widthHint > availableWidth) { widthHint = entry.getValue() > availableWidth ? entry.getValue() : availableWidth; } GridData.class.cast(entry.getKey().getLayoutData()).widthHint = widthHint; } composite.layout(true, true); }</code><technical_language>double</technical_language>

Target:
public void controlResized(ControlEvent e) { for (final Entry<Control, Integer> entry : controlsToAlign.entrySet()) { final int availableWidth = entry.getKey().getParent().getSize().x; if (availableWidth == 0) { continue; } final int prefWidth = entry.getValue(); int widthHint = computePreferredWidthBasedOnPixelGridSize(prefWidth, pixelGridSize); if (widthHint > availableWidth) { widthHint = prefWidth > availableWidth ? prefWidth : availableWidth; } GridData.class.cast(entry.getKey().getLayoutData()).widthHint = widthHint; } composite.layout(true, true); }