auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testWriteAttributeWithCredentialReferenceWithStoreOnly() throws Exception { try { getNonEmptyCredentialStore(); addKeyStoreWithCredentialReference(KS_NAME, NON_EMPTY_CS_NAME, EXISTING_ALIAS, null, true); testWriteCredentialReferenceAttribute("key-store", KS_NAME, NON_EMPTY_CS_NAME, null, null, true); <START> assertEquals(null, readAttribute(KS_NAME, CLEAR_TEXT_ATTRIBUTE_NAME)); <END> assertEquals(EXISTING_ALIAS, readAttribute(KS_NAME, ALIAS_ATTRIBUTE_NAME)); assertEquals(NON_EMPTY_CS_NAME, readAttribute(KS_NAME, STORE_ATTRIBUTE_NAME)); } finally { removeKeyStore(KS_NAME); } }</code><technical_language>simplified assertNull</technical_language>

Target:
public void testWriteAttributeWithCredentialReferenceWithStoreOnly() throws Exception { try { getNonEmptyCredentialStore(); addKeyStoreWithCredentialReference(KS_NAME, NON_EMPTY_CS_NAME, EXISTING_ALIAS, null, true); testWriteCredentialReferenceAttribute("key-store", KS_NAME, NON_EMPTY_CS_NAME, null, null, true); assertNull(readAttribute(KS_NAME, CLEAR_TEXT_ATTRIBUTE_NAME)); assertEquals(EXISTING_ALIAS, readAttribute(KS_NAME, ALIAS_ATTRIBUTE_NAME)); assertEquals(NON_EMPTY_CS_NAME, readAttribute(KS_NAME, STORE_ATTRIBUTE_NAME)); } finally { removeKeyStore(KS_NAME); } }
Source:
<code>public boolean isPageComplete() { if (availableBusinessData.isEmpty() && dataTypeSelectionOptions.isBusinessDataTypeSelected()) { return false; } if (availableDocuments.isEmpty() && !dataTypeSelectionOptions.isBusinessDataTypeSelected()) { return false; <START> } <END> if (selectedDataObservable.getValue() instanceof BusinessObjectData) { return isNoBusinessDataSelected() ? false : super.isPageComplete(); } if (selectedDataObservable.getValue() instanceof Document) { return super.isPageComplete(); } return super.isPageComplete(); }</code><technical_language><> if (availableBusinessData.isEmpty()) return false;</technical_language>

Target:
public boolean isPageComplete() { if (availableBusinessData.isEmpty() && isBusinessDataTypeSelected() || availableDocuments.isEmpty() && !isBusinessDataTypeSelected()) { return false; } if (selectedDataObservable.getValue() instanceof BusinessObjectData) { return isNoBusinessDataSelected() ? false : super.isPageComplete(); } if (selectedDataObservable.getValue() instanceof Document) { return super.isPageComplete(); } return super.isPageComplete(); }
Source:
<code>public void addOrUpdateExpression(final Expression expression) { <START> LOGGER.info() <END> .setMessage("This is a read only repository.") .log(); }</code><technical_language>above, lets throw exception here</technical_language>

Target:
public void addOrUpdateExpression(final Expression expression) { throw new UnsupportedOperationException("This is a read only repository."); }
Source:
<code>public boolean reserveSeatForTicket(String seatGroup, int seatNumber, Long ticketId) { <START> Seat seat = seatRepository.findBySeatGroupAndSeatNumber(seatGroup, seatNumber); <END> if (seat.isTaken()) { return false; } else { reserveSeat(seat, ticketId); return true; } }</code><technical_language>invalid requests (seatgroup/number exist)? I propose a (private?) service method handling this in a reusable way, throwing exceptions such</technical_language>

Target:
public boolean reserveSeatForTicket(String seatGroup, int seatNumber, Long ticketId) { Seat seat = getSeatBySeatGroupAndSeatNumber(seatGroup, seatNumber); if (seat.isTaken()) { return false; } else { reserveSeat(seat, ticketId); return true; } }
Source:
<code>public void generatesDeclarations(Boolean withExterns, String expected) { Options opts = new Options(!withExterns); List<SourceFile> sourceFiles = new ArrayList<>(); sourceFiles.add(SourceFile.fromFile("src/resources/base.js", UTF_8)); for (File nonroot : getSubject().nonroots) { sourceFiles.add(SourceFile.fromFile(nonroot, UTF_8)); } List<String> roots = new ArrayList<>(); roots.add("src/resources/base.js"); for (File root : getSubject().roots) { sourceFiles.add(SourceFile.fromFile(root, UTF_8)); roots.add(root.getPath()); } <START> <END> String actual = new DeclarationGenerator(opts) .generateDeclarations(sourceFiles, NO_EXTERNS, new Depgraph(roots)); actual = DeclarationGenerator.GOLDEN_FILE_COMMENTS_REGEXP.matcher(actual).replaceAll(""); if (!actual.equals(expected)) { failureStrategy.failComparing("compilation result doesn't match", expected, actual); } }</code><technical_language>surely empty line enough</technical_language>

Target:
public void generatesDeclarations(Boolean withExterns, String expected) { Options opts = new Options(!withExterns); List<SourceFile> sourceFiles = new ArrayList<>(); if (!getSubject().roots.get(0).getName().equals("base.js")) { sourceFiles.add(SourceFile.fromFile("src/test/java/com/google/javascript/clutz/base.js", UTF_8)); } for (File nonroot : getSubject().nonroots) { sourceFiles.add(SourceFile.fromFile(nonroot, UTF_8)); } List<String> roots = new ArrayList<>(); for (File root : getSubject().roots) { sourceFiles.add(SourceFile.fromFile(root, UTF_8)); roots.add(root.getPath()); } String actual = new DeclarationGenerator(opts) .generateDeclarations(sourceFiles, NO_EXTERNS, new Depgraph(roots)); actual = DeclarationGenerator.GOLDEN_FILE_COMMENTS_REGEXP.matcher(actual).replaceAll(""); if (!actual.equals(expected)) { failureStrategy.failComparing("compilation result doesn't match", expected, actual); } }
Source:
<code>private static List<VariableTree> matchingTypesWrongOrder(ParametersList formalParameterList, List<IdentifierTree> argumentList) { Iterator<IdentifierTree> argumentsIterator = argumentList.stream().filter(Objects::nonNull).iterator(); List<VariableTree> misplacedParameters = new ArrayList<>(); while (argumentsIterator.hasNext()) { IdentifierTree argument = argumentsIterator.next(); int index = formalParameterList.indexOf(argument.name().toLowerCase(Locale.ENGLISH)); Type formalType = formalParameterList.typeOfIndex(index); Type argType = argument.symbolType(); if (!formalType.is(argType.fullyQualifiedName()) || formalType.isUnknown() || argType.isUnknown()) { <START> return new ArrayList<>(); <END> } if (argumentList.indexOf(argument) != index) { misplacedParameters.add(formalParameterList.parameterAt(index)); } } if (misplacedParameters.size() >= 2) { return misplacedParameters; } return new ArrayList<>(); }</code><technical_language>I prefer Collections.emptyList() returned collection unmodifiable other methods</technical_language>

