auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public synchronized void registerDeviceStatusListener(DeviceStatusListener deviceStatusListener) { if (this.devStatMan != null) { if (deviceStatusListener == null) { throw new IllegalArgumentException("It's not allowed to pass null."); } if (deviceStatusListener.getDeviceStatusListenerID() != null) { if (devStatMan.getManagerState().equals(ManagerStates.RUNNING)) { devStatMan.registerDeviceListener(deviceStatusListener); <START> return; <END> } if (deviceStatusListener.getDeviceStatusListenerID().equals(DeviceStatusListener.DEVICE_DISCOVERY)) { devStatMan.registerDeviceListener(deviceStatusListener); } } else { throw new IllegalArgumentException("It's not allowed to pass a DeviceStatusListener with ID = null."); } } else { if (deviceStatusListener.getDeviceStatusListenerID().equals(DeviceStatusListener.DEVICE_DISCOVERY)) { deviceDiscovery = deviceStatusListener; } } }</code><technical_language>This if block strange early return</technical_language>

Target:
public synchronized void registerDeviceStatusListener(DeviceStatusListener deviceStatusListener) { if (this.devStatMan != null) { if (deviceStatusListener == null) { throw new IllegalArgumentException("It's not allowed to pass null."); } if (deviceStatusListener.getDeviceStatusListenerID() != null) { if (devStatMan.getManagerState().equals(ManagerStates.RUNNING)) { devStatMan.registerDeviceListener(deviceStatusListener); } else if (deviceStatusListener.getDeviceStatusListenerID() .equals(DeviceStatusListener.DEVICE_DISCOVERY)) { devStatMan.registerDeviceListener(deviceStatusListener); } } else { throw new IllegalArgumentException("It's not allowed to pass a DeviceStatusListener with ID = null."); } } else { if (deviceStatusListener.getDeviceStatusListenerID().equals(DeviceStatusListener.DEVICE_DISCOVERY)) { deviceDiscovery = deviceStatusListener; } } }
Source:
<code>public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(KEY_LOGIN_FINISHED, mLoginFinished); <START> outState.putBoolean(KEY_LOGIN_FINISHED, mLoginStarted); <END> outState.putString(KEY_REQUESTED_USERNAME, mRequestedUsername); outState.putString(KEY_REQUESTED_PASSWORD, mRequestedPassword); outState.putIntegerArrayList(KEY_OLD_SITES_IDS, mOldSitesIDs); }</code><technical_language>I key is wrong, KEY_LOGIN_STARTED</technical_language>

Target:
public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(KEY_LOGIN_FINISHED, mLoginFinished); outState.putBoolean(KEY_LOGIN_STARTED, mLoginStarted); outState.putString(KEY_REQUESTED_USERNAME, mRequestedUsername); outState.putString(KEY_REQUESTED_PASSWORD, mRequestedPassword); outState.putIntegerArrayList(KEY_OLD_SITES_IDS, mOldSitesIDs); }
Source:
<code>public BloomFilter getBloomFilter(int size, double falsePositiveRate, long nTweak) { BloomFilter filter = new BloomFilter(size, falsePositiveRate, nTweak); if (basic.numKeys() > 0) filter.merge(basic.getFilter(size, falsePositiveRate, nTweak)); for (DeterministicKeyChain chain : chains) { <START> if (isMarried(chain)) { <END> for (Script script : marriedKeysScripts.values()) { filter.insert(script.getPubKeyHash()); filter.insert(script.getProgram()); } } else { filter.merge(chain.getFilter(size, falsePositiveRate, nTweak)); } } return filter; }</code><technical_language>this logic include keys in keychain expected receive money themselves</technical_language>

Target:
public BloomFilter getBloomFilter(int size, double falsePositiveRate, long nTweak) { BloomFilter filter = new BloomFilter(size, falsePositiveRate, nTweak); if (basic.numKeys() > 0) filter.merge(basic.getFilter(size, falsePositiveRate, nTweak)); for (DeterministicKeyChain chain : chains) { if (isMarried(chain)) { for (Map.Entry<ByteString, Script> entry : marriedKeysScripts.entrySet()) { filter.insert(entry.getKey().toByteArray()); filter.insert(ScriptBuilder.createP2SHOutputScript(entry.getValue()).getProgram()); } } else { filter.merge(chain.getFilter(size, falsePositiveRate, nTweak)); } } return filter; }
Source:
<code><START> public void receiveActivityResult(int resultCode, Intent data, Activity activity) { <END> for (String key : editableUdfDefinitions.keySet()) { if (data.getExtras().containsKey(key)) { final String json = data.getStringExtra(key); final UDFCollectionDefinition udfDef = editableUdfDefinitions.get(key); final JSONObject value; try { value = new JSONObject(json); } catch (JSONException e) { Log.e(App.LOG_TAG, "Error parsing JSON passed as activity result", e); continue; } final UDFCollectionValueField field = new UDFCollectionValueField(udfDef, sortKey, value); if (data.getExtras().containsKey(UDFCollectionEditActivity.TAG)) { final int tag = data.getIntExtra(UDFCollectionEditActivity.TAG, -1); if (tag == -1 || fields.isEmpty()) { Log.w(App.LOG_TAG, "Invalid tag for UDF, ignoring it"); } else { fields = newArrayList(concat(filter(fields, f -> f.getTag() != tag), newArrayList(field))); } } else { fields.add(field); } } } replaceEditFields(activity); }</code><technical_language>I this method is big a generic name receiveActivityResult, applies is called, does</technical_language>

