auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void changeDeck(int selectedDeck) { List<Card> cards = new ArrayList<>(); try { mNewDid = mDropDownDecks.get(selectedDeck).getLong("id"); } catch (JSONException e) { <START> e.printStackTrace(); <END> return; } for (int cardPosition : mCheckedCardPositions) { final Card card = getCol().getCard(Long.parseLong(getCards().get(cardPosition).get("id"))); cards.add(card); } List<Card> changedCards = new ArrayList<>(); for (Card card : cards) { if (card.getDid() != mNewDid) { changedCards.add(card); mReloadRequired = true; } } if (changedCards.isEmpty()) { endMultiSelectMode(); mCardsAdapter.notifyDataSetChanged(); return; } DeckTask.launchDeckTask(DeckTask.TASK_TYPE_DISMISS_MULTI, mChangeMultiHandler, new DeckTask.TaskData(new Object[]{changedCards.toArray(new Card[changedCards.size()]), Collection.DismissType.CHANGE_DECK_MULTI, mNewDid})); }</code><technical_language>Change this throw new RuntimeException(e);. impossible for this situation occur, if want app crash it</technical_language>

Target:
private void changeDeck(int selectedDeck) { long[] ids = getSelectedCardIds(); try { mNewDid = mDropDownDecks.get(selectedDeck).getLong("id"); } catch (JSONException e) { throw new RuntimeException(e); } if (ids.length == 0) { endMultiSelectMode(); mCardsAdapter.notifyDataSetChanged(); return; } if (CardUtils.isIn(ids, getReviewerCardId())) { mReloadRequired = true; } DeckTask.launchDeckTask(DeckTask.TASK_TYPE_DISMISS_MULTI, mChangeDeckHandler, new DeckTask.TaskData(new Object[]{ids, Collection.DismissType.CHANGE_DECK_MULTI, mNewDid})); }
Source:
<code>public Object onMessage(String id, Object data) { if(id.equals("onPageStarted")) { this.isPageFinished = false; } if (id.equals("onPageFinished")) { this.isPageFinished = true; <START> if (intent != null) { <END> new android.os.Handler().postDelayed( new Runnable() { public void run() { handleNotificationData(intent); } }, 500); } } return super.onMessage(id, data); }</code><technical_language>is funny indentation</technical_language>

Target:
public Object onMessage(String id, Object data) { if(id.equals("onPageStarted")) { this.isPageFinished = false; } if (id.equals("onPageFinished")) { this.isPageFinished = true; if (this.lastPushIntent != null) { new android.os.Handler().postDelayed( new Runnable() { public void run() { handleNotificationData(lastPushIntent); } }, 500); } } return super.onMessage(id, data); }
Source:
<code>public Long time() { Long time = microseconds(); <START> return time == null ? null : time / 1000; <END> }</code><technical_language>TimeUnit constants for conversion</technical_language>

Target:
public Long time() { Long time = microseconds(); return time == null ? null : TimeUnit.MICROSECONDS.toMillis(time); }
Source:
<code>public boolean onTouchEvent(MotionEvent event) { try { return super.onTouchEvent(event); } catch (RuntimeException e) { <START> return true; <END> } }</code><technical_language>Generally agree + good find. This method return false handled event. <LINK_0></technical_language>

Target:
public boolean onTouchEvent(MotionEvent event) { try { return super.onTouchEvent(event); } catch (RuntimeException e) { return false; } }
Source:
<code>private PerAlleleCollection<Double> getHetGenotypeLogOdds(ReadLikelihoods<Allele> likelihoods, final boolean isGermline, final Strand strand, final String sample) { final OptionalDouble givenAltAlleleFraction = isGermline ? GERMLINE_HET_ALT_FRACTION : NO_FIXED_TUMOR_ALT_FRACTION; <START> final String sampleForAlleleFractions = (sample == matchedNormalSampleName && isGermline) ? matchedNormalSampleName : tumorSampleName; <END> final PerAlleleCollection<Double> hetGenotypeLogLks = getHetGenotypeLogLikelihoods(likelihoods, sampleForAlleleFractions, sample, givenAltAlleleFraction, strand); final PerAlleleCollection<Double> lods = new PerAlleleCollection<>(PerAlleleCollection.Type.ALT_ONLY); final int flipLodFactor = isGermline ? -1 : 1; final List<Allele> altAlleles = likelihoods.alleles().stream().filter(Allele::isNonReference).collect(Collectors.toList()); lods.set(altAlleles, a -> flipLodFactor * (hetGenotypeLogLks.get(a) - hetGenotypeLogLks.getRef())); return lods; }</code><technical_language>I understand code 3 cases of getHetGenotypeLogOdds: 1. tumor lod: allele fraction of tumor reads tumor 2. normal lod: 0.5 (GERMLINE_HET_ALT_FRACTION) allele fraction reads normal 3. normal artifact lod: allele fraction of _tumor_ reads normal current code, for case 3) allele fraction of normal. understanding is sampleForAlleleFractions set tumorSampleName</technical_language>

Target:
private PerAlleleCollection<Double> getHetGenotypeLogOdds(ReadLikelihoods<Allele> likelihoods, final boolean isGermline, final Strand strand, final String sample) { final OptionalDouble givenAltAlleleFraction = isGermline ? GERMLINE_HET_ALT_FRACTION : NO_FIXED_TUMOR_ALT_FRACTION; final String sampleForAlleleFractions = (sample.equals(matchedNormalSampleName) && isGermline) ? matchedNormalSampleName : tumorSampleName; final PerAlleleCollection<Double> hetGenotypeLogLks = getHetGenotypeLogLikelihoods(likelihoods, sampleForAlleleFractions, sample, givenAltAlleleFraction, strand); final PerAlleleCollection<Double> lods = new PerAlleleCollection<>(PerAlleleCollection.Type.ALT_ONLY); final int flipLodFactor = isGermline ? -1 : 1; final List<Allele> altAlleles = likelihoods.alleles().stream().filter(Allele::isNonReference).collect(Collectors.toList()); lods.set(altAlleles, a -> flipLodFactor * (hetGenotypeLogLks.get(a) - hetGenotypeLogLks.getRef())); return lods; }
Source:
<code>public KafkaSupervisorSpec( @JsonProperty("dataSchema") DataSchema dataSchema, @JsonProperty("tuningConfig") KafkaSupervisorTuningConfig tuningConfig, @JsonProperty("ioConfig") KafkaSupervisorIOConfig ioConfig, @JsonProperty("context") Map<String, Object> context, @JsonProperty("suspended") Boolean suspended, @JacksonInject TaskStorage taskStorage, @JacksonInject TaskMaster taskMaster, @JacksonInject IndexerMetadataStorageCoordinator indexerMetadataStorageCoordinator, @JacksonInject KafkaIndexTaskClientFactory kafkaIndexTaskClientFactory, @JacksonInject @Json ObjectMapper mapper, @JacksonInject ServiceEmitter emitter, @JacksonInject DruidMonitorSchedulerConfig monitorSchedulerConfig, @JacksonInject RowIngestionMetersFactory rowIngestionMetersFactory, @JacksonInject SupervisorStateManagerConfig supervisorStateManagerConfig ) { super( dataSchema, tuningConfig != null ? tuningConfig : new KafkaSupervisorTuningConfig( null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, <START> null <END> ), ioConfig, context, suspended, taskStorage, taskMaster, indexerMetadataStorageCoordinator, kafkaIndexTaskClientFactory, mapper, emitter, monitorSchedulerConfig, rowIngestionMetersFactory, supervisorStateManagerConfig ); }</code><technical_language>Change is unrelated PR</technical_language>

