auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void doTestEventsGeneratedCaseMediaDownloadSuccess(boolean enqueueDownloaded, int numEventsExpected) throws Exception { DownloadService.setDownloaderFactory(new StubDownloaderFactory(50, DownloadStatus::setSuccessful)); UserPreferences.setEnqueueDownloadedEpisodes(enqueueDownloaded); withFeedItemEventListener(feedItemEventListener -> { try { assertEquals(0, feedItemEventListener.getEvents().size()); assertFalse("The media in test should not yet been downloaded", DBReader.getFeedMedia(testMedia11.getId()).isDownloaded()); DownloadRequester.getInstance().downloadMedia(false, InstrumentationRegistry.getTargetContext(), true, testMedia11.getItem()); Awaitility.await() .atMost(5000, TimeUnit.MILLISECONDS) .until(() -> feedItemEventListener.getEvents().size() >= numEventsExpected); assertTrue("After media download has completed, FeedMedia object in db should indicate so.", DBReader.getFeedMedia(testMedia11.getId()).isDownloaded()); assertEquals("The FeedItem should have been " + (enqueueDownloaded ? "" : "not ") + "enqueued", enqueueDownloaded, DBReader.getQueueIDList().contains(testMedia11.getItem().getId())); } catch (ConditionTimeoutException cte) { fail("The expected FeedItemEvent (for media download complete) has not been posted. " + cte.getMessage()); } }); }

Target:
private void doTestEventsGeneratedCaseMediaDownloadSuccess(boolean enqueueDownloaded, int numEventsExpected) throws Exception { DownloadService.setDownloaderFactory(new StubDownloaderFactory(50, DownloadStatus::setSuccessful)); UserPreferences.setEnqueueDownloadedEpisodes(enqueueDownloaded); withFeedItemEventListener(feedItemEventListener -> { try { assertEquals(0, feedItemEventListener.getEvents().size()); assertFalse("The media in test should not yet been downloaded", DBReader.getFeedMedia(testMedia11.getId()).isDownloaded()); DownloadRequester.getInstance().downloadMedia(false, InstrumentationRegistry .getInstrumentation().getTargetContext(), true, testMedia11.getItem()); Awaitility.await() .atMost(5000, TimeUnit.MILLISECONDS) .until(() -> feedItemEventListener.getEvents().size() >= numEventsExpected); assertTrue("After media download has completed, FeedMedia object in db should indicate so.", DBReader.getFeedMedia(testMedia11.getId()).isDownloaded()); assertEquals("The FeedItem should have been " + (enqueueDownloaded ? "" : "not ") + "enqueued", enqueueDownloaded, DBReader.getQueueIDList().contains(testMedia11.getItem().getId())); } catch (ConditionTimeoutException cte) { fail("The expected FeedItemEvent (for media download complete) has not been posted. " + cte.getMessage()); } }); }
Source:
void findBySimpleProperty() { Airport vie = null; try { vie = new Airport("airports::vie", "vie", "loww"); vie = airportRepository.save(vie); List<Airport> airports = airportRepository.findAllByIata("vie"); assertEquals(1, airports.size()); System.out.println("findAllByIata(0): " + airports.get(0)); Airport airport1 = airportRepository.findById(airports.get(0).getId()).get(); assertEquals(airport1.getIata(), vie.getIata()); System.out.println("findById: " + airport1); Airport airport2 = airportRepository.findByIata(airports.get(0).getIata()); assertEquals(airport1.getId(), vie.getId()); System.out.println("findByIata: " + airport2); } finally { airportRepository.delete(vie); } }

Target:
void findBySimpleProperty() { Airport vie = null; try { vie = new Airport("airports::vie", "vie", "loww"); vie = airportRepository.save(vie); List<Airport> airports = airportRepository.findAllByIata("vie"); assertEquals(1, airports.size()); Airport airport1 = airportRepository.findById(airports.get(0).getId()).get(); assertEquals(airport1.getIata(), vie.getIata()); Airport airport2 = airportRepository.findByIata(airports.get(0).getIata()); assertEquals(airport1.getId(), vie.getId()); } finally { airportRepository.delete(vie); } }
Source:
Decoder getDecoder(byte[] value) { return DecoderFactory.get().binaryDecoder(value, this.skipBytes, value.length - this.skipBytes, null); }

Target:
Decoder getDecoder(byte[] value) throws SerDeException { try { return DecoderFactory.get().binaryDecoder(value, this.skipBytes, value.length - this.skipBytes, null); } catch (ArrayIndexOutOfBoundsException e) { throw new SerDeException("Skip bytes value is larger than the message length.", e); } }
Source:
private void addChangeset(long changesetId, long userId) { if (insertStatement == null) { insertStatement = statementContainer.add(dbCtx.prepareStatement(SQL_INSERT_CHANGESET)); insertTagStatement = statementContainer.add(dbCtx.prepareStatement(SQL_INSERT_CHANGESET_TAG)); } try { int prmIndex; prmIndex = 1; insertStatement.setLong(prmIndex++, changesetId); insertStatement.setLong(prmIndex++, userId); insertStatement.executeUpdate(); prmIndex = 1; insertTagStatement.setLong(++prmIndex, changesetId); insertTagStatement.executeUpdate(); knownChangesetIds.add(changesetId); if (knownChangesetIds.size() > MAX_CHANGESET_ID_CACHE_SIZE) { Iterator<Long> i = knownChangesetIds.iterator(); i.next(); i.remove(); } } catch (SQLException e) { throw new OsmosisRuntimeException("Unable to insert a new changeset for user with id " + userId + ".", e); } }

Target:
private void addChangeset(long changesetId, long userId) { if (insertStatement == null) { insertStatement = statementContainer.add(dbCtx.prepareStatement(SQL_INSERT_CHANGESET)); insertTagStatement = statementContainer.add(dbCtx.prepareStatement(SQL_INSERT_CHANGESET_TAG)); } try { int prmIndex; prmIndex = 0; insertStatement.setLong(++prmIndex, changesetId); insertStatement.setLong(++prmIndex, userId); insertStatement.executeUpdate(); prmIndex = 0; insertTagStatement.setLong(++prmIndex, changesetId); insertTagStatement.executeUpdate(); knownChangesetIds.add(changesetId); if (knownChangesetIds.size() > MAX_CHANGESET_ID_CACHE_SIZE) { Iterator<Long> i = knownChangesetIds.iterator(); i.next(); i.remove(); } } catch (SQLException e) { throw new OsmosisRuntimeException("Unable to insert a new changeset for user with id " + userId + ".", e); } }
Source:
public static AtBScenarioModifier Deserialize(String fileName) { AtBScenarioModifier resultingList = null; try { JAXBContext context = JAXBContext.newInstance(AtBScenarioModifier.class); Unmarshaller um = context.createUnmarshaller(); File xmlFile = new File(fileName); if(!xmlFile.exists()) { MekHQ.getLogger().warning(AtBScenarioModifier.class, "Deserialize", String.format("Specified file %d does not exist", fileName)); return null; } JAXBElement<AtBScenarioModifier> templateElement = um.unmarshal(new StreamSource(xmlFile), AtBScenarioModifier.class); resultingList = templateElement.getValue(); } catch(Exception e) { MekHQ.getLogger().error(ScenarioModifierManifest.class, "Deserialize", "Error Deserializing Scenario Modifier", e); } return resultingList; }

