auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static boolean isSimilar(Object expected, Object actual) { logger.debug("Comparing expected and actual {}", expected, actual); if (expected instanceof String && expected.equals(ANY_VALUE)) { return true; } if (expected instanceof String && actual instanceof String) { return expected.equals(ANY_VALUE) || expected.equals(actual); } else if (expected instanceof Number && actual instanceof Number) { return expected.getClass() == actual.getClass() && expected.equals(actual); } else if (expected instanceof JSONObject && actual instanceof JSONObject) { return areJsonObjectsSimilarEnough((JSONObject) expected, (JSONObject) actual); } else if (expected instanceof JSONArray && actual instanceof JSONArray) { JSONArray expectedArray = (JSONArray) expected; JSONArray actualArray = (JSONArray) expected; for(int i = 0; i < expectedArray.length(); i++) { if(!isSimilar(expectedArray.get(i), actualArray.get(i))) { return false; } } return true; } return false; }

Target:
private static boolean isSimilar(Object expected, Object actual) { logger.debug("Comparing expected and actual {}", expected, actual); if (expected instanceof String && expected.equals(ANY_VALUE)) { return true; } if (expected instanceof String && actual instanceof String) { return expected.equals(ANY_VALUE) || expected.equals(actual); } else if (expected instanceof Number && actual instanceof Number) { return expected.getClass() == actual.getClass() && expected.equals(actual); } else if (expected instanceof JSONObject && actual instanceof JSONObject) { return areJsonObjectsSimilarEnough((JSONObject) expected, (JSONObject) actual); } else if (expected instanceof JSONArray && actual instanceof JSONArray) { JSONArray expectedArray = (JSONArray) expected; JSONArray actualArray = (JSONArray) actual; for(int i = 0; i < expectedArray.length(); i++) { if(!isSimilar(expectedArray.get(i), actualArray.get(i))) { return false; } } return true; } return false; }
Source:
protected boolean supportsJBoss7Markers() { IService service = OpenShiftServerUtils.getService(getServer()); return service.getName().startsWith("eap"); }

Target:
protected boolean supportsJBoss7Markers() { IService service = OpenShiftServerUtils.getService(getServer()); String templateName = service.getLabels().getOrDefault("template", ""); return templateName.startsWith("eap"); }
Source:
public String deserialize(JsonParser parser, DeserializationContext context) throws IOException { TreeNode node = parser.readValueAsTree(); if (node.isObject()) { log.debug("Processing " + this.fieldName + " as an containing object node."); String fieldName = ""; for (Iterator<String> fieldNames = node.fieldNames(); fieldNames.hasNext();) { fieldName = fieldNames.next(); if (fieldName.equals(this.fieldName)) { break; } } if (!fieldName.equals(this.fieldName)) { throw new CandlepinJsonProcessingException( "Unexpected field name: '" + fieldName + "'. Expected '" + this.fieldName + "'.", parser.getCurrentLocation() ); } TreeNode valueNode = node.get(fieldName); if (!valueNode.isValueNode()) { throw new CandlepinJsonProcessingException( "Unexpected value type in: " + valueNode.asToken(), parser.getCurrentLocation() ); } return parseValueNode(valueNode); } else if (node.isValueNode()) { log.debug("Processing " + this.fieldName + " as a value node."); return parseValueNode(node); } else { throw new CandlepinJsonProcessingException( "Unexpected " + this.fieldName + " node type: " + node.asToken(), parser.getCurrentLocation() ); } }

Target:
public String deserialize(JsonParser parser, DeserializationContext context) throws IOException { TreeNode node = parser.readValueAsTree(); if (node.isObject()) { log.debug("Processing as a containing object node.", this.fieldName); TreeNode valueNode = node.path(this.fieldName); if (valueNode.isMissingNode()) { throw new CandlepinJsonProcessingException( "The field " + this.fieldName + " is missing from: " + node.asToken(), parser.getCurrentLocation() ); } return parseValueNode(valueNode); } else if (node.isValueNode()) { log.debug("Processing as a value node.", this.fieldName); return parseValueNode(node); } else { throw new CandlepinJsonProcessingException( "Unexpected " + this.fieldName + " node type: " + node.asToken(), parser.getCurrentLocation() ); } }
Source:
public void TXBegin() { OptimisticTXBegin(); }

Target:
public void TXBegin() { TXBegin(TransactionType.OPTIMISTIC); }
Source:
public void queued_entries_with_expiration_times_are_not_lost_when_cluster_scaled_down() { final int entryCount = 1000; final int ttlSec = 10; final int writeDelaySec = 5; final int backupCount = 1; final String mapName = randomMapName(); TestEntryStore<Integer, Integer> testEntryStore = new TestEntryStore<>(); Config config = getConfigWithEntryStore(testEntryStore, writeDelaySec, backupCount); TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(3); HazelcastInstance[] instances = factory.newInstances(config); IMap<Integer, Integer> map = instances[0].getMap(mapName); long expectedExpirationTime = System.currentTimeMillis() + ttlSec * 1000; for (int i = 0; i < 1000; i++) { map.put(i, i, ttlSec, TimeUnit.SECONDS); } instances[0].shutdown(); waitAllForSafeState(instances); instances[1].shutdown(); waitAllForSafeState(instances); IMap<Integer, Integer> mapFromSurvivingInstance = instances[2].getMap(mapName); assertTrueEventually(() -> { for (int i = 0; i < entryCount; i++) { testEntryStore.assertRecordStored(i, i, expectedExpirationTime, 2000); } }); assertTrueEventually(() -> { for (int i = 0; i < entryCount; i++) { assertNull(mapFromSurvivingInstance.get(i)); } }); }