Target:
private static List<VariableTree> matchingTypesWrongOrder(ParametersList formalParameterList, List<IdentifierTree> argumentList) { Iterator<IdentifierTree> argumentsIterator = argumentList.stream().filter(Objects::nonNull).iterator(); List<VariableTree> misplacedParameters = new ArrayList<>(); while (argumentsIterator.hasNext()) { IdentifierTree argument = argumentsIterator.next(); int index = formalParameterList.indexOf(argument.name().toLowerCase(Locale.ENGLISH)); Type formalType = formalParameterList.typeOfIndex(index); Type argType = argument.symbolType(); if (!formalType.is(argType.fullyQualifiedName()) || formalType.isUnknown() || argType.isUnknown()) { return Collections.emptyList(); } if (argumentList.indexOf(argument) != index) { misplacedParameters.add(formalParameterList.parameterAt(index)); } } if (misplacedParameters.size() >= 2) { return misplacedParameters; } return Collections.emptyList(); }
Source:
<code>public boolean filter(String fromUrl, String toUrl) { if (exemptions != null) { for (Pattern pattern : exemptions) { <START> if (pattern.matcher(toUrl).matches()) { <END> return true; } } } return false; }</code><technical_language>possibly Pattern.find() instead of Pattern.matches(): - patterns shorter: \.jpg$ instead of .*\.jpg (or .*\.jpg$) - (more important) syntax for urlfilter-regex rules</technical_language>

Target:
public boolean filter(String fromUrl, String toUrl) { return this.filter(toUrl) != null; }
Source:
<code>public void duplicateForm( ModelMap model, HttpServletRequest request, HttpServletResponse response, @RequestParam(required = true, value = "formId") Integer formId, @RequestParam(required = true, value = "patientId") Integer patientId, @RequestParam(required = true, value = "date") String date, @RequestParam(required = false, value = "dateFormat") String dateFormat) throws Exception { response.setContentType("text/html"); ServletOutputStream out = response.getOutputStream(); List<Locale> l = new Vector<Locale>(); l.add(Context.getLocale()); List<Encounter> encounters = Context.getEncounterService().getEncountersByPatientId(patientId); SimpleDateFormat dateFormatter; if (dateFormat != null) { dateFormatter = new SimpleDateFormat(dateFormat); } else { dateFormatter = Context.getDateFormat(); } Date dateToCheck = dateFormatter.parse(date); boolean duplicate = false; for(Encounter enc: encounters) { if(enc.getForm() != null) { String encounterDate = dateFormatter.format(enc.getEncounterDatetime()); <START> Form encForm = enc.getForm(); <END> HtmlForm htmlForm = HtmlFormEntryUtil.getService().getHtmlFormByForm(encForm); if(htmlForm != null && htmlForm.getId().equals(formId) && dateToCheck.compareTo(dateFormatter.parse(encounterDate)) == 0) { duplicate = true; } } } if(duplicate) { out.print("true"); } else { out.print("false"); } }</code><technical_language>Move this line surrounding "if" test result in if statement, instead of calling enc.getForm() twice</technical_language>

Target:
public void duplicateForm( ModelMap model, HttpServletRequest request, HttpServletResponse response, @RequestParam(required = true, value = "formId") Integer formId, @RequestParam(required = true, value = "patientId") Integer patientId, @RequestParam(required = true, value = "date") String date, @RequestParam(required = false, value = "dateFormat") String dateFormat) throws Exception { response.setContentType("text/html"); ServletOutputStream out = response.getOutputStream(); List<Locale> l = new Vector<Locale>(); l.add(Context.getLocale()); List<Encounter> encounters = Context.getEncounterService().getEncountersByPatientId(patientId); SimpleDateFormat dateFormatter; if (dateFormat != null) { dateFormatter = new SimpleDateFormat(dateFormat); } else { dateFormatter = Context.getDateFormat(); } Date dateToCheck = dateFormatter.parse(date); boolean duplicate = false; for(Encounter enc: encounters) { Form encForm = enc.getForm(); if(encForm != null) { String encounterDate = dateFormatter.format(enc.getEncounterDatetime()); HtmlForm htmlForm = HtmlFormEntryUtil.getService().getHtmlFormByForm(encForm); if(htmlForm != null && htmlForm.getId().equals(formId) && dateToCheck.compareTo(dateFormatter.parse(encounterDate)) == 0) { duplicate = true; } } } if(duplicate) { out.print("true"); } else { out.print("false"); } }
Source:
<code>public SpoolingResultIterator(ResultIterator scanner, MemoryManager mm, int thresholdBytes, RowCounter rowCounter) throws SQLException { boolean success = false; boolean usedOnDiskIterator = false; final MemoryChunk chunk = mm.allocate(0, thresholdBytes); File tempFile = null; try { int size = (int)chunk.getSize(); tempFile = File.createTempFile("ResultSpooler",".bin"); DeferredFileOutputStream spoolTo = new DeferredFileOutputStream(size, tempFile) { @Override protected void thresholdReached() throws IOException { super.thresholdReached(); chunk.close(); } }; DataOutputStream out = new DataOutputStream(spoolTo); int maxSize = 0; for (Tuple result = scanner.next(); result != null; result = scanner.next()) { int length = TupleUtil.write(result, out); maxSize = Math.max(length, maxSize); rowCount += rowCounter.calculate(result); } spoolTo.close(); if (spoolTo.isInMemory()) { byte[] data = spoolTo.getData(); chunk.resize(data.length); spoolFrom = new InMemoryResultIterator(data, chunk); } else { spoolFrom = new OnDiskResultIterator(maxSize, spoolTo.getFile()); usedOnDiskIterator = true; } <START> success = true; <END> } catch (IOException e) { throw SQLExceptionInfo.getNewInfoObject(SQLExceptionCodeEnum.IO_EXCEPTION).genWrappedException(e); } finally { try { scanner.close(); } finally { try { if (!usedOnDiskIterator) { tempFile.delete(); } } finally { if (!success) { chunk.close(); } } } } }</code><technical_language>lose exceptions here. other examples SQLException.setNextException() capture nested exceptions modify this those</technical_language>