Target:
public static AtBScenarioModifier Deserialize(String fileName) { AtBScenarioModifier resultingList = null; try { JAXBContext context = JAXBContext.newInstance(AtBScenarioModifier.class); Unmarshaller um = context.createUnmarshaller(); File xmlFile = new File(fileName); if(!xmlFile.exists()) { MekHQ.getLogger().warning(AtBScenarioModifier.class, "Deserialize", String.format("Specified file %d does not exist", fileName)); return null; } Source inputSource = MekHqXmlUtil.createSafeXmlSource(new FileInputStream(xmlFile)); JAXBElement<AtBScenarioModifier> templateElement = um.unmarshal(inputSource, AtBScenarioModifier.class); resultingList = templateElement.getValue(); } catch(Exception e) { MekHQ.getLogger().error(ScenarioModifierManifest.class, "Deserialize", "Error Deserializing Scenario Modifier", e); } return resultingList; }
Source:
public DhcpClient(final String macAddress, final boolean relayMode, final String myIpAddress, final boolean extendedMode, final String requestIpAddress, final int timeout, final int retries, final Dhcpd dhcpd) { this.m_macAddress = macAddress; this.m_relayMode = relayMode; this.m_myIpAddress = myIpAddress; this.m_extendedMode = extendedMode; this.m_requestIpAddress = requestIpAddress; this.m_timeout = timeout; this.m_retries = retries; this.m_dhcpd = dhcpd; }

Target:
public DhcpClient(final String macAddress, final boolean relayMode, final String myIpAddress, final boolean extendedMode, final String requestIpAddress, final int timeout, final int retries, final Dhcpd dhcpd) { this.macAddress = macAddress; this.relayMode = relayMode; this.myIpAddress = myIpAddress; this.extendedMode = extendedMode; this.requestIpAddress = requestIpAddress; this.timeout = timeout; this.retries = retries; this.dhcpd = dhcpd; }
Source:
protected void postInit() { super.postInit(); modelChangeListener = new ModelChangeListener() { @Override public void notifyChange(ModelChangeNotification notification) { if (isDisposed) { return; } final EMFFormsStructuralChangeTester changeTester = getViewModelContext() .getService(EMFFormsStructuralChangeTester.class); if (changeTester.isStructureChanged(getVElement().getDomainModelReference(), getViewModelContext().getDomainModel(), notification)) { Display.getDefault().asyncExec(() -> { if (!isDisposed) { applyReadOnly(); applyEnable(); } }); } } }; if (getVElement().getDomainModelReference() != null) { getViewModelContext().registerDomainChangeListener(modelChangeListener); } applyEnable(); applyReadOnly(); if (isUnchangeableFeature()) { applyUnchangeableFeature(); } }

Target:
protected void postInit() { super.postInit(); modelChangeListener = new ModelChangeListener() { @Override public void notifyChange(ModelChangeNotification notification) { if (isDisposed) { return; } final EMFFormsStructuralChangeTester changeTester = getViewModelContext() .getService(EMFFormsStructuralChangeTester.class); if (changeTester.isStructureChanged(getVElement().getDomainModelReference(), getViewModelContext().getDomainModel(), notification)) { Display.getDefault().asyncExec(() -> { if (!isDisposed) { applyEnable(); } }); } } }; if (getVElement().getDomainModelReference() != null) { getViewModelContext().registerDomainChangeListener(modelChangeListener); } applyEnable(); applyReadOnly(); if (isUnchangeableFeature()) { applyUnchangeableFeature(); } }
Source:
public PaxosRuntimeConfiguration paxos() { if (optionalPaxos().isPresent()) { return optionalPaxos().get(); } return ImmutablePaxosRuntimeConfiguration.builder().build(); }

Target:
public PaxosRuntimeConfiguration paxos() { return ImmutablePaxosRuntimeConfiguration.builder().build(); }
Source:
private User toInternalUser(org.carlspring.strongbox.security.User user) { User internalUser = new User(); internalUser.setUsername(user.getUsername()); Credentials credentials = user.getCredentials(); EncryptionAlgorithms algorithms = EncryptionAlgorithms.valueOf(credentials.getEncryptionAlgorithm() .toUpperCase()); switch (algorithms) { case PLAIN: internalUser.setPassword(credentials.getPassword()); break; default: throw new UnsupportedOperationException(algorithms.toString()); } internalUser.setEnabled(true); internalUser.setRoles(user.getRoles()); internalUser.setSalt(user.getSeed() + ""); org.carlspring.strongbox.security.Features features = user.getFeatures(); if (features != null) { Features internalFeatures = new Features(); internalFeatures.setPerRepositoryAuthorities(new HashMap<>()); features.getStorages() .getStorages() .forEach( storage -> storage.getRepositories() .getRepositories() .forEach( repository -> { Set<String> privileges = new HashSet<>(); repository.getPrivileges() .getPrivileges() .forEach(privilege -> privileges.add(privilege.getName() .toUpperCase())); internalFeatures.getPerRepositoryAuthorities() .put(repository.getRepositoryId(), privileges); })); internalUser.setFeatures(internalFeatures); } return internalUser; }

Target:
private User toInternalUser(org.carlspring.strongbox.security.User user) { User internalUser = new User(); internalUser.setUsername(user.getUsername()); Credentials credentials = user.getCredentials(); EncryptionAlgorithms algorithms = EncryptionAlgorithms.valueOf(credentials.getEncryptionAlgorithm() .toUpperCase()); switch (algorithms) { case PLAIN: internalUser.setPassword(credentials.getPassword()); break; default: throw new UnsupportedOperationException(algorithms.toString()); } internalUser.setEnabled(true); internalUser.setRoles(user.getRoles()); internalUser.setSalt(user.getSeed() + ""); UserAccessModel userAccessModel = user.getUserAccessModel(); if (userAccessModel != null) { AccessModel internalAccessModel = new AccessModel(); userAccessModel.getStorages() .getStorages() .forEach(storage -> storage.getRepositories() .getRepositories() .forEach(repository -> processRepository(internalAccessModel, storage.getStorageId(), repository))); internalUser.setAccessModel(internalAccessModel); } return internalUser; }
Source:
public static Expression dateExpression(final String command) { return dateExpression(command, TimeZone.getDefault().getID(), ""); }