Target:
public void queued_entries_with_expiration_times_are_not_lost_when_cluster_scaled_down() { final int entryCount = 1000; final int ttlSec = 10; final int writeDelaySec = 5; final int backupCount = 1; final String mapName = randomMapName(); TestEntryStore<Integer, Integer> testEntryStore = new TestEntryStore<>(); Config config = getConfigWithEntryStore(testEntryStore, writeDelaySec, backupCount); TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(3); HazelcastInstance[] instances = factory.newInstances(config); IMap<Integer, Integer> map = instances[0].getMap(mapName); long expectedExpirationTime = System.currentTimeMillis() + ttlSec * 1000; for (int i = 0; i < 1000; i++) { map.put(i, i, ttlSec, TimeUnit.SECONDS); } instances[0].shutdown(); instances[1].shutdown(); IMap<Integer, Integer> mapFromSurvivingInstance = instances[2].getMap(mapName); assertTrueEventually(() -> { for (int i = 0; i < entryCount; i++) { testEntryStore.assertRecordStored(i, i, expectedExpirationTime, 2000); } }); assertTrueEventually(() -> { for (int i = 0; i < entryCount; i++) { assertNull(mapFromSurvivingInstance.get(i)); } }); }
Source:
protected void refreshAppliedStereotypesPropertiesInBrace(IPapyrusNodeUMLElementFigure figure) { String toDisplayInBrace = helper.getStereotypePropertiesInBrace(hostView); if (!"".equals(toDisplayInBrace)) { figure.setStereotypePropertiesInBrace(toDisplayInBrace); } else { figure.setStereotypePropertiesInBrace(null); } }

Target:
protected void refreshAppliedStereotypesPropertiesInBrace(IPapyrusNodeUMLElementFigure figure) { String toDisplayInBrace = helper.getStereotypePropertiesInBrace(hostView); if (!EMPTY_STRING.equals(toDisplayInBrace)) { figure.setStereotypePropertiesInBrace(toDisplayInBrace); } else { figure.setStereotypePropertiesInBrace(null); } }
Source:
public int rank() { if ((columns == 0) || (rows == 0)) { return 0; } Matrix copy = copy(); int min = (columns > rows) ? rows : columns; for (int k = 0; k < min; k++) { if (Math.abs(copy.get(k, k)) <= Matrices.EPS) { int x = 0; int y = 0; boolean nz = false; for (int i = k; i < rows && !nz; i++) { for (int j = k; j < columns && !nz; j++) { if (Math.abs(copy.get(i, j)) > Matrices.EPS) { y = i; x = j; nz = true; } } } if (!nz) { break; } if (k != y) { copy.swapRows(k, y); } if (k != x) { copy.swapColumns(k, x); } } double d = copy.get(k, k); for (int j = k; j < columns; j++) { copy.set(k, j, copy.get(k, j) / d); } for (int i = k + 1; i < rows; i++) { double t = copy.get(i, k); for (int j = k; j < columns; j++) { copy.set(i, j, copy.get(i, j) - t * copy.get(k, j)); } } for (int j = k + 1; j < columns; j++) { double t = copy.get(k, j); for (int i = k; i < rows; i++) { copy.set(i, j, copy.get(i, j) - t * copy.get(i, k)); } } } int result = 0; while (result < min && Math.abs(copy.get(result, result)) > Matrices.EPS) { result++; } return result; }

Target:
public int rank() { if ((columns == 0) || (rows == 0)) { return 0; } Matrix copy = copy(); int min = (columns > rows) ? rows : columns; for (int k = 0; k < min; k++) { if (Math.abs(copy.get(k, k)) <= Matrices.EPS) { int x = 0; int y = 0; boolean nz = false; for (int i = k; i < rows && !nz; i++) { for (int j = k; j < columns && !nz; j++) { if (Math.abs(copy.get(i, j)) > Matrices.EPS) { y = i; x = j; nz = true; } } } if (!nz) { break; } if (k != y) { copy.swapRows(k, y); } if (k != x) { copy.swapColumns(k, x); } } double d = copy.get(k, k); for (int j = k; j < columns; j++) { copy.update(k, j, Matrices.asDivFunction(d)); } for (int i = k + 1; i < rows; i++) { double t = copy.get(i, k); for (int j = k; j < columns; j++) { copy.update(i, j, Matrices.asMinusFunction(t * copy.get(k, j))); } } for (int j = k + 1; j < columns; j++) { double t = copy.get(k, j); for (int i = k; i < rows; i++) { copy.update(i, j, Matrices.asMinusFunction(t * copy.get(i, k))); } } } int result = 0; while (result < min && Math.abs(copy.get(result, result)) > Matrices.EPS) { result++; } return result; }
Source:
public void initSelectedProfile(ListModel<VnicProfileView> profileList, VmNetworkInterface networkInterface) { Collection<VnicProfileView> profiles = Optional.ofNullable(profileList.getItems()).orElse(Collections.emptyList()); profileList.setSelectedItem(profiles.stream() .filter(profile -> !Objects.equals(profile, VnicProfileView.EMPTY)) .findFirst() .orElse(VnicProfileView.EMPTY)); }

Target:
public void initSelectedProfile(ListModel<VnicProfileView> profileList, VmNetworkInterface networkInterface) { Collection<VnicProfileView> profiles = Optional.ofNullable(profileList.getItems()).orElse(Collections.emptyList()); Stream<VnicProfileView> profileStream = profiles.stream() .filter(profile -> !Objects.equals(profile, VnicProfileView.EMPTY)); if (StringHelper.isNotNullOrEmpty(getManagementNetworkName())) { profileStream = profileStream.filter(profile -> Objects.equals(profile.getNetworkName(), getManagementNetworkName())); } profileList.setSelectedItem(profileStream.findFirst().orElse(VnicProfileView.EMPTY)); }
Source:
public Transceiver readRandom() throws IOException { Criteria criteria = hibernateTemplate.getSessionFactory() .getCurrentSession().createCriteria(Article.class); criteria.add(Restrictions.sqlRestriction("1=1 order by rand()")); criteria.setMaxResults(1); Article randomArticle = (Article) criteria.uniqueResult(); return readMetadata(randomArticle, true ); }

Target:
public Transceiver readRandom() throws IOException { Criteria criteria = hibernateTemplate.getSessionFactory() .getCurrentSession().createCriteria(Article.class); criteria.add(Restrictions.sqlRestriction("1=1 order by rand()")); criteria.setMaxResults(1); Object result = criteria.uniqueResult(); if (result != null) { Article randomArticle = (Article) result; return readMetadata(randomArticle, true ); } throw new RestClientException("No articles present in database.", HttpStatus.NOT_FOUND); }
Source:
public void testShowLastFailureOnProjectPage() throws Exception { FreeStyleProject project = createFreeStyleProject(); final CommandInterpreter = Functions.isWindows() ? new BatchFile("test %BUILD_NUMBER% -eq 2") : new Shell("test $BUILD_NUMBER -eq 2"); project.getBuildersList().add(script); project.scheduleBuild2(0).get(); FailureCauseProjectAction action = project.getAction(FailureCauseProjectAction.class); assertNotNull(action.getAction()); assertEquals(project.getLastBuild().getAction(FailureCauseBuildAction.class), action.getAction()); project.scheduleBuild2(0).get(); assertNull(project.getAction(FailureCauseProjectAction.class).getAction()); }

