auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>@Override public boolean isEmpty() { try { return grp.mvccEnabled() ? dataTree.isEmpty() : storageSize.get() == 0; } catch (IgniteCheckedException e) { <START> U.error(grp.shared().logger(IgniteCacheOffheapManagerImpl.class), "Failed to perform operation.", e); <END> return false; } }</code><technical_language>I know, replace filed access</technical_language>

Target:
@Override public boolean isEmpty() { try { return grp.mvccEnabled() ? dataTree.isEmpty() : storageSize.get() == 0; } catch (IgniteCheckedException e) { U.error(log, "Failed to perform operation.", e); return false; } }
Source:
<code>void fixMissingStoreKeys(ConnectedChannel connectedChannel, List<RemoteReplicaInfo> replicasToReplicatePerNode, List<ExchangeMetadataResponse> exchangeMetadataResponseList, boolean remoteColoGetRequestForStandby) throws IOException, ReplicationException { long fixMissingStoreKeysStartTimeInMs = time.milliseconds(); try { if (exchangeMetadataResponseList.size() != replicasToReplicatePerNode.size() || replicasToReplicatePerNode.size() == 0) { throw new IllegalArgumentException("ExchangeMetadataResponseList size " + exchangeMetadataResponseList.size() + " and replicasToReplicatePerNode size " + replicasToReplicatePerNode.size() + " should be the same and greater than zero"); } DataNodeId remoteNode = replicasToReplicatePerNode.get(0).getReplicaId().getDataNodeId(); GetResponse getResponse = getMessagesForMissingKeys(connectedChannel, exchangeMetadataResponseList, replicasToReplicatePerNode, remoteNode, remoteColoGetRequestForStandby); if (remoteColoGetRequestForStandby) { <START> batchConvertGetResponseKeys(getResponse); <END> } writeMessagesToLocalStoreAndAdvanceTokens(exchangeMetadataResponseList, getResponse, replicasToReplicatePerNode, remoteNode, remoteColoGetRequestForStandby); } finally { long fixMissingStoreKeysTime = time.milliseconds() - fixMissingStoreKeysStartTimeInMs; replicationMetrics.updateFixMissingStoreKeysTime(fixMissingStoreKeysTime, replicatingFromRemoteColo, replicatingOverSsl, datacenterName); } }</code><technical_language>If move this handling progress replicas code block (line 438 ~470), able re-use batchConvertReplicaMetadataResponseKeys creating a new method. minor change suffice: change argument of batchConvertReplicaMetadataResponseKeys ReplicaMetadataResponse List<ExchangeMetadataResponse></technical_language>

Target:
void fixMissingStoreKeys(ConnectedChannel connectedChannel, List<RemoteReplicaInfo> replicasToReplicatePerNode, List<ExchangeMetadataResponse> exchangeMetadataResponseList, boolean remoteColoGetRequestForStandby) throws IOException, ReplicationException { long fixMissingStoreKeysStartTimeInMs = time.milliseconds(); try { if (exchangeMetadataResponseList.size() != replicasToReplicatePerNode.size() || replicasToReplicatePerNode.size() == 0) { throw new IllegalArgumentException("ExchangeMetadataResponseList size " + exchangeMetadataResponseList.size() + " and replicasToReplicatePerNode size " + replicasToReplicatePerNode.size() + " should be the same and greater than zero"); } DataNodeId remoteNode = replicasToReplicatePerNode.get(0).getReplicaId().getDataNodeId(); GetResponse getResponse = getMessagesForMissingKeys(connectedChannel, exchangeMetadataResponseList, replicasToReplicatePerNode, remoteNode, remoteColoGetRequestForStandby); writeMessagesToLocalStoreAndAdvanceTokens(exchangeMetadataResponseList, getResponse, replicasToReplicatePerNode, remoteNode, remoteColoGetRequestForStandby); } finally { long fixMissingStoreKeysTime = time.milliseconds() - fixMissingStoreKeysStartTimeInMs; replicationMetrics.updateFixMissingStoreKeysTime(fixMissingStoreKeysTime, replicatingFromRemoteColo, replicatingOverSsl, datacenterName); } }
Source:
<code>public static NetworkSecurityGroup create(final String id, final String name, final String location, final Map<String, String> tags, final NetworkSecurityGroupProperties properties, final String etag) { <START> return new AutoValue_NetworkSecurityGroup(id, name, location, (tags == null) ? ImmutableMap.<String, String>of() : ImmutableMap.copyOf(tags), <END> properties, etag); }</code><technical_language>initialize empty null</technical_language>