Target:
public KafkaSupervisorSpec( @JsonProperty("dataSchema") DataSchema dataSchema, @JsonProperty("tuningConfig") KafkaSupervisorTuningConfig tuningConfig, @JsonProperty("ioConfig") KafkaSupervisorIOConfig ioConfig, @JsonProperty("context") Map<String, Object> context, @JsonProperty("suspended") Boolean suspended, @JacksonInject TaskStorage taskStorage, @JacksonInject TaskMaster taskMaster, @JacksonInject IndexerMetadataStorageCoordinator indexerMetadataStorageCoordinator, @JacksonInject KafkaIndexTaskClientFactory kafkaIndexTaskClientFactory, @JacksonInject @Json ObjectMapper mapper, @JacksonInject ServiceEmitter emitter, @JacksonInject DruidMonitorSchedulerConfig monitorSchedulerConfig, @JacksonInject RowIngestionMetersFactory rowIngestionMetersFactory, @JacksonInject SupervisorStateManagerConfig supervisorStateManagerConfig ) { super( dataSchema, tuningConfig != null ? tuningConfig : new KafkaSupervisorTuningConfig( null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null ), ioConfig, context, suspended, taskStorage, taskMaster, indexerMetadataStorageCoordinator, kafkaIndexTaskClientFactory, mapper, emitter, monitorSchedulerConfig, rowIngestionMetersFactory, supervisorStateManagerConfig ); }
Source:
<code><START> CosmosSyncUserResponse convertUserResponse(CosmosUserResponse response) { <END> return new CosmosSyncUserResponse(response, this); }</code><technical_language>this private. other methods in class turned private</technical_language>

Target:
private CosmosSyncUserResponse convertUserResponse(CosmosUserResponse response) { return new CosmosSyncUserResponse(response, this); }
Source:
<code>public JaxbRule(Rule rule) { id = rule.getId(); priority = rule.getPriority(); userName = rule.getUsername(); roleName = rule.getRolename(); addressRange = rule.getAddressRange() == null ? null : rule.getAddressRange().getCidrSignature(); workspace = rule.getWorkspace(); layer = rule.getLayer(); service = rule.getService() == null ? null : rule.getService().toUpperCase(); request = rule.getRequest(); access = rule.getAccess().toString(); if (rule.getRuleLimits() != null) { limits = new Limits(); limits.setAllowedArea(rule.getRuleLimits().getAllowedArea()); limits.setCatalogMode(rule.getRuleLimits().getCatalogMode().toString()); } if (rule.getLayerDetails() != null) { layerDetails = new LayerDetails(); layerDetails.setAllowedArea(rule.getLayerDetails().getArea()); layerDetails.getAllowedStyles().addAll(rule.getLayerDetails().getAllowedStyles()); <START> if (rule.getLayerDetails().getCatalogMode() != null) { <END> layerDetails.setCatalogMode(rule.getLayerDetails().getCatalogMode().toString()); } else { layerDetails.setCatalogMode(CatalogMode.HIDE.toString()); } layerDetails.setCqlFilterRead(rule.getLayerDetails().getCqlFilterRead()); layerDetails.setCqlFilterWrite(rule.getLayerDetails().getCqlFilterWrite()); layerDetails.setDefaultStyle(rule.getLayerDetails().getDefaultStyle()); layerDetails.setLayerType(rule.getLayerDetails().getType().toString()); for (org.geoserver.geofence.core.model.LayerAttribute att : rule.getLayerDetails().getAttributes()) { layerDetails.getAttributes().add(new LayerAttribute(att)); } } }</code><technical_language>this appears a fix unrelated upgrade</technical_language>

Target:
public JaxbRule(Rule rule) { id = rule.getId(); priority = rule.getPriority(); userName = rule.getUsername(); roleName = rule.getRolename(); addressRange = rule.getAddressRange() == null ? null : rule.getAddressRange().getCidrSignature(); workspace = rule.getWorkspace(); layer = rule.getLayer(); service = rule.getService() == null ? null : rule.getService().toUpperCase(); request = rule.getRequest(); access = rule.getAccess().toString(); if (rule.getRuleLimits() != null) { limits = new Limits(); limits.setAllowedArea(rule.getRuleLimits().getAllowedArea()); limits.setCatalogMode(rule.getRuleLimits().getCatalogMode().toString()); } if (rule.getLayerDetails() != null) { layerDetails = new LayerDetails(); layerDetails.setAllowedArea(rule.getLayerDetails().getArea()); layerDetails.getAllowedStyles().addAll(rule.getLayerDetails().getAllowedStyles()); layerDetails.setCatalogMode(rule.getLayerDetails().getCatalogMode().toString()); layerDetails.setCqlFilterRead(rule.getLayerDetails().getCqlFilterRead()); layerDetails.setCqlFilterWrite(rule.getLayerDetails().getCqlFilterWrite()); layerDetails.setDefaultStyle(rule.getLayerDetails().getDefaultStyle()); layerDetails.setLayerType(rule.getLayerDetails().getType().toString()); for (org.geoserver.geofence.core.model.LayerAttribute att : rule.getLayerDetails().getAttributes()) { layerDetails.getAttributes().add(new LayerAttribute(att)); } } }
Source:
<code>public synchronized void closeCursor(String cursorId) { ReadCursor reader = m_readCursors.remove(cursorId); if (reader != null && reader.m_segment != null) { try { <START> reader.m_segment.getReader(cursorId).close(); <END> } catch (IOException e) { } } }</code><technical_language>check if segments closed deleted a result of closing cursors? I guess OK if delete this point next ack deletes a segment this delete this well</technical_language>