Target:
public SpoolingResultIterator(ResultIterator scanner, MemoryManager mm, int thresholdBytes, RowCounter rowCounter) throws SQLException { boolean success = false; boolean usedOnDiskIterator = false; final MemoryChunk chunk = mm.allocate(0, thresholdBytes); File tempFile = null; try { int size = (int)chunk.getSize(); tempFile = File.createTempFile("ResultSpooler",".bin"); DeferredFileOutputStream spoolTo = new DeferredFileOutputStream(size, tempFile) { @Override protected void thresholdReached() throws IOException { super.thresholdReached(); chunk.close(); } }; DataOutputStream out = new DataOutputStream(spoolTo); int maxSize = 0; for (Tuple result = scanner.next(); result != null; result = scanner.next()) { int length = TupleUtil.write(result, out); maxSize = Math.max(length, maxSize); rowCount += rowCounter.calculate(result); } spoolTo.close(); if (spoolTo.isInMemory()) { byte[] data = spoolTo.getData(); chunk.resize(data.length); spoolFrom = new InMemoryResultIterator(data, chunk); } else { spoolFrom = new OnDiskResultIterator(maxSize, spoolTo.getFile()); usedOnDiskIterator = true; } success = true; } catch (IOException e) { throw new PhoenixIOException(e); } finally { try { scanner.close(); } finally { try { if (!usedOnDiskIterator) { tempFile.delete(); } } finally { if (!success) { chunk.close(); } } } } }
Source:
<code>public boolean looselyMatch(URIish url, URIish urIish) { LOGGER.log(Level.FINE, "repo scheme: {0}", urIish.getScheme()); if ("ssh".equalsIgnoreCase(urIish.getScheme().toLowerCase())) { int indexOfLastSlash = url.getPath().lastIndexOf('/'); int indexOfLastButOneSlash = url.getPath().lastIndexOf('/', indexOfLastSlash - 1); String projectRepoPath = url.getPath().substring(indexOfLastButOneSlash); url = url.setPath(projectRepoPath); } else { <START> urIish = urIish.setPath(urIish.getPath().replaceFirst("/scm", "")); <END> } LOGGER.log(Level.FINE, "Trying to match {0} ", urIish.toString() + "<-->" + url.toString()); return GitStatus.looselyMatches(urIish, url); }</code><technical_language>("/scm/", "/") instead in case a unfortunate name there. For example <LINK_0> update unit tests accordingly</technical_language>

Target:
public boolean looselyMatch(URIish url, URIish urIish) { LOGGER.log(Level.FINE, "repo scheme: {0}", urIish.getScheme()); if ("ssh".equalsIgnoreCase(urIish.getScheme().toLowerCase())) { int indexOfLastSlash = url.getPath().lastIndexOf('/'); int indexOfLastButOneSlash = url.getPath().lastIndexOf('/', indexOfLastSlash - 1); String projectRepoPath = url.getPath().substring(indexOfLastButOneSlash); url = url.setPath(projectRepoPath); } else { urIish = urIish.setPath(urIish.getPath().replaceFirst("/scm/", "/")); if (StringUtils.isEmpty(url.getHost())) { urIish = urIish.setHost(url.getHost()); } } LOGGER.log(Level.FINE, "Trying to match {0} ", urIish.toString() + "<-->" + url.toString()); return GitStatus.looselyMatches(urIish, url); }
Source:
<code>protected void firstListenerAdded() { <START> if (!isDisposed()) { if (listener == null) { <END> listener = property .adaptListener(new ISimplePropertyListener<SetDiff<E>>() { @Override public void handleEvent( final SimplePropertyEvent<SetDiff<E>> event) { if (!isDisposed() && !updating) { getRealm().exec(new Runnable() { @Override public void run() { if (event.type == SimplePropertyEvent.CHANGE) { modCount++; notifyIfChanged(event.diff); } else if (event.type == SimplePropertyEvent.STALE && !stale) { stale = true; fireStale(); } } }); } } }); } getRealm().exec(new Runnable() { @Override public void run() { cachedSet = new HashSet<>(getSet()); stale = false; if (listener != null) listener.addTo(source); } }); } }</code><technical_language>combine conditions of 'if' statements</technical_language>

Target:
protected void firstListenerAdded() { if (!isDisposed() && listener == null) { listener = property.adaptListener(new ISimplePropertyListener<SetDiff<E>>() { @Override public void handleEvent(final SimplePropertyEvent<SetDiff<E>> event) { if (!isDisposed() && !updating) { getRealm().exec(new Runnable() { @Override public void run() { if (event.type == SimplePropertyEvent.CHANGE) { modCount++; notifyIfChanged(event.diff); } else if (event.type == SimplePropertyEvent.STALE && !stale) { stale = true; fireStale(); } } }); } } }); } getRealm().exec(new Runnable() { @Override public void run() { cachedSet = new HashSet<>(getSet()); stale = false; if (listener != null) listener.addTo(source); } }); }
Source:
<code>public RMStateDelta getRMStateDelta(@HeaderParam("sessionid") String sessionId, @HeaderParam("clientCounter") @DefaultValue("-1") String clientCounter) throws NotConnectedException { checkAccess(sessionId); long counter = Integer.valueOf(clientCounter); <START> return RMStateCaching.getRMInitialState(counter); <END> }</code><technical_language>rename this method (e.g. RMStateCaching.getRMStateDelta(counter)), wish</technical_language>

Target:
public RMStateDelta getRMStateDelta(@HeaderParam("sessionid") String sessionId, @HeaderParam("clientCounter") @DefaultValue("-1") String clientCounter) throws NotConnectedException { checkAccess(sessionId); long counter = Integer.valueOf(clientCounter); return RMStateCaching.getRMStateDelta(counter); }
Source:
<code>private PAPropertyString createNodeSourceProperty() { <START> PAPropertyString nodeSourceNameProperty = new PAPropertyString("proactive.node.nodesource", false, "local"); <END> nodeSourceNameProperty.setValue(System.getProperty("proactive.node.nodesource")); return nodeSourceNameProperty; }</code><technical_language>default for a node source is "Default" (when node is deployed proactive-node command agent speicifying node-source parameter)</technical_language>

