auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private PatchList readPatchList(final PatchListKey key, final Repository repo) throws IOException { final PatchList pList = get(key, repo); if (key.isRebaseTransparent() && key.getOldId() != null) { final ObjectReader reader = repo.newObjectReader(); try { final RevWalk rw = new RevWalk(reader); final RevCommit b = rw.parseCommit(key.getNewId()); final RevCommit a = rw.parseCommit(key.getOldId()); if (Collections.disjoint(Arrays.asList(a.getParents()), Arrays.asList(b.getParents()))) { final Set<String> patchfileList = get( new PatchListKey(key.projectKey, null, key.getNewId(), key.getWhitespace()), repo).toPatchFileList(); patchfileList.addAll(get( new PatchListKey(key.projectKey, null, key.getOldId(), key .getWhitespace()), repo).toPatchFileList()); <START> pList.retainAll(patchfileList); <END> return pList; } } finally { reader.release(); } } return pList; }</code><technical_language>modify a patch list of cache</technical_language>

Target:
private PatchList readPatchList(final PatchListKey key, final Repository repo) throws IOException { final PatchList pList = get(key, repo); if (key.isRebaseTransparent() && key.getOldId() != null) { final ObjectReader reader = repo.newObjectReader(); try { final RevWalk rw = new RevWalk(reader); final RevCommit b = rw.parseCommit(key.getNewId()); final RevCommit a = rw.parseCommit(key.getOldId()); if (Collections.disjoint(Arrays.asList(a.getParents()), Arrays.asList(b.getParents()))) { final Set<String> patchfileList = get( new PatchListKey(key.projectKey, null, key.getNewId(), key.getWhitespace()), repo).toFileList(); patchfileList.addAll(get( new PatchListKey(key.projectKey, null, key.getOldId(), key .getWhitespace()), repo).toFileList()); return pList.copyBy(patchfileList); } } finally { reader.release(); } } return pList; }
Source:
<code>private static void populateUnresolvedDependencies(@NotNull DataNode<ProjectData> projectInfo, @NotNull Set<String> unresolvedDependencies) { String category = "Unresolved dependencies:"; for (String dep : unresolvedDependencies) { <START> String url = "search" + dep; <END> NotificationHyperlink hyperlink = new SearchInBuildFilesHyperlink(url, "Search", dep); projectInfo.createChild(AndroidProjectKeys.IMPORT_EVENT_MSG, new ProjectImportEventMessage(category, dep, hyperlink)); } }</code><technical_language>some sort of separator url action argument? I url handler is, I "search:foobar" more sense a url "searchfoobar" if prefixes</technical_language>

Target:
private static void populateUnresolvedDependencies(@NotNull DataNode<ProjectData> projectInfo, @NotNull Set<String> unresolvedDependencies) { String category = "Unresolved dependencies:"; for (String dep : unresolvedDependencies) { String url = "search:" + dep; NotificationHyperlink hyperlink = new SearchInBuildFilesHyperlink(url, "Search", dep); projectInfo.createChild(AndroidProjectKeys.IMPORT_EVENT_MSG, new ProjectImportEventMessage(category, dep, hyperlink)); } }
Source:
<code>public void getFieldByLanguage(String barcode, ArrayList<String> fields, final OnFieldByLanguageCallback fieldByLanguageCallback) { StringBuilder fieldQuery = new StringBuilder(); for (String s : fields) { fieldQuery.append(s); fieldQuery.append(","); } apiService.getFieldByLangCode(barcode, fieldQuery.toString()).enqueue(new Callback<JsonNode>() { @Override public void onResponse(Call<JsonNode> call, Response<JsonNode> response) { JsonNode responseNode = response.body(); HashMap<String,String> resultMap = new HashMap<>(); for (String field : fields) { <START> if (responseNode.findValue("product").findValue(field) != null && <END> (!responseNode.findValue("product").findValue(field).toString().equals(""))) { String value = responseNode.findValue("product").findValue(field).toString(); resultMap.put(field, value); } else { resultMap.put(field, null); } } fieldByLanguageCallback.onFieldByLanguageResponse(true,resultMap); } @Override public void onFailure(Call<JsonNode> call, Throwable t) { fieldByLanguageCallback.onFieldByLanguageResponse(false,null); } }); }</code><technical_language>Null check for responseNode</technical_language>

Target:
public void getFieldByLanguage(String barcode, ArrayList<String> fields, final OnFieldByLanguageCallback fieldByLanguageCallback) { StringBuilder fieldQuery = new StringBuilder(); for (String s : fields) { fieldQuery.append(s); fieldQuery.append(","); } apiService.getFieldByLangCode(barcode, fieldQuery.toString()).enqueue(new Callback<JsonNode>() { @Override public void onResponse(Call<JsonNode> call, Response<JsonNode> response) { JsonNode responseNode = response.body(); if (responseNode != null) { HashMap<String, String> resultMap = new HashMap<>(); for (String field : fields) { if (responseNode.findValue("product").findValue(field) != null && (!responseNode.findValue("product").findValue(field).toString().equals(""))) { String value = responseNode.findValue("product").findValue(field).toString(); resultMap.put(field, value); } else { resultMap.put(field, null); } } fieldByLanguageCallback.onFieldByLanguageResponse(true, resultMap); } } @Override public void onFailure(Call<JsonNode> call, Throwable t) { fieldByLanguageCallback.onFieldByLanguageResponse(false, null); } }); }
Source:
<code>public DefaultNode(InetSocketAddress connectAddress, InternalDriverContext context) { this.connectAddress = connectAddress; <START> this.metricUpdater = context.metricUpdaterFactory().newNodeUpdater(this); <END> this.state = NodeState.UNKNOWN; this.distance = NodeDistance.IGNORED; this.rawTokens = Collections.emptySet(); this.extras = Collections.emptyMap(); }</code><technical_language>a worse that, I constructor of DefaultNodeUpdater do following: ChannelPool pool = context.poolManager().getPools().get(node);</technical_language>