Target:
public synchronized void closeCursor(String cursorId) { if (m_closed) { return; } ReadCursor reader = m_readCursors.remove(cursorId); if (reader != null && reader.m_segment != null) { try { reader.m_segment.getReader(cursorId).close(); } catch (IOException e) { } } try { boolean isLastSegment = true; for (PBDSegment segment : m_segments.descendingMap().values()) { if (isLastSegment) { isLastSegment = false; continue; } if (canDeleteSegment(segment)) { closeAndDeleteSegmentsBefore(segment.segmentId(), "because of close of cursor"); break; } } } catch (IOException e) { LOG.error("Exception closing and deleting PBD segment", e); } }
Source:
<code>private void handleMetadataOnlyResponseMessage(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType deviceResult, final OsgpException exception) { ResponseMessageResultType result = deviceResult; if (exception != null) { LOGGER.error(DEVICE_RESPONSE_NOT_OK_LOG_MSG, exception); result = ResponseMessageResultType.NOT_OK; } <START> this.webServiceResponseMessageSender.send(ResponseMessage.newResponseMessageBuilder() <END> .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception).withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(), deviceMessageMetadata.getMessageType()); }</code><technical_language>Extract building of ResponseMessage variable (in eclipse, select text, right-click > refactor > extract local variable / select code + shift+alt+L). This code a bit more readable, especially passing in other besides ResponseMessage</technical_language>

Target:
private void handleMetadataOnlyResponseMessage(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType deviceResult, final OsgpException exception) { ResponseMessageResultType result = deviceResult; if (exception != null) { LOGGER.error(DEVICE_RESPONSE_NOT_OK_LOG_MSG, exception); result = ResponseMessageResultType.NOT_OK; } final ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception).withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(); this.webServiceResponseMessageSender.send(responseMessage, deviceMessageMetadata.getMessageType()); }
Source:
<code>private void testCreatePartitionedBucketedTableAs(HiveStorageFormat storageFormat) { String tableName = "test_create_partitioned_bucketed_table_as"; @Language("SQL") String createTable = "" + "CREATE TABLE " + tableName + " " + "WITH (" + "format = '" + storageFormat + "', " + "partitioned_by = ARRAY[ 'orderstatus' ], " + "bucketed_by = ARRAY[ 'custkey', 'custkey2' ], " + "bucket_count = 11 " + ") " + "AS " + "SELECT custkey, custkey AS custkey2, comment, orderstatus " + "FROM tpch.tiny.orders"; assertUpdate( getParallelWriteSession(), createTable, <START> "SELECT COUNT(*) FROM orders"); <END> verifyPartitionedBucketedTable(storageFormat, tableName); assertUpdate("DROP TABLE " + tableName); assertFalse(getQueryRunner().tableExists(getSession(), tableName)); }</code><technical_language>count -> COUNT / -> unrelated this commit. I suggest do in a separate PR :)</technical_language>

Target:
private void testCreatePartitionedBucketedTableAs(HiveStorageFormat storageFormat) { String tableName = "test_create_partitioned_bucketed_table_as"; @Language("SQL") String createTable = "" + "CREATE TABLE " + tableName + " " + "WITH (" + "format = '" + storageFormat + "', " + "partitioned_by = ARRAY[ 'orderstatus' ], " + "bucketed_by = ARRAY[ 'custkey', 'custkey2' ], " + "bucket_count = 11 " + ") " + "AS " + "SELECT custkey, custkey AS custkey2, comment, orderstatus " + "FROM tpch.tiny.orders"; assertUpdate( getParallelWriteSession(), createTable, "SELECT count(*) from orders"); verifyPartitionedBucketedTable(storageFormat, tableName); assertUpdate("DROP TABLE " + tableName); assertFalse(getQueryRunner().tableExists(getSession(), tableName)); }
Source:
<code>public void testVFE5() { T_check_cast_3 t = new T_check_cast_3(); try { t.run(); <START> fail("expected NoClassDefFoundError"); <END> } catch (NoClassDefFoundError iae) { } }</code><technical_language>If a NoClassDefFoundError, a class found. exception class found. logcat output more</technical_language>

Target:
public void testVFE5() { T_check_cast_3 t = new T_check_cast_3(); try { t.run(); fail("expected IllegalAccessError"); } catch (IllegalAccessError iae) { } }
Source:
<code>private JSONObject getTopology(StartAction startAction, Map<Integer, String> hostGroups, JoinCoordinator joinCoordinator) { JSONObject topo = null; int sitesperhost = m_catalogContext.getDeployment().getCluster().getSitesperhost(); int kfactor = m_catalogContext.getDeployment().getCluster().getKfactor(); if (startAction == StartAction.JOIN) { assert(joinCoordinator != null); topo = joinCoordinator.getTopology(); } else { final Set<Integer> liveHostIds = m_messenger.getLiveHostIds(); Preconditions.checkArgument(hostGroups.keySet().equals(liveHostIds)); int hostcount = liveHostIds.size(); ClusterConfig clusterConfig = new ClusterConfig(hostcount, sitesperhost, kfactor); if (!clusterConfig.validate()) { VoltDB.crashLocalVoltDB(clusterConfig.getErrorMsg(), false, null); } try { <START> final Multimap<Integer, Long> replicas = m_cartographer.getReplicasForPartitions(m_cartographer.getPartitions()); <END> final Map<Integer, Long> masters = m_cartographer.getHSIdsForSinglePartitionMasters(); replicas.removeAll(MpInitiator.MP_INIT_PID); masters.remove(MpInitiator.MP_INIT_PID); topo = clusterConfig.getTopology(hostGroups, replicas, masters); } catch (Exception e) { VoltDB.crashLocalVoltDB("Unable to calculate topology", false, e); } if (!startAction.doesRejoin()) { topo = registerClusterConfig(topo); } } return topo; }</code><technical_language>getReplicasForPartitions() returns masters replicas, need do is a diff remove master partitions it</technical_language>