Target:
private PAPropertyString createNodeSourceProperty() { PAPropertyString nodeSourceNameProperty = new PAPropertyString("proactive.node.nodesource", false, "Default"); try { nodeSourceNameProperty.setValue(System.getProperty("proactive.node.nodesource")); } catch (NullPointerException npe) { logger.warn("System property proactive.node.nodesource can't be found."); } return nodeSourceNameProperty; }
Source:
<code>public FieldSolver clone() { SimpleSolver clone = new SimpleSolver(); <START> clone.copyBaseClassFields(this); <END> clone.solveForE = solveForE; clone.solveForB = solveForB; return clone; }</code><technical_language>I clone step avoid potential bugs in future</technical_language>

Target:
public FieldSolver clone() { SimpleSolver clone = new SimpleSolver(); clone.copyBaseClassFields(this); clone.timeStep = timeStep; clone.solveForE = solveForE; clone.solveForB = solveForB; return clone; }
Source:
<code>public static String toJSONStringV2(ClientResponse clientResponse) { JSONStringer js = new JSONStringer(); try { js.object(); js.keySymbolValuePair(JSON_STATUS_KEY, clientResponse.getStatus()); js.keySymbolValuePair(JSON_APPSTATUS_KEY, clientResponse.getAppStatus()); js.keySymbolValuePair(JSON_STATUSSTRING_KEY, clientResponse.getStatusString()); js.keySymbolValuePair(JSON_APPSTATUSSTRING_KEY, clientResponse.getAppStatusString()); js.key(JSON_RESULTS_KEY); js.object(); VoltTable[] results = clientResponse.getResults(); for (int i=0; i<results.length; i++) { js.key(String.valueOf(i)); VoltTable o = results[i]; o.toJSONStringerV2(js); } js.endObject(); js.endObject(); } catch (JSONException e) { <START> e.printStackTrace(); <END> throw new RuntimeException("Failed to serialize a parameter set to JSON.", e); } return js.toString(); }</code><technical_language>Printing exception stdout is ideal I remove this throwing exception original exception next line</technical_language>

Target:
public static String toJSONStringV2(ClientResponse clientResponse) throws JSONException { JSONStringer js = new JSONStringer(); js.object(); js.keySymbolValuePair(JSON_STATUS_KEY, clientResponse.getStatus()); js.keySymbolValuePair(JSON_APPSTATUS_KEY, clientResponse.getAppStatus()); js.keySymbolValuePair(JSON_STATUSSTRING_KEY, clientResponse.getStatusString()); js.keySymbolValuePair(JSON_APPSTATUSSTRING_KEY, clientResponse.getAppStatusString()); js.key(JSON_RESULTS_KEY); js.object(); VoltTable[] results = clientResponse.getResults(); for (int i=0; i<results.length; i++) { js.key(String.valueOf(i)); VoltTable o = results[i]; o.toJSONStringerV2(js); } js.endObject(); js.endObject(); return js.toString(); }
Source:
<code>protected boolean canDoAction() { VDS vds = getVds(); if (vds == null) { addCanDoActionMessage(VdcBllMessages.VDS_INVALID_SERVER_ID); return false; } if (!ObjectIdentityChecker.CanUpdateField(vds, "vds_group_id", vds.getstatus())) { addCanDoActionMessage(VdcBllMessages.VDS_STATUS_NOT_VALID_FOR_UPDATE); return false; } VDSGroup targetCluster = DbFacade.getInstance().getVdsGroupDAO().get(getParameters().getClusterId()); if (targetCluster == null) { addCanDoActionMessage(VdcBllMessages.VDS_CLUSTER_IS_NOT_VALID); return false; } if (getVdsGroup().getstorage_pool_id() != null <START> && isNumberOfVdsInStoragePoolExceed(getVdsGroup().getstorage_pool_id().getValue())) { <END> addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_EXCEEDED_MAXIMUM_NUMBER_OF_HOSTS_IN_DATA_CENTER); return false; } targetStoragePool = DbFacade.getInstance().getStoragePoolDAO().getForVdsGroup(targetCluster.getId()); if (targetStoragePool != null && targetStoragePool.getstorage_pool_type() == StorageType.LOCALFS) { if (!DbFacade.getInstance().getVdsStaticDAO().getAllForVdsGroup(getParameters().getClusterId()).isEmpty()) { addCanDoActionMessage(VdcBllMessages.VDS_CANNOT_ADD_MORE_THEN_ONE_HOST_TO_LOCAL_STORAGE); return false; } } return true; }</code><technical_language>If moving host cluster A cluster B DC operation succeed host a host id assigned it. check DC ID is verify number of hosts</technical_language>

Target:
protected boolean canDoAction() { VDS vds = getVds(); if (vds == null) { addCanDoActionMessage(VdcBllMessages.VDS_INVALID_SERVER_ID); return false; } if (!ObjectIdentityChecker.CanUpdateField(vds, "vds_group_id", vds.getstatus())) { addCanDoActionMessage(VdcBllMessages.VDS_STATUS_NOT_VALID_FOR_UPDATE); return false; } if (getTargetCluster() == null) { addCanDoActionMessage(VdcBllMessages.VDS_CLUSTER_IS_NOT_VALID); return false; } if (getVdsGroup().getstorage_pool_id() != null && !getVdsGroup().getstorage_pool_id().equals(getTargetCluster().getId()) && reachedMaxNumOfVdsInPool(getTargetCluster().getId().getValue())) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_EXCEEDED_MAXIMUM_NUMBER_OF_HOSTS_IN_DATA_CENTER); return false; } targetStoragePool = DbFacade.getInstance().getStoragePoolDAO().getForVdsGroup(getTargetCluster().getId()); if (targetStoragePool != null && targetStoragePool.getstorage_pool_type() == StorageType.LOCALFS) { if (!DbFacade.getInstance().getVdsStaticDAO().getAllForVdsGroup(getParameters().getClusterId()).isEmpty()) { addCanDoActionMessage(VdcBllMessages.VDS_CANNOT_ADD_MORE_THEN_ONE_HOST_TO_LOCAL_STORAGE); return false; } } if (getVdsGroup().supportsGlusterService()) { if (getGlusterUtils().hasBricks(getSourceCluster().getId())) { addCanDoActionMessage(VdcBllMessages.VDS_CANNOT_REMOVE_HOST_HAVING_GLUSTER_VOLUME); return false; } if (!hasUpServer(getSourceCluster())) { return false; } } if (getTargetCluster().supportsGlusterService() && !hasUpServer(getTargetCluster())) { return false; } return true; }
Source:
<code>public static Block registerBlock(Block block, ItemBlock item, String name) { if (Loader.instance().isInState(LoaderState.CONSTRUCTING)) { FMLLog.warning("The mod %s is attempting to register a block whilst it it being constructed. This is bad modding practice - please use a proper mod lifecycle event.", Loader.instance().activeModContainer()); } try { <START> assert block != null : "registerBlock: block cannot be null"; <END> GameData.getMain().registerBlock(block, name); if (item != null) { GameData.getMain().registerItem(item, name); GameData.getBlockItemMap().put(block, item); } return block; } catch (Exception e) { FMLLog.log(Level.ERROR, e, "Caught an exception during block registration"); throw new LoaderException(e); } }</code><technical_language>replace this a normal null check, throwing a nice exception if block is null</technical_language>