Target:
public static Expression dateExpression(final String command) { return dateExpression(command, null, null); }
Source:
private JComponent buildProgressBars() { FormLayout layout = new FormLayout( "pref, 3dlu, fill:0:grow", "p, 3dlu, p, 3dlu, p"); PanelBuilder builder = new PanelBuilder(layout); CellConstraints cc = new CellConstraints(); builder.addSeparator("Sub-analyses are required. Please run them.", cc.xyw(1, 1, 3)); builder.add(createRunAllButton(), cc.xyw(1, 3, 3)); int row = 3; Iterator<MCMCWrapper> iter = d_pm.getWrappedModels().iterator(); while (iter.hasNext()) { LayoutUtil.addRow(layout); row += 2; MCMCWrapper next = iter.next(); AnalysisComponentFactory.createSimulationControls(next,builder, row, d_mainWindow, true); } return builder.getPanel(); }

Target:
private JComponent buildProgressBars() { FormLayout layout = new FormLayout( "pref, 3dlu, fill:0:grow", "p, 3dlu, p, 3dlu, p"); PanelBuilder builder = new PanelBuilder(layout); CellConstraints cc = new CellConstraints(); builder.addSeparator("Sub-analyses are required. Please run them.", cc.xyw(1, 1, 3)); builder.add(createRunAllButton(), cc.xyw(1, 3, 3)); int row = 3; for (MCMCWrapper mw : d_pm.getWrappedModels()) { LayoutUtil.addRow(layout); row += 2; builder.add(AnalysisComponentFactory.createSimulationControls(mw, row, d_mainWindow, true), cc.xyw(1, row, 3)); } return builder.getPanel(); }
Source:
public final boolean automaticBuild(@NonNull SCMSource source, @NonNull SCMHead head, @NonNull SCMRevision currRevision, @CheckForNull SCMRevision prevRevision, @NonNull TaskListener listener) { return automaticBuild(source, head, currRevision, prevRevision, listener, null); }

Target:
public final boolean automaticBuild(@NonNull SCMSource source, @NonNull SCMHead head, @NonNull SCMRevision currRevision, @CheckForNull SCMRevision prevRevision, @NonNull TaskListener listener) { return automaticBuild(source, head, currRevision, prevRevision, prevRevision, listener); }
Source:
public void testBatchDoesntHang() throws Exception { Connection closedConnection = ConnectionFactory.createConnection(IntegrationTests.getConfiguration()); Table table = closedConnection.getTable(TABLE_NAME); closedConnection.close(); thrown.expect(RetriesExhaustedWithDetailsException.class); table.batch(Arrays.asList(new Get(Bytes.toBytes("key"))), new Object[1]); }

Target:
public void testBatchDoesntHang() throws Exception { Connection closedConnection = ConnectionFactory.createConnection(IntegrationTests.getConfiguration()); Table table = closedConnection.getTable(TABLE_NAME); closedConnection.close(); try { table.batch(Arrays.asList(new Get(Bytes.toBytes("key"))), new Object[1]); Assert.fail("Expected an exception"); } catch(RetriesExhaustedWithDetailsException e) { Assert.assertEquals(1, e.getCauses().size()); Assert.assertEquals(IOException.class, e.getCause(0).getClass()); Assert.assertTrue(e.getCause(0).getMessage().toLowerCase().contains("closed")); } }
Source:
public AppendBlobClientBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint); URL url; try { url = new URL(endpoint); this.endpoint = new URL(url.getProtocol() + "://" + url.getAuthority()); String path = url.getPath(); if (path != null && !path.isEmpty() && !path.equals("/")) { path = path.replaceAll("^/", "").replaceAll("/$", ""); String[] segments = path.split("/", 2); if (segments.length != 2) { throw new IllegalArgumentException("Endpoint should contain 0 or at least 2 path segments"); } else { this.containerName = segments[0]; this.blobName = segments[1]; } } } catch (MalformedURLException ex) { throw new IllegalArgumentException("The Azure Storage Blob endpoint url is malformed."); } SASTokenCredential credential = SASTokenCredential.fromQuery(url.getQuery()); if (credential != null) { this.sasTokenCredential = credential; } return this; }

Target:
public AppendBlobClientBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint); URL url; try { url = new URL(endpoint); BlobURLParts parts = URLParser.parse(url); this.endpoint = parts.scheme() + "://" + parts.host(); if (parts.containerName() != null) { this.containerName = parts.containerName(); } if (parts.blobName() != null) { this.blobName = parts.blobName(); } if (parts.snapshot() != null) { this.snapshot = parts.snapshot(); } } catch (MalformedURLException | UnknownHostException ex) { throw new IllegalArgumentException("The Azure Storage Blob endpoint url is malformed."); } SASTokenCredential credential = SASTokenCredential.fromQuery(url.getQuery()); if (credential != null) { this.credential(credential); } return this; }
Source:
public void anonCanNotSignUpIfYoungerThanTwelve() { WikiBasePageObject base = new WikiBasePageObject(); base.openSpecialUserSignUpPage(wikiURL); AttachedRegisterPage register = new AttachedRegisterPage(); register.typeUsername(register.getTimeStamp() + " some letters"); register.typeEmailAddress(credentials.emailQaart1); register.typePassword(register.getTimeStamp()); Calendar currentDate = Calendar.getInstance(); register.typeBirthdate( Integer.toString(currentDate.get(Calendar.MONTH) + 1), Integer.toString(currentDate.get(Calendar.DAY_OF_MONTH)), Integer.toString(currentDate.get(Calendar.YEAR) - PageContent.MIN_AGE)); register.submit(); Assertion.assertEquals(register.getError(), "We cannot complete your registration at this time"); }

Target:
public void anonCanNotSignUpIfYoungerThanTwelve() { WikiBasePageObject base = new WikiBasePageObject(); base.openSpecialUserSignUpPage(wikiURL); AttachedRegisterPage register = new AttachedRegisterPage(); register.typeUsername(register.getTimeStamp() + " some letters"); register.typeEmailAddress(credentials.emailQaart1); register.typePassword(register.getTimeStamp()); Calendar currentDate = Calendar.getInstance(); register.typeBirthdate( Integer.toString(currentDate.get(Calendar.MONTH) + 1), Integer.toString(currentDate.get(Calendar.DAY_OF_MONTH)), Integer.toString(currentDate.get(Calendar.YEAR) - PageContent.MIN_AGE)); register.submit(); assertEquals(register.getError(), "We cannot complete your registration at this time"); }
Source:
private static Label createErrorLabel(Composite parent) { final Label label = new Label(parent, SWT.WRAP); label.setForeground(new Color(parent.getDisplay(), 0xe7, 0x4c, 0x3c)); final FontDescriptor fd = FontDescriptor.createFrom(parent.getFont()); fd.setHeight(9); label.setFont(fd.createFont(parent.getDisplay())); return label; }