Target:
public DefaultNode(InetSocketAddress connectAddress, InternalDriverContext context) { this.connectAddress = connectAddress; this.state = NodeState.UNKNOWN; this.distance = NodeDistance.IGNORED; this.rawTokens = Collections.emptySet(); this.extras = Collections.emptyMap(); this.metricUpdater = context.metricUpdaterFactory().newNodeUpdater(this); }
Source:
<code>public void convertToIndexUpdatesAndApply( Iterable<NodeUpdates> updates, IndexUpdateMode updateMode ) throws IOException, IndexEntryConflictException { final List<IndexEntryUpdate<LabelSchemaDescriptor>> indexUpdates = new ArrayList<>(); for ( NodeUpdates nodeUpdate : updates ) { <START> for ( IndexEntryUpdate<LabelSchemaDescriptor> indexUpdate : convertToIndexUpdates( nodeUpdate ) ) <END> { indexUpdates.add( indexUpdate ); } } apply( indexUpdates, updateMode ); }</code><technical_language>create lazy iterator instead of collecting updates array list pass iterator apply, avoid top additional for loop</technical_language>

Target:
public void convertToIndexUpdatesAndApply( Iterable<NodeUpdates> updates, IndexUpdateMode updateMode ) throws IOException, IndexEntryConflictException { apply( Iterables.flatMap( this::convertToIndexUpdates, updates ), updateMode ); }
Source:
<code>public void doRouteStatusChange(DocumentHeader header) { super.doRouteStatusChange(header); VendorDetail vendorDetail = (VendorDetail) getBusinessObject(); WorkflowDocument workflowDoc = header.getWorkflowDocument(); boolean isExistingNewVendor = getPaymentWorksVendorService().isExistingPaymentWorksVendorByDocumentNumber(this.getDocumentNumber()); <START> if (workflowDoc.isFinal()) { <END> processFinalizedWorkflowDocument(vendorDetail, isExistingNewVendor); } else if (workflowDoc.isDisapproved()) { if (StringUtils.equals(KFSConstants.MAINTENANCE_NEW_ACTION, this.getMaintenanceAction())) { if (isExistingNewVendor) { LOG.info("Updating new vendor request to vendor disapproved for document number: " + this.getDocumentNumber()); getPaymentWorksVendorService().updatePaymentWorksVendorProcessStatusByDocumentNumber(this.getDocumentNumber(), PaymentWorksConstants.ProcessStatus.VENDOR_DISAPPROVED); } } } }</code><technical_language>do want this happen final processed docs</technical_language>

Target:
public void doRouteStatusChange(DocumentHeader header) { super.doRouteStatusChange(header); VendorDetail vendorDetail = (VendorDetail) getBusinessObject(); WorkflowDocument workflowDoc = header.getWorkflowDocument(); boolean existingPaymentWorksVendor = getPaymentWorksVendorService().isExistingPaymentWorksVendorByDocumentNumber(this.getDocumentNumber()); if (workflowDoc.isProcessed()) { updatePaymentWorks(vendorDetail, existingPaymentWorksVendor); } else if (workflowDoc.isDisapproved()) { if (StringUtils.equals(KFSConstants.MAINTENANCE_NEW_ACTION, this.getMaintenanceAction())) { if (existingPaymentWorksVendor) { LOG.debug("Updating new vendor request to vendor disapproved for document number: " + this.getDocumentNumber()); getPaymentWorksVendorService().updatePaymentWorksVendorProcessStatusByDocumentNumber(this.getDocumentNumber(), PaymentWorksConstants.ProcessStatus.VENDOR_DISAPPROVED); } } } }
Source:
<code>public void testSerialization () throws IOException { DeltaLengthByteArrayValuesWriter writer = new DeltaLengthByteArrayValuesWriter(64 * 1024, 64 * 1024, new DirectByteBufferAllocator()); DeltaLengthByteArrayValuesReader reader = new DeltaLengthByteArrayValuesReader(); <START> <END> Utils.writeData(writer, values); Binary[] bin = Utils.readData(reader, writer.getBytes().toByteArray(), values.length); for(int i =0; i< bin.length ; i++) { Assert.assertEquals(Binary.fromString(values[i]).toStringUsingUTF8(), bin[i].toStringUsingUTF8()); } }</code><technical_language>ide is configured remove end of line whitespace</technical_language>

Target:
public void testSerialization () throws IOException { DeltaLengthByteArrayValuesWriter writer = getDeltaLengthByteArrayValuesWriter(); DeltaLengthByteArrayValuesReader reader = new DeltaLengthByteArrayValuesReader(); Utils.writeData(writer, values); Binary[] bin = Utils.readData(reader, writer.getBytes().toByteArray(), values.length); for(int i =0; i< bin.length ; i++) { Assert.assertEquals(Binary.fromString(values[i]), bin[i]); } }
Source:
<code><START> String toDMNString(final String years, <END> final String months) { final YearsMonthsValue value = new YearsMonthsValue(); value.setYears(years); value.setMonths(months); return toDMNString(value); }</code><technical_language>I fromDMNString toDMNString public main feature of this class, do I miss something</technical_language>

Target:
public String toDMNString(final String years, final String months) { final YearsMonthsValue value = new YearsMonthsValue(); value.setYears(years); value.setMonths(months); return toDMNString(value); }
Source:
<code>public void update(Observable arg0, Object argN) { if (arg0 != player) { return; } final String arg1 = OoyalaNotification.getNameOrUnknown(argN); if (arg1 == OoyalaPlayer.TIME_CHANGED_NOTIFICATION_NAME) { return; } if (arg1 == OoyalaPlayer.ERROR_NOTIFICATION_NAME) { final String msg = "Error Event Received"; if (player != null && player.getError() != null) { Log.e(TAG, msg, player.getError()); } else { Log.e(TAG, msg); } return; } String text = "Notification Received: " + arg1 + " - state: " + player.getState(); <START> log.writeToSdcardLog(text); <END> Log.d(TAG, text); }</code><technical_language>missed writePermission variable</technical_language>