Target:
public static Block registerBlock(Block block, ItemBlock item, String name) { if (Loader.instance().isInState(LoaderState.CONSTRUCTING)) { FMLLog.warning("The mod %s is attempting to register a block whilst it it being constructed. This is bad modding practice - please use a proper mod lifecycle event.", Loader.instance().activeModContainer()); } try { Preconditions.checkNotNull(block, "block cannot be null"); GameData.getMain().registerBlock(block, name); if (item != null) { GameData.getMain().registerItem(item, name); GameData.getBlockItemMap().put(block, item); } return block; } catch (Exception e) { FMLLog.log(Level.ERROR, e, "Caught an exception during block registration"); throw new LoaderException(e); } }
Source:
<code>public GroupInfo format(GroupDescription.Basic group) throws ResourceNotFoundException, OrmException { GroupInfo info = new GroupInfo(); info.id = Url.encode(group.getGroupUUID().get()); info.name = Strings.emptyToNull(group.getName()); info.url = Strings.emptyToNull(group.getUrl()); info.options = new GroupOptionsInfo(group); AccountGroup g = GroupDescriptions.toAccountGroup(group); if (g != null) { info.description = Strings.emptyToNull(g.getDescription()); info.groupId = g.getId().get(); if (g.getOwnerGroupUUID() != null) { info.ownerId = Url.encode(g.getOwnerGroupUUID().get()); AccountGroup o = groupCache.get(g.getOwnerGroupUUID()); if (o != null) { info.owner = o.getName(); } } if (options.contains(MEMBERS) || options.contains(INCLUDES)) { <START> GroupResource r = new GroupResource(groupControlFactory.controlFor(group)); <END> if (options.contains(MEMBERS)) { info.members = listMembers.get().apply(r); } if (options.contains(INCLUDES)) { info.includes = listIncludes.get().apply(r); } } } return info; }</code><technical_language>This passed in, generated again. Rework caller give GroupResource</technical_language>