Target:
private static Label createErrorLabel(Composite parent) { final Label label = new Label(parent, SWT.WRAP); Color color = new Color(parent.getDisplay(), 0xe7, 0x4c, 0x3c); label.setForeground(color); final FontDescriptor fd = FontDescriptor.createFrom(parent.getFont()); fd.setHeight(9); Font font = fd.createFont(parent.getDisplay()); label.setFont(font); label.addDisposeListener(e -> { color.dispose(); font.dispose(); }); return label; }
Source:
public SingleScheduler(ThreadFactory threadFactory) { this.threadFactory = ObjectHelper.requireNonNull(threadFactory, "threadFactory was null"); executor.lazySet(createExecutor(threadFactory)); }

Target:
public SingleScheduler(ThreadFactory threadFactory) { this.threadFactory = threadFactory; executor.lazySet(createExecutor(threadFactory)); }
Source:
public boolean isConventional() { if (CONFIGURED.containsKey(this)) { return true; } Integer basePriority = CURRENCY_ORDERING.getOrDefault(base, Integer.MAX_VALUE); Integer counterPriority = CURRENCY_ORDERING.getOrDefault(counter, Integer.MAX_VALUE); if (basePriority < counterPriority) { return true; } else if (basePriority > counterPriority) { return false; } return base.getCode().compareTo(counter.getCode()) < 0; }

Target:
public boolean isConventional() { if (CONFIGURED.containsKey(this)) { return true; } Integer basePriority = CURRENCY_ORDERING.getOrDefault(base, Integer.MAX_VALUE); Integer counterPriority = CURRENCY_ORDERING.getOrDefault(counter, Integer.MAX_VALUE); if (basePriority < counterPriority) { return true; } else if (basePriority > counterPriority) { return false; } return base.compareTo(counter) < 0; }
Source:
private void processWorkItemHandler(Runnable handler) { if (isInversionOfControl()) { ((ProcessInstance) getProcessInstance()).getKnowledgeRuntime() .update(((ProcessInstance) getProcessInstance()).getKnowledgeRuntime().getFactHandle(this), this); } else { try { handler.run(); } catch (WorkItemHandlerNotFoundException wihnfe) { getProcessInstance().setState(ProcessInstance.STATE_ABORTED); throw wihnfe; } catch (ProcessWorkItemHandlerException handlerException) { this.workItemId = workItem.getId(); handleWorkItemHandlerException(handlerException, workItem); } catch (Exception e) { String exceptionName = e.getClass().getName(); ExceptionScopeInstance exceptionScopeInstance = (ExceptionScopeInstance) resolveContextInstance(ExceptionScope.EXCEPTION_SCOPE, exceptionName); if (exceptionScopeInstance == null) { throw new WorkflowRuntimeException(this, getProcessInstance(), "Unable to execute Action: " + e.getMessage(), e); } this.workItemId = workItem.getId(); exceptionScopeInstance.handleException(exceptionName, e); } } }

Target:
private void processWorkItemHandler(Runnable handler) { if (isInversionOfControl()) { ((ProcessInstance) getProcessInstance()).getKnowledgeRuntime() .update(((ProcessInstance) getProcessInstance()).getKnowledgeRuntime().getFactHandle(this), this); } else { try { handler.run(); } catch (WorkItemHandlerNotFoundException wihnfe) { getProcessInstance().setState(ProcessInstance.STATE_ABORTED); throw wihnfe; } catch (ProcessWorkItemHandlerException handlerException) { if (triggerCount++ < handlerException.getRetries() + 1) { this.workItemId = workItem.getId(); handleWorkItemHandlerException(handlerException, workItem); } else { throw handlerException; } } catch (Exception e) { String exceptionName = e.getClass().getName(); ExceptionScopeInstance exceptionScopeInstance = (ExceptionScopeInstance) resolveContextInstance(ExceptionScope.EXCEPTION_SCOPE, exceptionName); if (exceptionScopeInstance == null) { throw new WorkflowRuntimeException(this, getProcessInstance(), "Unable to execute Action: " + e.getMessage(), e); } this.workItemId = workItem.getId(); exceptionScopeInstance.handleException(exceptionName, e); } } }
Source:
private BlockPlaceHandler onPlace() { return new BlockPlaceHandler(false) { @Override public void onPlayerPlace(BlockPlaceEvent e) { Block b = e.getBlockPlaced(); BlockStorage.addBlockInfo(b, "text", ChatColors.color("&fEdit me via the Projector")); BlockStorage.addBlockInfo(b, Y_OFFSET_PARAMETER, "0.5"); BlockStorage.addBlockInfo(b, X_OFFSET_PARAMETER, "0.5"); BlockStorage.addBlockInfo(b, Z_OFFSET_PARAMETER, "0.5"); BlockStorage.addBlockInfo(b, "owner", e.getPlayer().getUniqueId().toString()); getArmorStand(b, true); } }; }

Target:
private BlockPlaceHandler onPlace() { return new BlockPlaceHandler(false) { @Override public void onPlayerPlace(BlockPlaceEvent e) { Block b = e.getBlockPlaced(); BlockStorage.addBlockInfo(b, "text", "Edit me via the Projector"); BlockStorage.addBlockInfo(b, X_OFFSET_PARAMETER, DEFAULT_OFFSET); BlockStorage.addBlockInfo(b, Y_OFFSET_PARAMETER, DEFAULT_OFFSET); BlockStorage.addBlockInfo(b, Z_OFFSET_PARAMETER, DEFAULT_OFFSET); BlockStorage.addBlockInfo(b, "owner", e.getPlayer().getUniqueId().toString()); getArmorStand(b, true); } }; }
Source:
public boolean canFindVdsToRunOn(List<String> messages, boolean isMigrate) { boolean returnValue = false; if (getDestinationVdsId() != null) { returnValue = canRunOnDestinationVds(messages, isMigrate); } if (!returnValue) { if (privateVm.getMigrationSupport() == MigrationSupport.PINNED_TO_HOST) { if (messages.size() > 2) { messages.add(2, VdcBllMessages.VM_PINNED_TO_HOST_CANNOT_RUN_ON_THE_DEFAULT_VDS_WITH_REASON.toString()); } else { messages.add(VdcBllMessages.VM_PINNED_TO_HOST_CANNOT_RUN_ON_THE_DEFAULT_VDS.toString()); } return false; } returnValue = canFindAnyVds(messages, isMigrate); } return returnValue; }