Target:
public void testShowLastFailureOnProjectPage() throws Exception { assumeFalse(Functions.isWindows()); FreeStyleProject project = createFreeStyleProject(); project.getBuildersList().add(new Shell("test $BUILD_NUMBER -eq 2")); project.scheduleBuild2(0).get(); FailureCauseProjectAction action = project.getAction(FailureCauseProjectAction.class); assertNotNull(action.getAction()); assertEquals(project.getLastBuild().getAction(FailureCauseBuildAction.class), action.getAction()); project.scheduleBuild2(0).get(); assertNull(project.getAction(FailureCauseProjectAction.class).getAction()); }
Source:
public static CellProcessor getStringCellProcessor(Boolean required, Integer strLen, Integer minLength, Integer maxLength, String equals, String pattern) { CellProcessor cellProcessor = null; if (StringUtils.isNotBlank(pattern)) { cellProcessor = addRegex(pattern); } if (maxLength != null || minLength != null) { cellProcessor = addStrMinMax(cellProcessor, minLength, maxLength); } if (strLen != null) { cellProcessor = addStrLength(cellProcessor, strLen); } if (StringUtils.isNotBlank(equals)) { cellProcessor = addEquals(cellProcessor, equals); } if (required == null || !required) { cellProcessor = addOptional(cellProcessor); } return cellProcessor; }

Target:
public static CellProcessor getStringCellProcessor(Boolean required, Integer strLen, Integer minLength, Integer maxLength, String equals, String pattern) { CellProcessor cellProcessor = null; if (StringUtils.isNotBlank(pattern)) { cellProcessor = addRegex(pattern); } else if (maxLength != null || minLength != null) { cellProcessor = addStrMinMax(cellProcessor, minLength, maxLength); } else if (strLen != null) { cellProcessor = addStrLength(cellProcessor, strLen); } else if (StringUtils.isNotBlank(equals)) { cellProcessor = addEquals(cellProcessor, equals); } if (required == null || !required) { cellProcessor = addOptional(cellProcessor); } return cellProcessor; }
Source:
public Map<IProject, File> getProjects() { final TreeItem[] selection = tree.getSelection(); Map<IProject, File> ret = new HashMap<IProject, File>(selection.length); for (int i = 0; i < selection.length; ++i) { TreeItem treeItem = selection[i]; while (treeItem.getData() == null && treeItem.getParentItem() != null) { treeItem = treeItem.getParentItem(); } final IProject project = (IProject) treeItem.getData(); final IPath selectedRepo = Path.fromOSString(treeItem.getText(2)); IPath localPathToRepo = selectedRepo; if (!selectedRepo.isAbsolute()) { localPathToRepo = project.getLocation().append("/").append(selectedRepo); } ret.put(project, localPathToRepo.toFile()); } return ret; }

Target:
public Map<IProject, File> getProjects() { final TreeItem[] selection = tree.getSelection(); Map<IProject, File> ret = new HashMap<IProject, File>(selection.length); for (int i = 0; i < selection.length; ++i) { TreeItem treeItem = selection[i]; while (treeItem.getData() == null && treeItem.getParentItem() != null) { treeItem = treeItem.getParentItem(); } final IProject project = (IProject) treeItem.getData(); final IPath selectedRepo = Path.fromOSString(treeItem.getText(2)); IPath localPathToRepo = selectedRepo; if (!selectedRepo.isAbsolute()) { localPathToRepo = project.getLocation().append(selectedRepo); } ret.put(project, localPathToRepo.toFile()); } return ret; }
Source:
public void applyConfig(Configuration config, boolean reindex, boolean interactive) { setConfiguration(config); LOGGER.log(Level.INFO, "Configuration updated: {0}", configuration.getSourceRoot()); if (reindex) { refreshSearcherManagerMap(); maybeRefreshIndexSearchers(); refreshDateForLastIndexRun(); } if (isAuthorizationWatchdog() && config.getPluginDirectory() != null) { startWatchDogService(new File(config.getPluginDirectory())); } else { stopWatchDogService(); } getAuthorizationFramework().setPluginDirectory(config.getPluginDirectory()); getAuthorizationFramework().setStack(config.getPluginStack()); getAuthorizationFramework().reload(); }

Target:
public void applyConfig(Configuration config, boolean reindex, boolean interactive) { setConfiguration(config, interactive); LOGGER.log(Level.INFO, "Configuration updated: {0}", configuration.getSourceRoot()); if (reindex) { refreshSearcherManagerMap(); maybeRefreshIndexSearchers(); refreshDateForLastIndexRun(); } if (isAuthorizationWatchdog() && config.getPluginDirectory() != null) { startWatchDogService(new File(config.getPluginDirectory())); } else { stopWatchDogService(); } getAuthorizationFramework().setPluginDirectory(config.getPluginDirectory()); getAuthorizationFramework().setStack(config.getPluginStack()); getAuthorizationFramework().reload(); }
Source:
public boolean saveFile(File dest, InputStream stream, boolean shouldUnzip, int attempt) { String destPath = dest.getAbsolutePath(); try { LOGGER.trace("Saving file [" + destPath + "]"); if (shouldUnzip) { zipUtil.unzip(new ZipInputStream(stream), dest); } else { systemService.streamToFile(stream, dest); } LOGGER.trace("File [" + destPath + "] saved."); return true; } catch (IOException e) { final String message = format("Failed to save the file to: [%s]", destPath); if (attempt < GoConstants.PUBLISH_MAX_RETRIES) { LOGGER.warn(message, e); } else { LOGGER.error(message, e); } return false; } catch (IllegalPathException e) { final String message = format("Failed to save the file to: [%s]", destPath); LOGGER.error(message, e); return false; } }