Target:
private JSONObject getTopology(StartAction startAction, Map<Integer, String> hostGroups, JoinCoordinator joinCoordinator) { JSONObject topo = null; int sitesperhost = m_catalogContext.getDeployment().getCluster().getSitesperhost(); int kfactor = m_catalogContext.getDeployment().getCluster().getKfactor(); if (startAction == StartAction.JOIN) { assert(joinCoordinator != null); topo = joinCoordinator.getTopology(); } else { final Set<Integer> liveHostIds = m_messenger.getLiveHostIds(); Preconditions.checkArgument(hostGroups.keySet().equals(liveHostIds)); int hostcount = liveHostIds.size(); ClusterConfig clusterConfig = new ClusterConfig(hostcount, sitesperhost, kfactor); if (!startAction.doesRejoin() && !clusterConfig.validate()) { VoltDB.crashLocalVoltDB(clusterConfig.getErrorMsg(), false, null); } try { final Multimap<Integer, Long> replicas = m_cartographer.getReplicasForPartitions(m_cartographer.getPartitions()); final Map<Integer, Long> masters = m_cartographer.getHSIdsForSinglePartitionMasters(); replicas.removeAll(MpInitiator.MP_INIT_PID); masters.remove(MpInitiator.MP_INIT_PID); topo = clusterConfig.getTopology(hostGroups, replicas, masters); } catch (Exception e) { VoltDB.crashLocalVoltDB("Unable to calculate topology", false, e); } if (!startAction.doesRejoin()) { topo = registerClusterConfig(topo); } } return topo; }
Source:
<code>lookupOrCreateAdaptiveTrackProjection( TrackBitrateAllocation trackBitrateAllocation) { synchronized (adaptiveTrackProjectionMap) { AdaptiveTrackProjection adaptiveTrackProjection = adaptiveTrackProjectionMap.get( trackBitrateAllocation.targetSSRC); if (adaptiveTrackProjection != null || trackBitrateAllocation.track == null) { return adaptiveTrackProjection; } RTPEncodingDesc[] rtpEncodings = trackBitrateAllocation.track.getRTPEncodings(); if (ArrayUtils.isNullOrEmpty(rtpEncodings)) { return null; } final String endpointID = trackBitrateAllocation.endpointID; <START> final Endpoint endpointOwningTrack = destinationEndpoint.getConference().getLocalEndpoint(endpointID); <END> if (endpointOwningTrack == null) { return null; } final long targetSSRC = trackBitrateAllocation.targetSSRC; adaptiveTrackProjection = new AdaptiveTrackProjection( diagnosticContext, trackBitrateAllocation.track, () -> destinationEndpoint.getConference().requestKeyframe( endpointID, targetSSRC), endpointOwningTrack.getBitrateController().payloadTypes, logger); logger.debug(() -> "new track projection for " + trackBitrateAllocation.track); for (RTPEncodingDesc rtpEncoding : rtpEncodings) { adaptiveTrackProjectionMap.put( rtpEncoding.getPrimarySSRC(), adaptiveTrackProjection); } return adaptiveTrackProjection; } }</code><technical_language>discuss if want fix this (as seen, a assuming payload types), if do do this, expose payload types a way, I think. mind is Transceiver expose a read-only version of StreamInformationStore (which expose Endpoint level)</technical_language>

Target:
lookupOrCreateAdaptiveTrackProjection( TrackBitrateAllocation trackBitrateAllocation) { synchronized (adaptiveTrackProjectionMap) { AdaptiveTrackProjection adaptiveTrackProjection = adaptiveTrackProjectionMap.get( trackBitrateAllocation.targetSSRC); if (adaptiveTrackProjection != null || trackBitrateAllocation.track == null) { return adaptiveTrackProjection; } RTPEncodingDesc[] rtpEncodings = trackBitrateAllocation.track.getRTPEncodings(); if (ArrayUtils.isNullOrEmpty(rtpEncodings)) { return null; } final String endpointID = trackBitrateAllocation.endpointID; final Endpoint endpointOwningTrack = destinationEndpoint.getConference().getLocalEndpoint(endpointID); if (endpointOwningTrack == null) { return null; } final Map<Byte, PayloadType> endpointOwningTrackPayloadTypes = endpointOwningTrack .getTransceiver() .getReadOnlyStreamInformationStore() .getRtpPayloadTypes(); final long targetSSRC = trackBitrateAllocation.targetSSRC; adaptiveTrackProjection = new AdaptiveTrackProjection( diagnosticContext, trackBitrateAllocation.track, () -> destinationEndpoint.getConference().requestKeyframe( endpointID, targetSSRC), endpointOwningTrackPayloadTypes, logger); logger.debug(() -> "new track projection for " + trackBitrateAllocation.track); for (RTPEncodingDesc rtpEncoding : rtpEncodings) { adaptiveTrackProjectionMap.put( rtpEncoding.getPrimarySSRC(), adaptiveTrackProjection); } return adaptiveTrackProjection; } }
Source:
<code>public void downloadAllServerChanges() { checkMainThread("downloadAllServerChanges() cannot be called from the main thread."); <START> synchronized (waitForChangesMutex) { <END> if (!isClosed) { waitingForServerChanges = new WaitForServerChangesWrapper(); boolean listenerRegistered = nativeWaitForDownloadCompletion(configuration.getPath()); if (!listenerRegistered) { waitingForServerChanges = null; throw new ObjectServerError(ErrorCode.UNKNOWN, "It was not possible to download all changes. Have the Sync Client been started?"); } waitingForServerChanges.waitForServerChanges(); if (!isClosed) { if (!waitingForServerChanges.isSuccess()) { waitingForServerChanges.throwExceptionIfNeeded(); } } waitingForServerChanges = null; } } }</code><technical_language>is allowed call downloadAllServerChanges more once</technical_language>

Target:
public void downloadAllServerChanges() throws InterruptedException { checkIfNotOnMainThread("downloadAllServerChanges() cannot be called from the main thread."); synchronized (waitForChangesMutex) { if (!isClosed) { WaitForServerChangesWrapper wrapper = new WaitForServerChangesWrapper(); waitingForServerChanges.set(wrapper); boolean listenerRegistered = nativeWaitForDownloadCompletion(configuration.getPath()); if (!listenerRegistered) { waitingForServerChanges.set(null); throw new ObjectServerError(ErrorCode.UNKNOWN, "It was not possible to download all changes. Has the SyncClient been started?"); } wrapper.waitForServerChanges(); try { if (!isClosed) { if (!wrapper.isSuccess()) { wrapper.throwExceptionIfNeeded(); } } } finally { waitingForServerChanges.set(null); } } } }
Source:
<code>public Date getUpdatedAt() { if (updatedAt == null) { setCreatedAt(new Date(Const.DEFAULT_STUDENT_CREATION_DATE)); } <START> return updatedAt; <END> }</code><technical_language>issue in attributes</technical_language>