Target:
public void receiveActivityResult(int resultCode, Intent data, Activity activity) { for (String key : editableUdfDefinitions.keySet()) { if (data.getExtras().containsKey(key)) { final String json = data.getStringExtra(key); final UDFCollectionDefinition udfDef = editableUdfDefinitions.get(key); final JSONObject value; try { value = new JSONObject(json); } catch (JSONException e) { Log.e(App.LOG_TAG, "Error parsing JSON passed as activity result", e); continue; } final UDFCollectionValueField field = new UDFCollectionValueField(udfDef, sortKey, value); if (data.getExtras().containsKey(UDFCollectionEditActivity.TAG)) { final int tag = data.getIntExtra(UDFCollectionEditActivity.TAG, -1); if (tag == -1 || fields.isEmpty()) { Log.w(App.LOG_TAG, "Invalid tag for UDF, ignoring it"); } else { fields = newArrayList(concat(filter(fields, f -> f.getTag() != tag), newArrayList(field))); } } else { fields.add(field); } } } rerenderEditFields(activity); }
Source:
<code>private static String formatBytes(byte[] bytes, String contentType) { if (contentType.contains("json")) { try { return new JSONObject(new String(bytes)).toString(4); } catch (JSONException e) { return new String(bytes).trim(); } } else if (contentType.contains("text")) { return new String(bytes).trim(); } else { <START> return "Not supported contentType"; <END> } }</code><technical_language>"[No preview for contentType]"</technical_language>

Target:
private static String formatBytes(byte[] bytes, String contentType) { if (contentType.contains("json")) { try { return new JSONObject(new String(bytes)).toString(4); } catch (JSONException e) { return new String(bytes).trim(); } } else if (contentType.contains("text")) { return new String(bytes).trim(); } else { throw new IllegalStateException("We can not print this " + contentType); } }
Source:
<code>public static List<JavaTypeDefinition> inferTypes(List<Constraint> constraints, List<Bound> bounds, List<Variable> variables) { List<Bound> newBounds = new ArrayList<>(); while (!constraints.isEmpty()) { List<BoundOrConstraint> reduceResult = constraints.get(constraints.size() - 1).reduce(); <START> constraints.remove(constraints.size() - 1); <END> for (BoundOrConstraint boundOrConstraint : reduceResult) { if (boundOrConstraint instanceof Bound) { newBounds.add((Bound) boundOrConstraint); } else if (boundOrConstraint instanceof Constraint) { constraints.add((Constraint) boundOrConstraint); } else { throw new IllegalStateException("Unknown BoundOrConstraint subclass"); } } constraints.addAll(incorporateBounds(bounds, newBounds)); newBounds.clear(); } Map<Variable, JavaTypeDefinition> resolutionResult = resolveVariables(bounds); List<JavaTypeDefinition> result = new ArrayList<>(); for (Variable variable : variables) { result.add(resolutionResult.get(variable)); } return result; }</code><technical_language>2 lines condensed. remove returns removed element, write: List<BoundOrConstraint> reduceResult = constraints.remove(constraints.size() - 1).reduce();</technical_language>

Target:
public static List<JavaTypeDefinition> inferTypes(List<Constraint> constraints, List<Bound> bounds, List<Variable> variables) { List<Bound> newBounds = new ArrayList<>(); while (!constraints.isEmpty()) { List<BoundOrConstraint> reduceResult = constraints.remove(constraints.size() - 1).reduce(); for (BoundOrConstraint boundOrConstraint : reduceResult) { if (boundOrConstraint instanceof Bound) { newBounds.add((Bound) boundOrConstraint); } else if (boundOrConstraint instanceof Constraint) { constraints.add((Constraint) boundOrConstraint); } else { throw new IllegalStateException("Unknown BoundOrConstraint subclass"); } } constraints.addAll(incorporateBounds(bounds, newBounds)); newBounds.clear(); } Map<Variable, JavaTypeDefinition> resolutionResult = resolveVariables(bounds); List<JavaTypeDefinition> result = new ArrayList<>(); for (Variable variable : variables) { result.add(resolutionResult.get(variable)); } return result; }
Source:
<code>private void trimPrefix() { <START> long endSegment = dataStore.getStartingAddress() / RECORDS_PER_LOG_FILE - 1; <END> if (endSegment < 0) { log.debug("Only one segment detected, ignoring trim"); return; } closeSegmentHandlers(endSegment); deleteFilesMatchingFilter(file -> { try { String segmentStr = file.getName().split("\\.")[0]; return Long.parseLong(segmentStr) <= endSegment; } catch (Exception e) { log.warn("trimPrefix: ignoring file {}", file.getName()); return false; } }); log.info("trimPrefix: completed, end segment {}", endSegment); }</code><technical_language>drop -1 than, instead of equal. I more clear way</technical_language>

Target:
private void trimPrefix() { long endSegment = getStartingSegment() - 1; if (endSegment < 0) { log.debug("Only one segment detected, ignoring trim"); return; } closeSegmentHandlers(endSegment); deleteFilesMatchingFilter(file -> { try { String segmentStr = file.getName().split("\\.")[0]; return Long.parseLong(segmentStr) <= endSegment; } catch (Exception e) { log.warn("trimPrefix: ignoring file {}", file.getName()); return false; } }); log.info("trimPrefix: completed, end segment {}", endSegment); }
Source:
<code><START> public boolean getProfileDefinitionStatus() { <END> String profilePath = getProfileURI(); if (profilePath == null || profilePath == "") { return true; } URI profileURI = URI.createURI(profilePath); ResourceSet resourceSet = new ResourceSetImpl(); Resource resource = null; try { resource = resourceSet.getResource(profileURI, true); } catch (WrappedException ex) { return false; } if (resource == null) { return false; } EObject eObject = resource.getContents().get(0); if (!(eObject instanceof Profile)) { return false; } Profile profile = (Profile) eObject; if (!profile.isDefined()) { return false; } return true; }</code><technical_language>boolean is detailed enough (It explain profile is valid. File exist? File is a Profile? Profile is defined?) usual pattern for this is return IStatus instead of boolean. IStatus a status code (OK / Warning / Error), a message optional Java Exception. UI print proper messages depending exact status</technical_language>