Target:
public boolean saveFile(File dest, InputStream stream, boolean shouldUnzip, int attempt) { String destPath = dest.getAbsolutePath(); try { LOGGER.trace("Saving file [{}]", destPath); if (shouldUnzip) { zipUtil.unzip(new ZipInputStream(stream), dest); } else { systemService.streamToFile(stream, dest); } LOGGER.trace("File saved.", destPath); return true; } catch (IOException e) { final String message = format("Failed to save the file to: [%s]", destPath); if (attempt < GoConstants.PUBLISH_MAX_RETRIES) { LOGGER.warn(message, e); } else { LOGGER.error(message, e); } return false; } catch (IllegalPathException e) { final String message = format("Failed to save the file to: [%s]", destPath); LOGGER.error(message, e); return false; } }
Source:
private Map<TopicPartition, Long> committedOffsetForChangelogs(final Set<TopicPartition> partitions) { final Map<TopicPartition, Long> committedOffsets; try { committedOffsets = fetchCommittedOffsets(partitions, mainConsumer); } catch (final StreamsException e) { if (e.getCause() instanceof TimeoutException) { return Collections.emptyMap(); } else { throw e; } } lastUpdateOffsetTime = time.milliseconds(); return committedOffsets; }

Target:
private Map<TopicPartition, Long> committedOffsetForChangelogs(final Set<TopicPartition> partitions) { final Map<TopicPartition, Long> committedOffsets; try { committedOffsets = fetchCommittedOffsets(partitions, mainConsumer); } catch (final TimeoutException e) { return Collections.emptyMap(); } lastUpdateOffsetTime = time.milliseconds(); return committedOffsets; }
Source:
public void finish() { ListenableFuture<?> currentlyBlocked = blocked; statisticAggregation.finish(); ListenableFuture<?> blockedOnAggregation = statisticAggregation.isBlocked(); ListenableFuture<?> blockedOnFinish = NOT_BLOCKED; if (state == State.RUNNING) { state = State.FINISHING; finishFuture = pageSink.finish(); blockedOnFinish = toListenableFuture(finishFuture); updateWrittenBytes(); } if (currentlyBlocked.isDone() && blockedOnAggregation.isDone() && blockedOnFinish.isDone()) { this.blocked = NOT_BLOCKED; } else { this.blocked = allAsList(currentlyBlocked, blockedOnAggregation, blockedOnFinish); } }

Target:
public void finish() { ListenableFuture<?> currentlyBlocked = blocked; statisticAggregationOperator.finish(); ListenableFuture<?> blockedOnAggregation = statisticAggregationOperator.isBlocked(); ListenableFuture<?> blockedOnFinish = NOT_BLOCKED; if (state == State.RUNNING) { state = State.FINISHING; finishFuture = pageSink.finish(); blockedOnFinish = toListenableFuture(finishFuture); updateWrittenBytes(); } this.blocked = allAsList(currentlyBlocked, blockedOnAggregation, blockedOnFinish); }
Source:
void setExpirationWaitMillis(int expirationWaitMillis) { this.expirationWaitMillis = expirationWaitMillis; }

Target:
static void setExpirationWaitMillis(int expirationWaitMillis) { EXPIRATION_WAIT_MILLIS = expirationWaitMillis; }
Source:
public UserProperty reconfigure(StaplerRequest req, JSONObject form) throws FormException { if (form==null) { return null; } UserPropertyDescriptor descriptor = getDescriptor(); return descriptor==null ? null : descriptor.newInstance(req, form); }

Target:
public UserProperty reconfigure(StaplerRequest req, JSONObject form) throws FormException { if (form==null) { return null; } UserPropertyDescriptor descriptor = getDescriptor(); return descriptor==null ? this : descriptor.newInstance(req, form); }
Source:
public Collection<Long> getSupportedCommands(long deviceId) { List<Long> result = new ArrayList<>(); Position lastPosition = Context.getIdentityManager().getLastPosition(deviceId); for (long commandId : getAllDeviceItems(deviceId)) { Command command = getById(commandId); if (lastPosition != null) { BaseProtocol protocol = Context.getServerManager().getProtocol(lastPosition.getProtocol()); if ((command.getTextChannel() ? protocol.getSupportedTextCommands() : protocol.getSupportedDataCommands()) .contains(command.getType())) { result.add(commandId); } } else if (command.getType().equals(Command.TYPE_CUSTOM)) { result.add(commandId); } } return result; }

Target:
public Collection<Long> getSupportedCommands(long deviceId) { List<Long> result = new ArrayList<>(); Position lastPosition = Context.getIdentityManager().getLastPosition(deviceId); for (long commandId : getAllDeviceItems(deviceId)) { Command command = getById(commandId); if (lastPosition != null) { BaseProtocol protocol = Context.getServerManager().getProtocol(lastPosition.getProtocol()); if (command.getTextChannel() && protocol.getSupportedTextCommands().contains(command.getType()) || !command.getTextChannel() && protocol.getSupportedDataCommands().contains(command.getType())) { result.add(commandId); } } else if (command.getType().equals(Command.TYPE_CUSTOM)) { result.add(commandId); } } return result; }
Source:
public void test_upcoming() throws IOException { Call<MovieResultsPage> call = getUnauthenticatedInstance().moviesService().upcoming( null, "el" ); MovieResultsPage page = call.execute().body(); assertThat(page).isNotNull(); assertThat(page.results).isNotEmpty(); }

Target:
public void test_upcoming() throws IOException { Call<MovieResultsPage> call = getUnauthenticatedInstance().moviesService().upcoming(); MovieResultsPage page = call.execute().body(); assertThat(page).isNotNull(); assertThat(page.results).isNotEmpty(); }
Source:
public int seekKeyExact(Slice nativeValue) { if (positionCount == 0) { return -1; } mapBlock.ensureHashTableLoaded(); int[] hashTable = mapBlock.getHashTables().get().get(); long hashCode; try { hashCode = (long) mapBlock.keyNativeHashCode.invokeExact(nativeValue); } catch (Throwable throwable) { throw handleThrowable(throwable); } int hashTableOffset = offset / 2 * HASH_MULTIPLIER; int hashTableSize = positionCount / 2 * HASH_MULTIPLIER; int position = computePosition(hashCode, hashTableSize); while (true) { int keyPosition = hashTable[hashTableOffset + position]; if (keyPosition == -1) { return -1; } Boolean match; try { Block keyBlock = mapBlock.getRawKeyBlock(); match = keyBlock.equals(offset / 2 + keyPosition, nativeValue); } catch (Throwable throwable) { throw handleThrowable(throwable); } checkNotIndeterminate(match); if (match) { return keyPosition * 2 + 1; } position++; if (position == hashTableSize) { position = 0; } } }