Target:
public static NetworkSecurityGroup create(final String id, final String name, final String location, final Map<String, String> tags, final NetworkSecurityGroupProperties properties, final String etag) { return new AutoValue_NetworkSecurityGroup(id, name, location, (tags == null) ? null : ImmutableMap.copyOf(tags), properties, etag); }
Source:
<code>protected void parseSplitSampleData(Variant variant, String fileId, String studyId, String[] fields, String[] alternateAlleles, String[] secondaryAlternates, int alternateAlleleIdx) throws NonStandardCompliantSampleField { String[] formatFields = variant.getSourceEntry(fileId, studyId).getFormat().split(":"); for (int i = 9; i < fields.length; i++) { Map<String, String> map = new TreeMap<>(); String[] sampleFields = fields[i].split(":"); for (int j = 0; j < sampleFields.length; j++) { <START> if(formatFields[j].equals("GT")) <END> { if(sampleFields[j].equals("0|0") || sampleFields[j].equals("0/0") || sampleFields[j].equals("./.")) { ctr++; } } String formatField = formatFields[j]; String sampleField = processSampleField(alternateAlleleIdx, formatField, sampleFields[j]); map.put(formatField, sampleField); } if(ctr==sampleFields.length) { throw new NotAVariantException; } else { variant.getSourceEntry(fileId, studyId).addSampleData(map); } } }</code><technical_language>coding style braces in line, if(...) {</technical_language>

Target:
protected void parseSplitSampleData(Variant variant, String fileId, String studyId, String[] fields, String[] alternateAlleles, String[] secondaryAlternates, int alternateAlleleIdx) throws NonStandardCompliantSampleField, NotAVariantException { String[] formatFields = variant.getSourceEntry(fileId, studyId).getFormat().split(":"); for (int i = 9; i < fields.length; i++) { int numReferenceGenotypes=0; Map<String, String> map = new TreeMap<>(); String[] sampleFields = fields[i].split(":"); for (int j = 0; j < sampleFields.length; j++) { String formatField = formatFields[j]; if ((sampleFields[j].equals("0|0") || sampleFields[j].equals("0/0") || sampleFields[j].equals("./.")) && formatField.equals("GT")) { numReferenceGenotypes++; } String sampleField = processSampleField(alternateAlleleIdx, formatField, sampleFields[j]); map.put(formatField, sampleField); } if (numReferenceGenotypes==sampleFields.length) { throw new NotAVariantException("All the sample genotypes are non-variant"); } else { variant.getSourceEntry(fileId, studyId).addSampleData(map); } } }
Source:
<code>public Hash(HashType type){ this.type = type; try { digest = type.get(); } finally { <START> type.recycle(digest); <END> } }</code><technical_language>Recycling a digest references (namely in member variabledigest) is bound give problems some point: another thread obtain means of HashType.get() while it! If insist recycling digests, I guess this done in finalizer of Hash. Note semantics of finally do finalizers</technical_language>

Target:
public Hash(HashType type){ this.type = type; digest = type.get(); }
Source:
<code>private AuditLogCleanupManager() { <START> log.info("Start initializing " + this.getClass().getSimpleName()); <END> Calendar calendar = new GregorianCalendar(); Date mAuditLogCleanupTime = Config.<DateTime> GetValue(ConfigValues.AuditLogCleanupTime); calendar.setTimeInMillis(mAuditLogCleanupTime.getTime()); String cronExpression = String.format("%d %d %d * * ?", calendar.get(Calendar.SECOND), calendar.get(Calendar.MINUTE), calendar.get(Calendar.HOUR_OF_DAY)); log.info("Setting audit clean up manager to run at: " + cronExpression); SchedulerUtilQuartzImpl.getInstance().scheduleACronJob(this, "OnTimer", new Class[] {}, new Object[] {}, cronExpression); log.info("Finished initializing " + this.getClass().getSimpleName()); }</code><technical_language>I add classname log messages in this patch, AutoRecoveryManager a subclass (probably some others do either), this logger category, in is more log, more information. log messages good, anyway, I leave class names</technical_language>

Target:
private AuditLogCleanupManager() { log.info("Start initializing audit cleanup manager"); Calendar calendar = new GregorianCalendar(); Date mAuditLogCleanupTime = Config.<DateTime> GetValue(ConfigValues.AuditLogCleanupTime); calendar.setTimeInMillis(mAuditLogCleanupTime.getTime()); String cronExpression = String.format("%d %d %d * * ?", calendar.get(Calendar.SECOND), calendar.get(Calendar.MINUTE), calendar.get(Calendar.HOUR_OF_DAY)); log.info("Setting audit cleanup manager to run at: " + cronExpression); SchedulerUtilQuartzImpl.getInstance().scheduleACronJob(this, "OnTimer", new Class[] {}, new Object[] {}, cronExpression); log.info("Finished initializing audit cleanup manager"); }
Source:
<code>public void loginDropDown(String username, String password) { triggerLoginDropDown(); typeInUserNameAndPassword(username, password); loginButton.click(); waitForElementByElement(avatar); <START> PageObjectLogging.log("login", "user logged in successfully", true, <END> driver); }</code><technical_language>change "login" "loginDropDown"</technical_language>

Target:
public void loginDropDown(String username, String password) { triggerLoginDropDown(); typeInUserNameAndPassword(username, password); loginButton.click(); waitForElementByElement(avatar); PageObjectLogging.log("loginDropDown", "user logged in successfully", true, driver); }
Source:
<code>public final void validate(final List<Throwable> validationErrors, final Configuration config) { this.accessAssertion.validate(validationErrors, config); int numberOfTableConfigurations = this.tableDataKey == null ? 0 : 1; numberOfTableConfigurations += this.jdbcUrl == null ? 0 : 1; if (numberOfTableConfigurations > 1) { validationErrors.add(new ConfigurationException("Only one of 'iterValue' or 'tableData' or 'jdbcUrl' should be defined.")); } for (Processor processor : this.processors) { processor.validate(validationErrors, config); } for (Attribute attribute : this.attributes.values()) { attribute.validate(validationErrors, config); } try { getProcessorGraph(); } catch (Throwable t) { validationErrors.add(t); } if (getJdbcUrl() != null) { Connection connection = null; try { if (getJdbcUser() != null) { connection = DriverManager.getConnection(getJdbcUrl(), getJdbcUser(), getJdbcPassword()); } else { connection = DriverManager.getConnection(getJdbcUrl()); } } catch (SQLException e) { validationErrors.add(e); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { validationErrors.add(e); } } } } if (this.mapExport) { int count = 0; for (Processor<?, ?> processor : getProcessors()) { if (processor instanceof CreateMapProcessor) { <START> count++; <END> } } if (count != 1) { validationErrors.add(new ConfigurationException("When using MapExport, exactly one CreateMapProcessor should be defined.")); } } }</code><technical_language>Minor optimization: stop count > 1</technical_language>

Target:
public final void validate(final List<Throwable> validationErrors, final Configuration config) { this.accessAssertion.validate(validationErrors, config); int numberOfTableConfigurations = this.tableDataKey == null ? 0 : 1; numberOfTableConfigurations += this.jdbcUrl == null ? 0 : 1; if (numberOfTableConfigurations > 1) { validationErrors.add(new ConfigurationException("Only one of 'iterValue' or 'tableData' or 'jdbcUrl' should be defined.")); } for (Processor processor : this.processors) { processor.validate(validationErrors, config); } for (Attribute attribute : this.attributes.values()) { attribute.validate(validationErrors, config); } try { getProcessorGraph(); } catch (Throwable t) { validationErrors.add(t); } if (getJdbcUrl() != null) { Connection connection = null; try { if (getJdbcUser() != null) { connection = DriverManager.getConnection(getJdbcUrl(), getJdbcUser(), getJdbcPassword()); } else { connection = DriverManager.getConnection(getJdbcUrl()); } } catch (SQLException e) { validationErrors.add(e); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { validationErrors.add(e); } } } } if (this.mapExport) { int count = 0; for (Processor<?, ?> processor : getProcessors()) { if (processor instanceof CreateMapProcessor) { count++; } if (count > 1) { break; } } if (count != 1) { validationErrors.add(new ConfigurationException("When using MapExport, exactly one CreateMapProcessor should be defined.")); } } }
Source:
<code>public int onStartCommand(Intent intent, int flags, int startId) { LogUtils.LOGD(TAG, "onStartCommand"); HostConnectionObserver connectionObserver = HostManager.getInstance(this) .getHostConnectionObserver(); if (mHostConnectionObserver == connectionObserver) { LogUtils.LOGD(TAG, "Already initialized"); stopForeground(true); <START> stopSelf(); <END> return START_NOT_STICKY; } createObservers(); if (mConnectionObservers.isEmpty()) { stopForeground(true); stopSelf(); return START_NOT_STICKY; } startForeground(NotificationObserver.NOTIFICATION_ID, mNotificationObserver.getNothingPlayingNotification()); if (mHostConnectionObserver != null) { mHostConnectionObserver.unregisterPlayerObserver(this); } mHostConnectionObserver = connectionObserver; mHostConnectionObserver.registerPlayerObserver(this, true); return START_STICKY; }</code><technical_language>I fail logic here. If service is running for HostConnectionObserver stop it</technical_language>