Target:
public IStatus getProfileDefinitionStatus() { String profilePath = getProfileURI(); IStatus okStatus = new Status(IStatus.OK, Activator.PLUGIN_ID, ""); if (profilePath == null || profilePath.equalsIgnoreCase("")) { return okStatus; } URI profileURI = URI.createURI(profilePath); ResourceSet resourceSet = new ResourceSetImpl(); Resource resource = null; try { resource = resourceSet.getResource(profileURI, true); } catch (WrappedException ex) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.ProfileChooserComposite_ProfileStatus_UnavailableResource); } if (resource == null) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.ProfileChooserComposite_ProfileStatus_NullResource); } if (resource.getContents().isEmpty()) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.ProfileChooserComposite_ProfileStatus_EmptyResource); } EObject eObject = resource.getContents().get(0); if (!(eObject instanceof Profile)) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.ProfileChooserComposite_ProfileStatus_NotAProfile); } Profile profile = (Profile) eObject; if (!profile.isDefined()) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.ProfileChooserComposite_ProfileStatus_ProfileNotDefined); } return okStatus; }
Source:
<code>public static Artifact getCommonAncestor(Conflict conflict) { <START> try { <END> if (conflict.getSourceBranch() == null) { return null; } TransactionRecord commonTransaction = ConflictManagerInternal.findCommonTransaction(conflict.getSourceBranch(), conflict.getDestBranch()); return ArtifactQuery.getHistoricalArtifactFromId(conflict.getArtifact().getGuid(), commonTransaction, INCLUDE_DELETED); } catch (OseeCoreException ex) { OseeLog.log(Activator.class, Level.SEVERE, ex); } return null; }</code><technical_language>Suggest checking conflict is null</technical_language>

Target:
public static Artifact getCommonAncestor(Conflict conflict) { Artifact toReturn = null; try { if (Conditions.notNull(conflict.getSourceBranch())) { TransactionRecord commonTransaction = ConflictManagerInternal.findCommonTransaction(conflict.getSourceBranch(), conflict.getDestBranch()); toReturn = ArtifactQuery.getHistoricalArtifactFromId(conflict.getArtifact().getGuid(), commonTransaction, INCLUDE_DELETED); } } catch (OseeCoreException ex) { OseeLog.log(Activator.class, Level.SEVERE, ex); } return toReturn; }
Source:
<code>protected void notifyListenersAboutRemovedElement(Thing element) { <START> notifyTrackers(element, ThingTrackerEvent.THING_REMOVED); <END> postEvent(ThingEventFactory.createRemovedEvent(element)); super.notifyListenersAboutRemovedElement(element); }</code><technical_language>I for removing a order fine. If remove ThingManager notifying listeners, try disable in short gap. Moreover, if leave order in this method unchanged, reverse order notifyListenersAboutAddedElement method, is I expect</technical_language>

Target:
protected void notifyListenersAboutRemovedElement(Thing element) { super.notifyListenersAboutRemovedElement(element); notifyTrackers(element, ThingTrackerEvent.THING_REMOVED); postEvent(ThingEventFactory.createRemovedEvent(element)); }
Source:
<code>public String getDescriptionOfValidInputs() { switch(this) { case ID: case UPDATED: return "a number or a number range"; case STATE: return "\"open\" or \"closed\""; case HAS: case NO: return "\"label\", \"milestone\", or \"assignee\""; case IN: return "\"title\" or \"body\""; case TYPE: return "\"issue\" or \"pr\""; case CREATED: return "a date or a date range"; case REPO: return "repo id"; default: <START> return "string"; <END> } }</code><technical_language>"a repo id", "a string"</technical_language>

Target:
public String getDescriptionOfValidInputs() { switch(this) { case ID: case UPDATED: return "a number or a number range"; case STATE: return "\"open\" or \"closed\""; case HAS: case NO: return "\"label\", \"milestone\", or \"assignee\""; case IN: return "\"title\" or \"body\""; case TYPE: return "\"issue\" or \"pr\""; case CREATED: return "a date or a date range"; case REPO: return "a repo id"; default: return "a string"; } }
Source:
<code>public void logAuditMessage(final Guid clusterId, final GlusterVolumeEntity volume, final VDS server, final AuditLogType logType, final Map<String, String> customValues) { AuditLogableBase logable = new AuditLogableBase(); logable.setVds(server); logable.setGlusterVolume(volume); <START> logable.setVdsGroupId(clusterId == null ? server.getVdsGroupId() : clusterId); <END> if (customValues != null) { for (Entry<String, String> entry : customValues.entrySet()) { logable.addCustomValue(entry.getKey(), entry.getValue()); } } AuditLogDirector.log(logable, logType); }</code><technical_language>clusterId null? I logServerMessage changed pass clusterId</technical_language>

Target:
public void logAuditMessage(final Guid clusterId, final GlusterVolumeEntity volume, final VDS server, final AuditLogType logType, final Map<String, String> customValues) { AuditLogableBase logable = new AuditLogableBase(); logable.setVds(server); logable.setGlusterVolume(volume); logable.setVdsGroupId(clusterId); if (customValues != null) { for (Entry<String, String> entry : customValues.entrySet()) { logable.addCustomValue(entry.getKey(), entry.getValue()); } } AuditLogDirector.log(logable, logType); }
Source:
<code>protected void upgrade(ConfigBag parameters) { Group cluster = (Group)entity(); Collection<Entity> initialMembers = cluster.getMembers(); int initialClusterSize = initialMembers.size(); if (!BrooklynNodeUpgradeEffectorBody.isPersistenceModeEnabled(cluster)) { DynamicTasks.queue( Tasks.warning("Check persistence", new IllegalStateException("Persistence does not appear to be enabled at this cluster. " + "Cluster upgrade will not succeed unless a custom launch script enables it.")) ); } TaskAdaptable<Collection<Entity>> initialNodeTask = DynamicTasks.queue(newCreateNodesTask(1, "Creating first upgraded version node")); TaskAdaptable<Collection<Entity>> remainingNodesTask = DynamicTasks.queue(newCreateNodesTask(initialClusterSize - 1, "Creating remaining upgraded version nodes ("+(initialClusterSize - 1)+")")); DynamicTasks.queue(Effectors.invocation(cluster, BrooklynCluster.SELECT_MASTER, MutableMap.of(SelectMasterEffector.NEW_MASTER_ID, Iterables.getOnlyElement(initialNodeTask.asTask().getUnchecked()).getId()))).asTask().getUnchecked(); <START> HashSet<Entity> oldMembers = new HashSet<Entity>(initialMembers); <END> oldMembers.removeAll(remainingNodesTask.asTask().getUnchecked()); oldMembers.removeAll(initialNodeTask.asTask().getUnchecked()); DynamicTasks.queue(Effectors.invocation(BrooklynNode.STOP_NODE_BUT_LEAVE_APPS, Collections.emptyMap(), oldMembers)).asTask().getUnchecked(); }</code><technical_language>Sets.newLinkedHashSet(initialMembers). I prefer determinism of a LinkedHashSet. important execute stop in parallel all</technical_language>