Target:
public Date getUpdatedAt() { return (updatedAt == null) ? Const.TIME_REPRESENTS_DEFAULT_TIMESTAMP : updatedAt; }
Source:
<code>public boolean check(VM vm) { <START> return vm.getStatus().isSuspended(); <END> }</code><technical_language>compare standard java for enum comparison (== VMStatus.Suspended) ? need check is Suspended</technical_language>

Target:
public boolean check(VM vm) { return vm.getStatus() != VMStatus.Suspended && vm.getStatus() != VMStatus.SavingState && vm.getStatus() != VMStatus.RestoringState; }
Source:
<code>private static String[] splitTypeNameValue(String typeNameToken) { String[] result; String[] keys = typeNameToken.split("=", 2); for (int i=0; i<keys.length; i++) { <START> } <END> if (keys.length == 2 && !StringUtils.isBlankOrEmptyString(keys[1])) { result = keys; } else { result = new String[2]; result[0] = keys[0]; result[1] = ""; } return result; }</code><technical_language>worries... done a bazillion times. :smile:</technical_language>

Target:
private static String[] splitTypeNameValue(String typeNameToken) { String[] result; String[] keys = typeNameToken.split("=", 2); if (keys.length == 2) { result = keys; } else { result = new String[2]; result[0] = keys[0]; result[1] = ""; } return result; }
Source:
<code>public static boolean isValid(String path) { try { VALIDATOR.get().validate(path); return true; } catch (Exception e) { <START> LOG.info("Request validation failed", e); <END> return false; } }</code><technical_language>"Path validation" instead of "Request validation"</technical_language>

Target:
public static boolean isValid(String path) { try { VALIDATOR.get().validate(path); return true; } catch (Exception e) { LOG.info("Path validation failed", e); return false; } }
Source:
<code>public Promise<Void> deleteProject(final String project) { return newPromise(new AsyncPromiseHelper.RequestCall<Void>() { @Override public void makeCall(AsyncCallback<Void> callback) { String url = openshiftPath + "/project/" + project; asyncRequestFactory.createDeleteRequest(url) <START> .loader(loader, "Deleting project...") <END> .send(newCallback(callback)); } }); }</code><technical_language>user OpenShift project Che: Deleting OpenShift project... "Deleting project [project name]..."</technical_language>

Target:
public Promise<Void> deleteProject(final String project) { return newPromise(new AsyncPromiseHelper.RequestCall<Void>() { @Override public void makeCall(AsyncCallback<Void> callback) { String url = openshiftPath + "/project/" + project; asyncRequestFactory.createDeleteRequest(url) .loader(loader, "Deleting OpenShift project...") .send(newCallback(callback)); } }); }
Source:
<code>private void updateGuideProgress(GuideMediaProgress guide, boolean rateLimit) { if (!rateLimit || System.currentTimeMillis() > mLastProgressUpdate + GUIDE_PROGRESS_INTERVAL_MS) { <START> Log.w(TAG, "Updating progress: " + guide.mMediaProgress + "/" + guide.mTotalMedia); <END> mDb.updateGuideProgress(mSite, mUser, guide.mGuide.getGuideid(), guide.mTotalMedia, guide.mMediaProgress); mLastProgressUpdate = System.currentTimeMillis(); } }</code><technical_language>Debug log well</technical_language>

Target:
private void updateGuideProgress(GuideMediaProgress guide, boolean rateLimit) { if (!rateLimit || System.currentTimeMillis() > mLastProgressUpdate + GUIDE_PROGRESS_INTERVAL_MS) { if (BuildConfig.DEBUG) { Log.d(TAG, "Updating progress: " + guide.mMediaProgress + "/" + guide.mTotalMedia); } mDb.updateGuideProgress(mSite, mUser, guide.mGuide.getGuideid(), guide.mTotalMedia, guide.mMediaProgress); mLastProgressUpdate = System.currentTimeMillis(); } }
Source:
<code>private Boolean expectedMatch(ExpectedArtifact e, Artifact a) { log.info("expected artifact fields: {}", e.getFields()); return e.getFields().stream() .filter(field -> field.getFieldType().equals(ExpectedArtifact.ArtifactField.FieldType.MUST_MATCH)) .allMatch(field -> { try { <START> <END> Field declaredField = a.getClass().getDeclaredField(field.getFieldName()); declaredField.setAccessible(true); String actualValue = (String) declaredField.get(a); declaredField.setAccessible(false); return actualValue.equals(field.getValue()); } catch (IllegalAccessException | NoSuchFieldException ex) { log.error(ex.getMessage()); return false; } }); }</code><technical_language>Extra spaces</technical_language>

Target:
private Boolean expectedMatch(ExpectedArtifact e, Artifact a) { return e.getFields().stream() .filter(field -> field.getFieldType().equals(ExpectedArtifact.ArtifactField.FieldType.MUST_MATCH)) .allMatch(field -> { try { Field declaredField = a.getClass().getDeclaredField(field.getFieldName()); declaredField.setAccessible(true); String actualValue = (String) declaredField.get(a); declaredField.setAccessible(false); return actualValue.equals(field.getValue()); } catch (IllegalAccessException | NoSuchFieldException ex) { log.error(ex.getMessage()); return false; } }); }
Source:
<code>public static String getMavenRepoDir(String defaultName) { <START> return "/tmp/maven/repo/" + defaultName; <END> }</code><technical_language>Do want hardcode paths this? this work windows? :)</technical_language>

Target:
public static String getMavenRepoDir(String defaultName) { boolean containedMaveRepo = System.getenv().containsKey(ArtifactRepositoryService.GLOBAL_M2_REPO_NAME); if(containedMaveRepo) { String mavenRepoName = ArtifactRepositoryService.GLOBAL_M2_REPO_NAME; return mavenRepoName + defaultName; }else { String tempDir = System.getProperty("java.io.tmpdir"); StringBuffer sb = new StringBuffer(); sb.append(tempDir).append("/maven/repo/").append(defaultName); return sb.toString(); } }
Source:
<code>protected boolean canDoAction() { if (!super.canDoAction()) { return false; } <START> if (getParameters().getRngDevice() == null) { <END> return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_RNG_NOT_FOUND); } if (!getRngDevices().isEmpty()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_RNG_ALREADY_EXISTS); } return true; }</code><technical_language>this in super well.</technical_language>