Target:
public int onStartCommand(Intent intent, int flags, int startId) { LogUtils.LOGD(TAG, "onStartCommand"); if (observers.isEmpty()) { createObservers(); } startForeground(NotificationObserver.NOTIFICATION_ID, notificationObserver.getCurrentNotification()); HostConnectionObserver connectionObserver = HostManager.getInstance(this).getHostConnectionObserver(); if (hostConnectionObserver == null) { hostConnectionObserver = connectionObserver; hostConnectionObserver.registerPlayerObserver(this, true); } else if (hostConnectionObserver != connectionObserver) { hostConnectionObserver.unregisterPlayerObserver(this); hostConnectionObserver = connectionObserver; hostConnectionObserver.registerPlayerObserver(this, true); } return START_STICKY; }
Source:
<code>OnheapIncrementalIndex( IncrementalIndexSchema incrementalIndexSchema, boolean deserializeComplexMetrics, boolean reportParseExceptions, boolean concurrentEventAdd, boolean sortFacts, int maxRowCount, long maxBytesInMemory ) { super(incrementalIndexSchema, deserializeComplexMetrics, reportParseExceptions, concurrentEventAdd); this.maxRowCount = maxRowCount; <START> this.maxBytesInMemory = maxBytesInMemory == 0 ? defaultMaxBytesInMemory : maxBytesInMemory; <END> this.facts = incrementalIndexSchema.isRollup() ? new RollupFactsHolder(sortFacts, dimsComparator(), getDimensions()) : new PlainFactsHolder(sortFacts); if (maxBytesInMemory != -1) { maxBytesPerRowForAggregators = getMaxBytesPerRowForAggregators(incrementalIndexSchema); } }</code><technical_language>this 0 in current implementation. Suggest throw exception if 0 remove defaultMaxBytesInMemory</technical_language>

Target:
OnheapIncrementalIndex( IncrementalIndexSchema incrementalIndexSchema, boolean deserializeComplexMetrics, boolean reportParseExceptions, boolean concurrentEventAdd, boolean sortFacts, int maxRowCount, long maxBytesInMemory ) { super(incrementalIndexSchema, deserializeComplexMetrics, reportParseExceptions, concurrentEventAdd); this.maxRowCount = maxRowCount; this.maxBytesInMemory = maxBytesInMemory == 0 ? -1 : maxBytesInMemory; this.facts = incrementalIndexSchema.isRollup() ? new RollupFactsHolder(sortFacts, dimsComparator(), getDimensions()) : new PlainFactsHolder(sortFacts); maxBytesPerRowForAggregators = getMaxBytesPerRowForAggregators(incrementalIndexSchema); }
Source:
<code>public void setUp() { MockitoAnnotations.initMocks(this); BigtableClusterName clusterName = new BigtableClusterName("project", "zone", "cluster"); Configuration configuration = new Configuration(); <START> HeapSizeManager heapsiManager = <END> new HeapSizeManager(AsyncExecutor.ASYNC_MUTATOR_MAX_MEMORY_DEFAULT, AsyncExecutor.MAX_INFLIGHT_RPCS_DEFAULT) { @Override public <T> FutureCallback<T> addCallback(ListenableFuture<T> future, Long id) { FutureCallback<T> callback = super.addCallback(future, id); callbacks.add(callback); return callback; } }; HBaseRequestAdapter adapter = new HBaseRequestAdapter(clusterName, TableName.valueOf("TABLE"), configuration); underTest = new BigtableBufferedMutator(client, adapter, configuration, null, listener, heapsiManager); }</code><technical_language>HeapSizeManager heapSizeManager</technical_language>

Target:
public void setUp() { MockitoAnnotations.initMocks(this); BigtableClusterName clusterName = new BigtableClusterName("project", "zone", "cluster"); Configuration configuration = new Configuration(); HeapSizeManager heapSizeManager = new HeapSizeManager(AsyncExecutor.ASYNC_MUTATOR_MAX_MEMORY_DEFAULT, AsyncExecutor.MAX_INFLIGHT_RPCS_DEFAULT) { @Override public <T> FutureCallback<T> addCallback(ListenableFuture<T> future, Long id) { FutureCallback<T> callback = super.addCallback(future, id); callbacks.add(callback); return callback; } }; HBaseRequestAdapter adapter = new HBaseRequestAdapter(clusterName, TableName.valueOf("TABLE"), configuration); underTest = new BigtableBufferedMutator( client, adapter, configuration, null, listener, heapSizeManager); }
Source:
<code><START> private final void parseRecord() { <END> Object value = null; if (consumerRecord.value() instanceof GenericRecord) { GenericRecord genericRecord = (GenericRecord)consumerRecord.value(); Object properties = genericRecord.get(KafkaForkliftProducer.SCHEMA_FIELD_NAME_PROPERTIES); if (properties != null) { this.setProperties(KeyValueParser.parse(properties.toString())); } value = genericRecord.get(KafkaForkliftProducer.SCHEMA_FIELD_NAME_VALUE); if (value == null) { String jsonValue = genericRecord.toString(); value = jsonValue != null && jsonValue.startsWith("{") ? jsonValue : null; } } if (value == null) { this.setFlagged(true); this.setWarning("Unable to parse message for topic: " + consumerRecord.topic() + " with value: " + consumerRecord.value()); } else { this.setMsg(value.toString()); } }</code><technical_language>Nit: This method some more spacing</technical_language>