Target:
public void update(Observable arg0, Object argN) { if (arg0 != player) { return; } final String arg1 = OoyalaNotification.getNameOrUnknown(argN); if (arg1 == OoyalaPlayer.TIME_CHANGED_NOTIFICATION_NAME) { return; } if (arg1 == OoyalaPlayer.ERROR_NOTIFICATION_NAME) { final String msg = "Error Event Received"; if (player != null && player.getError() != null) { Log.e(TAG, msg, player.getError()); } else { Log.e(TAG, msg); } return; } String text = "Notification Received: " + arg1 + " - state: " + player.getState(); Log.d(TAG, text); if (writePermission) { log.writeToSdcardLog(text); } }
Source:
<code>protected ResourceBundle getPluginResourceBundle() { Bundle bundle = <START> FrameworkUtil.getBundle(PDETemplateSection.class); <END> return Platform.getResourceBundle(bundle); }</code><technical_language>I result of this call change time. improve code keeping Bundle in instance variable is needed request everytime</technical_language>

Target:
protected ResourceBundle getPluginResourceBundle() { return Platform.getResourceBundle(bundle); }
Source:
<code>public void addEvictedInstance(WorkflowExecutionContext context) throws FalconException { final String outputFeedPaths = context.getOutputFeedInstancePaths(); if (IGNORE.equals(outputFeedPaths)) { LOG.info("There were no evicted instances, nothing to record"); return; } LOG.info("Recording lineage for evicted instances {}", outputFeedPaths); String feedName = context.getOutputFeedNames(); String[] evictedFeedInstancePathList = context.getOutputFeedInstancePathsList(); String clusterName = context.getClusterName(); for (String evictedFeedInstancePath : evictedFeedInstancePathList) { LOG.info("Computing feed instance for : name= {}, path={}, in cluster: {}", feedName, evictedFeedInstancePath, clusterName); String feedInstanceName = getFeedInstanceName(feedName, clusterName, evictedFeedInstancePath, context.getNominalTimeAsISO8601()); Vertex feedInstanceVertex = addFeedInstance( feedInstanceName, context, feedName, clusterName); Map<RelationshipProperty, String> properties = new HashMap<RelationshipProperty, String>(); <START> properties.put(RelationshipProperty.TIMESTAMP, context.getTimeStampAsISO8601()); <END> addInstanceToEntity(feedInstanceVertex, clusterName, RelationshipType.CLUSTER_ENTITY, RelationshipLabel.FEED_CLUSTER_EVICTED_EDGE, properties); } }</code><technical_language>edge nominal time. Please add STATUS edge</technical_language>

Target:
public void addEvictedInstance(WorkflowExecutionContext context) throws FalconException { final String outputFeedPaths = context.getOutputFeedInstancePaths(); if (IGNORE.equals(outputFeedPaths)) { LOG.info("There were no evicted instances, nothing to record"); return; } LOG.info("Recording lineage for evicted instances {}", outputFeedPaths); String feedName = context.getOutputFeedNames(); String[] evictedFeedInstancePathList = context.getOutputFeedInstancePathsList(); String clusterName = context.getClusterName(); for (String evictedFeedInstancePath : evictedFeedInstancePathList) { LOG.info("Computing feed instance for : name= {}, path={}, in cluster: {}", feedName, evictedFeedInstancePath, clusterName); String feedInstanceName = getFeedInstanceName(feedName, clusterName, evictedFeedInstancePath, context.getNominalTimeAsISO8601()); Vertex feedInstanceVertex = addFeedInstance( feedInstanceName, context, feedName, clusterName); Map<RelationshipProperty, String> properties = edgePropertiesForIndexing(context); properties.put(RelationshipProperty.TIMESTAMP, context.getTimeStampAsISO8601()); addInstanceToEntity(feedInstanceVertex, clusterName, RelationshipType.CLUSTER_ENTITY, RelationshipLabel.FEED_CLUSTER_EVICTED_EDGE, properties); } }
Source:
<code>public void copyShellFile(TarArchiveOutputStream tarOutputStream) throws IOException { ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Resource[] resources = resolver.getResources(getShellScriptsPath()); InputStream shellFileIs; byte[] shellFileBytes; for (Resource resource : resources) { shellFileIs = resource.getInputStream(); shellFileBytes = IOUtils.toByteArray(shellFileIs); <START> IOUtils.closeQuietly(shellFileIs); <END> addByteToTar(tarOutputStream, shellFileBytes, getBasePath() + FilenameUtils.getName(resource.getFilename()), shellFileBytes.length, EXEC); } }</code><technical_language>I shellFileIs wrapped try catch resource leak happen</technical_language>

Target:
public void copyShellFile(TarArchiveOutputStream tarOutputStream) throws IOException { ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Resource[] resources = resolver.getResources(getShellScriptsPath()); byte[] shellFileBytes; for (Resource resource : resources) { try (InputStream shellFileIs = resource.getInputStream()) { shellFileBytes = IOUtils.toByteArray(shellFileIs); addByteToTar(tarOutputStream, shellFileBytes, getBasePath() + FilenameUtils.getName(resource.getFilename()), shellFileBytes.length, EXEC); } } }
Source:
<code>protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) { return; } boolean protoFormat = hasOption(args, "--proto"); ProtoOutputStream proto = null; CoreLibrary.DebugInfo coreLibraryDebugInfo = CoreLibrary.getDebugInfo(); addTimeZoneApkDebugInfo(coreLibraryDebugInfo); if (protoFormat) { proto = new ProtoOutputStream(fd); reportTimeZoneInfoProto(coreLibraryDebugInfo, proto); } else { reportTimeZoneInfo(coreLibraryDebugInfo, pw); } if (protoFormat) { <START> proto.flush(); <END> } }</code><technical_language>this line 61 move line 68</technical_language>