Target:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (!getRngDevices().isEmpty()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_RNG_ALREADY_EXISTS); } return true; }
Source:
<code>public ImmutableMap<String, String> getDefaultParameters() { <START> return ImmutableMap.<String, String>builder() <END> .put(PARAM_MAC_ADDRESS_AD_SEQUENCE_ID, "555224") .build(); }</code><technical_language>hardcoded declared class constants</technical_language>

Target:
public ImmutableMap<String, String> getDefaultParameters() { return DEFAULT_PARAMETERS; }
Source:
<code><START> private Channels() { <END> }</code><technical_language>leave super() avoid empty block complaint Sonar</technical_language>

Target:
private Channels() { super(); }
Source:
<code>public final void testDiscoverDevicesNDError() throws Exception { DiscoveryListener listener = new DiscoveryListener(); listeners.add(listener); String error = "error"; Mockito.doThrow(new XBeeException(error)).when(deviceMock).sendPacketAsync(Mockito.any(XBeePacket.class)); long start = System.currentTimeMillis(); nd.startDiscoveryProcess(listeners); long endBlock = System.currentTimeMillis(); assertThat("The 'discoverDevices' should not block", endBlock - start < TIMEOUT, is(equalTo(true))); assertThat("The 'discoverDevices' should be running", listener.isFinished(), is(equalTo(false))); <START> while(!listener.isFinished()) { <END> Thread.sleep(100); } long end = System.currentTimeMillis(); assertThat("The 'discoverDevices' process should finish after " + TIMEOUT + " ms", end - start < TIMEOUT + 150 , is(equalTo(true))); assertThat("The discovered devices list should be empty", listener.getDiscoveredDevices().size(), is(equalTo(ndAnswers.size()))); assertThat("The discovery process should finish with the '" + error + "' error", listener.getFinishError(), is(equalTo(error))); }</code><technical_language>50ms for sleep: java while (!listener.isFinished()) { Thread.sleep(50); }</technical_language>

Target:
public final void testDiscoverDevicesNDError() throws Exception { DiscoveryListener listener = new DiscoveryListener(); listeners.add(listener); String error = "error"; Mockito.doThrow(new XBeeException(error)).when(deviceMock).sendPacketAsync(Mockito.any(XBeePacket.class)); long start = System.currentTimeMillis(); nd.startDiscoveryProcess(listeners); long endBlock = System.currentTimeMillis(); assertThat("The 'discoverDevices' should not block", endBlock - start < TIMEOUT, is(equalTo(true))); assertThat("The 'discoverDevices' should be running", listener.isFinished(), is(equalTo(false))); while(!listener.isFinished()) { Thread.sleep(50); } long end = System.currentTimeMillis(); assertThat("The 'discoverDevices' process should finish after " + TIMEOUT + " ms", end - start < TIMEOUT + 150 , is(equalTo(true))); assertThat("The discovered devices list should be empty", listener.getDiscoveredDevices().size(), is(equalTo(ndAnswers.size()))); assertThat("The discovery process should finish with the '" + error + "' error", listener.getFinishError(), is(equalTo(error))); }
Source:
<code><START> private Optional<SustainedConnection> findConnectionToMaintain() { <END> synchronized (SustainedConnectionWorker.this) { for (SustainedConnection connection : this.connections) { if (connection.needsRefresh()) { connection.claim(); return Optional.of(connection); } } } return Optional.empty(); }</code><technical_language>nit: this private synchronized Optional... need synchronized block</technical_language>

Target:
private synchronized Optional<SustainedConnection> findConnectionToMaintain() { final long milliseconds = SustainedConnectionWorker.SYSTEM_TIME.milliseconds(); for (SustainedConnection connection : this.connections) { if (connection.needsRefresh(milliseconds)) { connection.claim(); return Optional.of(connection); } } return Optional.empty(); }
Source:
<code>public static JsonObject mapToJson(Map<String, ?> map) { if (map == null) { throw new RuntimeException(CANNOT_CONVERT_NULL_TO_A_JSON_OBJECT); <START> } <END> try { return Json.instance().parse(objectMapper.writeValueAsString(map)); } catch (JsonProcessingException e) { throw new RuntimeException("Error converting map to JSON", e); } }</code><technical_language>![MAJOR](<LINK_1> 'Severity: MAJOR') Define throw a dedicated exception instead of a generic one. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
public static JsonObject mapToJson(Map<String, ?> map) { Objects.requireNonNull(map, CANNOT_CONVERT_NULL_TO_A_JSON_OBJECT); try { return Json.instance().parse(objectMapper.writeValueAsString(map)); } catch (JsonProcessingException e) { throw new RuntimeException("Error converting map to JSON", e); } }
Source:
<code>private boolean extractAndLoadAgain(Context context, String libraryName, String[] supportedABIs) { final String METHOD_TAG = TAG + ":extractAndLoadAgain"; ApplicationInfo appInfo = context.getApplicationInfo(); String destPath = context.getFilesDir().toString(); Log.i(METHOD_TAG, "Extracting to destination : " + destPath); try { String soName = destPath + File.separator + libraryName; new File(soName).delete(); boolean fileCopied = false; for (String abi : supportedABIs) { Log.i(METHOD_TAG, "Using ABI : " + abi); <START> UnzipUtil.extractFile(appInfo.sourceDir, "lib/" + abi + "/" + libraryName, destPath); <END> if (canReadFile(new File(soName))) { Log.i(METHOD_TAG, "File exists after extracting to " + abi); fileCopied = true; break; } } if (fileCopied) { System.load(soName); return true; } } catch (IOException | UnsatisfiedLinkError e) { Log.e(METHOD_TAG, "An error occurred when extracting and loading libs", e); } return false; }</code><technical_language>mind. I below</technical_language>