Target:
private final String parseRecord(){ Object value = null; if (consumerRecord.value() instanceof GenericRecord) { GenericRecord genericRecord = (GenericRecord)consumerRecord.value(); Object properties = genericRecord.get(KafkaForkliftProducer.SCHEMA_FIELD_NAME_PROPERTIES); if (properties != null) { this.setProperties(KeyValueParser.parse(properties.toString())); } value = genericRecord.get(KafkaForkliftProducer.SCHEMA_FIELD_NAME_VALUE); if (value == null) { String jsonValue = genericRecord.toString(); value = jsonValue != null && jsonValue.startsWith("{") ? jsonValue : null; } } return value == null?null:value.toString(); }
Source:
<code>public void queryDocumentsArrayValue(){ FeedOptions options = new FeedOptions(); options.setEnableCrossPartitionQuery(true); options.setMaxDegreeOfParallelism(2); List<List<Integer>> expectedValues = new ArrayList<>(); <START> ArrayList<Integer> a1 = new ArrayList<Integer>(); <END> ArrayList<Integer> a2 = new ArrayList<Integer>(); a1.add(6519456); a1.add(1471916863); a2.add(2498434); a2.add(1455671440); expectedValues.add(a1); expectedValues.add(a2); String query = "Select top 2 value c.sgmts from c"; Flux<FeedResponse<List>> queryObservable = createdCollection.queryItems(query, options, List.class); List<List> fetchedResults = new ArrayList<>(); queryObservable.map(feedResponse -> fetchedResults.addAll(feedResponse.getResults())).blockLast(); }</code><technical_language>Please diamond operator, repeat time a time. ArrayList<Integer> a1 = new ArrayList<>();</technical_language>

Target:
public void queryDocumentsArrayValue(){ FeedOptions options = new FeedOptions(); options.setEnableCrossPartitionQuery(true); options.setMaxDegreeOfParallelism(2); Collection<List<List<Integer>>> expectedValues = new ArrayList<>(); List<List<Integer>> lists = new ArrayList<>(); List<Integer> a1 = new ArrayList<>(); ArrayList<Integer> a2 = new ArrayList<>(); a1.add(6519456); a1.add(1471916863); a2.add(2498434); a2.add(1455671440); lists.add(a1); lists.add(a2); expectedValues.add(lists); expectedValues.add(lists); expectedValues.add(lists); expectedValues.add(lists); String query = "Select top 2 value c.sgmts from c"; Flux<FeedResponse<List>> queryObservable = createdCollection.queryItems(query, options, List.class); List<List> fetchedResults = new ArrayList<>(); queryObservable.map(feedResponse -> fetchedResults.addAll(feedResponse.getResults())).blockLast(); assertThat(fetchedResults).containsAll(expectedValues); }
Source:
<code>private TDigest(double compression) { checkArgument(!isNaN(compression)); checkArgument(compression <= MAX_COMPRESSION_FACTOR, "Compression factor cannot exceed %s", MAX_COMPRESSION_FACTOR); <START> this.publicCompression = max(compression, 10); <END> this.compression = 2 * publicCompression; maxBufferSize = 5 * (int) ceil(this.publicCompression + sizeFudge); maxCentroidCount = (int) ceil(this.compression + sizeFudge); weight = new double[1]; mean = new double[1]; tempWeight = new double[1]; tempMean = new double[1]; order = new int[1]; activeCentroids = 0; }</code><technical_language>Please consistent of this</technical_language>

Target:
private TDigest(double compression) { checkArgument(!isNaN(compression)); checkArgument(compression <= MAX_COMPRESSION_FACTOR, "Compression factor cannot exceed %s", MAX_COMPRESSION_FACTOR); this.publicCompression = max(compression, 10); this.compression = 2 * this.publicCompression; this.maxBufferSize = 5 * (int) ceil(this.publicCompression + sizeFudge); this.maxCentroidCount = (int) ceil(this.compression + sizeFudge); this.weight = new double[1]; this.mean = new double[1]; this.tempWeight = new double[1]; this.tempMean = new double[1]; this.order = new int[1]; this.activeCentroids = 0; }
Source:
<code>private static Set<Account.Id> getAccountSources(final ReviewDb db, final String userName) throws OrmException { AccountAccess dbAccounts = db.accounts(); ResultSet<Account>[] allAccounts = new ResultSet[] { dbAccounts.suggestBySshUserName(userName, userName + "\u9fa5", 10), dbAccounts.suggestByFullName(userName, userName + "\u9fa5", 10), db.accountExternalIds().suggestByEmailAddress(userName, userName + "\u9fa5", 10), }; Set<Account.Id> result = new HashSet<Account.Id>(); for (ResultSet<Account> rs : allAccounts) { <START> for (Iterator<Account> it = rs.iterator(); it.hasNext();) { <END> result.add(it.next().getId()); } } return result; }</code><technical_language>FWIW this written as: for(Account matchedAccount : rs) { result.add(matchedAccount.getId()); } ResultSet<T> type is Iteratable</technical_language>

Target:
private static Set<Account.Id> getAccountSources(final ReviewDb db, final String userName) throws OrmException { AccountAccess dbAccounts = db.accounts(); ResultSet<Account>[] allAccounts = new ResultSet[] { dbAccounts.suggestBySshUserName(userName, userName + "\u9fa5", 10), dbAccounts.suggestByFullName(userName, userName + "\u9fa5", 10), db.accountExternalIds().suggestByEmailAddress(userName, userName + "\u9fa5", 10), }; Set<Account.Id> result = new HashSet<Account.Id>(); for (ResultSet<Account> rs : allAccounts) { for (Account account : rs) { result.add(account.getId()); } } return result; }
Source:
<code>public List<VDS> filter(List<VDS> hosts, VM vm, Map<String, String> parameters, List<String> messages) { List<VDS> toRemoveHostList = new ArrayList<VDS>(); List<VmNetworkInterface> vmNICs; List<Network> clusterNetworks; Map<String, Network> networksByName; if (hosts != null && hosts.size() > 0) { clusterNetworks = getNetworkDAO().getAllForCluster(hosts.get(0).getVdsGroupId()); networksByName = Entities.entitiesByName(clusterNetworks); vmNICs = getVmNetworkInterfaceDao().getAllForVm(vm.getId()); } else { return null; } <START> Map<Guid, List<VdsNetworkInterface>> allInterfacesForVdsMap = <END> getAllInterfacesForVdsGroupMap(hosts.get(0).getVdsGroupId()); for (VDS host : hosts) { VdcBllMessages returnValue = validateRequiredNetworksAvailable(host, vm, vmNICs, clusterNetworks, networksByName, allInterfacesForVdsMap.get(host.getId())); if (VdcBllMessages.ACTION_TYPE_FAILED_VDS_VM_NETWORKS == returnValue) { StringBuilder sbBuilder = new StringBuilder(); sbBuilder.append(Entities.vmInterfacesByNetworkName(vmNICs).keySet()); log.debugFormat("host {0} is missing networks required by VM nics {1}", host.getName(), sbBuilder.toString()); } else if (VdcBllMessages.ACTION_TYPE_FAILED_MISSING_DISPLAY_NETWORK == returnValue) { log.debugFormat("host {0} is missing the cluster's display network", host.getName()); } if (returnValue != null) { messages.add(returnValue.toString()); toRemoveHostList.add(host); } } hosts.removeAll(toRemoveHostList); return hosts; }</code><technical_language>name simplified hostNics instead of allInterfacesForVdsMap</technical_language>