Target:
protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) { return; } boolean protoFormat = hasOption(args, "--proto"); ProtoOutputStream proto = null; DebugInfo coreLibraryDebugInfo = CoreLibraryDebug.getDebugInfo(); addTimeZoneApkDebugInfo(coreLibraryDebugInfo); if (protoFormat) { proto = new ProtoOutputStream(fd); reportTimeZoneInfoProto(coreLibraryDebugInfo, proto); } else { reportTimeZoneInfo(coreLibraryDebugInfo, pw); } if (protoFormat) { proto.flush(); } }
Source:
<code>public NotificationListener listenBucketNotification(String bucketName, String prefix, String suffix, String[] events) throws IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException, <START> InvalidResponseException, InternalException, NoResponseException, InvalidBucketNameException, <END> XmlPullParserException, ErrorResponseException { Multimap<String, String> queryParamMap = HashMultimap.create(); queryParamMap.put("prefix", prefix); queryParamMap.put("suffix", suffix); for (String event : events) { queryParamMap.put("events", event); } HttpResponse response = executeReq(Method.GET, getRegion(bucketName), bucketName, "", null, queryParamMap, null, 0); return new NotificationListener(response.body().charStream()); }</code><technical_language>executeGet()</technical_language>

Target:
public CloseableIterator<Result<NotificationInfo>> listenBucketNotification(String bucketName, String prefix, String suffix, String[] events) throws IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException, InvalidResponseException, InternalException, NoResponseException, InvalidBucketNameException, XmlPullParserException, ErrorResponseException { Multimap<String, String> queryParamMap = HashMultimap.create(); queryParamMap.put("prefix", prefix); queryParamMap.put("suffix", suffix); for (String event : events) { queryParamMap.put("events", event); } HttpResponse response = executeReq(Method.GET, getRegion(bucketName), bucketName, "", null, queryParamMap, null, 0); return new CloseableIterator<Result<NotificationInfo>>() { Scanner scanner = new Scanner(response.body().charStream()).useDelimiter("\n"); String notificationString = null; ObjectMapper mapper = new ObjectMapper(); NotificationInfo notificationInfo = null; boolean isClosed = false; @Override public void close() throws IOException { if (!isClosed) { try { response.body().close(); scanner.close(); } finally { isClosed = true; } } } public boolean populate() { if (isClosed) { return false; } if (notificationString != null) { return true; } while (scanner.hasNext()) { notificationString = scanner.next().trim(); if ( !notificationString.equals("")) { break; } } if (notificationString == null || notificationString.equals("")) { try { close(); } catch (IOException e) { isClosed = true; } return false; } return true; } @Override public boolean hasNext() { return populate(); } @Override public Result<NotificationInfo> next() { if (isClosed) { throw new NoSuchElementException(); } if ((notificationString == null || notificationString.equals("")) && !populate() ) { throw new NoSuchElementException(); } try { notificationInfo = mapper.readValue(notificationString, NotificationInfo.class); return new Result<>(notificationInfo, null); } catch (JsonParseException e) { return new Result<>(null, e); } catch ( JsonMappingException e) { return new Result<>(null, e); } catch ( IOException e) { return new Result<>(null, e); } finally { notificationInfo = null; } } }; }
Source:
<code>protected SCMRevision retrieve(@NonNull String thingName, @NonNull TaskListener listener) throws IOException, InterruptedException { MercurialInstallation inst = MercurialSCM.findInstallation(installation); if (inst == null) { listener.error("No configured Mercurial installation"); return null; } if (!inst.isUseCaches()) { listener.error("Mercurial installation " + installation + " does not support caches"); return null; } final Node node = Jenkins.getInstance(); <START> if (node == null) { END> listener.error("Cannot retrieve the Jenkins master node"); return null; } Launcher launcher = node.createLauncher(listener); StandardUsernameCredentials credentials = getCredentials(); final FilePath cache = Cache.fromURL(source, credentials, inst.getMasterCacheRoot()).repositoryCache(inst, node, launcher, listener, true); if (cache == null) { listener.error("Could not use caches, not fetching branch heads"); return null; } final HgExe hg = new HgExe(inst, credentials, launcher, node, listener, new EnvVars()); try { String revision = hg.popen(cache, listener, true, new ArgumentListBuilder("id", "-r", thingName, "--id", "--branch")); String hash = revision.substring(0, revision.indexOf(' ')); String branch = revision.substring(revision.indexOf(' ')+1, revision.length()-1); return new MercurialRevision(new SCMHead(branch), hash); } finally { hg.close(); } }</code><technical_language>Depending baseline version, getActiveInstance</technical_language>

Target:
protected SCMRevision retrieve(@NonNull String thingName, @NonNull TaskListener listener) throws IOException, InterruptedException { MercurialInstallation inst = MercurialSCM.findInstallation(installation); if (inst == null) { listener.error("No configured Mercurial installation"); return null; } if (!inst.isUseCaches()) { listener.error("Mercurial installation " + installation + " does not support caches"); return null; } final Node node = Jenkins.getActiveInstance(); Launcher launcher = node.createLauncher(listener); StandardUsernameCredentials credentials = getCredentials(); final FilePath cache = Cache.fromURL(source, credentials, inst.getMasterCacheRoot()).repositoryCache(inst, node, launcher, listener, true); if (cache == null) { listener.error("Could not use caches, not fetching branch heads"); return null; } final HgExe hg = new HgExe(inst, credentials, launcher, node, listener, new EnvVars()); try { String revision = hg.popen(cache, listener, true, new ArgumentListBuilder("log", "-r", "present("+thingName+")", "--template", "{node} {branch}")); if (revision.isEmpty()){ return null; } String hash = revision.substring(0, revision.indexOf(' ')); String branch = revision.substring(revision.indexOf(' ')+1, revision.length()); return new MercurialRevision(new SCMHead(branch), hash); } finally { hg.close(); } }
Source:
<code>public int compareTo(BenchmarkResult benchmarkResult) { int cmp = type.index - benchmarkResult.type.index; if (cmp == 0) { long delta = this.time - benchmarkResult.time; <START> if (delta > 0) { <END> cmp = 1; } else if (delta < 0) { cmp = -1; } else { cmp = 0; } } return cmp; }</code><technical_language>cmp = Integer.compare(delta, 0)</technical_language>