Target:
private static boolean extractAndLoadAgain(Context context, String libraryName, String[] supportedABIs) { final String METHOD_TAG = TAG + ":extractAndLoadAgain"; ApplicationInfo appInfo = context.getApplicationInfo(); String destPath = context.getFilesDir().toString(); Log.i(METHOD_TAG, "Extracting to destination : " + destPath); try { String soName = destPath + File.separator + libraryName; new File(soName).delete(); boolean fileCopied = false; for (String abi : supportedABIs) { Log.i(METHOD_TAG, "Using ABI : " + abi); UnzipUtil.extractFile(appInfo.sourceDir, "lib/" + abi + "/" + libraryName, destPath); if (canReadFile(new File(soName))) { Log.i(METHOD_TAG, "File exists after extracting to " + abi); fileCopied = true; break; } } if (fileCopied) { System.load(soName); return true; } } catch (IOException | UnsatisfiedLinkError e) { Log.e(METHOD_TAG, "An error occurred when extracting and loading libs", e); } return false; }
Source:
<code>public boolean canUseLlapIo(Configuration conf) { if (AcidUtils.isFullAcidScan(conf)) { if (HiveConf.getBoolVar(conf, ConfVars.LLAP_IO_ACID_ENABLED) && Utilities.getIsVectorized(conf)) { boolean hasDeleteDelta = deltas != null && !deltas.isEmpty(); return VectorizedOrcAcidRowBatchReader.canUseLlapIoForAcid(this, hasDeleteDelta, conf); } else { <START> return false; <END> } } else { return true; } }</code><technical_language>add a warn log line debug this</technical_language>

Target:
public boolean canUseLlapIo(Configuration conf) { if (AcidUtils.isFullAcidScan(conf)) { if (HiveConf.getBoolVar(conf, ConfVars.LLAP_IO_ACID_ENABLED) && Utilities.getIsVectorized(conf)) { boolean hasDeleteDelta = deltas != null && !deltas.isEmpty(); return VectorizedOrcAcidRowBatchReader.canUseLlapIoForAcid(this, hasDeleteDelta, conf); } else { LOG.info("Skipping Llap IO based on the following: [vectorized={}, hive.llap.io.acid={}] for {}", Utilities.getIsVectorized(conf), HiveConf.getBoolVar(conf, ConfVars.LLAP_IO_ACID_ENABLED), this); return false; } } else { return true; } }
Source:
<code>public DataFetcher(Map<String, DataSource> dataSourceMap) { int numColumns = dataSourceMap.size(); _dictionaryMap = new HashMap<>(numColumns); _singleValueSetMap = new HashMap<>(numColumns); _multiValueSetMap = new HashMap<>(numColumns); int maxNumValuesPerMVEntry = 0; for (Map.Entry<String, DataSource> entry : dataSourceMap.entrySet()) { String column = entry.getKey(); DataSource dataSource = entry.getValue(); _dictionaryMap.put(column, dataSource.getDictionary()); DataSourceMetadata dataSourceMetadata = dataSource.getDataSourceMetadata(); <START> BlockValSet blockValueSet = dataSourceMap.get(column).nextBlock().getBlockValueSet(); <END> if (dataSourceMetadata.isSingleValue()) { _singleValueSetMap.put(column, (SingleValueSet) blockValueSet); } else { _multiValueSetMap.put(column, (MultiValueSet) blockValueSet); maxNumValuesPerMVEntry = Math.max(maxNumValuesPerMVEntry, dataSourceMetadata.getMaxNumValuesPerMVEntry()); } } _reusableMVDictIds = new int[maxNumValuesPerMVEntry]; }</code><technical_language>Revert this line</technical_language>

Target:
public DataFetcher(Map<String, DataSource> dataSourceMap) { int numColumns = dataSourceMap.size(); _dictionaryMap = new HashMap<>(numColumns); _singleValueSetMap = new HashMap<>(numColumns); _multiValueSetMap = new HashMap<>(numColumns); int maxNumValuesPerMVEntry = 0; for (Map.Entry<String, DataSource> entry : dataSourceMap.entrySet()) { String column = entry.getKey(); DataSource dataSource = entry.getValue(); _dictionaryMap.put(column, dataSource.getDictionary()); DataSourceMetadata dataSourceMetadata = dataSource.getDataSourceMetadata(); BlockValSet blockValueSet = dataSource.nextBlock().getBlockValueSet(); if (dataSourceMetadata.isSingleValue()) { _singleValueSetMap.put(column, (SingleValueSet) blockValueSet); } else { _multiValueSetMap.put(column, (MultiValueSet) blockValueSet); maxNumValuesPerMVEntry = Math.max(maxNumValuesPerMVEntry, dataSourceMetadata.getMaxNumValuesPerMVEntry()); } } _reusableMVDictIds = new int[maxNumValuesPerMVEntry]; }
Source:
<code>public ReplTxnWork(String dbName, String tableName, Long txnId, OperationType type) { <START> this.txnIds = Lists.newArrayList(); <END> this.txnIds.add(txnId); this.dbName = dbName; this.tableName = tableName; this.operation = type; }</code><technical_language>initialise newArrayList(txnId) instead of 2 statements</technical_language>

Target:
public ReplTxnWork(String dbName, String tableName, Long txnId, OperationType type) { this.txnIds = Lists.newArrayList(txnId); this.dbName = dbName; this.tableName = tableName; this.operation = type; }
Source:
<code>public AbstractProAi( final String name, final IBattleCalculator battleCalculator, final ProData proData) { super(name); this.proData = proData; calc = new ProOddsCalculator(battleCalculator); combatMoveAi = new ProCombatMoveAi(this); nonCombatMoveAi = new ProNonCombatMoveAi(this); purchaseAi = new ProPurchaseAi(this); retreatAi = new ProRetreatAi(this); scrambleAi = new ProScrambleAi(this); politicsAi = new ProPoliticsAi(this); storedCombatMoveMap = null; storedFactoryMoveMap = null; storedPurchaseTerritories = null; storedPoliticalActions = null; storedStrafingTerritories = new ArrayList<>(); <START> DebugMenu.unregisterMenuCallback("Hard AI"); <END> DebugMenu.registerMenuCallback("Hard AI", this::initialize); }</code><technical_language>registerMenuCallback handle this detail for us</technical_language>