Target:
public List<VDS> filter(List<VDS> hosts, VM vm, Map<String, String> parameters, List<String> messages) { List<VDS> toRemoveHostList = new ArrayList<VDS>(); List<VmNetworkInterface> vmNICs; List<Network> clusterNetworks; Map<String, Network> networksByName; if (hosts != null && hosts.size() > 0) { clusterNetworks = getNetworkDAO().getAllForCluster(hosts.get(0).getVdsGroupId()); networksByName = Entities.entitiesByName(clusterNetworks); vmNICs = getVmNetworkInterfaceDao().getAllForVm(vm.getId()); } else { return null; } Map<Guid, List<VdsNetworkInterface>> hostNics = getAllInterfacesForVdsGroupMap(hosts.get(0).getVdsGroupId()); for (VDS host : hosts) { VdcBllMessages returnValue = validateRequiredNetworksAvailable(host, vm, vmNICs, clusterNetworks, networksByName, hostNics.get(host.getId())); if (VdcBllMessages.ACTION_TYPE_FAILED_VDS_VM_NETWORKS == returnValue) { StringBuilder sbBuilder = new StringBuilder(); sbBuilder.append(Entities.vmInterfacesByNetworkName(vmNICs).keySet()); log.debugFormat("host {0} is missing networks required by VM nics {1}", host.getName(), sbBuilder.toString()); } else if (VdcBllMessages.ACTION_TYPE_FAILED_MISSING_DISPLAY_NETWORK == returnValue) { log.debugFormat("host {0} is missing the cluster's display network", host.getName()); } if (returnValue != null) { messages.add(returnValue.toString()); toRemoveHostList.add(host); } } hosts.removeAll(toRemoveHostList); return hosts; }
Source:
<code>private void setupVCFWriter() { vcfWriter = createVCFWriter(outputFile); vcfWriter.writeHeader(OrientationBiasFilterer.createVCFHeader(getHeaderForVariants(), getCommandLine(), <START> artifactModes)); <END> }</code><technical_language>This need a new line</technical_language>

Target:
private void setupVCFWriter() { vcfWriter = createVCFWriter(outputFile); vcfWriter.writeHeader(OrientationBiasFilterer.createVCFHeader(getHeaderForVariants(), getCommandLine(), transitions)); }
Source:
<code><START> public static Double sphericalDistance(Geometry leftGeometry, Geometry rightGeometry) { <END> if (leftGeometry.isEmpty() || rightGeometry.isEmpty()) { return null; } validateGeographyType("ST_Distance", leftGeometry, EnumSet.of(GeometryType.POINT)); validateGeographyType("ST_Distance", rightGeometry, EnumSet.of(GeometryType.POINT)); Point leftPoint = (Point) leftGeometry; Point rightPoint = (Point) rightGeometry; return greatCircleDistance(leftPoint.getY(), leftPoint.getX(), rightPoint.getY(), rightPoint.getX()) * 1000; }</code><technical_language>Return primitive double, throw NPE</technical_language>

Target:
private static double sphericalDistance(Geometry leftGeometry, Geometry rightGeometry) { Preconditions.checkArgument(leftGeometry instanceof Point, "The left argument must be a point"); Preconditions.checkArgument(rightGeometry instanceof Point, "The right argument must be a point"); Point leftPoint = (Point) leftGeometry; Point rightPoint = (Point) rightGeometry; return greatCircleDistance(leftPoint.getY(), leftPoint.getX(), rightPoint.getY(), rightPoint.getX()); }
Source:
<code>public void testWithProvisioningConfig() throws Exception { boolean isRasberryPiSharedWithTenants = (rasberrypiDeviceConfiguration.getProvisioningConfig() != null) && rasberrypiDeviceConfiguration .getProvisioningConfig().isSharedWithAllTenants(); <START> setProvisioningConfig.invoke(androidDeviceTypeManagerService, "carbon.super", androidDeviceConfiguration); <END> ProvisioningConfig provisioningConfig = androidDeviceTypeManagerService.getProvisioningConfig(); Assert.assertEquals(provisioningConfig.isSharedWithAllTenants(), androidDeviceConfiguration.getProvisioningConfig().isSharedWithAllTenants(), "Provisioning configs " + "are not correctly set as per the configuration file provided"); setProvisioningConfig.invoke(rasberrypiDeviceTypeManagerService, "carbon.super", rasberrypiDeviceConfiguration); provisioningConfig = rasberrypiDeviceTypeManagerService.getProvisioningConfig(); Assert.assertEquals(provisioningConfig.isSharedWithAllTenants(), isRasberryPiSharedWithTenants, "Provisioning configs are not correctly set as per the configuration file provided."); }</code><technical_language>MultitenantUtils.SUPER_TENANT_DOMAIN. Please in remaining places well</technical_language>

Target:
public void testWithProvisioningConfig() throws Exception { boolean isRasberryPiSharedWithTenants = (rasberrypiDeviceConfiguration.getProvisioningConfig() != null) && rasberrypiDeviceConfiguration .getProvisioningConfig().isSharedWithAllTenants(); setProvisioningConfig.invoke(androidDeviceTypeManagerService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, androidDeviceConfiguration); ProvisioningConfig provisioningConfig = androidDeviceTypeManagerService.getProvisioningConfig(); Assert.assertEquals(provisioningConfig.isSharedWithAllTenants(), androidDeviceConfiguration.getProvisioningConfig().isSharedWithAllTenants(), "Provisioning configs " + "are not correctly set as per the configuration file provided"); setProvisioningConfig.invoke(rasberrypiDeviceTypeManagerService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, rasberrypiDeviceConfiguration); provisioningConfig = rasberrypiDeviceTypeManagerService.getProvisioningConfig(); Assert.assertEquals(provisioningConfig.isSharedWithAllTenants(), isRasberryPiSharedWithTenants, "Provisioning configs are not correctly set as per the configuration file provided."); }
Source:
<code>public void setUp() { MockitoAnnotations.initMocks(this); translator = new StandardTranslator(this.consumerTypeCurator, <START> this.environmentCurator, <END> this.ownerCurator, this.entitlementCurator); InputStream is = this.getClass().getResourceAsStream(RulesCurator.DEFAULT_RULES_FILE); Rules rules = new Rules(Util.readFile(is)); Locale locale = new Locale("en_US"); when(rulesCuratorMock.getUpdated()).thenReturn(new Date()); when(rulesCuratorMock.getRules()).thenReturn(rules); when(cacheProvider.get()).thenReturn(cache); this.provider = new JsRunnerProvider(rulesCuratorMock, cacheProvider); i18n = I18nFactory.getI18n(getClass(), "org.candlepin.i18n.Messages", locale, I18nFactory.FALLBACK); RulesObjectMapper objectMapper = new RulesObjectMapper(new ProductCachedSerializationModule(productCurator)); this.complianceRules = new ComplianceRules(provider.get(), this.entCurator, new StatusReasonMessageGenerator(i18n), eventSink, this.consumerCurator, this.consumerTypeCurator, objectMapper, translator); this.consumerEnricher = new ConsumerEnricher(this.complianceRules, this.ownerProductCurator); }</code><technical_language>For blocks this, follow existing formatting (each new param a new line), update formatting for statement. This occurs a number of times this PR</technical_language>