Target:
public int compareTo(BenchmarkResult benchmarkResult) { int cmp = Integer.compare(type.index, benchmarkResult.type.index); if (cmp == 0) { cmp = Long.compare(this.time, benchmarkResult.time); } return cmp; }
Source:
<code>public String getItemsDescription(PurchaseRequest request){ String itemName = ""; ArrayList<PurchaseItem> items = request.getPurchaseList(); if(items.size() == 1) { return itemName + items.get(0).getItemName(); } <START> else { <END> itemName = items.get(0).getItemName(); for (int i = 1; i <= 3;i++){ if(i < items.size()){ itemName = itemName + ", " + items.get(i).getItemName(); } } if(items.size() > 3){ itemName += itemName + "..."; } return itemName; } }</code><technical_language>NITPICK: I is a need do this loop inside. do a multiple check if items == 1, items > 1 < 3, else do other things</technical_language>

Target:
public String getItemsDescription(PurchaseRequest request){ int limit = 3; ArrayList<PurchaseItem> items = request.getPurchaseList(); String itemName = items.get(0).getItemName(); for (int i = 1; i <= limit ;i++){ if(i < items.size()){ itemName = itemName + ", " + items.get(i).getItemName(); } } if(items.size() > limit ){ itemName += "..."; } return itemName; }
Source:
<code>public void optimize(TupleExpr tupleExpr, Dataset dataset, BindingSet bindings) { <START> if (conf instanceof MongoDBRdfConfiguration) { <END> MongoDBRdfConfiguration mongoConf = (MongoDBRdfConfiguration) conf; SparqlToPipelineTransformVisitor pipelineVisitor = new SparqlToPipelineTransformVisitor(mongoConf); try { tupleExpr.visit(pipelineVisitor); } catch (Exception e) { logger.error("Error attempting to transform query using the aggregation pipeline", e); } } }</code><technical_language>This change a StatefulMongoDBRdfConfiguration in 414 (which is a MongoDBRdfConfiguration). Is optimizer stateful? If so, want more instance of it, shared config</technical_language>

Target:
public void optimize(TupleExpr tupleExpr, Dataset dataset, BindingSet bindings) { SparqlToPipelineTransformVisitor pipelineVisitor = new SparqlToPipelineTransformVisitor(conf); try { tupleExpr.visit(pipelineVisitor); } catch (Exception e) { logger.error("Error attempting to transform query using the aggregation pipeline", e); } }
Source:
<code>public void setStarred(TaskRepository taskRepository, String taskID, boolean starred) throws CoreException { GerritClient client = getClient(taskRepository); SaveStarredRequest saveStarRequest = new SaveStarredRequest(taskRepository, taskID, starred); try { <START> client.saveStarred(saveStarRequest.getReviewId(), starred, null); <END> } catch (GerritException e) { Status status = new Status(IStatus.ERROR, GerritCorePlugin.PLUGIN_ID, "Unable to set the starred, received", e); throw new CoreException(status); } }</code><technical_language>setStarred a name imo</technical_language>

Target:
public void setStarred(TaskRepository taskRepository, String taskID, boolean starred) throws CoreException { GerritClient client = getClient(taskRepository); SaveStarredRequest saveStarRequest = new SaveStarredRequest(taskRepository, taskID, starred); try { client.setStarred(saveStarRequest.getReviewId(), starred, null); } catch (GerritException e) { Status status = new Status(IStatus.ERROR, GerritCorePlugin.PLUGIN_ID, "Unable to set the starred, received", e); throw new CoreException(status); } }
Source:
<code>public boolean isClosed() { final Status currentStatus = this.updateAndGetStatus(); <START> return currentStatus == Status.CLOSED; <END> }</code><technical_language>Update this method return true if status is HALF_OPEN</technical_language>

Target:
public boolean isClosed() { final Status currentStatus = this.updateAndGetStatus(); return currentStatus != Status.OPEN; }
Source:
<code>protected void initQualifiers(Set<Annotation> qualifiers) { if (qualifiers.isEmpty()) { this.qualifiers = DEFAULT_QUALIFIERS; } else { <START> Set<Annotation> normalizedQualifiers = new HashSet<Annotation>(qualifiers.size() + 2); <END> if (qualifiers.size() == 1) { if (qualifiers.iterator().next().annotationType().equals(Named.class)) { normalizedQualifiers.add(DefaultLiteral.INSTANCE); } } normalizedQualifiers.addAll(qualifiers); normalizedQualifiers.add(AnyLiteral.INSTANCE); if (name != null && normalizedQualifiers.remove(NamedLiteral.DEFAULT)) { normalizedQualifiers.add(new NamedLiteral(name)); } this.qualifiers = SharedObjectCache.instance(manager).getSharedSet(normalizedQualifiers); } }</code><technical_language>org.jboss.weld.util.collections.ImmutableSet.Builder</technical_language>

Target:
protected void initQualifiers(Set<Annotation> qualifiers) { if (qualifiers.isEmpty()) { this.qualifiers = DEFAULT_QUALIFIERS; } else { ImmutableSet.Builder<Annotation> normalizedQualifiers = ImmutableSet.builder(); if (qualifiers.size() == 1 && qualifiers.iterator().next().annotationType().equals(Named.class)) { normalizedQualifiers.add(DefaultLiteral.INSTANCE); } for (Annotation annotation : qualifiers) { if (name != null && annotation.equals(NamedLiteral.DEFAULT)) { normalizedQualifiers.add(new NamedLiteral(name)); } else { normalizedQualifiers.add(annotation); } } normalizedQualifiers.add(AnyLiteral.INSTANCE); this.qualifiers = SharedObjectCache.instance(manager).getSharedSet(normalizedQualifiers.build()); } }
Source:
<code>public WebServer(Config config) { initServer(config); ServletContextHandler servletHandler = new ServletContextHandler(ServletContextHandler.SESSIONS); int sessionTimeout = config.getInteger("web.sessionTimeout"); if (sessionTimeout > 0) { servletHandler.getSessionHandler().setMaxInactiveInterval(sessionTimeout); } initApi(config, servletHandler); if (config.getBoolean("web.console")) { servletHandler.addServlet(new ServletHolder(new ConsoleServlet()), "/console/*"); } initWebApp(config, servletHandler); servletHandler.setErrorHandler(new ErrorHandler() { @Override protected void handleErrorPage( HttpServletRequest request, Writer writer, int code, String message) throws IOException { writer.write("<!DOCTYPE<html><head><title>Error</title></head><html><body>" + code + " - " + HttpStatus.getMessage(code) + "</body></html>"); } }); HandlerList handlers = new HandlerList(); initClientProxy(config, handlers); handlers.addHandler(servletHandler); GzipHandler gzipHandler = new GzipHandler(); gzipHandler.setHandler(handlers); <START> server.setHandler(gzipHandler); <END> }</code><technical_language>addHandler for GzipHandler</technical_language>