Target:
protected void upgrade(ConfigBag parameters) { Group cluster = (Group)entity(); Collection<Entity> initialMembers = cluster.getMembers(); int initialClusterSize = initialMembers.size(); if (!BrooklynNodeUpgradeEffectorBody.isPersistenceModeEnabled(cluster)) { DynamicTasks.queue( Tasks.warning("Check persistence", new IllegalStateException("Persistence does not appear to be enabled at this cluster. " + "Cluster upgrade will not succeed unless a custom launch script enables it.")) ); } TaskAdaptable<Collection<Entity>> initialNodeTask = DynamicTasks.queue(newCreateNodesTask(1, "Creating first upgraded version node")); @SuppressWarnings("unused") TaskAdaptable<Collection<Entity>> remainingNodesTask = DynamicTasks.queue(newCreateNodesTask(initialClusterSize - 1, "Creating remaining upgraded version nodes ("+(initialClusterSize - 1)+")")); DynamicTasks.queue(Effectors.invocation(cluster, BrooklynCluster.SELECT_MASTER, MutableMap.of(SelectMasterEffector.NEW_MASTER_ID, Iterables.getOnlyElement(initialNodeTask.asTask().getUnchecked()).getId()))).asTask().getUnchecked(); DynamicTasks.queue(Effectors.invocation(BrooklynNode.STOP_NODE_BUT_LEAVE_APPS, Collections.emptyMap(), initialMembers)).asTask().getUnchecked(); }
Source:
<code>private static Ordering<ProjectNode> createProjectNodeOrdering(final boolean isHierarchyFlattened) { return new Ordering<ProjectNode>() { @Override public int compare(ProjectNode left, ProjectNode right) { if (!isHierarchyFlattened) { <START> return left.toString().compareTo(right.toString()); <END> } else { EclipseProject leftRoot = HierarchicalElementUtils.getRoot(left.getEclipseProject()); EclipseProject rightRoot = HierarchicalElementUtils.getRoot(right.getEclipseProject()); if (leftRoot.getProjectIdentifier() == rightRoot.getProjectIdentifier()) { return 0; } else { return leftRoot.getName().compareTo(rightRoot.getName()); } } } }; }</code><technical_language>leftRoot.getName().compareTo(rightRoot.getName())</technical_language>

Target:
private static Ordering<ProjectNode> createProjectNodeOrdering(final boolean isHierarchyFlattened) { return new Ordering<ProjectNode>() { @Override public int compare(ProjectNode left, ProjectNode right) { if (!isHierarchyFlattened) { return left.getDisplayName().compareTo(right.getDisplayName()); } else { EclipseProject leftRoot = HierarchicalElementUtils.getRoot(left.getEclipseProject()); EclipseProject rightRoot = HierarchicalElementUtils.getRoot(right.getEclipseProject()); if (leftRoot.getProjectIdentifier() == rightRoot.getProjectIdentifier()) { return 0; } else { return leftRoot.getName().compareTo(rightRoot.getName()); } } } }; }
Source:
<code>public HeartbeatConnector(Properties config) { <START> _hearbeatPeriodMs = Integer.parseInt(config.getProperty(CFG_HEARTBEAT_PERIOD, DEFAULT_HEARTBEAT_PERIOD_MS)); <END> }</code><technical_language>If log config, this is a load-balanced connector broadcast connector, right? differences all. enough. need some id for connector</technical_language>

Target:
public HeartbeatConnector(Properties config) { LOG.info(String.format("Creating Heartbeat connector with config: %s", config)); _hearbeatPeriodMs = Integer.parseInt(config.getProperty(CFG_HEARTBEAT_PERIOD, DEFAULT_HEARTBEAT_PERIOD_MS)); }
Source:
<code>private static String extractBase64String(String url) { if (url.startsWith(BASE64_URL_PREFIX)) { if (url.contains(BASE64_START)) { int base64StartIndex = url.indexOf(BASE64_START); String metadata = url.substring(BASE64_URL_PREFIX.length(), base64StartIndex); for (String md : acceptedMetadata) { if (md.equals(metadata)) { byte[] data = BaseEncoding.base64().decode( url.substring(base64StartIndex + BASE64_START.length())); <START> return new String(data, StandardCharsets.UTF_8); <END> } } } } return null; }</code><technical_language>nit: static-import UTF_8 remove StandardCharsets. here</technical_language>

Target:
private static String extractBase64String(String url) { if (url.startsWith(BASE64_URL_PREFIX)) { if (url.contains(BASE64_START)) { int base64StartIndex = url.indexOf(BASE64_START); String metadata = url.substring(BASE64_URL_PREFIX.length(), base64StartIndex); for (String md : acceptedMetadata) { if (md.equals(metadata)) { byte[] data = BaseEncoding.base64().decode( url.substring(base64StartIndex + BASE64_START.length())); return new String(data, UTF_8); } } } } return null; }
Source:
<code>public Object mapSearch(final String requestUrl, final List<RpslObject> objects, final Iterable<LocalDateTime> localDateTimes, final int maxResultSize) { final SearchResult searchResult = new SearchResult(); final Iterator<LocalDateTime> iterator = localDateTimes.iterator(); for (final RpslObject object : objects) { if (object.getType() == DOMAIN) { searchResult.addDomainSearchResult((Domain) getRdapObject(requestUrl, object, iterator.next(), null)); } else { searchResult.addEntitySearchResult((Entity) getRdapObject(requestUrl, object, iterator.next(), null)); } } if(objects.size() == maxResultSize) { final Notice notice = new Notice(); notice.setTitle("Search result cap to " + maxResultSize); <START> notice.getDescription().add("Due to performace issue, we have capped the maximum search result to " + maxResultSize); <END> searchResult.getNotices().add(notice); } return mapCommons(searchResult, requestUrl); }</code><technical_language>Typo performace -> performance</technical_language>