Target:
public void setUp() { MockitoAnnotations.initMocks(this); translator = new StandardTranslator(this.consumerTypeCurator, this.environmentCurator, this.ownerCurator); InputStream is = this.getClass().getResourceAsStream(RulesCurator.DEFAULT_RULES_FILE); Rules rules = new Rules(Util.readFile(is)); Locale locale = new Locale("en_US"); when(rulesCuratorMock.getUpdated()).thenReturn(new Date()); when(rulesCuratorMock.getRules()).thenReturn(rules); when(cacheProvider.get()).thenReturn(cache); this.provider = new JsRunnerProvider(rulesCuratorMock, cacheProvider); i18n = I18nFactory.getI18n(getClass(), "org.candlepin.i18n.Messages", locale, I18nFactory.FALLBACK); RulesObjectMapper objectMapper = new RulesObjectMapper(new ProductCachedSerializationModule(productCurator)); this.complianceRules = new ComplianceRules(provider.get(), this.entCurator, new StatusReasonMessageGenerator(i18n), eventSink, this.consumerCurator, this.consumerTypeCurator, objectMapper, translator); this.consumerEnricher = new ConsumerEnricher(this.complianceRules, this.ownerProductCurator); }
Source:
<code>public WebElement forElementPresent(By by) { changeImplicitWait(250, TimeUnit.MILLISECONDS); try { return wait.until(ExpectedConditions.presenceOfElementLocated(by)); } catch(TimeoutException e) { PageObjectLogging.log( ELEMENT_PRESENT_MESSAGE, String.format(ELEMENT_PRESENT_ERROR_FORMAT, by.toString()), <START> true <END> ); throw e; } finally { restoreDeaultImplicitWait(); } }</code><technical_language>true -> false</technical_language>

Target:
public WebElement forElementPresent(By by) { changeImplicitWait(250, TimeUnit.MILLISECONDS); try { return wait.until(ExpectedConditions.presenceOfElementLocated(by)); } catch(TimeoutException e) { PageObjectLogging.log( ELEMENT_PRESENT_MESSAGE, String.format(ELEMENT_PRESENT_ERROR_FORMAT, by.toString()), false ); throw e; } finally { restoreDeaultImplicitWait(); } }
Source:
<code>public void beforeAll(ExtensionContext extensionContext) throws Exception { LOGGER.debug("initializing"); ClusterConnection clusterConnection = getClusterConnection(extensionContext); Class<?> testClass = extensionContext.getRequiredTestClass(); <START> AnnotationSupport.findAnnotatedFields(testClass, SpringDataElasticsearch.class).forEach(field -> { <END> if (field.getType().isAssignableFrom(ClusterConnectionInfo.class)) { field.setAccessible(true); try { field.set(null, clusterConnection.getClusterConnectionInfo()); } catch (IllegalAccessException e) { LOGGER.warn("could not set value in field of class {}", field.getName(), testClass.getName(), e); } } }); }</code><technical_language>built-in injection mechanism instead of assigning values static fields</technical_language>

Target:
public void beforeAll(ExtensionContext extensionContext) throws Exception { initLock.lock(); try { ExtensionContext.Store store = getStore(extensionContext); ClusterConnection clusterConnection = store.getOrComputeIfAbsent(STORE_KEY_CLUSTER_CONNECTION, key -> { LOGGER.debug("creating ClusterConnection"); return createClusterConnection(); }, ClusterConnection.class); store.getOrComputeIfAbsent(STORE_KEY_CLUSTER_CONNECTION_INFO, key -> clusterConnection.getClusterConnectionInfo()); } finally { initLock.unlock(); } }
Source:
<code>protected void launchDeployCommand(final IServer server, final MBeanServerConnection connection, final ObjectName objectName, final String methodName, IProgressMonitor monitor) throws Exception { final Exception[] e = new Exception[1]; final Object waitObject = new Object(); final Boolean[] subtaskComplete = new Boolean[1]; <START> subtaskComplete[0] = new Boolean(false); <END> Thread t = new Thread() { public void run() { Exception exception = null; try { executeDeploymentCommand(connection, objectName, methodName); } catch( Exception ex ) { exception = ex; } synchronized(waitObject) { e[0] = exception; subtaskComplete[0] = new Boolean(true); waitObject.notifyAll(); } } }; t.start(); int count = 0; while(t.isAlive() && !monitor.isCanceled() && count <= 4000) { count+= 1000; synchronized(waitObject) { if( subtaskComplete[0].booleanValue() ) break; waitObject.wait(1000); } } synchronized(waitObject) { if( !subtaskComplete[0].booleanValue()) { t.interrupt(); IStatus status = new Status(IStatus.WARNING, JBossServerCorePlugin.PLUGIN_ID, IEventCodes.DEPLOYMENT_SCANNER_TRANSITION_CANCELED, Messages.JMXScannerCanceled, null); ServerLogger.getDefault().log(server, status); } else if( e[0] != null ) { String error = methodName.equals(IJBossRuntimeConstants.START) ? Messages.JMXResumeScannerError : Messages.JMXPauseScannerError; IStatus status = new Status(IStatus.ERROR, JBossServerCorePlugin.PLUGIN_ID, IEventCodes.DEPLOYMENT_SCANNER_TRANSITION_FAILED, error, e[0]); ServerLogger.getDefault().log(server, status); } } }</code><technical_language>do new Boolean(false). Boolean.FALSE instead</technical_language>