Target:
public WebServer(Config config) { initServer(config); ServletContextHandler servletHandler = new ServletContextHandler(ServletContextHandler.SESSIONS); int sessionTimeout = config.getInteger("web.sessionTimeout"); if (sessionTimeout > 0) { servletHandler.getSessionHandler().setMaxInactiveInterval(sessionTimeout); } initApi(config, servletHandler); if (config.getBoolean("web.console")) { servletHandler.addServlet(new ServletHolder(new ConsoleServlet()), "/console/*"); } initWebApp(config, servletHandler); servletHandler.setErrorHandler(new ErrorHandler() { @Override protected void handleErrorPage( HttpServletRequest request, Writer writer, int code, String message) throws IOException { writer.write("<!DOCTYPE<html><head><title>Error</title></head><html><body>" + code + " - " + HttpStatus.getMessage(code) + "</body></html>"); } }); HandlerList handlers = new HandlerList(); initClientProxy(config, handlers); handlers.addHandler(servletHandler); handlers.addHandler(new GzipHandler()); server.setHandler(handlers); }
Source:
<code>public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } if (!super.equals(obj)) { return false; } final Tag other = (Tag)obj; <START> return Objects.equals(this.getId(), other.getId()) && Objects.equals(this.lastBuilt, other.lastBuilt); <END> }</code><technical_language>(Hmmm, I original suggested fix wrong. <LINK_0> ) I for now, continue pattern. Create issue investigate affected issue described</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } if (!super.equals(obj)) { return false; } final Tag other = (Tag)obj; return Objects.equals(this.getId(), other.getId()); }
Source:
<code>public abstract @Nullable PcapPacket parseNextPacket() throws IOException, BadPcapFileException, BadPacketException; public abstract void skipNextPacket() throws IOException, BadPcapFileException; public abstract void seekPacket(long rank) throws IOException, BadPcapFileException; public synchronized long getTotalNbPackets() throws IOException, BadPcapFileException { if (fTotalNumberPackets == -1) { long rank = fCurrentRank; fCurrentRank = fFileIndex.floorKey(rank); <START> while (hasNextPacket()) { <END> skipNextPacket(); } fTotalNumberPackets = fCurrentRank; fCurrentRank = rank; seekPacket(rank); } return fTotalNumberPackets; }</code><technical_language>This method assumes file channel is positioned beginning of file</technical_language>

Target:
public abstract @Nullable PcapPacket parseNextPacket() throws IOException, BadPcapFileException, BadPacketException; public abstract void skipNextPacket() throws IOException, BadPcapFileException; public abstract void seekPacket(long rank) throws IOException, BadPcapFileException; public abstract PcapTimestampScale getTimestampPrecision(); public synchronized long getTotalNbPackets() throws IOException, BadPcapFileException { if (fTotalNumberPackets == -1) { long rank = fCurrentRank; fCurrentRank = fFileIndex.floorKey(rank); while (hasNextPacket()) { skipNextPacket(); } fTotalNumberPackets = fCurrentRank; fCurrentRank = rank; seekPacket(rank); } return fTotalNumberPackets; }
Source:
<code>public void unlock() { if (!this.localLock.isHeldByCurrentThread()) { throw new IllegalStateException("You do not own lock at " + this.lockKey); } if (this.localLock.getHoldCount() > 1) { this.localLock.unlock(); return; } try { if (!isAcquiredInThisProcess()) { <START> throw new IllegalStateException("Lock was released in the store due to expiration."); <END> } if (Thread.currentThread().isInterrupted()) { RedisLockRegistry.this.executor.execute(this::removeLockKey); } else { removeLockKey(); } if (logger.isDebugEnabled()) { logger.debug("Released lock; " + this); } } catch (Exception e) { ReflectionUtils.rethrowRuntimeException(e); } finally { this.localLock.unlock(); } }</code><technical_language>more explicit? ...due expiration. integrity of data protected this lock compromised.</technical_language>

Target:
public void unlock() { if (!this.localLock.isHeldByCurrentThread()) { throw new IllegalStateException("You do not own lock at " + this.lockKey); } if (this.localLock.getHoldCount() > 1) { this.localLock.unlock(); return; } try { if (!isAcquiredInThisProcess()) { throw new IllegalStateException("Lock was released in the store due to expiration. " + "The integrity of data protected by this lock may have been compromised."); } if (Thread.currentThread().isInterrupted()) { RedisLockRegistry.this.executor.execute(this::removeLockKey); } else { removeLockKey(); } if (logger.isDebugEnabled()) { logger.debug("Released lock; " + this); } } catch (Exception e) { ReflectionUtils.rethrowRuntimeException(e); } finally { this.localLock.unlock(); } }
Source:
<code><START> private void startMapCameraSpinningAnimation(@NonNull final LatLng mapCameraTargetLocation) { <END> animator = ValueAnimator.ofFloat(0, DESIRED_NUM_OF_SPINS * 360); animator.setDuration( DESIRED_NUM_OF_SPINS * DESIRED_SECONDS_PER_ONE_FULL_360_SPIN * 1000); animator.setInterpolator(new LinearInterpolator()); animator.setStartDelay(1000); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { Float newBearingValue = (Float) valueAnimator.getAnimatedValue(); mapboxMap.animateCamera(CameraUpdateFactory .newCameraPosition(new CameraPosition.Builder() .target(new LatLng(mapCameraTargetLocation.getLatitude(), mapCameraTargetLocation.getLongitude())) .bearing(newBearingValue) .build())); } }); animator.start(); }</code><technical_language>need check if animator is null cancel creating a new animator</technical_language>