Target:
public Object mapSearch(final String requestUrl, final List<RpslObject> objects, final Iterable<LocalDateTime> localDateTimes, final int maxResultSize) { final SearchResult searchResult = new SearchResult(); final Iterator<LocalDateTime> iterator = localDateTimes.iterator(); for (final RpslObject object : objects) { if (object.getType() == DOMAIN) { searchResult.addDomainSearchResult((Domain) getRdapObject(requestUrl, object, iterator.next(), null)); } else { searchResult.addEntitySearchResult((Entity) getRdapObject(requestUrl, object, iterator.next(), null)); } } if(objects.size() == maxResultSize) { final Notice notice = new Notice(); notice.setTitle(String.format("limited search results to %s maximum" , maxResultSize)); searchResult.getNotices().add(notice); } return mapCommons(searchResult, requestUrl); }
Source:
<code>public int getChunkSize() { int networkType = NetworkHelper.INSTANCE.getNetworkType(getApplicationContext()); <START> if (networkType == ConnectivityManager.TYPE_WIFI) { <END> return (1024 * 1024); } else { return (256 * 1024); } }</code><technical_language>I idea of deciding size based connection type, I wise autodetect junk size (no idea find out server is configured, piwigo server it, I is a REST service read it) provide a configuration option (but this in case chance autodetect. If maximum size limit decision max server allowed size</technical_language>

Target:
public int getChunkSize() { int networkType = NetworkHelper.INSTANCE.getNetworkType(getApplicationContext()); int chunkSize = userManager.getChunkSize(userManager.getActiveAccount().getValue()); if (networkType == ConnectivityManager.TYPE_WIFI) { return chunkSize; } else { return (chunkSize / 2); } }
Source:
<code>public void testFindWorkerForTask() throws Exception { final EqualDistributionWorkerSelectStrategy strategy = new EqualDistributionWorkerSelectStrategy(); Optional<ImmutableWorkerInfo> optional = strategy.findWorkerForTask( new RemoteTaskRunnerConfig(), ImmutableMap.of( "lhost", new ImmutableWorkerInfo( <START> new Worker("lhost", "lhost", 5, "v1"), 5, <END> Sets.<String>newHashSet(), Sets.<String>newHashSet(), DateTime.now() ), "localhost", new ImmutableWorkerInfo( new Worker("localhost", "localhost", 10, "v1"), 5, Sets.<String>newHashSet(), Sets.<String>newHashSet(), DateTime.now() ) ), new NoopTask(null, 1, 0, null, null, null) { @Override public String getDataSource() { return "foo"; } } ); ImmutableWorkerInfo worker = optional.get(); Assert.assertEquals("localhost", worker.getWorker().getHost()); }</code><technical_language>Please testing data sets: (1, 0, 1, 1) (5, 5, 10, 5)</technical_language>

Target:
public void testFindWorkerForTask() throws Exception { final EqualDistributionWorkerSelectStrategy strategy = new EqualDistributionWorkerSelectStrategy(); Optional<ImmutableWorkerInfo> optional = strategy.findWorkerForTask( new RemoteTaskRunnerConfig(), ImmutableMap.of( "lhost", new ImmutableWorkerInfo( new Worker("lhost", "lhost", 1, "v1"), 0, Sets.<String>newHashSet(), Sets.<String>newHashSet(), DateTime.now() ), "localhost", new ImmutableWorkerInfo( new Worker("localhost", "localhost", 1, "v1"), 1, Sets.<String>newHashSet(), Sets.<String>newHashSet(), DateTime.now() ) ), new NoopTask(null, 1, 0, null, null, null) { @Override public String getDataSource() { return "foo"; } } ); ImmutableWorkerInfo worker = optional.get(); Assert.assertEquals("lhost", worker.getWorker().getHost()); }
Source:
<code>private ProcessVariableValue buildProcessVariableValue(Object value) throws JsonProcessingException { ProcessVariableValue variableValue = null; if (value != null) { Class<?> entryValueClass = value.getClass(); String entryType = resolveEntryType(entryValueClass, value); <START> if("object".equals(entryType)) { <END> value = new ObjectValue(value); } String entryValue = conversionService.convert(value, String.class); variableValue = new ProcessVariableValue(entryType, entryValue); } return variableValue; }</code><technical_language>Re-use constant</technical_language>

Target:
private ProcessVariableValue buildProcessVariableValue(Object value) { ProcessVariableValue variableValue = null; if (value != null) { Class<?> entryValueClass = value.getClass(); String entryType = resolveEntryType(entryValueClass, value); if (OBJECT_TYPE_KEY.equals(entryType)) { value = new ObjectValue(value); } String entryValue = conversionService.convert(value, String.class); variableValue = new ProcessVariableValue(entryType, entryValue); } return variableValue; }
Source:
<code>public Long getUuid() { <START> return new Long(getArtId()); <END> }</code><technical_language>Long.valueOf() instead of new Long() - for performance reasons</technical_language>

Target:
public Long getUuid() { return Long.valueOf(getArtId()); }
Source:
<code>protected void checkCount( XpathEngine xpathEngine, Document document, int expectedCount, String xpath) { try { assertThat( xpathEngine.getMatchingNodes(xpath, document).getLength(), is(expectedCount)); } catch (Exception exception) { <START> throw new RuntimeException("Error evaluating xpath.", exception); <END> } }</code><technical_language>include xpath in error message</technical_language>

Target:
protected void checkCount( XpathEngine xpathEngine, Document document, int expectedCount, String xpath) { try { assertThat( xpathEngine.getMatchingNodes(xpath, document).getLength(), is(expectedCount)); } catch (Exception exception) { throw new RuntimeException("Error evaluating xpath: " + xpath, exception); } }
Source:
<code>protected void handleNodeHistoryRequest(NodeHistoryRequest serviceRequest) { try { mCacheHelper.getMessagesForGroup(serviceRequest.getGroup(), serviceRequest.getDate(), NodeHistoryRequest.MESSAGE_COUNT); } catch (CacheDatabaseException e) { <START> e.printStackTrace(); <END> } ServerRequest serverRequest = serviceRequest.parseRequestForServer(); mController.sendToServer(serverRequest); }</code><technical_language>Log</technical_language>

Target:
protected void handleNodeHistoryRequest(NodeHistoryRequest serviceRequest) { try { mCacheHelper.getMessagesForGroup(serviceRequest.getGroup(), serviceRequest.getDate(), NodeHistoryRequest.MESSAGE_COUNT); } catch (CacheDatabaseException e) { Log.d("Y:" + this.getClass().toString(), "Failed to retrieve messages from Cache !"); } ServerRequest serverRequest = serviceRequest.parseRequestForServer(); mController.sendToServer(serverRequest); }
Source:
<code>public void readBytes(final byte[] bytes) { try { <START> mCompressedStream.read(bytes); <END> } catch (IOException ioe) { throw(new RuntimeIOException("Read error in CSI compressed stream: " + ioe)); } }</code><technical_language>I a subtle bug here. mCompressedStream.read(bytes) guarantee read bytes ask for. check return of read continue reading read bytes require, returns -1 in case throw</technical_language>

Target:
public void readBytes(final byte[] bytes) { binaryCodec.readBytes(bytes); }
Source:
<code>public String getText(Object element) { String text = super.getText(element); if (hashMap.containsKey(element)) { <START> text = text + " (found in"; for (String s : hashMap.get(element)) { text = text + " \"" + s + "\","; } text = text.substring(0, text.length() - 1) + ")"; <END> } return text; }</code><technical_language>This a problem in this case, a general rule, avoid string concatenations +. cases compiler produce optimized code, produce code creates a lot of intermediate objects. in simple cases, recommended pattern is this: StringBuilder sb = new StringBuilder("initialString"); sb.append(var).append("fixed string"); ... sb.append("something else"); return sb.toString(); In this case, loop replaced by: com.google.common.base.Joiner.on(", ").join(hashMap.get(element)) tricky (and common) logic of inserting a separator elements one</technical_language>

Target:
public String getText(Object element) { StringBuilder sb = new StringBuilder(super.getText(element)); if (multimap.containsKey(element)) { sb.append(" (found in "); Joiner joiner = Joiner.on(", "); sb.append(joiner.join(multimap.get(element).toArray())); sb.append(")"); } return sb.toString(); }
Source:
<code>private void printTxn(byte[] bytes, String prefix) { try { TxnHeader hdr = new TxnHeader(); Record txn = SerializeUtils.deserializeTxn(bytes, hdr); String txnStr; txnStr = getFormattedTxnStr(txn); String txns = String.format("%s session 0x%s cxid 0x%s zxid 0x%s %s %s", DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG).format(new Date(hdr.getTime())), Long.toHexString(hdr.getClientId()), Long.toHexString(hdr.getCxid()), Long.toHexString(hdr.getZxid()), TraceFormatter.op2String(hdr.getType()), txnStr); if (prefix != null && !"".equals(prefix.trim())) { System.out.print(prefix + " - "); } if (txns.endsWith("\n")) { System.out.print(txns); } else { System.out.println(txns); } } catch (Exception e) { <START> e.printStackTrace(); <END> } }</code><technical_language>fixed 'null' reference problem, do catch here? If wrong a txn, happen for others end flooding console error messages. I full stop in case of unhandled error</technical_language>