Target:
public int seekKeyExact(Slice nativeValue) { if (positionCount == 0) { return -1; } mapBlock.ensureHashTableLoaded(); int[] hashTable = mapBlock.getHashTables().get(); long hashCode; try { hashCode = (long) mapBlock.keyNativeHashCode.invokeExact(nativeValue); } catch (Throwable throwable) { throw handleThrowable(throwable); } int hashTableOffset = offset / 2 * HASH_MULTIPLIER; int hashTableSize = positionCount / 2 * HASH_MULTIPLIER; int position = computePosition(hashCode, hashTableSize); while (true) { int keyPosition = hashTable[hashTableOffset + position]; if (keyPosition == -1) { return -1; } Boolean match; try { match = mapBlock.getRawKeyBlock().bytesEqual(offset / 2 + keyPosition, 0, nativeValue, 0, nativeValue.length()); } catch (Throwable throwable) { throw handleThrowable(throwable); } checkNotIndeterminate(match); if (match) { return keyPosition * 2 + 1; } position++; if (position == hashTableSize) { position = 0; } } }
Source:
public void addChild(String where, DocStruct inchild) throws TypeNotAllowedAsChildException { if (where == null || inchild == null || inchild.getType() == null) { logger.warn("DocStruct or DocStructType is null"); return; } int next = where.indexOf(44) + 1; if( next != 0 ){ ((DocStruct) children.get(Integer.parseInt(where.substring(0, next - 1)))).addChild(where.substring(next), inchild) ;}else{ addChild(Integer.valueOf(where), inchild); } }

Target:
public void addChild(String where, DocStruct inchild) throws TypeNotAllowedAsChildException { if (where == null || inchild == null || inchild.getType() == null) { logger.warn("DocStruct or DocStructType is null"); return; } int next = where.indexOf(44) + 1; if (next != 0) { int first = Integer.parseInt(where.substring(0, next - 1)); String rest = where.substring(next); ((DocStruct) children.get(first)).addChild(rest, inchild); } else { addChild(Integer.valueOf(where), inchild); } }
Source:
public List<Integer> getScores() { return scores; }

Target:
public List<Score> getScores() { return scores; }
Source:
public void shouldThrowExceptionIfNoTypeMappingWasFoundWithoutAccessingContentProviderBlocking() { final StorIOContentResolver storIOContentResolver = mock(StorIOContentResolver.class); final StorIOContentResolver.Internal internal = mock(StorIOContentResolver.Internal.class); when(storIOContentResolver.internal()).thenReturn(internal); when(storIOContentResolver.get()).thenReturn(new PreparedGet.Builder(storIOContentResolver)); final PreparedGet<TestItem> preparedGet = storIOContentResolver .get() .object(TestItem.class) .withQuery(Query.builder().uri(mock(Uri.class)).build()) .prepare(); try { preparedGet.executeAsBlocking(); failBecauseExceptionWasNotThrown(StorIOException.class); } catch (StorIOException expected) { assertThat(expected).hasCauseInstanceOf(IllegalStateException.class); } verify(storIOContentResolver).get(); verify(storIOContentResolver).internal(); verify(internal).typeMapping(TestItem.class); verify(internal, never()).query(any(Query.class)); verifyNoMoreInteractions(storIOContentResolver, internal); }

Target:
public void shouldThrowExceptionIfNoTypeMappingWasFoundWithoutAccessingContentProviderBlocking() { final StorIOContentResolver storIOContentResolver = mock(StorIOContentResolver.class); final StorIOContentResolver.Internal internal = mock(StorIOContentResolver.Internal.class); when(storIOContentResolver.internal()).thenReturn(internal); when(storIOContentResolver.get()).thenReturn(new PreparedGet.Builder(storIOContentResolver)); final PreparedGet<TestItem> preparedGet = storIOContentResolver .get() .object(TestItem.class) .withQuery(Query.builder().uri(mock(Uri.class)).build()) .prepare(); try { preparedGet.executeAsBlocking(); failBecauseExceptionWasNotThrown(StorIOException.class); } catch (StorIOException expected) { assertThat(expected).hasCauseInstanceOf(IllegalStateException.class); assertThat(expected.getCause()).hasMessage("This type does not have type mapping: " + "type = " + TestItem.class + "," + "ContentProvider was not touched by this operation, please add type mapping for this type"); } verify(storIOContentResolver).get(); verify(storIOContentResolver).internal(); verify(internal).typeMapping(TestItem.class); verify(internal, never()).query(any(Query.class)); verifyNoMoreInteractions(storIOContentResolver, internal); }
Source:
public String readResource(String resource) { try { URL resourceUrl = Customer.class.getResource(resource); return Resources.toString(resourceUrl, Charsets.UTF_8); } catch (IOException e) { throw new RuntimeException(e); } }

Target:
public String readResource(String resource) { try { URL resourceUrl = Customer.class.getResource(resource); return Resources.toString(resourceUrl, StandardCharsets.UTF_8); } catch (IOException e) { throw new RuntimeException(e); } }
Source:
private void vmwareProviderChanged() { Provider provider = getProviders().getSelectedItem(); if (provider == null) { provider = new Provider<>(); provider.setAdditionalProperties(new VmwareVmProviderProperties()); } getUsername().setEntity(provider.getUsername()); getPassword().setEntity(provider.getPassword()); VmwareVmProviderProperties properties = (VmwareVmProviderProperties) provider.getAdditionalProperties(); getvCenter().setEntity(properties.getvCenter()); getEsx().setEntity(properties.getEsx()); getVmwareDatacenter().setEntity(properties.getDataCenter()); getVerify().setEntity(properties.isVerifySSL()); if (properties.getProxyHostId() == null) { getProxyHosts().setSelectedItem(null); } else { for (VDS host : getProxyHosts().getItems()) { if (host != null && host.getId().equals(properties.getProxyHostId())) { getProxyHosts().setSelectedItem(host); break; } } } }

Target:
private void vmwareProviderChanged() { Provider<VmwareVmProviderProperties> provider = getVmwareProviders().getSelectedItem(); if (provider == null) { provider = new Provider<>(); provider.setAdditionalProperties(new VmwareVmProviderProperties()); } getUsername().setEntity(provider.getUsername()); getPassword().setEntity(provider.getPassword()); VmwareVmProviderProperties properties = (VmwareVmProviderProperties) provider.getAdditionalProperties(); getvCenter().setEntity(properties.getvCenter()); getEsx().setEntity(properties.getEsx()); getVmwareDatacenter().setEntity(properties.getDataCenter()); getVerify().setEntity(properties.isVerifySSL()); if (properties.getProxyHostId() == null) { getProxyHosts().setSelectedItem(null); } else { for (VDS host : getProxyHosts().getItems()) { if (host != null && host.getId().equals(properties.getProxyHostId())) { getProxyHosts().setSelectedItem(host); break; } } } }
Source:
public static <T, QueryType extends Query<T>> QueryRunner<T> makeQueryRunner( QueryRunnerFactory<T, QueryType> factory, Segment adapter ) { return new FinalizeResultsQueryRunner<T>( new BySegmentQueryRunner<T>( adapter.getIdentifier(), adapter.getDataInterval().getStart(), factory.createRunner(adapter) ), (QueryToolChest<T, Query<T>>)factory.getToolchest() ); }