Target:
private void startMapCameraSpinningAnimation(@NonNull final LatLng mapCameraTargetLocation) { if (animator != null) { animator.cancel(); } animator = ValueAnimator.ofFloat(0, DESIRED_NUM_OF_SPINS * 360); animator.setDuration( DESIRED_NUM_OF_SPINS * DESIRED_SECONDS_PER_ONE_FULL_360_SPIN * 1000); animator.setInterpolator(new LinearInterpolator()); animator.setStartDelay(1000); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { Float newBearingValue = (Float) valueAnimator.getAnimatedValue(); mapboxMap.moveCamera(CameraUpdateFactory .newCameraPosition(new CameraPosition.Builder() .target(new LatLng(mapCameraTargetLocation.getLatitude(), mapCameraTargetLocation.getLongitude())) .bearing(newBearingValue) .build())); } }); animator.start(); }
Source:
<code>public void update() { briefcaseDir.ifPresent(path -> { Set<String> scannedFiles = new HashSet<>(); list(path.resolve("forms")) .map(this::getFormFilePath) <START> .peek(p -> scannedFiles.add(p.toString())) <END> .forEach(form -> { String hash = FileSystemUtils.getMd5Hash(form.toFile()); if (isFormNewOrChanged(form, hash)) { try { formDefByPath.put(form.toString(), new BriefcaseFormDefinition(form.getParent().toFile(), form.toFile())); hashByPath.put(form.toString(), hash); } catch (BadFormDefinition e) { log.warn("Can't parse form file", e); } } }); hashByPath.keySet().stream().filter(p -> !scannedFiles.contains(p)).collect(toList()).forEach(hashByPath::remove); formDefByPath.keySet().stream().filter(p -> !scannedFiles.contains(p)).collect(toList()).forEach(formDefByPath::remove); EventBus.publish(new CacheUpdateEvent()); save(); }); }</code><technical_language>benefit of peek here</technical_language>

Target:
public void update() { briefcaseDir.ifPresent(path -> { Set<String> scannedFiles = new HashSet<>(); list(path.resolve("forms")).forEach(formDir -> { Path form = getFormFilePath(formDir); scannedFiles.add(form.toString()); String hash = FileSystemUtils.getMd5Hash(form.toFile()); if (isFormNewOrChanged(form, hash)) { try { formDefByPath.put(form.toString(), new BriefcaseFormDefinition(form.getParent().toFile(), form.toFile())); hashByPath.put(form.toString(), hash); } catch (BadFormDefinition e) { log.warn("Can't parse form file", e); } } }); hashByPath.keySet().removeIf(negate(scannedFiles::contains)); formDefByPath.keySet().removeIf(negate(scannedFiles::contains)); EventBus.publish(new CacheUpdateEvent()); save(); }); }
Source:
<code><START> public boolean equals(Object obj) { <END> if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; JobSubjectEntityId other = (JobSubjectEntityId) obj; if (entityId == null) { if (other.entityId != null) return false; } else if (!entityId.equals(other.entityId)) return false; if (jobId == null) { if (other.jobId != null) return false; } else if (!jobId.equals(other.jobId)) return false; return true; }</code><technical_language>@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof JobSubjectEntityId)) { return false; } JobSubjectEntityId other = (JobSubjectEntityId) obj; return Objects.equals(entityId, other.entityId) && Objects.equals(jobId, other.jobId); }</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (this == obj) { return true; } if (!(obj instanceof JobSubjectEntityId)) { return false; } JobSubjectEntityId other = (JobSubjectEntityId) obj; return Objects.equals(entityId, other.entityId) && Objects.equals(jobId, other.jobId); }
Source:
<code>private void evaluateSiteBasedSubscription(Set<String> sourceIds, String metacardSourceId) { <START> String sourceId = <END> sourceIds .iterator() .next(); LOGGER.debug("subscription is a site-based subscription starting with site id {}", sourceId); if (sourceIds.contains(metacardSourceId)) { LOGGER.debug("event received from subscribed site"); evaluateEvent(event); } else { LOGGER.debug( "event received from remote site that is not in list of source IDs of subscription - not evaluating event"); } }</code><technical_language>performance hit here, walking iterator storing sourceId in a variable _only_ in debug. Instead... java if (LOGGER.isDebugEnabled()) { LOGGER.debug( "subscription is a site-based subscription starting site id {}", sourceIds.iterator().next()); }</technical_language>

Target:
private void evaluateSiteBasedSubscription(Set<String> sourceIds, String metacardSourceId) { if (LOGGER.isDebugEnabled()) { LOGGER.debug( "subscription is a site-based subscription starting with site id {}", sourceIds.iterator().next()); } if (sourceIds.contains(metacardSourceId)) { LOGGER.debug("event received from subscribed site"); evaluateEvent(event); } else { LOGGER.debug( "event received from remote site that is not in list of source IDs of subscription - not evaluating event"); } }
Source:
<code>public void whenPostEventOverflowsBufferThenUpdateItemStatus() throws Exception { <START> BatchItem item = new BatchItem(new JSONObject()); <END> item.setPartition("1"); List<BatchItem> batch = new ArrayList<>(); batch.add(item); Mockito .doThrow(BufferExhaustedException.class) .when(kafkaProducer) .send(any(), any()); try { kafkaTopicRepository.syncPostBatch(EXPECTED_PRODUCER_RECORD.topic(), batch); fail(); } catch (EventPublishingException e) { assertThat(item.getResponse().getPublishingStatus(), equalTo(EventPublishingStatus.FAILED)); assertThat(item.getResponse().getDetail(), equalTo("internal error")); } }</code><technical_language>final</technical_language>