Target:
public boolean canFindVdsToRunOn(List<String> messages, boolean isMigrate) { boolean returnValue = false; if (getDestinationVdsId() != null) { returnValue = canRunOnDestinationVds(messages, isMigrate); } if (!returnValue) { if (privateVm.getMigrationSupport() == MigrationSupport.PINNED_TO_HOST) { messages.add(VdcBllMessages.VM_PINNED_TO_HOST_CANNOT_RUN_ON_THE_DEFAULT_VDS.toString()); return false; } returnValue = canFindAnyVds(messages, isMigrate); } return returnValue; }
Source:
public void actionPerformed(ActionEvent event) { if (event.getSource().equals(btnStart) || event.getSource().equals(btnNextMonth)) { int days = (int)spnDays.getValue(); boolean firstDay = true; MekHQ.registerHandler(this); if (event.getSource().equals(btnNextMonth)) { GregorianCalendar cal = gui.getCampaign().getCalendar(); Duration duration = Duration.between(cal.getTime().toInstant(), new java.util.GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, 1).getTime().toInstant()); days = Math.abs((int)duration.toDays()); } for (int numDays = days; numDays > 0; numDays--) { if (gui.getCampaign().checkOverDueLoans() || gui.nagShortMaintenance() || (gui.getCampaign().getCampaignOptions().getUseAtB()) && (gui.nagShortDeployments() || gui.nagOutstandingScenarios())) { break; } if (gui.getCampaign().checkRetirementDefections() || gui.getCampaign().checkYearlyRetirements()) { gui.showRetirementDefectionDialog(); break; } if(!gui.getCampaign().newDay()) { break; } if(firstDay) { logPanel.refreshLog(gui.getCampaign().getCurrentReportHTML()); firstDay = false; } else { logPanel.appendLog(Collections.singletonList("<hr/>")); logPanel.appendLog(gui.getCampaign().fetchAndClearNewReports()); } } gui.refreshCalendar(); gui.refreshLocation(); gui.initReport(); gui.refreshAllTabs(); } }

Target:
public void actionPerformed(ActionEvent event) { if (event.getSource().equals(btnStart) || event.getSource().equals(btnNextMonth)) { int days = (int)spnDays.getValue(); boolean firstDay = true; MekHQ.registerHandler(this); if (event.getSource().equals(btnNextMonth)) { GregorianCalendar cal = gui.getCampaign().getCalendar(); Duration duration = Duration.between(cal.getTime().toInstant(), new java.util.GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, 1).getTime().toInstant()); days = Math.abs((int)duration.toDays()); } int numDays; for (numDays = days; numDays > 0; numDays--) { if (gui.getCampaign().checkOverDueLoans() || gui.nagShortMaintenance() || (gui.getCampaign().getCampaignOptions().getUseAtB()) && (gui.nagShortDeployments() || gui.nagOutstandingScenarios())) { break; } if (gui.getCampaign().checkRetirementDefections() || gui.getCampaign().checkYearlyRetirements()) { gui.showRetirementDefectionDialog(); break; } if(!gui.getCampaign().newDay()) { break; } if(firstDay) { logPanel.refreshLog(gui.getCampaign().getCurrentReportHTML()); firstDay = false; } else { logPanel.appendLog(Collections.singletonList("<hr/>")); logPanel.appendLog(gui.getCampaign().fetchAndClearNewReports()); } } if (numDays > 0) { this.spnDays.setValue(numDays); } gui.refreshCalendar(); gui.refreshLocation(); gui.initReport(); gui.refreshAllTabs(); } }
Source:
public ScheduleBootstrapper( ListeningExecutorService executor, ChannelIntervalScheduleBootstrapTaskFactory taskFactory ) { this.executor = executor; this.taskFactory = taskFactory; }

Target:
public ScheduleBootstrapper( ListeningExecutorService executor, ChannelIntervalScheduleBootstrapTaskFactory taskFactory ) { this.executor = checkNotNull(executor); this.taskFactory = checkNotNull(taskFactory); }
Source:
private void testRegexMountpoint( Configuration config, String regexStr, String dstPathStr, String interceptorSettings, Path dirPathBeforeMountPoint, Path expectedResolveResult, int childrenFilesCnt) throws IOException, URISyntaxException { FileSystem vfs = null; try { createDirWithChildren( fsTarget, expectedResolveResult, childrenFilesCnt); ConfigUtil.addLinkRegex( config, CLUSTER_NAME, regexStr, dstPathStr, interceptorSettings); URI viewFsUri = new URI( FsConstants.VIEWFS_SCHEME, CLUSTER_NAME, "/", null, null); vfs = FileSystem.get(viewFsUri, config); Assert.assertTrue( expectedResolveResult.equals( vfs.resolvePath(dirPathBeforeMountPoint))); Assert.assertTrue( vfs.getFileStatus(dirPathBeforeMountPoint).isDirectory()); Assert.assertEquals( childrenFilesCnt, vfs.listStatus(dirPathBeforeMountPoint).length); ViewFileSystem viewFileSystem = (ViewFileSystem) vfs; ChRootedFileSystem target1 = (ChRootedFileSystem) viewFileSystem .fsState.resolve( viewFileSystem.getUriPath( dirPathBeforeMountPoint), true).targetFileSystem; ChRootedFileSystem target2 = (ChRootedFileSystem) viewFileSystem .fsState.resolve( viewFileSystem.getUriPath( dirPathBeforeMountPoint), true).targetFileSystem; assertSame(target1.getMyFs(), target2.getMyFs()); } finally { if (vfs != null) { vfs.close(); } } }