Target:
public static <T, QueryType extends Query<T>> QueryRunner<T> makeQueryRunner( QueryRunnerFactory<T, QueryType> factory, Segment adapter ) { return makeQueryRunner(factory, segmentId, adapter); }
Source:
private static DigitalGoods deserializeDigitalGoods(JsonObject jsonObject) { if (jsonObject.has(MEMBER_DIGITAL_GOODS)) { JsonObject jsonDigitalGoods = jsonObject.get(MEMBER_DIGITAL_GOODS).getAsJsonObject(); return jsonDigitalGoods == null ? null : DigitalGoodsTypeAdapter.getInstance() .fromJson(jsonDigitalGoods); } else { return null; } }

Target:
private static DigitalGoods deserializeDigitalGoods(JsonObject jsonObject) { JsonElement digitalGoods = jsonObject.get(MEMBER_DIGITAL_GOODS); if (digitalGoods != null) { JsonObject jsonDigitalGoods = digitalGoods.getAsJsonObject(); return DigitalGoodsTypeAdapter.getInstance().fromJson(jsonDigitalGoods); } else { return null; } }
Source:
public Response associateBranchToArtifact(long branchUuid, int artifactId) { BranchReadable branch = getBranchById(branchUuid); boolean modified = false; if (isDifferent(branch.getAssociatedArtifactId(), artifactId)) { activityLog.createEntry(BRANCH_OPERATION_TYPEID, ActivityLog.INITIAL_STATUS, String.format( "Branch Operation Associate Branch to Artifact {branchUUID: %s prevArt: %s newArt: %s accountId: %s serverId: %s clientId: %s}", branchUuid, branch.getAssociatedArtifactId(), artifactId, accountId, serverId, clientId)); ArtifactReadable artifact = newQuery().fromBranch(COMMON_ID).andUuid(artifactId).getResults().getExactlyOne(); Callable<?> op = getBranchOps().associateBranchToArtifact(branch, artifact); executeCallable(op); modified = true; } return asResponse(modified); }

Target:
public Response associateBranchToArtifact(long branchUuid, int artifactId) { BranchReadable branch = getBranchById(branchUuid); boolean modified = false; if (isDifferent(branch.getAssociatedArtifactId(), artifactId)) { try { activityLog.createEntry(BRANCH_OPERATION_TYPEID, ActivityLog.INITIAL_STATUS, String.format( "Branch Operation Associate Branch to Artifact {branchUUID: %s prevArt: %s newArt: %s accountId: %s serverId: %s clientId: %s}", branchUuid, branch.getAssociatedArtifactId(), artifactId, RestUtil.getAccountId(httpHeaders), RestUtil.getServerId(httpHeaders), RestUtil.getClientId(httpHeaders))); } catch (OseeCoreException ex) { OseeLog.log(ActivityLog.class, OseeLevel.SEVERE_POPUP, ex); } ArtifactReadable artifact = newQuery().fromBranch(COMMON_ID).andUuid(artifactId).getResults().getExactlyOne(); Callable<?> op = getBranchOps().associateBranchToArtifact(branch, artifact); executeCallable(op); modified = true; } return asResponse(modified); }
Source:
private static Class getClass(String className, ClassLoader loader, String[] packages) throws ClassNotFoundException { String save = className; int dimensions = 0; int index = 0; while ((index = className.indexOf("[]", index) + 1) > 0) { dimensions++; } StringBuilder brackets = new StringBuilder(className.length() - dimensions); for (int i = 0; i < dimensions; i++) { brackets.append('['); } className = className.substring(0, className.length() - 2 * dimensions); String prefix = (dimensions > 0) ? brackets + "L" : ""; String suffix = (dimensions > 0) ? ";" : ""; try { return Class.forName(prefix + className + suffix, false, loader); } catch (ClassNotFoundException ignore) { } for (int i = 0; i < packages.length; i++) { try { return Class.forName(prefix + packages[i] + '.' + className + suffix, false, loader); } catch (ClassNotFoundException ignore) { } } if (dimensions == 0) { Class c = (Class) primitives.get(className); if (c != null) { return c; } } else { String transform = (String) transforms.get(className); if (transform != null) { try { return Class.forName(brackets + transform, false, loader); } catch (ClassNotFoundException ignore) { } } } throw new ClassNotFoundException(save); }

Target:
private static Class getClass(String className, ClassLoader loader, String[] packages) throws ClassNotFoundException { String save = className; int dimensions = 0; int index = 0; while ((index = className.indexOf("[]", index) + 1) > 0) { dimensions++; } StringBuffer brackets = new StringBuffer(className.length() - dimensions); for (int i = 0; i < dimensions; i++) { brackets.append('['); } className = className.substring(0, className.length() - 2 * dimensions); String prefix = (dimensions > 0) ? brackets + "L" : ""; String suffix = (dimensions > 0) ? ";" : ""; try { return Class.forName(prefix + className + suffix, false, loader); } catch (ClassNotFoundException ignore) { } for (int i = 0; i < packages.length; i++) { try { return Class.forName(prefix + packages[i] + '.' + className + suffix, false, loader); } catch (ClassNotFoundException ignore) { } } if (dimensions == 0) { Class c = (Class) primitives.get(className); if (c != null) { return c; } } else { String transform = (String) transforms.get(className); if (transform != null) { try { return Class.forName(brackets + transform, false, loader); } catch (ClassNotFoundException ignore) { } } } throw new ClassNotFoundException(save); }
Source:
private void enablePercentageOptions() { this.percentageThreshold.setEnabled(true); this.percentageThresholdCheck.setEnabled(true); this.percentageThresholdCheck.setSelected(true); }