Target:
private void printTxn(byte[] bytes, String prefix) throws IOException { TxnHeader hdr = new TxnHeader(); Record txn = SerializeUtils.deserializeTxn(bytes, hdr); String txnStr = getFormattedTxnStr(txn); String txns = String.format("%s session 0x%s cxid 0x%s zxid 0x%s %s %s", DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG).format(new Date(hdr.getTime())), Long.toHexString(hdr.getClientId()), Long.toHexString(hdr.getCxid()), Long.toHexString(hdr.getZxid()), TraceFormatter.op2String(hdr.getType()), txnStr); if (prefix != null && !"".equals(prefix.trim())) { System.out.print(prefix + " - "); } if (txns.endsWith("\n")) { System.out.print(txns); } else { System.out.println(txns); } }
Source:
<code><START> private static boolean useNativeEpoll() { <END> try { Class.forName("io.netty.channel.epoll.Epoll", true, TransportHelper.class.getClassLoader()); if (Epoll.isAvailable()) { return !EPOLL_DISABLED && IS_LINUX; } else { if (IS_LINUX) { log.epollNotAvailable(Epoll.unavailabilityCause().toString()); } } } catch (ClassNotFoundException e) { if (IS_LINUX) { log.epollNotAvailable(e.getMessage()); } } return false; }</code><technical_language>This Boolean.getBoolean :)</technical_language>

Target:
private static boolean useNativeEpoll() { try { Class.forName("io.netty.channel.epoll.Epoll", true, EPollAvailable.class.getClassLoader()); if (Epoll.isAvailable()) { return !EPOLL_DISABLED && IS_LINUX; } else { if (IS_LINUX) { log.epollNotAvailable(Epoll.unavailabilityCause().toString()); } } } catch (ClassNotFoundException e) { if (IS_LINUX) { log.epollNotAvailable(e.getMessage()); } } return false; }
Source:
<code>public void init(ByteBuffer buf, int position) { buf.putLong(position, Long.MIN_VALUE); <START> buf.putFloat(position + Longs.BYTES, 0); <END> }</code><technical_language>in this class this PR in general</technical_language>

Target:
public void init(ByteBuffer buf, int position) { buf.putLong(position, Long.MIN_VALUE); buf.putFloat(position + Long.BYTES, 0); }
Source:
<code>private void generateCommands() throws IOException, TemplateException { for (final Ds3Request request : spec.getRequests()) { generateRequest(request); } <START> if (null != spec.getTypes()) { <END> for (final Ds3Type typeEntry : spec.getTypes().values()) { generateType(typeEntry); generateTypeMatcher(typeEntry); } } }</code><technical_language>In utils package is a class called ConverterUtils isEmpty hasContent functions. I suggest want check if lists, sets, maps, strings empty/null full</technical_language>