Target:
public void whenPostEventOverflowsBufferThenUpdateItemStatus() throws Exception { final BatchItem item = new BatchItem(new JSONObject()); item.setPartition("1"); final List<BatchItem> batch = new ArrayList<>(); batch.add(item); Mockito .doThrow(BufferExhaustedException.class) .when(kafkaProducer) .send(any(), any()); try { kafkaTopicRepository.syncPostBatch(EXPECTED_PRODUCER_RECORD.topic(), batch); fail(); } catch (EventPublishingException e) { assertThat(item.getResponse().getPublishingStatus(), equalTo(EventPublishingStatus.FAILED)); assertThat(item.getResponse().getDetail(), equalTo("internal error")); } }
Source:
<code>private boolean areBricksInTheList(GlusterVolumeEntity volumeEntity, final List<GlusterBrickEntity> bricks, final List<GlusterBrickEntity> searchBricks) { boolean found = false; for (GlusterBrickEntity paramBrick : bricks) { GlusterBrickEntity paramBrickFromVolume = volumeEntity.getBrickWithId(paramBrick.getId()); if (paramBrickFromVolume == null) { paramBrickFromVolume = volumeEntity.getBrickWithQualifiedName(paramBrick.getQualifiedName()); } found = false; for (GlusterBrickEntity brick : searchBricks) { if (paramBrickFromVolume == null || paramBrickFromVolume.getId() == null) { return false; } if (paramBrickFromVolume.getId().equals(brick.getId())) { found = true; break; } if (!found) { <START> return false; <END> } } } return found; }</code><technical_language>this loop? check for brick in list</technical_language>

Target:
private boolean areBricksInTheList(GlusterVolumeEntity volumeEntity, final List<GlusterBrickEntity> bricks, final List<GlusterBrickEntity> searchBricks) { boolean found = false; for (GlusterBrickEntity paramBrick : bricks) { GlusterBrickEntity paramBrickFromVolume = volumeEntity.getBrickWithId(paramBrick.getId()); if (paramBrickFromVolume == null) { paramBrickFromVolume = volumeEntity.getBrickWithQualifiedName(paramBrick.getQualifiedName()); } found = false; for (GlusterBrickEntity brick : searchBricks) { if (paramBrickFromVolume == null || paramBrickFromVolume.getId() == null) { return false; } if (paramBrickFromVolume.getId().equals(brick.getId())) { found = true; break; } } if (!found) { return false; } } return found; }
Source:
<code>private String createDanglingImage() { CreateContainerResponse container = dockerClient.createContainerCmd("busybox").withCmd("sleep", "9999").exec(); LOG.info("Created container: {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); dockerClient.startContainerCmd(container.getId()).exec(); LOG.info("Committing container {}", container.toString()); String imageId = dockerClient.commitCmd(container.getId()).exec(); dockerClient.stopContainerCmd(container.getId()).exec(); dockerClient.removeContainerCmd(container.getId()).exec(); return imageId; <START> }} <END></code><technical_language>undo</technical_language>

Target:
private String createDanglingImage() { CreateContainerResponse container = dockerClient.createContainerCmd("busybox").withCmd("sleep", "9999").exec(); LOG.info("Created container: {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); dockerClient.startContainerCmd(container.getId()).exec(); LOG.info("Committing container {}", container.toString()); String imageId = dockerClient.commitCmd(container.getId()).exec(); dockerClient.stopContainerCmd(container.getId()).exec(); dockerClient.removeContainerCmd(container.getId()).exec(); return imageId; }
Source:
<code>public void setBreed(boolean breed) { if (breed) { setAge(AGE_ADULT); } else if (isAdult()) { <START> setAge(6000); <END> } }</code><technical_language>constant for this</technical_language>

Target:
public void setBreed(boolean breed) { if (breed) { setAge(AGE_ADULT); } else if (isAdult()) { setAge(BREEDING_AGE); } }
Source:
<code>public void load(GlowItemFrame entity, CompoundTag tag) { super.load(entity, tag); if (tag.isInt("Facing")) { entity.setFacingDirectionNumber((tag.getInt("Facing"))); } if (tag.isCompound("Item")) { <START> entity.setIteminFrame(NbtSerialization.readItem(tag.getCompound("Item"))); <END> } if (tag.isInt("Rotation")) { entity.setRotationAngle((tag.getInt("Rotation") * 45)); } }</code><technical_language>build failing capitalization, s/setIteminFrame/setItemInFrame/</technical_language>

Target:
public void load(GlowItemFrame entity, CompoundTag tag) { super.load(entity, tag); if (tag.isInt("Facing")) { entity.setFacingDirectionNumber((tag.getInt("Facing"))); } if (tag.isCompound("Item")) { entity.setItemInFrame(NbtSerialization.readItem(tag.getCompound("Item"))); } if (tag.isInt("Rotation")) { entity.setRotationAngle((tag.getInt("Rotation") * 45)); } }
Source:
<code>public String getLocalName() { if (localName == null) { if (stereotypeHelper.isStereotypeComment(getNotationElement())) { return <START> "StereotypeComment"; <END> } } return super.getLocalName(); }</code><technical_language>a constant</technical_language>

Target:
public String getLocalName() { if (localName == null) { if (stereotypeHelper.isStereotypeComment(getNotationElement())) { return STEREOTYPE_COMMENT; } } return super.getLocalName(); }
Source:
<code>void collectStaticMetrics(Collection<ProbeInstance> probeInstances) { for (ProbeInstance probeInstance : probeInstances) { ProbeFunction function = probeInstance.function; if (function instanceof LongProbeFunction) { collectLong(probeInstance.source, probeInstance.name, (LongProbeFunction) function); } else if (function instanceof DoubleProbeFunction) { collectDouble(probeInstance.source, probeInstance.name, (DoubleProbeFunction) function); } } <START> } <END></code><technical_language>Is other type of ProbeFunction expected</technical_language>

Target:
void collectStaticMetrics(Collection<ProbeInstance> probeInstances) { for (ProbeInstance probeInstance : probeInstances) { ProbeFunction function = probeInstance.function; if (function instanceof LongProbeFunction) { collectLong(probeInstance.source, probeInstance.name, (LongProbeFunction) function); } else if (function instanceof DoubleProbeFunction) { collectDouble(probeInstance.source, probeInstance.name, (DoubleProbeFunction) function); } else { throw new IllegalStateException("Unhandled ProbeFunction encountered: " + function.getClass().getName()); } } }