Target:
protected void launchDeployCommand(final IServer server, final MBeanServerConnection connection, final ObjectName objectName, final String methodName, IProgressMonitor monitor) throws Exception { final Exception[] e = new Exception[1]; final Object waitObject = new Object(); final Boolean[] subtaskComplete = new Boolean[1]; subtaskComplete[0] = Boolean.FALSE; Thread t = new Thread() { public void run() { Exception exception = null; try { executeDeploymentCommand(connection, objectName, methodName); } catch( Exception ex ) { exception = ex; } synchronized(waitObject) { e[0] = exception; subtaskComplete[0] = Boolean.TRUE; waitObject.notifyAll(); } } }; t.start(); int count = 0; while(t.isAlive() && !monitor.isCanceled() && count <= 4000) { count+= 1000; synchronized(waitObject) { if( subtaskComplete[0].booleanValue() ) break; waitObject.wait(1000); } } synchronized(waitObject) { if( !subtaskComplete[0].booleanValue()) { t.interrupt(); IStatus status = new Status(IStatus.WARNING, JBossServerCorePlugin.PLUGIN_ID, IEventCodes.DEPLOYMENT_SCANNER_TRANSITION_CANCELED, Messages.JMXScannerCanceled, null); ServerLogger.getDefault().log(server, status); } else if( e[0] != null ) { String error = methodName.equals(IJBossRuntimeConstants.START) ? Messages.JMXResumeScannerError : Messages.JMXPauseScannerError; IStatus status = new Status(IStatus.ERROR, JBossServerCorePlugin.PLUGIN_ID, IEventCodes.DEPLOYMENT_SCANNER_TRANSITION_FAILED, error, e[0]); ServerLogger.getDefault().log(server, status); } } }
Source:
<code>public void finishRecord() { checkState(field != -1, "not in record"); checkState(field == columnTypes.size(), "not all fields set"); field = -1; <START> cassandraSession.executeWithSession(s -> s.execute(insert.bind(values.toArray()))); <END> }</code><technical_language>Ditto need change CassandraSession rebased <LINK_0></technical_language>

Target:
public void finishRecord() { checkState(field != -1, "not in record"); checkState(field == columnTypes.size(), "not all fields set"); field = -1; cassandraSession.execute(insert.bind(values.toArray())); }
Source:
<code>public Comparator<LamiTableEntry> getComparator() { return (o1, o2) -> { Number d1 = resolveNumber(o1); Number d2 = resolveNumber(o2); if (d1 == null && d2 == null) { return 0; } if (d1 == null) { return 1; } if (d2 == null) { return -1; } <START> <END> BigDecimal bd1 = new BigDecimal(d1.toString()); BigDecimal bd2 = new BigDecimal(d2.toString()); return bd1.compareTo(bd2); }; }</code><technical_language>This class's implementation resolveNumber() return a Long, return Long.compare(d1.longValue(), d2.longValue())</technical_language>

Target:
public Comparator<LamiTableEntry> getComparator() { return (o1, o2) -> { Number d1 = resolveNumber(o1); Number d2 = resolveNumber(o2); if (d1 == null && d2 == null) { return 0; } if (d1 == null) { return 1; } if (d2 == null) { return -1; } return Long.compare(d1.longValue(), d2.longValue()); }; }
Source:
<code>private FinderPattern[] selectBestPatterns() throws NotFoundException { int startSize = possibleCenters.size(); if (startSize < 3) { throw NotFoundException.getNotFoundInstance(); } Collections.sort(possibleCenters, new EstimatedModuleComparator()); double distotion = Double.MAX_VALUE; double[] squares = new double[3]; FinderPattern[] bestPatterns = new FinderPattern[3]; for (int i = 0; i < possibleCenters.size() - 2; i++) { for (int j = i + 1; j < possibleCenters.size() - 1; j++) { for (int k = j + 1; k < possibleCenters.size(); k++) { <START> float minModuleSize = possibleCenters.get(i).getEstimatedModuleSize(); <END> float maxModuleSize = possibleCenters.get(k).getEstimatedModuleSize(); if (maxModuleSize > minModuleSize * 1.4f) { continue; } squares[0] = square(possibleCenters.get(i), possibleCenters.get(j)); squares[1] = square(possibleCenters.get(j), possibleCenters.get(k)); squares[2] = square(possibleCenters.get(k), possibleCenters.get(i)); Arrays.sort(squares); double d = Math.abs(squares[2] - 2 * squares[1]) + Math.abs(squares[2] - 2 * squares[0]); if (d < distotion) { distotion = d; bestPatterns[0] = possibleCenters.get(i); bestPatterns[1] = possibleCenters.get(j); bestPatterns[2] = possibleCenters.get(k); } } } } if (distotion == Double.MAX_VALUE) { throw NotFoundException.getNotFoundInstance(); } return bestPatterns; }</code><technical_language>lift call possibleCenters.get(i) out of loop for performance</technical_language>

Target:
private FinderPattern[] selectBestPatterns() throws NotFoundException { int startSize = possibleCenters.size(); if (startSize < 3) { throw NotFoundException.getNotFoundInstance(); } Collections.sort(possibleCenters, moduleComparator); double distortion = Double.MAX_VALUE; double[] squares = new double[3]; FinderPattern[] bestPatterns = new FinderPattern[3]; for (int i = 0; i < possibleCenters.size() - 2; i++) { FinderPattern fpi = possibleCenters.get(i); float minModuleSize = fpi.getEstimatedModuleSize(); for (int j = i + 1; j < possibleCenters.size() - 1; j++) { FinderPattern fpj = possibleCenters.get(j); double squares0 = squaredDistance(fpi, fpj); for (int k = j + 1; k < possibleCenters.size(); k++) { FinderPattern fpk = possibleCenters.get(k); float maxModuleSize = fpk.getEstimatedModuleSize(); if (maxModuleSize > minModuleSize * 1.4f) { continue; } squares[0] = squares0; squares[1] = squaredDistance(fpj, fpk); squares[2] = squaredDistance(fpi, fpk); Arrays.sort(squares); double d = Math.abs(squares[2] - 2 * squares[1]) + Math.abs(squares[2] - 2 * squares[0]); if (d < distortion) { distortion = d; bestPatterns[0] = fpi; bestPatterns[1] = fpj; bestPatterns[2] = fpk; } } } } if (distortion == Double.MAX_VALUE) { throw NotFoundException.getNotFoundInstance(); } return bestPatterns; }
Source:
<code>public static int hexStringToInt(String hexString) { <START> return ByteBuffer.wrap(hexStringToByteArray(hexString)).getInt(); <END> }</code><technical_language>add a length check of hexString is bytes</technical_language>