Target:
private void generateCommands() throws IOException, TemplateException { if (ConverterUtil.hasContent(spec.getRequests())) { for (final Ds3Request request : spec.getRequests()) { generateRequest(request); } } if (ConverterUtil.hasContent(spec.getTypes())) { for (final Ds3Type typeEntry : spec.getTypes().values()) { generateType(typeEntry); generateTypeMatcher(typeEntry); } } }
Source:
<code><START> public List<RemoteXBeeDevice> discoverDevices(List<String> ids) throws XBeeException { <END> logger.debug("{}ND for all devices.", toString(), ids.toString()); performNodeDiscovery(null, null); List<RemoteXBeeDevice> foundDevices = new ArrayList<RemoteXBeeDevice>(0); if (deviceList == null) return foundDevices; XBeeNetwork network = xbeeDevice.getNetwork(); for (RemoteXBeeDevice d: deviceList) { String nID = d.getNodeID(); if (nID != null) { for (String id : ids) { if (nID.equals(id)) { RemoteXBeeDevice rDevice = network.addRemoteDevice(d); if (rDevice != null && !foundDevices.contains(rDevice)) foundDevices.add(rDevice); } } } } return foundDevices; }</code><technical_language>if ids == null if ids.size() == 0? java /** * Discovers reports remote XBee devices match supplied * identifiers. * * [...] * * @throws IllegalArgumentException If {@code ids.size() == 0}. * @throws InterfaceNotOpenException If device is open. * @throws NullPointerException If {@code ids == null}. * @throws XBeeException If is error sending discovery command. */ public List<RemoteXBeeDevice> discoverDevices(List<String> ids) throws XBeeException { if (ids == null) throw new NullPointerException("List of device identifiers null."); if (id.size() == 0) throw new IllegalArgumentException("List of device identifiers empty."); logger.debug("{}ND for devices.", toString(), ids.toString()); [...] }</technical_language>

Target:
public List<RemoteXBeeDevice> discoverDevices(List<String> ids) throws XBeeException { if (!xbeeDevice.isOpen()) throw new InterfaceNotOpenException(); logger.debug("{}ND for all devices.", xbeeDevice.toString(), ids.toString()); running = true; discovering = true; performNodeDiscovery(null, null); List<RemoteXBeeDevice> foundDevices = new ArrayList<RemoteXBeeDevice>(0); if (deviceList == null) return foundDevices; XBeeNetwork network = xbeeDevice.getNetwork(); for (RemoteXBeeDevice d: deviceList) { String nID = d.getNodeID(); if (nID == null) continue; for (String id : ids) { if (nID.equals(id)) { RemoteXBeeDevice rDevice = network.addRemoteDevice(d); if (rDevice != null && !foundDevices.contains(rDevice)) foundDevices.add(rDevice); } } } return foundDevices; }
Source:
<code>private CompletableFuture<InternalCacheEntry> invokeClusterGetCommandRemotely(List<Address> targets, RpcOptionsBuilder rpcOptionsBuilder, ClusteredGetCommand get, Object key) { ResponseFilter filter = new ClusteredGetResponseValidityFilter(targets, rpcManager.getAddress()); RpcOptions options = rpcOptionsBuilder.responseFilter(filter).build(); return rpcManager.invokeRemotelyAsync(targets, get, options).thenApply(responses -> { boolean hasSuccesfulResponse = false; if (!responses.isEmpty()) { for (Response r : responses.values()) { if (r instanceof SuccessfulResponse) { hasSuccesfulResponse = true; SuccessfulResponse response = (SuccessfulResponse) r; Object responseValue = response.getResponseValue(); if (responseValue == null) { continue; } InternalCacheValue cacheValue = (InternalCacheValue) responseValue; InternalCacheEntry ice = cacheValue.toInternalCacheEntry(key); if (rvrl != null) { rvrl.remoteValueFound(ice); } return ice; } } } if (rvrl != null) { rvrl.remoteValueNotFound(key); } if (!hasSuccesfulResponse) { <START> RpcException rpcException = new RpcException("No successful response: " + responses); <END> for (Response r : responses.values()) { if (r instanceof ExceptionResponse) { rpcException.addSuppressed(((ExceptionResponse) r).getException()); } } throw rpcException; } else { return null; } }); }</code><technical_language>Indeed. send UnsureResponse in cases (with a check in DistributionResponseGenerator). ClusteredGetCommand a topology, check guaranteed false, I finally removed ISPN-5463. Besides, weird a locality check in response generator, remove ResponseGenerator create Response in command itself. (Or in interceptors...)</technical_language>

Target:
private CompletableFuture<InternalCacheEntry> invokeClusterGetCommandRemotely(List<Address> targets, RpcOptionsBuilder rpcOptionsBuilder, ClusteredGetCommand get, Object key) { ResponseFilter filter = new ClusteredGetResponseValidityFilter(targets, rpcManager.getAddress()); RpcOptions options = rpcOptionsBuilder.responseFilter(filter).build(); return rpcManager.invokeRemotelyAsync(targets, get, options).thenApply(responses -> { boolean hasSuccesfulResponse = false; if (!responses.isEmpty()) { for (Response r : responses.values()) { if (r instanceof SuccessfulResponse) { hasSuccesfulResponse = true; SuccessfulResponse response = (SuccessfulResponse) r; Object responseValue = response.getResponseValue(); if (responseValue == null) { continue; } InternalCacheValue cacheValue = (InternalCacheValue) responseValue; InternalCacheEntry ice = cacheValue.toInternalCacheEntry(key); if (rvrl != null) { rvrl.remoteValueFound(ice); } return ice; } } } if (rvrl != null) { rvrl.remoteValueNotFound(key); } if (!hasSuccesfulResponse) { throw new RpcException("No successful response: " + responses); } else { return null; } }); }
Source:
<code>public void openFromDropbox(DropboxRevisionsTopComponent drtc, RevisionDisplayTopComponent revtc) { DbxClient client = DbxUtil.getDbxClient(); if (client == null) { return; } List<DbxEntryDto> dbxEntries = new ArrayList<>(); try { for (DbxEntry entry : client.searchFileAndFolderNames("/", ".tex")) { dbxEntries.add(new DbxEntryDto(entry)); } } catch (DbxException ex) { DbxUtil.showDbxAccessDeniedPrompt(); <START> return; END> } JList<DbxEntryDto> list = new JList(dbxEntries.toArray()); list.setSelectionMode(DefaultListSelectionModel.SINGLE_SELECTION); int option = JOptionPane.showConfirmDialog(null, list, "Open file from Dropbox", JOptionPane.OK_CANCEL_OPTION); if (option == JOptionPane.OK_OPTION && !list.isSelectionEmpty()) { DbxEntryDto entry = list.getSelectedValue(); String localPath = ApplicationUtils.getAppDirectory() + File.separator + entry.getName(); File outputFile = DbxUtil.downloadRemoteFile(entry, localPath); revtc.close(); drtc.updateRevisionsList(entry.getPath()); drtc.open(); drtc.requestActive(); String content = FileService.readFromFile(outputFile.getAbsolutePath()); etc.setEditorContent(content); etc.setCurrentFile(outputFile); etc.setDbxState(new DbxState(entry.getPath(), entry.getRevision())); etc.setModified(false); } }</code><technical_language>Please refactor this a method List<DbxEntryDto> getDbxTexEntries() Return empty list, in case of DbxException Check if list is empty message user *.tex-Files found</technical_language>