Target:
private void enablePercentageOptions() { this.percentageThresholdTextOne.setEnabled(true); this.percentageThresholdCheck.setEnabled(true); this.percentageThresholdCheck.setSelected(true); this.percentageThresholdTextTwo.setEnabled(true); }
Source:
private ObjectRemoteQueryEngine getQueryEngineForMediaType(MediaType mediaType) { ObjectRemoteQueryEngine queryEngine = enginePerMediaType.get(mediaType.getTypeSubtype()); if (queryEngine == null) { ReflectionMatcher matcher = mediaType.match(APPLICATION_PROTOSTREAM) ? cr.getComponent(ProtobufObjectReflectionMatcher.class) : cr.getComponent(ObjectReflectionMatcher.class); queryEngine = new ObjectRemoteQueryEngine(cache, true, matcher.getClass()); enginePerMediaType.put(mediaType.getTypeSubtype(), queryEngine); } return queryEngine; }

Target:
private ObjectRemoteQueryEngine getQueryEngineForMediaType(MediaType mediaType) { ObjectRemoteQueryEngine queryEngine = enginePerMediaType.get(mediaType.getTypeSubtype()); if (queryEngine == null) { ReflectionMatcher matcher = mediaType.match(APPLICATION_PROTOSTREAM) ? cr.getComponent(ProtobufObjectReflectionMatcher.class) : cr.getComponent(ObjectReflectionMatcher.class); queryEngine = new ObjectRemoteQueryEngine(cache, searchMapping != null, matcher.getClass()); enginePerMediaType.put(mediaType.getTypeSubtype(), queryEngine); } return queryEngine; }
Source:
void setup() { MockitoAnnotations.initMocks(this); when(asyncClient.getEntityPath()).thenReturn(ENTITY_PATH); when(asyncClient.getFullyQualifiedNamespace()).thenReturn(NAMESPACE); when(asyncClient.getReceiverOptions()).thenReturn(new ReceiverOptions(ReceiveMode.PEEK_LOCK, 1, maxAutoLockRenewalDuration)); when(messageLockToken).thenReturn(LOCK_TOKEN); client = new ServiceBusReceiverClient(asyncClient, OPERATION_TIMEOUT); }

Target:
void setup() { MockitoAnnotations.initMocks(this); when(asyncClient.getEntityPath()).thenReturn(ENTITY_PATH); when(asyncClient.getFullyQualifiedNamespace()).thenReturn(NAMESPACE); when(asyncClient.getReceiverOptions()).thenReturn(new ReceiverOptions(ReceiveMode.PEEK_LOCK, 1, maxAutoLockRenewalDuration)); client = new ServiceBusReceiverClient(asyncClient, OPERATION_TIMEOUT); }
Source:
private static ProxyOptions attemptToLoadAzureProxy(Configuration configuration, String proxyProperty) { String proxyConfiguration = configuration.get(proxyProperty); if (CoreUtils.isNullOrEmpty(proxyConfiguration)) { return null; } try { URL proxyUrl = new URL(proxyConfiguration); int port = (proxyUrl.getPort() == -1) ? proxyUrl.getDefaultPort() : proxyUrl.getPort(); ProxyOptions proxyOptions = new ProxyOptions(Type.HTTP, new InetSocketAddress(proxyUrl.getHost(), port)) .setNonProxyHosts(configuration.get(Configuration.PROPERTY_NO_PROXY)); String userInfo = proxyUrl.getUserInfo(); if (userInfo != null) { String[] usernamePassword = userInfo.split(":", 2); if (usernamePassword.length == 2) { try { proxyOptions.setCredentials( URLDecoder.decode(usernamePassword[0], StandardCharsets.UTF_8.toString()), URLDecoder.decode(usernamePassword[1], StandardCharsets.UTF_8.toString()) ); } catch (UnsupportedEncodingException e) { return null; } } } return proxyOptions; } catch (MalformedURLException ex) { return null; } }

Target:
private static ProxyOptions attemptToLoadAzureProxy(Configuration configuration, String proxyProperty) { String proxyConfiguration = configuration.get(proxyProperty); if (CoreUtils.isNullOrEmpty(proxyConfiguration)) { return null; } try { URL proxyUrl = new URL(proxyConfiguration); int port = (proxyUrl.getPort() == -1) ? proxyUrl.getDefaultPort() : proxyUrl.getPort(); ProxyOptions proxyOptions = new ProxyOptions(Type.HTTP, new InetSocketAddress(proxyUrl.getHost(), port)) .setNonProxyHosts(configuration.get(Configuration.PROPERTY_NO_PROXY)); String userInfo = proxyUrl.getUserInfo(); if (userInfo != null) { String[] usernamePassword = userInfo.split(":", 2); if (usernamePassword.length == 2) { try { proxyOptions.setCredentials( URLDecoder.decode(usernamePassword[0], StandardCharsets.UTF_8.toString()), URLDecoder.decode(usernamePassword[1], StandardCharsets.UTF_8.toString()) ); } catch (UnsupportedEncodingException e) { return null; } } } return proxyOptions; } catch (MalformedURLException ex) { LOGGER.warning(INVALID_AZURE_PROXY_URL, proxyProperty); return null; } }
Source:
public static void endJob(ExecutionContext context, boolean exitStatus) { if (context.isMonitored()) { if (context.getExecutionMethod() == ExecutionMethod.AsJob) { if (!context.getJob().isAsyncJob()) { context.getJob().endJob(exitStatus); } } else if (context.getExecutionMethod() == ExecutionMethod.AsStep) { if (context.shouldEndJob()) { Job job = JobRepositoryFactory.getJobRepository().getJob(context.getStep().getJobId()); job.endJob(exitStatus); } } } }

Target:
public static void endJob(ExecutionContext context, boolean exitStatus) { Job job = context.getJob(); try { if (context.isMonitored()) { if (context.getExecutionMethod() == ExecutionMethod.AsJob && job != null) { if (!(job.isAsyncJob() && exitStatus)) { endJob(exitStatus, job); } } else { Step step = context.getStep(); if (context.getExecutionMethod() == ExecutionMethod.AsStep && step != null) { if (context.shouldEndJob()) { if (job == null) { job = JobRepositoryFactory.getJobRepository().getJob(step.getJobId()); } if (job != null) { endJob(exitStatus, job); } } } } } } catch (Exception e) { log.error(e); } }
Source:
public void showDocumentedCreatedSuccessfully(DocumentRelatedResponse documentCreationResponse) { if (onDocumentCreatedListener != null) { createdDocument.setId(documentCreationResponse.getResourceId()); onDocumentCreatedListener.onDocumentCreationSuccess(createdDocument); } else { Toaster.show(rootView, String.format(getString(R.string.uploaded_successfully), fileChoosen.getName())); } getDialog().dismiss(); }