Target:
public AbstractProAi( final String name, final IBattleCalculator battleCalculator, final ProData proData) { super(name); this.proData = proData; calc = new ProOddsCalculator(battleCalculator); combatMoveAi = new ProCombatMoveAi(this); nonCombatMoveAi = new ProNonCombatMoveAi(this); purchaseAi = new ProPurchaseAi(this); retreatAi = new ProRetreatAi(this); scrambleAi = new ProScrambleAi(this); politicsAi = new ProPoliticsAi(this); storedCombatMoveMap = null; storedFactoryMoveMap = null; storedPurchaseTerritories = null; storedPoliticalActions = null; storedStrafingTerritories = new ArrayList<>(); ProLogUi.registerDebugMenu(); }
Source:
<code>public double getLogProb(MatrixLib value) { checkHasParams(); if (value.numRows() != 1 || value.numCols() != this.k) { throw new IllegalArgumentException( "The matrix provided is of the incorrect dimensions. Expecting a 1 by " + this.k + " row vector but instead got a matrix of dimension " + value.numRows() + " by " + value.numCols()); } double sum = 0.0; for (int i = 0; i < k; i++) { double element = value.elementAt(0, i); if (element < 0 || element % 1 != 0.0) { return Double.NEGATIVE_INFINITY; } sum += element; } if (sum != n) { return Double.NEGATIVE_INFINITY; <START> } <END> double logProb = Util.logFactorial(n); for (int i = 0; i < k; i++) { logProb += value.elementAt(0, i) * Math.log(p[i]); logProb -= Util.logFactorial((int) Math.round(value.elementAt(0, i))); } return logProb; }</code><technical_language>line 220-238 line 174-191. consider create a seperate private method</technical_language>

Target:
public double getLogProb(MatrixLib value) { checkHasParams(); if (!inSupport(value)) { return Double.NEGATIVE_INFINITY; } double logProb = Util.logFactorial(n); for (int i = 0; i < k; i++) { logProb += value.elementAt(0, i) * Math.log(p[i]); logProb -= Util.logFactorial((int) Math.round(value.elementAt(0, i))); } return logProb; }
Source:
<code>public SearchResult query(SearchQuery query) { final String input = query.getInput(); final CriteriaBuilder builder = new CriteriaBuilder(OnmsCategory.class) .ilike("name", QueryUtils.ilike(input)) .orderBy("name") .distinct(); final int totalCount = categoryDao.countMatching(builder.toCriteria()); final Criteria criteria = builder.limit(query.getMaxResults()).toCriteria(); final List<OnmsCategory> matchingResult = categoryDao.findMatching(criteria); final List<SearchResultItem> searchResultItems = matchingResult.stream().map(category -> { final SearchResultItem searchResultItem = new SearchResultItem(); searchResultItem.setIdentifier(category.getId().toString()); searchResultItem.setLabel("Show nodes in category '" + category.getName() + "'"); <START> searchResultItem.setUrl("element/nodeList.htm?category1=" + category.getName()); <END> return searchResultItem; }).collect(Collectors.toList()); final SearchResult searchResult = new SearchResult(Contexts.Action).withMore(totalCount > searchResultItems.size()).withResults(searchResultItems); return searchResult; }</code><technical_language>category.getName() URL encoded</technical_language>

Target:
public SearchResult query(SearchQuery query) { final String input = query.getInput(); final CriteriaBuilder builder = new CriteriaBuilder(OnmsCategory.class) .ilike("name", QueryUtils.ilike(input)) .orderBy("name") .distinct(); final int totalCount = categoryDao.countMatching(builder.toCriteria()); final Criteria criteria = builder.limit(query.getMaxResults()).toCriteria(); final List<OnmsCategory> matchingResult = categoryDao.findMatching(criteria); final List<SearchResultItem> searchResultItems = matchingResult.stream().map(category -> { final SearchResultItem searchResultItem = new SearchResultItem(); searchResultItem.setIdentifier(category.getId().toString()); searchResultItem.setLabel("Show nodes in category '" + category.getName() + "'"); searchResultItem.setUrl("element/nodeList.htm?category1=" + UrlUtils.encode(category.getName())); return searchResultItem; }).collect(Collectors.toList()); final SearchResult searchResult = new SearchResult(Contexts.Action).withMore(totalCount > searchResultItems.size()).withResults(searchResultItems); return searchResult; }
Source:
<code>public boolean isServiceDetected(InetAddress address) { try { SnmpAgentConfig agentConfig = getAgentConfigFactory().getAgentConfig(address); String expectedValue = null; configureAgentPTR(agentConfig); configureAgentVersion(agentConfig); if (getVbvalue() != null) { expectedValue = getVbvalue(); } if (this.m_isTable) { LOG.debug(getServiceName() + ": Table detect enabled"); SnmpObjId snmpObjId = SnmpObjId.get(getOid()); Map<SnmpInstId, SnmpValue> table = SnmpUtils.getOidValues(agentConfig, DEFAULT_SERVICE_NAME, snmpObjId); for (Map.Entry<SnmpInstId, SnmpValue> e : table.entrySet()) { String retrievedValue; if (m_hex) { retrievedValue = e.getValue().toHexString(); } else { retrievedValue = e.getValue().toString(); } LOG.debug(getServiceName() + ": retrieved value [" + retrievedValue + "]"); if (retrievedValue != null && expectedValue != null && Pattern.compile(expectedValue).matcher(retrievedValue).matches()) { LOG.debug(getServiceName() + ": expected value matched"); return true; } else if (retrievedValue != null) { return true; } } return false; } else { String retrievedValue = getValue(agentConfig, getOid()); if (retrievedValue != null && expectedValue != null) { return (Pattern.compile(expectedValue).matcher(retrievedValue).matches()); } else { <START> return (retrievedValue != null); <END> } } } catch (Throwable t) { throw new UndeclaredThrowableException(t); } }</code><technical_language>Is this sufficient, check for !retrievedValue.isEmpty()</technical_language>

Target:
public boolean isServiceDetected(InetAddress address) { try { SnmpAgentConfig agentConfig = getAgentConfigFactory().getAgentConfig(address); configureAgentPTR(agentConfig); configureAgentVersion(agentConfig); final String expectedValue = getVbvalue(); if (this.m_isTable) { LOG.debug(getServiceName() + ": table detect enabled"); final SnmpObjId snmpObjId = SnmpObjId.get(getOid()); final Map<SnmpInstId, SnmpValue> table = SnmpUtils.getOidValues(agentConfig, DEFAULT_SERVICE_NAME, snmpObjId); final List<String> retrievedValues = table.values().stream().map(snmpValue -> m_hex ? snmpValue.toHexString() : snmpValue.toString()).collect(Collectors.toList()); return isServiceDetected(this.matchType, retrievedValues, expectedValue); } else { final String retrievedValue = getValue(agentConfig, getOid(), m_hex); MatchType matchType = this.matchType; if (matchType == null && expectedValue != null) { matchType = MatchType.Any; } return isServiceDetected(matchType, Lists.newArrayList(retrievedValue), expectedValue); } } catch (Throwable t) { throw new UndeclaredThrowableException(t); } }