Target:
private void testRegexMountpoint( Configuration config, String regexStr, String dstPathStr, String interceptorSettings, Path dirPathBeforeMountPoint, Path expectedResolveResult, int childrenFilesCnt) throws IOException, URISyntaxException { createDirWithChildren( fsTarget, expectedResolveResult, childrenFilesCnt); ConfigUtil.addLinkRegex( config, CLUSTER_NAME, regexStr, dstPathStr, interceptorSettings); URI viewFsUri = new URI( FsConstants.VIEWFS_SCHEME, CLUSTER_NAME, "/", null, null); try (FileSystem vfs = FileSystem.get(viewFsUri, config)) { Assert.assertEquals(expectedResolveResult.toString(), vfs.resolvePath(dirPathBeforeMountPoint).toString()); Assert.assertTrue( vfs.getFileStatus(dirPathBeforeMountPoint).isDirectory()); Assert.assertEquals( childrenFilesCnt, vfs.listStatus(dirPathBeforeMountPoint).length); ViewFileSystem viewFileSystem = (ViewFileSystem) vfs; ChRootedFileSystem target1 = (ChRootedFileSystem) viewFileSystem.fsState .resolve(viewFileSystem.getUriPath(dirPathBeforeMountPoint), true) .targetFileSystem; ChRootedFileSystem target2 = (ChRootedFileSystem) viewFileSystem.fsState .resolve(viewFileSystem.getUriPath(dirPathBeforeMountPoint), true) .targetFileSystem; assertSame(target1.getMyFs(), target2.getMyFs()); } }
Source:
public int generate( final MasterReport report, final int acceptedPage, final OutputStream outputStream, final int yieldRate ) throws ReportProcessingException, IOException, ContentIOException { FastHtmlContentItems contentItems = computeContentItems( outputStream ); final HtmlPrinter printer = new AllItemsHtmlPrinter( report.getResourceManager() ); printer.setContentWriter( contentItems.getContentLocation(), contentItems.getContentNameGenerator() ); printer.setDataWriter( contentItems.getDataLocation(), contentItems.getDataNameGenerator() ); printer.setUrlRewriter( contentItems.getUrlRewriter() ); final HtmlOutputProcessor outputProcessor = new StreamHtmlOutputProcessor( report.getConfiguration() ); outputProcessor.setPrinter( printer ); final StreamReportProcessor sp = new StreamReportProcessor( report, outputProcessor ); final ReportProgressListener listener = ReportListenerThreadHolder.getListener(); if ( listener != null ) { sp.addReportProgressListener( listener ); } try { sp.processReport(); if ( listener != null && listener instanceof IAsyncReportListener ) { ( (IAsyncReportListener) listener ).setIsQueryLimitReached( sp.isQueryLimitReached() ); } } finally { if ( listener != null ) { sp.removeReportProgressListener( listener ); } sp.close(); } outputStream.flush(); return 1; }

Target:
public int generate( final MasterReport report, final int acceptedPage, final OutputStream outputStream, final int yieldRate ) throws ReportProcessingException, IOException, ContentIOException { FastHtmlContentItems contentItems = computeContentItems( outputStream ); final HtmlPrinter printer = new AllItemsHtmlPrinter( report.getResourceManager() ); printer.setContentWriter( contentItems.getContentLocation(), contentItems.getContentNameGenerator() ); printer.setDataWriter( contentItems.getDataLocation(), contentItems.getDataNameGenerator() ); printer.setUrlRewriter( contentItems.getUrlRewriter() ); final HtmlOutputProcessor outputProcessor = new StreamHtmlOutputProcessor( report.getConfiguration() ); outputProcessor.setPrinter( printer ); final StreamReportProcessor sp = new StreamReportProcessor( report, outputProcessor ); final IAsyncReportListener listener = ReportListenerThreadHolder.getListener(); if ( listener != null ) { sp.addReportProgressListener( listener ); } try { sp.processReport(); if ( listener != null ) { listener.setIsQueryLimitReached( sp.isQueryLimitReached() ); } } finally { if ( listener != null ) { sp.removeReportProgressListener( listener ); } sp.close(); } outputStream.flush(); return 1; }
Source:
private Workspace getWorkspaceConfiguration() { UriBuilder builder = fromUri(apiEndpoint) .path(WorkspaceService.class) .path(WorkspaceService.class, "getByKey") .queryParam("includeInternalServers", true); String href = builder.build(WORKSPACE_ID).toString(); try { return httpJsonRequestFactory .fromUrl(href) .useGetMethod() .request() .asDto(WorkspaceDto.class); } catch (IOException | ApiException e) { return null; } }

Target:
private Workspace getWorkspaceConfiguration() { if (workspace != null) { return workspace; } String href = fromUri(apiEndpoint) .path(WorkspaceService.class) .path(WorkspaceService.class, "getByKey") .queryParam("includeInternalServers", true) .build(workspaceId) .toString(); try { return workspace = httpJsonRequestFactory.fromUrl(href).useGetMethod().request().asDto(WorkspaceDto.class); } catch (IOException | ApiException e) { LOG.error("Did not manage to get workspace configuration: {}", workspaceId, e); return null; } }
Source:
protected String[] customCommandLineValidation() { if ((!VALIDATE_INDEX && INDEX_VALIDATION_STRINGENCY != IndexValidationStringency.NONE) || (INDEX_VALIDATION_STRINGENCY == IndexValidationStringency.NONE && VALIDATE_INDEX)) { return new String[]{"VALIDATE_INDEX and INDEX_VALIDATION_STRINGENCY must be consistent: " + "VALIDATE_INDEX is " + VALIDATE_INDEX + " and INDEX_VALIDATION_STRINGENCY is " + INDEX_VALIDATION_STRINGENCY}; } return super.customCommandLineValidation(); }

Target:
protected String[] customCommandLineValidation() { if ((!VALIDATE_INDEX && INDEX_VALIDATION_STRINGENCY != IndexValidationStringency.NONE) || (VALIDATE_INDEX && INDEX_VALIDATION_STRINGENCY == IndexValidationStringency.NONE)) { return new String[]{"VALIDATE_INDEX and INDEX_VALIDATION_STRINGENCY must be consistent: " + "VALIDATE_INDEX is " + VALIDATE_INDEX + " and INDEX_VALIDATION_STRINGENCY is " + INDEX_VALIDATION_STRINGENCY}; } return super.customCommandLineValidation(); }
Source:
private void ensureProgramIsSet(ProgramWorkflow workflow, Program program) throws APIException { if (workflow.getConcept() == null) { throw new APIException("ProgramWorkflow.concept.required", (Object[]) null); } if (workflow.getProgram() == null) { workflow.setProgram(program); } else if (!workflow.getProgram().equals(program)) { throw new APIException("Program.error.contains.ProgramWorkflow", new Object[] { workflow.getProgram() }); } }

Target:
private void ensureProgramIsSet(ProgramWorkflow workflow, Program program) { if (workflow.getProgram() == null) { workflow.setProgram(program); } else if (!workflow.getProgram().equals(program)) { throw new APIException("Program.error.contains.ProgramWorkflow", new Object[] { workflow.getProgram() }); } }
Source:
public boolean activeChanged() { return prevState.active() ^ msg.state().active(); }