Target:
public static int hexStringToInt(String hexString) { if (hexString.length() != 8) { throw new IllegalArgumentException("Invalid hex string length for integer type"); } return ByteBuffer.wrap(hexStringToByteArray(hexString)).getInt(); }
Source:
<code>public void readPayload(int id, PacketBuffer buffer, Side side, MessageContext ctx) throws IOException { super.readPayload(id, buffer, side, ctx); if(id == NET_RENDER_DATA) { power = buffer.readLong(); <START> } <END> }</code><technical_language>(Another NET_RENDER_DATA -> NET_GUI_DATA bit)</technical_language>

Target:
public void readPayload(int id, PacketBuffer buffer, Side side, MessageContext ctx) throws IOException { super.readPayload(id, buffer, side, ctx); if(id == NET_GUI_DATA) { power = buffer.readLong(); } }
Source:
<code>public Schema outputSchema(Schema input) { try { return Utils .getSchemaFromString("PopulationInfo:Tuple(columnId : int, binLen : int, unitSum : double, positiveCounter : chararray, negativeCounter : chararray)"); } catch (ParserException e) { <START> log.debug("Error when generating output schema.", e); <END> return null; } }</code><technical_language>error level here</technical_language>

Target:
public Schema outputSchema(Schema input) { try { return Utils .getSchemaFromString("PopulationInfo:Tuple(columnId : int, binLen : int, unitSum : double, positiveCounter : chararray, negativeCounter : chararray)"); } catch (ParserException e) { log.error("Error when generating output schema.", e); return null; } }
Source:
<code><START> private BlobId addBlobToSet(MockMessageWriteSet messageWriteSet, long size, long expiresAtMs, short accountId, <END> short containerId) throws StoreException { BlobId id = getUniqueId(accountId, containerId); long crc = random.nextLong(); MessageInfo info = new MessageInfo(id, size, false, false, expiresAtMs, crc, accountId, containerId, Utils.Infinite_Time); ByteBuffer buffer = ByteBuffer.wrap(TestUtils.getRandomBytes((int) size)); messageWriteSet.add(info, buffer); return id; }</code><technical_language>throws StoreException is needed</technical_language>

Target:
private BlobId addBlobToSet(MockMessageWriteSet messageWriteSet, long size, long expiresAtMs, short accountId, short containerId) { BlobId id = getUniqueId(accountId, containerId); long crc = random.nextLong(); MessageInfo info = new MessageInfo(id, size, false, false, expiresAtMs, crc, accountId, containerId, Utils.Infinite_Time); ByteBuffer buffer = ByteBuffer.wrap(TestUtils.getRandomBytes((int) size)); messageWriteSet.add(info, buffer); return id; }
Source:
<code>public void run() { try { while (true) { Request request = submittedRequests.take(); if (Request.requestOfDeath == request) { break; } if (request.mustDrop()) { continue; } if (maxRequests > 0) { while (!killed) { if (dropStaleRequests && request.isStale()) { dropRequest(request); ServerMetrics.getMetrics().STALE_REQUESTS_DROPPED.add(1); request = null; break; } if (zks.getInProcess() < maxRequests) { break; } throttleSleep(stallTime); } } if (killed) { break; } if (request != null) { if (request.isStale()) { ServerMetrics.getMetrics().STALE_REQUESTS.add(1); } zks.submitRequestNow(request); } } } catch (InterruptedException e) { LOG.error("Unexpected interruption", e); } int dropped = drainQueue(); <START> LOG.info("RequestThrottler shutdown. Dropped " + dropped + " requests"); <END> }</code><technical_language>nit: consider parameterized logging</technical_language>

Target:
public void run() { try { while (true) { if (killed) { break; } Request request = submittedRequests.take(); if (Request.requestOfDeath == request) { break; } if (request.mustDrop()) { continue; } if (maxRequests > 0) { while (!killed) { if (dropStaleRequests && request.isStale()) { dropRequest(request); ServerMetrics.getMetrics().STALE_REQUESTS_DROPPED.add(1); request = null; break; } if (zks.getInProcess() < maxRequests) { break; } throttleSleep(stallTime); } } if (killed) { break; } if (request != null) { if (request.isStale()) { ServerMetrics.getMetrics().STALE_REQUESTS.add(1); } zks.submitRequestNow(request); } } } catch (InterruptedException e) { LOG.error("Unexpected interruption", e); } int dropped = drainQueue(); LOG.info("RequestThrottler shutdown. Dropped requests", dropped); }
Source:
<code>protected void ExecuteVmCommand() { lockVmWithCompensationIfNeeded(); if (!isInternalExecution()) { freeLock(); } restoreSnapshotAndRemoveObsoleteSnapshots(); VdcReturnValueBase returnValue = null; for (DiskImage image : getImagesList()) { if (image.getimageStatus() != ImageStatus.ILLEGAL) { ImagesContainterParametersBase params = new RestoreFromSnapshotParameters(image.getImageId(), getVmId(), targetSnapshot, removedSnapshotId); returnValue = runAsyncTask(VdcActionType.RestoreFromSnapshot, params); } } <START> if (getImagesList().size() > 0) { <END> if (getTaskIdList().size() == 0) { log.errorFormat("Can't restore snapshot for VM, since no destroyImage task could be established in the VDSM."); if (returnValue != null) { getReturnValue().setFault(returnValue.getFault()); return; } } else { setSucceeded(true); } deleteOrphanedImages(); removeSnapshotsFromDB(); } else { removeSnapshotsFromDB(); EndVmCommand(); setSucceeded(true); } }</code><technical_language>works, I put this 'if' 'for' loop</technical_language>

Target:
protected void ExecuteVmCommand() { lockVmWithCompensationIfNeeded(); if (!isInternalExecution()) { freeLock(); } restoreSnapshotAndRemoveObsoleteSnapshots(); if (getImagesList().size() > 0) { VdcReturnValueBase returnValue = null; for (DiskImage image : getImagesList()) { if (image.getimageStatus() != ImageStatus.ILLEGAL) { ImagesContainterParametersBase params = new RestoreFromSnapshotParameters(image.getImageId(), getVmId(), targetSnapshot, removedSnapshotId); returnValue = runAsyncTask(VdcActionType.RestoreFromSnapshot, params); } } if (getTaskIdList().size() == 0) { log.errorFormat("Can't restore snapshot for VM, since no destroyImage task could be established in the VDSM."); if (returnValue != null) { getReturnValue().setFault(returnValue.getFault()); return; } } else { setSucceeded(true); } deleteOrphanedImages(); removeSnapshotsFromDB(); } else { removeSnapshotsFromDB(); EndVmCommand(); setSucceeded(true); } }