Target:
public GroupInfo format(GroupDescription.Basic group) throws ResourceNotFoundException, OrmException { GroupInfo info = init(group); if (options.contains(MEMBERS) || options.contains(INCLUDES)) { GroupResource rsrc = new GroupResource(groupControlFactory.controlFor(group)); initMembersAndIncludes(rsrc, info); } return info; }
Source:
<code>public void call(final Subscriber<? super T> subscriber) { lock.writeLock().lock(); if (subscriptionCount.incrementAndGet() == 1) { <START> source.connect(new Action1<Subscription>() { <END> @Override public void call(Subscription subscription) { baseSubscription = subscription; subscriber.add(disconnect()); source.unsafeSubscribe(subscriber); lock.writeLock().unlock(); } }); } else { lock.writeLock().unlock(); lock.readLock().lock(); subscriber.add(disconnect()); source.unsafeSubscribe(subscriber); lock.readLock().unlock(); } }</code><technical_language>put unlock in a finally clause Action1 if unsubscribed. E.g., java try { source.connect(new Action1<Subscription>() { @Override public void call(Subscription subscription) { baseSubscription = subscription; // handle unsubscribing base subscription subscriber.add(disconnect()); // ready subscribe source do source.unsafeSubscribe(subscriber); } }); } finally { // release write lock lock.writeLock().unlock(); }</technical_language>

Target:
public void call(final Subscriber<? super T> subscriber) { lock.lock(); if (subscriptionCount.incrementAndGet() == 1) { final AtomicBoolean writeLocked = new AtomicBoolean(true); try { source.connect(onSubscribe(subscriber, writeLocked)); } finally { if (writeLocked.get()) { lock.unlock(); } } } else { try { subscriber.add(disconnect()); source.unsafeSubscribe(subscriber); } finally { lock.unlock(); } } }
Source:
<code>public static IntervalList overlaps(final Collection<IntervalList> lists1, final Collection<IntervalList> lists2) { <START> final SAMFileHeader header = lists1.iterator().next().getHeader().clone(); <END> header.setSortOrder(SAMFileHeader.SortOrder.unsorted); final IntervalList overlapIntervals = new IntervalList(header); for (final IntervalList list : lists2) { SequenceUtil.assertSequenceDictionariesEqual(header.getSequenceDictionary(), list.getHeader().getSequenceDictionary()); overlapIntervals.addall(list.getIntervals()); } final OverlapDetector<Interval> detector = new OverlapDetector<>(0, 0); for (final Interval interval : overlapIntervals.sorted().uniqued()) { detector.addLhs(interval, interval); } final IntervalList merged = new IntervalList(header); for (final IntervalList list : lists1) { SequenceUtil.assertSequenceDictionariesEqual(header.getSequenceDictionary(), list.getHeader().getSequenceDictionary()); for (final Interval interval : list.getIntervals()) { if (detector.overlapsAny(interval)) { merged.add(interval); } } } return merged; }</code><technical_language>break empty list....but header work with...you grab header intervalList in lists2...but empty well.. Do need Collections of IntervalLists? this robust overlaps(final IntervalList lhs, final IntervalList rhs) caller addAll outside</technical_language>

Target:
public static IntervalList overlaps(final Collection<IntervalList> lists1, final Collection<IntervalList> lists2) { if(lists1.isEmpty()){ throw new SAMException("Cannot call overlaps with the first collection having empty list of IntervalLists."); } final SAMFileHeader header = lists1.iterator().next().getHeader().clone(); header.setSortOrder(SAMFileHeader.SortOrder.unsorted); final IntervalList overlapIntervals = new IntervalList(header); for (final IntervalList list : lists2) { SequenceUtil.assertSequenceDictionariesEqual(header.getSequenceDictionary(), list.getHeader().getSequenceDictionary()); overlapIntervals.addall(list.getIntervals()); } final OverlapDetector<Integer> detector = new OverlapDetector<>(0, 0); final int dummy = -1; for (final Interval interval : overlapIntervals.sorted().uniqued()) { detector.addLhs(dummy, interval); } final IntervalList merged = new IntervalList(header); for (final IntervalList list : lists1) { SequenceUtil.assertSequenceDictionariesEqual(header.getSequenceDictionary(), list.getHeader().getSequenceDictionary()); for (final Interval interval : list.getIntervals()) { if (detector.overlapsAny(interval)) { merged.add(interval); } } } return merged; }
Source:
<code>public Sort sort() { <START> return KSorts.MAP; <END> }</code><technical_language>I Sort KSorts Sort constants</technical_language>

Target:
public Sort sort() { return Sort.MAP; }
Source:
<code>private static boolean search(DetailAST root, String xpath, Deque<DetailAST> nodes) { boolean result = false; if (xpath.equals(XpathQueryGenerator.generateXpathQuery(root))) { nodes.push(root); result = true; } else { <START> if (root.hasChildren()) { <END> DetailAST child = root.getFirstChild(); while (child != null) { if (search(child, xpath, nodes)) { nodes.push(root); result = true; break; } child = child.getNextSibling(); } } } return result; }</code><technical_language>This if is redundant. root children, root.getFirstChild() return null entire loop skipped</technical_language>

Target:
private static boolean search(DetailAST root, String xpath, Deque<DetailAST> nodes) { boolean result = false; if (xpath.equals(XpathQueryGenerator.generateXpathQuery(root))) { nodes.push(root); result = true; } else { DetailAST child = root.getFirstChild(); while (child != null) { if (search(child, xpath, nodes)) { nodes.push(root); result = true; break; } child = child.getNextSibling(); } } return result; }
Source:
<code>private Server createServer(String zoneId, String availabilityZoneId) { ServerApi serverApi = api.getServerApiForZone(zoneId); CreateServerOptions options = new CreateServerOptions(); <START> if (availabilityZoneId != null) options = options.availabilityZone(availabilityZoneId); <END> ServerCreated server = serverApi.create(hostName, imageIdForZone(zoneId), flavorRefForZone(zoneId), options); awaitActive(serverApi).apply(server); return serverApi.get(server.getId()); }</code><technical_language>[minor] Formatting? if (availabilityZoneId != null) { options = options.availabilityZone(availabilityZoneId); }</technical_language>

Target:
private Server createServer(String zoneId, String availabilityZoneId) { ServerApi serverApi = api.getServerApiForZone(zoneId); CreateServerOptions options = new CreateServerOptions(); if (availabilityZoneId != null) { options = options.availabilityZone(availabilityZoneId); } ServerCreated server = serverApi.create(hostName, imageIdForZone(zoneId), flavorRefForZone(zoneId), options); awaitActive(serverApi).apply(server.getId()); return serverApi.get(server.getId()); }
Source:
<code>public long getLastExtentIndexId() throws Exception{ long lastIndex; Connection connection = connect(); String sql = "SELECT MAX(" + EXTENT_INDEX_ID + ") AS " + EXTENT_INDEX_ID + " FROM " + EXTENT_TABLE; try (PreparedStatement getLastIndex = connection.prepareStatement(sql)) { ResultSet results = getLastIndex.executeQuery(); if (results.next()) { lastIndex = results.getLong(EXTENT_INDEX_ID); } else { lastIndex = 0; } <START> } catch (SQLiteException e) { <END> throw new SQLiteException(e.getMessage() + ". SQL query was: " + sql, e.getResultCode()); } return lastIndex; }</code><technical_language>catch a JDBC exception instead? This runs multiple databases..</technical_language>

Target:
public long getLastExtentIndexId() throws Exception { long lastIndex; Connection connection = connect(); String sql = "SELECT MAX(" + EXTENT_INDEX_ID + ") AS " + EXTENT_INDEX_ID + " FROM " + EXTENT_TABLE; try (PreparedStatement getLastIndex = connection.prepareStatement(sql)) { ResultSet results = getLastIndex.executeQuery(); if (results.next()) { lastIndex = results.getLong(EXTENT_INDEX_ID); } else { lastIndex = 0; } } catch (SQLException e) { throw new SQLException(e.getMessage() + ". SQL query was: " + sql, e); } return lastIndex; }
Source:
<code>public void areUniqueAndOrderedUUID() { final int iterations = PARAMETERS.NUM_ITERATIONS_MODERATE; OrderedGuidGenerator guidGenerator = new CorfuGuidGenerator(getDefaultRuntime()); <START> UUID lastValue = new UUID(0,0); <END> HashSet<UUID> uniq = new HashSet<>(iterations); for (int i = 0; i < iterations; i++) { UUID current = guidGenerator.nextUUID(); lastValue = current; assertThat(uniq).doesNotContain(current); uniq.add(current); } }</code><technical_language>lastValue is used, order is checked</technical_language>

Target:
public void areUniqueAndOrderedUUID() { final int iterations = PARAMETERS.NUM_ITERATIONS_MODERATE; OrderedGuidGenerator guidGenerator = new CorfuGuidGenerator(getDefaultRuntime().connect()); UUID lastValue = new UUID(0,0); HashSet<UUID> uniq = new HashSet<>(iterations); for (int i = 0; i < iterations; i++) { UUID current = guidGenerator.nextUUID(); assertThat(uniq).doesNotContain(current); assertThat(current).isGreaterThan(lastValue); lastValue = current; uniq.add(current); } }
Source:
<code><START> private void convertStitchPointsUnit(ArrayList<PointF> stitchPoints) { <END> DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics(); Project project = ProjectManager.getInstance().getCurrentProject(); Float inchMmFactor = 25.4f; Float dotOneMmFactor = 10.0f; Float aspectRatioMultiplierX = (float) metrics.widthPixels / project.getXmlHeader().getVirtualScreenWidth(); Float aspectRatioMultiplierY = (float) metrics.heightPixels / project.getXmlHeader().getVirtualScreenHeight(); if (project.getScreenMode() == ScreenModes.MAXIMIZE) { if (aspectRatioMultiplierX > aspectRatioMultiplierY) { aspectRatioMultiplierX = aspectRatioMultiplierY; } else { aspectRatioMultiplierY = aspectRatioMultiplierX; } } for (PointF stitch: stitchPoints) { PointF stitchUnitMm = new PointF(); stitchUnitMm.x = stitch.x * inchMmFactor * dotOneMmFactor * aspectRatioMultiplierX / metrics.densityDpi; stitchUnitMm.y = stitch.y * inchMmFactor * dotOneMmFactor * aspectRatioMultiplierY / metrics.densityDpi; this.stitchPoints.add(stitchUnitMm); } }</code><technical_language>calling method convert fitting return something. also, convert is filling points member stitchPoints (where parameter named stitchPoints isnt helping readability)</technical_language>

Target:
private ArrayList<PointF> convertStitchPointsUnit(ArrayList<PointF> stitchPoints) { ArrayList<PointF> convertedStitchPoints = new ArrayList<>(); for (PointF stitch: stitchPoints) { PointF stitchUnitMm = new PointF(); stitchUnitMm.x = Math.round(stitch.x * STITCH_POINT_UNIT_FACTOR); stitchUnitMm.y = Math.round(stitch.y * STITCH_POINT_UNIT_FACTOR); convertedStitchPoints.add(stitchUnitMm); } return convertedStitchPoints; }
Source:
<code>private PushShuffleReceiverImpl( final ShuffleDescription shuffleDescription, final DataReceiver<K, V> dataReceiver, final ESControlMessageSender controlMessageSender, @Parameter(ReceiverTimeout.class) final long receiverTimeout) { dataReceiver.registerTupleMessageHandler(new TupleMessageHandler()); this.shuffleDescription = shuffleDescription; this.controlMessageSender = controlMessageSender; this.synchronizer = new ControlMessageSynchronizer(); this.receiverTimeout = receiverTimeout; this.completedSenderCount = new AtomicInteger(); final List<String> senderIdList = shuffleDescription.getSenderIdList(); this.senderNum = senderIdList.size(); this.senderStateMachineMap = new HashMap<>(senderNum); for (final String senderId : senderIdList) { <START> final StateMachine senderStateMachine = PushShuffleSenderImpl.createStateMachine(); <END> senderStateMachine.setState("SENDING"); senderStateMachineMap.put(senderId, senderStateMachine); } this.stateMachine = createStateMachine(); controlMessageSender.sendToManager(PushShuffleCode.RECEIVER_INITIALIZED); }</code><technical_language>More reason for state machine tight</technical_language>

Target:
private PushShuffleReceiverImpl( final ShuffleDescription shuffleDescription, final DataReceiver<K, V> dataReceiver, final ESControlMessageSender controlMessageSender, @Parameter(ReceiverTimeout.class) final long receiverTimeout) { dataReceiver.registerTupleMessageHandler(new TupleMessageHandler()); this.shuffleDescription = shuffleDescription; this.controlMessageSender = controlMessageSender; this.synchronizer = new ControlMessageSynchronizer(); this.receiverTimeout = receiverTimeout; this.completedSenderCount = new AtomicInteger(); final List<String> senderIdList = shuffleDescription.getSenderIdList(); this.totalNumSenders = senderIdList.size(); this.senderStateMachineMap = new HashMap<>(totalNumSenders); for (final String senderId : senderIdList) { final StateMachine senderStateMachine = PushShuffleSenderState.createStateMachine(); senderStateMachine.setState(PushShuffleSenderState.SENDING); senderStateMachineMap.put(senderId, senderStateMachine); } this.stateMachine = PushShuffleReceiverState.createStateMachine(); controlMessageSender.sendToManager(PushShuffleCode.RECEIVER_INITIALIZED); }
Source:
<code>public void processExpiration() { long start = 0; if (!Thread.currentThread().isInterrupted()) { try { if (trace) { log.trace("Purging data container of expired entries"); start = timeService.time(); } long currentTimeMillis = timeService.wallClockTime(); for (Iterator<InternalCacheEntry<K, V>> purgeCandidates = dataContainer.iteratorIncludingExpired(); purgeCandidates.hasNext();) { InternalCacheEntry<K, V> e = purgeCandidates.next(); if (e.canExpire()) { synchronized (e) { long lifespan = e.getLifespan(); if (ExpiryHelper.isExpiredMortal(lifespan, e.getCreated(), currentTimeMillis)) { <START> handleLifespanExpireEntry(e.getKey(), e.getValue(), lifespan, true); <END> } else if (ExpiryHelper.isExpiredTransient(e.getMaxIdle(), e.getLastUsed(), currentTimeMillis)) { super.handleInMemoryExpiration(e, currentTimeMillis); } } } } if (trace) { log.tracef("Purging data container completed in %s", Util.prettyPrintTime(timeService.timeDuration(start, TimeUnit.MILLISECONDS))); } } catch (Exception e) { log.exceptionPurgingDataContainer(e); } } if (!Thread.currentThread().isInterrupted()) { persistenceManager.purgeExpired(); } }</code><technical_language>need call this synchronized block</technical_language>

Target:
public void processExpiration() { long start = 0; if (!Thread.currentThread().isInterrupted()) { try { if (trace) { log.trace("Purging data container of expired entries"); start = timeService.time(); } long currentTimeMillis = timeService.wallClockTime(); for (Iterator<InternalCacheEntry<K, V>> purgeCandidates = dataContainer.iteratorIncludingExpired(); purgeCandidates.hasNext();) { InternalCacheEntry<K, V> e = purgeCandidates.next(); if (e.canExpire()) { boolean expiredMortal; boolean expiredTransient; V value; long lifespan; synchronized (e) { value = e.getValue(); lifespan = e.getLifespan(); expiredMortal = ExpiryHelper.isExpiredMortal(lifespan, e.getCreated(), currentTimeMillis); expiredTransient = ExpiryHelper.isExpiredTransient(e.getMaxIdle(), e.getLastUsed(), currentTimeMillis); } if (expiredMortal) { handleLifespanExpireEntry(e.getKey(), value, lifespan, true); } else if (expiredTransient) { super.handleInMemoryExpiration(e, currentTimeMillis); } } } if (trace) { log.tracef("Purging data container completed in %s", Util.prettyPrintTime(timeService.timeDuration(start, TimeUnit.MILLISECONDS))); } } catch (Exception e) { log.exceptionPurgingDataContainer(e); } } if (!Thread.currentThread().isInterrupted()) { persistenceManager.purgeExpired(); } }
Source:
<code>public void onItemClick(@ButtonId int id) { switch (id) { case CONTINUE: ProjectLoaderTask loaderTask = new ProjectLoaderTask(getActivity(), this); setShowProgressBar(true); loaderTask.execute(Utils.getCurrentProjectName(getActivity())); break; case NEW: new NewProjectDialogFragment().show(getFragmentManager(), NewProjectDialogFragment.TAG); break; case PROGRAMS: setShowProgressBar(true); startActivity(new Intent(getActivity(), ProjectListActivity.class)); break; case HELP: setShowProgressBar(true); startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(Constants.CATROBAT_HELP_URL))); break; case EXPLORE: setShowProgressBar(true); startActivity(new Intent(getActivity(), WebViewActivity.class)); break; case UPLOAD: Project currentProject = null; try { currentProject = XstreamSerializer.getInstance().loadProject(Utils.getCurrentProjectName(getActivity()), getActivity()); } catch (IOException | LoadingProjectException e) { Log.e(TAG, e.getMessage()); } <START> if (Utils.isDefaultProject(currentProject, getActivity())) { <END> ToastUtil.showError(getActivity(), R.string.error_upload_default_project); } else { setShowProgressBar(true); Intent intent = new Intent(getActivity(), ProjectUploadActivity.class) .putExtra(ProjectUploadActivity.PROJECT_NAME, Utils.getCurrentProjectName(getActivity())); startActivity(intent); } break; } }</code><technical_language>currentProject is null if exception occurred -> move this code try block</technical_language>

Target:
public void onItemClick(@ButtonId int id) { switch (id) { case CONTINUE: ProjectLoaderTask loaderTask = new ProjectLoaderTask(getActivity(), this); setShowProgressBar(true); loaderTask.execute(Utils.getCurrentProjectName(getActivity())); break; case NEW: new NewProjectDialogFragment().show(getFragmentManager(), NewProjectDialogFragment.TAG); break; case PROGRAMS: setShowProgressBar(true); startActivity(new Intent(getActivity(), ProjectListActivity.class)); break; case HELP: setShowProgressBar(true); startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(Constants.CATROBAT_HELP_URL))); break; case EXPLORE: setShowProgressBar(true); startActivity(new Intent(getActivity(), WebViewActivity.class)); break; case UPLOAD: String currentProjectName = Utils.getCurrentProjectName(getActivity()); try { Project currentProject = XstreamSerializer.getInstance().loadProject(currentProjectName, getActivity()); if (Utils.isDefaultProject(currentProject, getActivity())) { ToastUtil.showError(getActivity(), R.string.error_upload_default_project); } else { setShowProgressBar(true); Intent intent = new Intent(getActivity(), ProjectUploadActivity.class) .putExtra(ProjectUploadActivity.PROJECT_NAME, currentProjectName); startActivity(intent); } } catch (IOException | LoadingProjectException e) { Log.e(TAG, e.getMessage()); } break; } }
Source:
<code>public void testIndexExpressionIsNotInteger() throws Exception { <START> expectedException.expectMessage("No cast function found for return type undefined"); <END> assertNormalize("subscript(['Youri', 'Ruben'], '1')", isLiteral("Ruben")); }</code><technical_language>I this error message is understandable for users. Is improve here</technical_language>