Target:
public boolean activeChanged() { return prevState.active() != msg.state().active(); }
Source:
public void onRemoteClose(Link link) throws Exception { handler.requireHandler(); runLater(() -> { link.close(); link.free(); ProtonDeliveryHandler linkContext = (ProtonDeliveryHandler) link.getContext(); if (linkContext != null) { try { linkContext.close(true); } catch (Exception e) { log.error(e.getMessage(), e); } } flush(); }); }

Target:
public void onRemoteClose(Link link) throws Exception { handler.requireHandler(); runNow(() -> { link.close(); link.free(); ProtonDeliveryHandler linkContext = (ProtonDeliveryHandler) link.getContext(); if (linkContext != null) { try { linkContext.close(true); } catch (Exception e) { log.error(e.getMessage(), e); } } flush(); }); }
Source:
public String toString() { StringBuilder builder = new StringBuilder(); builder.append(getName()) .append(" {id=") .append(getId()) .append(", vdsId=") .append(getVdsId()) .append(", name=") .append(getName()) .append(", macAddress=") .append(getMacAddress()) .append(", networkName=") .append(getNetworkName()) .append(", bondOptions=") .append(getBondOptions()) .append(", bootProtocol=") .append(getBootProtocol()) .append(", address=") .append(getAddress()) .append(", subnet=") .append(getSubnet()) .append(", gateway=") .append(getGateway()) .append(", mtu=") .append(getMtu()) .append(", bridged=") .append(isBridged()) .append(", type=") .append(getType()) .append(", networkImplementationDetails=") .append(getNetworkImplementationDetails()) .append("]"); return builder.toString(); }

Target:
public String toString() { StringBuilder builder = new StringBuilder(); builder.append(getName()) .append(" {id=") .append(getId()) .append(", vdsId=") .append(getVdsId()) .append(", name=") .append(getName()) .append(", macAddress=") .append(getMacAddress()) .append(", networkName=") .append(getNetworkName()) .append(", bondOptions=") .append(getBondOptions()) .append(", bootProtocol=") .append(getBootProtocol()) .append(", address=") .append(getAddress()) .append(", subnet=") .append(getSubnet()) .append(", gateway=") .append(getGateway()) .append(", mtu=") .append(getMtu()) .append(", bridged=") .append(isBridged()) .append(", type=") .append(getType()) .append(", networkImplementationDetails=") .append(getNetworkImplementationDetails()) .append("}"); return builder.toString(); }
Source:
public BufferedReader getDumpFileReader() throws IOException { String fileName = this.projectName + "-" + this.dateStamp + WmfDumpFile.getDumpFilePostfix(DumpContentType.DAILY); String urlString = getBaseUrl() + fileName; if (this.getMaximalRevisionId() == -1L) { throw new IOException( "Failed to retrieve maximal revision id. Aborting dump retrieval."); } DirectoryManager dailyDirectoryManager = this.dumpfileDirectoryManager .getSubdirectoryManager("daily-" + this.dateStamp); try (InputStream inputStream = webResourceFetcher .getInputStreamForUrl(urlString)) { dailyDirectoryManager.createFile(fileName, inputStream); } dailyDirectoryManager.createFile("maxrevid.txt", this .getMaximalRevisionId().toString()); return dailyDirectoryManager.getBufferedReaderForBz2File(fileName); }

Target:
public BufferedReader getDumpFileReader() throws IOException { String fileName = WmfDumpFile.getDumpFileName(DumpContentType.DAILY, this.projectName, this.dateStamp); String urlString = getBaseUrl() + fileName; if (this.getMaximalRevisionId() == -1L) { throw new IOException( "Failed to retrieve maximal revision id. Aborting dump retrieval."); } DirectoryManager dailyDirectoryManager = this.dumpfileDirectoryManager .getSubdirectoryManager(WmfDumpFile.getDumpFileDirectoryName( DumpContentType.DAILY, this.dateStamp)); try (InputStream inputStream = webResourceFetcher .getInputStreamForUrl(urlString)) { dailyDirectoryManager.createFile(fileName, inputStream); } dailyDirectoryManager.createFile(WmfDumpFile.LOCAL_FILENAME_MAXREVID, this.getMaximalRevisionId().toString()); return dailyDirectoryManager.getBufferedReaderForBz2File(fileName); }
Source:
public void testSAdd_withExistingKey_ofWrongType_shouldNotOverWriteExistingKey() { String key = "key"; String stringValue = "preexistingValue"; String[] setValue = new String[1]; setValue[0] = "set value that should never get added"; jedis.set(key, stringValue); try { jedis.sadd(key, setValue); } catch (Exception exception) { } String result = jedis.get(key); assertThat(result).isEqualTo(stringValue); }

Target:
public void testSAdd_withExistingKey_ofWrongType_shouldNotOverWriteExistingKey() { String key = "key"; String stringValue = "preexistingValue"; String[] setValue = new String[1]; setValue[0] = "set value that should never get added"; jedis.set(key, stringValue); try { jedis.sadd(key, setValue); } catch (JedisDataException exception) { } String result = jedis.get(key); assertThat(result).isEqualTo(stringValue); }
Source:
private static TraceResponse observeSpanAndDownstream(String encodings) { Span span = tracingContext.currentSpan(); TraceResponse response = new TraceResponse(); JaegerSpanContext context = (JaegerSpanContext) span.context(); response.traceId = String.format("%s", context.getTraceId()); response.sampled = context.isSampled(); response.baggage = span.getBaggageItem(BAGGAGE_KEY); try { response.downstream = callDownstream(encodings); } catch (Exception e) { e.printStackTrace(); } return response; }

Target:
private static TraceResponse observeSpanAndDownstream(String encodings) { Span span = tracingContext.currentSpan(); TraceResponse response = new TraceResponse(); JaegerSpanContext context = (JaegerSpanContext) span.context(); response.traceId = context.toTraceId(); response.sampled = context.isSampled(); response.baggage = span.getBaggageItem(BAGGAGE_KEY); try { response.downstream = callDownstream(encodings); } catch (Exception e) { e.printStackTrace(); } return response; }
Source:
public String withdrawFunds(Currency currency, BigDecimal amount, String address) throws IOException { String result; try { result = withdrawFunds(new DefaultWithdrawFundsParams(address, currency, amount)); return result; } catch (CoingiException e) { throw CoingiErrorAdapter.adapt(e); } }

Target:
public String withdrawFunds(Currency currency, BigDecimal amount, String address) throws IOException { try { return withdrawFunds(new DefaultWithdrawFundsParams(address, currency, amount)); } catch (CoingiException e) { throw CoingiErrorAdapter.adapt(e); } }
Source:
public FSAccessNative() { }