Target:
public void openFromDropbox(DropboxRevisionsTopComponent drtc, RevisionDisplayTopComponent revtc) { List<DbxEntryDto> dbxEntries = getDbxTexEntries(DbxUtil.getDbxClient()); if (!dbxEntries.isEmpty()) { JList<DbxEntryDto> list = new JList(dbxEntries.toArray()); list.setSelectionMode(DefaultListSelectionModel.SINGLE_SELECTION); int option = JOptionPane.showConfirmDialog(null, list, "Open file from Dropbox", JOptionPane.OK_CANCEL_OPTION); if (option == JOptionPane.OK_OPTION && !list.isSelectionEmpty()) { DbxEntryDto entry = list.getSelectedValue(); String localPath = ApplicationUtils.getAppDirectory() + File.separator + entry.getName(); File outputFile = DbxUtil.downloadRemoteFile(entry, localPath); revtc.close(); drtc.updateRevisionsList(entry.getPath()); drtc.open(); drtc.requestActive(); String content = FileService.readFromFile(outputFile.getAbsolutePath()); etc.setEditorContent(content); etc.setCurrentFile(outputFile); etc.setDbxState(new DbxState(entry.getPath(), entry.getRevision())); etc.setModified(false); etc.setPreviewDisplayed(false); } } else{ JOptionPane.showMessageDialog(etc, "No .tex files found!", "Error", JOptionPane.ERROR_MESSAGE); } }
Source:
<code>public void verifyLnpTestSuccess(double errorRateLimit, double meanResTimeLimit) { checkErrorLimit(errorRateLimit); checkMeanResTimeLimit(meanResTimeLimit); <START> if (resultsErrorMessage != null) { <END> throw new AssertionError(resultsErrorMessage); } }</code><technical_language>Add empty line</technical_language>

Target:
public void verifyLnpTestSuccess(double errorRateLimit, double meanResTimeLimit) { checkErrorLimit(errorRateLimit); checkMeanResTimeLimit(meanResTimeLimit); if (resultsErrorMessage.isEmpty()) { throw new AssertionError(resultsErrorMessage); } }
Source:
<code>public Object decode(String alias, U value) { checkNotNull(alias, "Not allowed to have a null alias"); checkNotNull(value, "Value for decoding can not be null"); TypeEncoder<?, U> encoder = aliasMapping.get(alias); if (encoder != null) return encoder.decode(value); <START> throw new TypeDecodingException("An unknown alias [" + alias + "] was encountered while decoding value [" + value + "]. Valid aliases are " + String.join(", ", aliasMapping.keySet())); <END> }</code><technical_language>problems this. 1. assume is easily representable a string. instances for example byte[] instead of strings. print out a cryptic error message. error message incorrectly instead of alias. 2. String.join is a java 8 method. Mango is compatible Java 6 work older applications in production</technical_language>

Target:
public Object decode(String alias, U value) { checkNotNull(alias, "Not allowed to have a null alias"); checkNotNull(value, "Value for decoding can not be null"); TypeEncoder<?, U> encoder = aliasMapping.get(alias); if (encoder != null) return encoder.decode(value); throw new TypeDecodingException("An unknown alias [" + alias + "] was encountered while decoding value [" + value + "]. Valid aliases are " + Joiner.on(", ").join(aliasMapping.keySet())); }
Source:
<code>public void teardown() { try { client.close(); } catch (IOException e) { <START> LOGGER.error(e.getMessage(), e); <END> } }</code><technical_language>throw exception</technical_language>

Target:
public void teardown() { LOGGER.debug("Tearing down operator..."); windowDataManager.teardown(); try { client.close(); } catch (IOException e) { DTThrowable.rethrow(e); } }
Source:
<code>public ResignatureCommand(final Map<String, String> details) { <START> _details = details; <END> }</code><technical_language>Copy details ImmutableMap map avoid side-effects caller making subsequence changes map. prevent side-effects returned getDetails</technical_language>

Target:
public ResignatureCommand(final Map<String, String> details) { this.details = Utils.getImmutableMap(details); }
Source:
<code>private void checkState() { if (!useCookies) { resetState(); setClientsCookiePolicy(CookiePolicy.IGNORE_COOKIES); } else if (useGlobalState) { if (param.isHttpStateEnabled()) { client.setState(param.getHttpState()); clientViaProxy.setState(param.getHttpState()); setProxyAuth(clientViaProxy); setClientsCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); } else { setClientsCookiePolicy(CookiePolicy.IGNORE_COOKIES); } } else { <START> client.setState(new HttpState()); <END> clientViaProxy.setState(new HttpState()); setProxyAuth(clientViaProxy); setClientsCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); } }</code><technical_language>call resetState</technical_language>

Target:
private void checkState() { if (!useCookies) { resetState(); setClientsCookiePolicy(CookiePolicy.IGNORE_COOKIES); } else if (useGlobalState) { if (param.isHttpStateEnabled()) { client.setState(param.getHttpState()); clientViaProxy.setState(param.getHttpState()); setProxyAuth(clientViaProxy); setClientsCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); } else { setClientsCookiePolicy(CookiePolicy.IGNORE_COOKIES); } } else { resetState(); setClientsCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); } }