Target:
public void testIndexExpressionIsNotInteger() throws Exception { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Base argument to subscript must be an object, not [Youri, Ruben]"); assertNormalize("subscript(['Youri', 'Ruben'], '1')", isLiteral("Ruben")); }
Source:
<code>private void sendError(ChannelHandlerContext ctx, String message, HttpResponseStatus status) { HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status); <START> response.setHeader(CONTENT_TYPE, "org/apache/tajo/storage/text/plain; charset=UTF-8"); <END> response.setContent( ChannelBuffers.copiedBuffer(message, CharsetUtil.UTF_8)); ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE); }</code><technical_language>intend change it</technical_language>

Target:
private void sendError(ChannelHandlerContext ctx, String message, HttpResponseStatus status) { HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status); response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8"); response.setContent( ChannelBuffers.copiedBuffer(message, CharsetUtil.UTF_8)); ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE); }
Source:
<code>public static HistoryPageInput getMostFittingInput( @NonNull IStructuredSelection selection, Object mandatoryObject) { Set<IResource> resources = getSelectedResourcesSet(selection); if (!resources.contains(mandatoryObject)) { return null; } <START> Repository repository = getRepository((IResource) mandatoryObject); <END> if (repository == null) { return null; } for (Iterator<IResource> it = resources.iterator(); it.hasNext();) { IResource resource = it.next(); if (getRepository(resource) != repository) { it.remove(); } } IResource[] resourceArray = resources.toArray(new IResource[resources .size()]); return new HistoryPageInput(repository, resourceArray); }</code><technical_language>ResourceUtil.getRepository(IResource)</technical_language>