Target:
FSAccessNative() { }
Source:
private List<CourseStudent> getCourseStudentEntitiesForGoogleId(String googleId) { Query q = getPm().newQuery(CourseStudent.class); q.declareParameters("String googleIdParam"); q.setFilter("googleId == googleIdParam"); @SuppressWarnings("unchecked") List<CourseStudent> studentList = (List<CourseStudent>) q.execute(googleId); return studentList; }

Target:
private List<CourseStudent> getCourseStudentEntitiesForGoogleId(String googleId) { Query q = getPm().newQuery(CourseStudent.class); q.declareParameters("String googleIdParam"); q.setFilter("googleId == googleIdParam"); return (List<CourseStudent>) q.execute(googleId); }
Source:
public void delete(String tab) { try { HQLOperation op = HQLOperation.getInstance(); int indexBoolean = this.panelGeneralAdmin.getTbl_gral().getColumnModel().getColumnIndex(""); int indexdescription = this.panelGeneralAdmin.getTbl_gral().getColumnModel().getColumnIndex("DESCRIPCION"); for (int i = 0; i < this.panelGeneralAdmin.getTbl_gral().getRowCount(); i++) { if (this.panelGeneralAdmin.getTbl_gral().getValueAt(i, indexBoolean).equals(true)) { switch (tab) { case Category: op.Delete(MapDb.categoryList.get(this.panelGeneralAdmin.getTbl_gral().getValueAt(i, indexdescription).toString())); break; case Measure: Measure measure = (Measure) MapDb.measureList.get(this.panelGeneralAdmin.getTbl_gral().getValueAt(i, indexdescription).toString()); measure.getProductMeasures().stream().forEach((productMeasure) -> { op.Delete(productMeasure); }); measure.setProductMeasures(null); op.Delete(measure); break; case Store: op.Delete(MapDb.storeList.get(this.panelGeneralAdmin.getTbl_gral().getValueAt(i, indexdescription).toString())); break; case Price: op.Delete(MapDb.priceList.get(this.panelGeneralAdmin.getTbl_gral().getValueAt(i, indexdescription).toString())); break; } } } list(tab); } catch (org.hibernate.exception.ConstraintViolationException ex) { JOptionPane.showMessageDialog(null, "No se puede eliminar ya que existen otros elementos que usan este valor", "Error", JOptionPane.ERROR_MESSAGE); } }

Target:
public void delete(String tab) { try { HQLOperation op = HQLOperation.getInstance(); int indexCheck = this.panelGeneralAdmin.getTbl_gral().getColumnModel().getColumnIndex(""); int indexdescription = this.panelGeneralAdmin.getTbl_gral().getColumnModel().getColumnIndex("DESCRIPCION"); for (int i = 0; i < this.panelGeneralAdmin.getTbl_gral().getRowCount(); i++) { if (this.panelGeneralAdmin.getTbl_gral().getValueAt(i, indexCheck).equals(true)) { switch (tab) { case Category: op.Delete(MapDb.categoryList.get(this.panelGeneralAdmin.getTbl_gral().getValueAt(i, indexdescription).toString())); break; case Measure: Measure measure = (Measure) MapDb.measureList.get(this.panelGeneralAdmin.getTbl_gral().getValueAt(i, indexdescription).toString()); measure.getProductMeasures().stream().forEach((productMeasure) -> { op.Delete(productMeasure); } ); measure.setProductMeasures(null); op.Delete(measure); break; case Store: op.Delete(MapDb.storeList.get(this.panelGeneralAdmin.getTbl_gral().getValueAt(i, indexdescription).toString())); break; case Price: op.Delete(MapDb.priceList.get(this.panelGeneralAdmin.getTbl_gral().getValueAt(i, indexdescription).toString())); break; } } } list(tab); } catch (org.hibernate.exception.ConstraintViolationException ex) { JOptionPane.showMessageDialog(null, "No se puede eliminar ya que existen otros elementos que usan este valor", "Error", JOptionPane.ERROR_MESSAGE); } }
Source:
private void initUi() { this.setTitle(R.string.dish_title); LayoutInflater inflater = LayoutInflater.from(this.getApplicationContext()); RelativeLayout mainPage = (RelativeLayout) inflater.inflate(R.layout.main_list_activity, null); LinearLayout galleryFrame = (LinearLayout) mainPage.findViewById(R.id.gallery_frame); mCategoryGallery = new GridView[mCategoryNum]; for (int i = 0; i < mCategoryNum; i++) { LinearLayout categoryLayout = (LinearLayout) inflater.inflate(R.layout.main_list_item, null); TextView cagegoryNameTextView = (TextView) categoryLayout .findViewById(R.id.id_category_name); cagegoryNameTextView.setText("�Ȳ�"); mCategoryGallery[i] = (GridView) categoryLayout.findViewById(R.id.id_dish_grid); mCategoryGallery[i].setId(i); mCategoryGallery[i].setAdapter(new GridViewAdapter(this)); mCategoryGallery[i].setOnItemClickListener(this); int dishNumber = 9; int rowNum = (dishNumber % DISHNUM_IN_ONEROW == 0) ? dishNumber / DISHNUM_IN_ONEROW : dishNumber / DISHNUM_IN_ONEROW + 1; mCategoryGallery[i].getLayoutParams().height = rowNum * HEIGHT_ONEROW; galleryFrame.addView(categoryLayout); } Button buttonForOrderedList = (Button) mainPage.findViewById(R.id.id_orderedlist_button); buttonForOrderedList.setOnClickListener(this); setContentView(mainPage); }

Target:
private void initUi() { setTitle(R.string.dish_title); setContentView(R.layout.main_list_activity); LinearLayout galleryFrame = (LinearLayout) findViewById(R.id.gallery_frame); Button orderListButton = (Button) findViewById(R.id.orderedlist_button); orderListButton.setOnClickListener(this); LayoutInflater inflater = LayoutInflater.from(getApplicationContext()); for (int i = 0; i < mCategoryNum; i++) { LinearLayout categoryLayout = (LinearLayout) inflater.inflate( R.layout.main_list_item, null); TextView cagegoryNameTextView = (TextView) categoryLayout.findViewById( R.id.category_name); cagegoryNameTextView.setText(CATEGORY_NAME); GridView categoryView = (GridView) categoryLayout.findViewById(R.id.dish_grid); categoryView.setId(i); categoryView.setAdapter(new GridViewAdapter(this)); categoryView.setOnItemClickListener(this); int dishNumber = 9; int rowNum = (dishNumber % DISHNUM_IN_ONEROW == 0) ? (dishNumber / DISHNUM_IN_ONEROW) : (dishNumber / DISHNUM_IN_ONEROW + 1); categoryView.getLayoutParams().height = rowNum * HEIGHT_ONEROW; galleryFrame.addView(categoryLayout); } }