Target:
public void showDocumentedCreatedSuccessfully(DocumentRelatedResponse documentCreationResponse) { if (onDocumentChangedListener != null) { createdDocument.setId(documentCreationResponse.getResourceId()); onDocumentChangedListener.onDocumentCreationSuccess(createdDocument); } else { Toaster.show(rootView, String.format(getString(R.string.uploaded_successfully), fileChoosen.getName())); } getDialog().dismiss(); }
Source:
public int write(ByteBuffer src) throws IOException { if (state == State.CLOSING) throw closingException(); if (state != State.READY) return 0; if (!flush(netWriteBuffer)) return 0; netWriteBuffer.clear(); SSLEngineResult wrapResult = sslEngine.wrap(src, netWriteBuffer); netWriteBuffer.flip(); if (wrapResult.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING && wrapResult.getStatus() == Status.OK) throw renegotiationException(); if (wrapResult.getStatus() == Status.OK) { int written = wrapResult.bytesConsumed(); flush(netWriteBuffer); return written; } else if (wrapResult.getStatus() == Status.BUFFER_OVERFLOW) { int currentNetWriteBufferSize = netWriteBufferSize(); netWriteBuffer.compact(); netWriteBuffer = Utils.ensureCapacity(netWriteBuffer, currentNetWriteBufferSize); netWriteBuffer.flip(); if (netWriteBuffer.limit() >= currentNetWriteBufferSize) throw new IllegalStateException("SSL BUFFER_OVERFLOW when available data size (" + netWriteBuffer.limit() + ") >= network buffer size (" + currentNetWriteBufferSize + ")"); } else if (wrapResult.getStatus() == Status.BUFFER_UNDERFLOW) { throw new IllegalStateException("SSL BUFFER_UNDERFLOW during write"); } else if (wrapResult.getStatus() == Status.CLOSED) { throw new EOFException(); } return 0; }

Target:
public int write(ByteBuffer src) throws IOException { if (state == State.CLOSING) throw closingException(); if (state != State.READY) return 0; int written = 0; while (flush(netWriteBuffer) && src.hasRemaining()) { netWriteBuffer.clear(); SSLEngineResult wrapResult = sslEngine.wrap(src, netWriteBuffer); netWriteBuffer.flip(); if (wrapResult.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING && wrapResult.getStatus() == Status.OK) throw renegotiationException(); if (wrapResult.getStatus() == Status.OK) { written += wrapResult.bytesConsumed(); } else if (wrapResult.getStatus() == Status.BUFFER_OVERFLOW) { netWriteBuffer = Utils.ensureCapacity(netWriteBuffer, netWriteBufferSize()); netWriteBuffer.position(netWriteBuffer.limit()); } else if (wrapResult.getStatus() == Status.BUFFER_UNDERFLOW) { throw new IllegalStateException("SSL BUFFER_UNDERFLOW during write"); } else if (wrapResult.getStatus() == Status.CLOSED) { throw new EOFException(); } } return written; }
Source:
public Envelope findCode(String refId) throws Exception { Envelope projectionBounds = null; CoordinateReferenceSystem crs = null; CRSAuthorityFactory authorityFactory = CRS.getAuthorityFactory(true); Set<String> authorityCodes = authorityFactory.getAuthorityCodes(CoordinateReferenceSystem.class); if (refId.contains("WGS 84")) { crs = authorityFactory.createCoordinateReferenceSystem("EPSG:4326"); projectionBounds = getExtents(crs); } else { for (String code : authorityCodes) { if (code.startsWith("EPSG:") && code.contains(refId)) { try { crs = authorityFactory.createCoordinateReferenceSystem(code); } catch (Exception e) { System.err.printf("%s: Unable to create CRS: %s\n", code, e.getMessage()); } projectionBounds = getExtents(crs); System.err.printf("%s, %s \n", code, projectionBounds); } } } return projectionBounds; }

Target:
public Envelope findCode(String refId) throws Exception { Envelope projectionBounds = null; CoordinateReferenceSystem crs = null; CRSAuthorityFactory authorityFactory = CRS.getAuthorityFactory(true); crs = authorityFactory.createCoordinateReferenceSystem(refId); projectionBounds = getExtents(crs); return projectionBounds; }
Source:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!BuildConfig.DEBUG) { Fabric.with(this, new Crashlytics()); } this.setContentView(R.layout.main); if (savedInstanceState == null) { Uri uri = BaseballCardContract.getUri(this.getPackageName()); Cursor cursor = this.getContentResolver().query(uri, BaseballCardContract.PROJECTION, null, null, null); FragmentTransaction ft = this.getSupportFragmentManager().beginTransaction(); ft.add(R.id.fragment_holder, new BaseballCardList(), FragmentTags.CARD_LIST); ft.commit(); if (cursor == null || cursor.getCount() == 0) { this.getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_holder, new BaseballCardDetails(), FragmentTags.EDIT_CARD) .addToBackStack(FragmentTags.EDIT_CARD).commit(); } cursor.close(); this.getSupportFragmentManager().addOnBackStackChangedListener(this); } prefs = getSharedPreferences(SharedPreferenceKeys.PREFS, MODE_PRIVATE); showSurvey1Dialog(); showSurvey2Dialog(); }

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!BuildConfig.DEBUG) { Fabric.with(this, new Crashlytics()); } this.setContentView(R.layout.main); fragmentManager = getSupportFragmentManager(); if (savedInstanceState == null) { Uri uri = BaseballCardContract.getUri(this.getPackageName()); Cursor cursor = this.getContentResolver().query(uri, BaseballCardContract.PROJECTION, null, null, null); fragmentManager.beginTransaction() .add(R.id.fragment_holder, new BaseballCardList(), FragmentTags.CARD_LIST) .addToBackStack(FragmentTags.CARD_LIST) .commit(); if (cursor == null || cursor.getCount() == 0) { fragmentManager.beginTransaction() .replace(R.id.fragment_holder, new BaseballCardDetails(), FragmentTags.EDIT_CARD) .addToBackStack(FragmentTags.EDIT_CARD) .commit(); } cursor.close(); fragmentManager.addOnBackStackChangedListener(this); } prefs = getSharedPreferences(SharedPreferenceKeys.PREFS, MODE_PRIVATE); showSurvey1Dialog(); showSurvey2Dialog(); }