Target:
public static HistoryPageInput getMostFittingInput( @NonNull IStructuredSelection selection, Object mandatoryObject) { Set<IResource> resources = getSelectedResourcesSet(selection); if (!resources.contains(mandatoryObject)) { return null; } Repository repository = ResourceUtil .getRepository((IResource) mandatoryObject); if (repository == null) { return null; } for (Iterator<IResource> it = resources.iterator(); it.hasNext();) { IResource resource = it.next(); if (ResourceUtil.getRepository(resource) != repository) { it.remove(); } } IResource[] resourceArray = resources.toArray(new IResource[resources .size()]); return new HistoryPageInput(repository, resourceArray); }
Source:
<code>private void loadPathNames() { pathToName = null; if (modulesConfig != null) { HashMap<String, String> pathNames = new <START> HashMap<>(modulesConfig .getSubsections(ConfigConstants.CONFIG_SUBMODULE_SECTION) <END> .size()); for (String name : modulesConfig .getSubsections(ConfigConstants.CONFIG_SUBMODULE_SECTION)) { pathNames.put(modulesConfig.getString( ConfigConstants.CONFIG_SUBMODULE_SECTION, name, ConfigConstants.CONFIG_KEY_PATH), name); } pathToName = pathNames; } }</code><technical_language>extracting this in a variable reuse in next statement</technical_language>

Target:
private void loadPathNames() { pathToName = null; if (modulesConfig != null) { HashMap<String, String> pathNames = new HashMap<>(); for (String name : modulesConfig .getSubsections(ConfigConstants.CONFIG_SUBMODULE_SECTION)) { pathNames.put(modulesConfig.getString( ConfigConstants.CONFIG_SUBMODULE_SECTION, name, ConfigConstants.CONFIG_KEY_PATH), name); } pathToName = pathNames; } }