auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean updateMetricsFromNotification(Run source, Run target) { if (source.getMetrics() != null && source.getMetrics().equals(target.getMetrics())) return false; if (source.getMetrics() == null && target.getMetrics() != null) { return false; } if (source.getMetrics() != null && target.getMetrics() == null) { target.setMetrics(source.getMetrics()); return true; } ObjectMapper mapper = new ObjectMapper(); ArrayNode sourceMetrics; try { sourceMetrics = mapper.readValue(source.getMetrics(), ArrayNode.class); } catch (IOException e) { log.debug("Impossible junk metrics were passed in for run " + target.getId(), e); return false; } ArrayNode targetMetrics; try { targetMetrics = mapper.readValue(target.getMetrics(), ArrayNode.class); } catch (IOException e) { log.debug("The database is full of garbage metrics for run " + target.getId(), e); return false; } Map<String, JsonNode> sourceMetricsMap = parseMetrics(sourceMetrics); Map<String, JsonNode> targetMetricsMap = parseMetrics(targetMetrics); if (sourceMetricsMap.equals(targetMetricsMap)) return false; targetMetricsMap.putAll(sourceMetricsMap); ArrayNode combinedMetrics = mapper.createArrayNode(); combinedMetrics.addAll(targetMetricsMap.values()); try { target.setMetrics(mapper.writeValueAsString(combinedMetrics)); } catch (JsonProcessingException e) { log.error("Failed to save data just unserialised.", e); return false; } return false; }

Target:
private boolean updateMetricsFromNotification(Run source, Run target) { if (source.getMetrics() != null && source.getMetrics().equals(target.getMetrics())) return false; if (source.getMetrics() == null) { return false; } if (source.getMetrics() != null && target.getMetrics() == null) { target.setMetrics(source.getMetrics()); return true; } ObjectMapper mapper = new ObjectMapper(); ArrayNode sourceMetrics; try { sourceMetrics = mapper.readValue(source.getMetrics(), ArrayNode.class); } catch (IOException e) { log.error("Impossible junk metrics were passed in for run " + target.getId(), e); return false; } ArrayNode targetMetrics; try { targetMetrics = mapper.readValue(target.getMetrics(), ArrayNode.class); } catch (IOException e) { log.error("The database is full of garbage metrics for run " + target.getId(), e); return false; } Map<String, JsonNode> sourceMetricsMap = parseMetrics(sourceMetrics); Map<String, JsonNode> targetMetricsMap = parseMetrics(targetMetrics); if (sourceMetricsMap.equals(targetMetricsMap)) return false; targetMetricsMap.putAll(sourceMetricsMap); ArrayNode combinedMetrics = mapper.createArrayNode(); combinedMetrics.addAll(targetMetricsMap.values()); try { target.setMetrics(mapper.writeValueAsString(combinedMetrics)); } catch (JsonProcessingException e) { log.error("Failed to save data just unserialised.", e); return false; } return true; }
Source:
public RiakTsPB.TsCell getPbCell() { final RiakTsPB.TsCell.Builder builder = RiakTsPB.TsCell.newBuilder(); if (hasVarcharValue()) { builder.setVarcharValue(ByteString.copyFromUtf8(varcharValue)); } if (hasLong()) { builder.setSint64Value(sint64Value); } if (hasTimestamp()) { builder.setTimestampValue(timestampValue); } if (hasBoolean()) { builder.setBooleanValue(booleanValue); } if (hasDouble()) { builder.setDoubleValue(doubleValue); } return builder.build(); }

Target:
RiakTsPB.TsCell getPbCell() { final RiakTsPB.TsCell.Builder builder = RiakTsPB.TsCell.newBuilder(); if (hasVarcharValue()) { builder.setVarcharValue(ByteString.copyFromUtf8(varcharValue)); } else if (hasLong()) { builder.setSint64Value(sint64Value); } else if (hasTimestamp()) { builder.setTimestampValue(timestampValue); } else if (hasBoolean()) { builder.setBooleanValue(booleanValue); } else if (hasDouble()) { builder.setDoubleValue(doubleValue); } return builder.build(); }
Source:
protected @CheckForNull MimeMessage createMail(Run<?,?> build, TaskListener listener) throws MessagingException, UnsupportedEncodingException, InterruptedException { try { Method m = getClass().getDeclaredMethod("getMail", AbstractBuild.class, BuildListener.class); if (m.getDeclaringClass() != MailSender.class) { if (build instanceof AbstractBuild && listener instanceof BuildListener) { return getMail((AbstractBuild) build, (BuildListener) listener); } else { throw new AbstractMethodError("you must override createMail rather than getMail"); } } } catch (NoSuchMethodException x) { } if (build.getResult() == Result.FAILURE) { return createFailureMail(build, listener); } if (build.getResult() == Result.UNSTABLE) { if (!dontNotifyEveryUnstableBuild) { return createUnstableMail(build, listener); } Result prev = findPreviousBuildResult(build); if (prev == Result.SUCCESS || prev == null) { return createUnstableMail(build, listener); } } if (build.getResult() == Result.SUCCESS) { Result prev = findPreviousBuildResult(build); if (prev == Result.FAILURE) { return createBackToNormalMail(build, Messages.MailSender_BackToNormal_Normal(), listener); } if (prev == Result.UNSTABLE) { return createBackToNormalMail(build, Messages.MailSender_BackToNormal_Stable(), listener); } } System.out.println("Not sending any mail as BuildResult is not set at all."); return null; }

Target:
protected @CheckForNull MimeMessage createMail(Run<?,?> build, TaskListener listener) throws MessagingException, UnsupportedEncodingException, InterruptedException { try { Method m = getClass().getDeclaredMethod("getMail", AbstractBuild.class, BuildListener.class); if (m.getDeclaringClass() != MailSender.class) { if (build instanceof AbstractBuild && listener instanceof BuildListener) { return getMail((AbstractBuild) build, (BuildListener) listener); } else { throw new AbstractMethodError("you must override createMail rather than getMail"); } } } catch (NoSuchMethodException x) { } if (build.getResult() == Result.FAILURE) { return createFailureMail(build, listener); } if (build.getResult() == Result.UNSTABLE) { if (!dontNotifyEveryUnstableBuild) { return createUnstableMail(build, listener); } Result prev = findPreviousBuildResult(build); if (prev == Result.SUCCESS || prev == null) { return createUnstableMail(build, listener); } } if (build.getResult() == Result.SUCCESS) { Result prev = findPreviousBuildResult(build); if (prev == Result.FAILURE) { return createBackToNormalMail(build, Messages.MailSender_BackToNormal_Normal(), listener); } if (prev == Result.UNSTABLE) { return createBackToNormalMail(build, Messages.MailSender_BackToNormal_Stable(), listener); } } listener.getLogger().println("No mail will be sent out, as '" + build.getFullDisplayName() + "' does not have a result yet. Please make sure you set a proper result in case of pipeline/build scripts."); return null; }
Source:
public CategoryTree createSubtree(final CategoryTree categoryTree, final Collection<? extends Identifiable<Category>> subtreeRoots) { final List<Category> subtreeRootsCategories = subtreeRoots.stream() .map(identifiable -> getCategoryOrThrow(identifiable, categoryTree)) .collect(toList()); final List<String> subtreeRootIds = subtreeRoots.parallelStream().map(Identifiable::getId).collect(toList()); subtreeRootsCategories.forEach(subtreeRoot -> { final Optional<String> rootAncestorOptional = subtreeRoot.getAncestors() .stream() .map(x -> x.getId()) .filter(ancestorId -> subtreeRootIds.contains(ancestorId)) .findFirst(); if (rootAncestorOptional.isPresent()) { throw new IllegalArgumentException(String.format("category of ID [%s] cannot be subtree root and decedent of [%s]", subtreeRoot.getId(), rootAncestorOptional.get())); } }); final List<Category> includedCategories = new LinkedList<>(); subtreeRootsCategories.forEach(parentCategory -> { includedCategories.add(parentCategory); final List<Category> children = categoryTree.findChildren(parentCategory); includedCategories.addAll(getSubtreeAsFlatList(categoryTree, children)); }); final List<Category> roots = findRoots(includedCategories); return create(includedCategories, roots, subtreeRootsCategories); }

Target:
public CategoryTree createSubtree(final CategoryTree categoryTree, final Collection<? extends Identifiable<Category>> subtreeRoots) { final List<Category> subtreeRootsCategories = subtreeRoots.stream() .map(identifiable -> getCategoryOrThrow(identifiable, categoryTree)) .collect(toList()); final List<String> subtreeRootIds = subtreeRoots.parallelStream().map(Identifiable::getId).collect(toList()); subtreeRootsCategories.forEach(subtreeRoot -> { final Optional<String> rootAncestorOptional = subtreeRoot.getAncestors() .stream() .map(x -> x.getId()) .filter(ancestorId -> subtreeRootIds.contains(ancestorId)) .findFirst(); if (rootAncestorOptional.isPresent()) { throw new IllegalArgumentException(String.format("category of ID [%s] cannot be subtree root and descendant of [%s]", subtreeRoot.getId(), rootAncestorOptional.get())); } }); final List<Category> includedCategories = new LinkedList<>(); subtreeRootsCategories.forEach(parentCategory -> { includedCategories.add(parentCategory); final List<Category> children = categoryTree.findChildren(parentCategory); includedCategories.addAll(getSubtreeAsFlatList(categoryTree, children)); }); final List<Category> roots = findRoots(includedCategories); return create(includedCategories, roots, subtreeRootsCategories); }
Source:
public static void register(){ CapabilityManager.INSTANCE.register(IGuiProvider.class, new Capability.IStorage<IGuiProvider>() { @Override public NBTBase writeNBT(Capability<IGuiProvider> capability, IGuiProvider instance, EnumFacing side) { return null; } @Override public void readNBT(Capability<IGuiProvider> capability, IGuiProvider instance, EnumFacing side, NBTBase nbt) { } }, new Callable<IGuiProvider>() { @Override public IGuiProvider call() throws Exception { return new GuiProviderBlank(); } }); }

Target:
public static void register() { CapabilityManager.INSTANCE.register(IGuiProvider.class, new Capability.IStorage<IGuiProvider>() { @Override public NBTBase writeNBT(Capability<IGuiProvider> capability, IGuiProvider instance, EnumFacing side) { return null; } @Override public void readNBT(Capability<IGuiProvider> capability, IGuiProvider instance, EnumFacing side, NBTBase nbt) { } }, new Callable<IGuiProvider>() { @Override public IGuiProvider call() throws Exception { return new GuiProviderBase(); } }); }
Source:
public boolean isNull() { return objectValue == null; }

Target:
public boolean isNull() { return false; }
Source:
public static boolean isValidVideoUrl(@NonNull String videoUrl) { if (videoUrl.contains("edx-course-videos")) { return true; } for (final String format : AppConstants.SUPPORTED_VIDEO_FORMATS) { if (isVideoHasFormat(videoUrl, format)) { return true; } } return false; }

Target:
public static boolean isValidVideoUrl(@NonNull String videoUrl) { return isSupportedVideoFormat(videoUrl, SUPPORTED_VIDEO_FORMATS); }
Source:
public void testFinalFunction() throws Exception { String code = getAboveComment(); IASTTranslationUnit tu = parseAndCheckBindings(code); ICPPASTCompositeTypeSpecifier typeDeclarationS = getCompositeType(tu, 0); IASTSimpleDeclaration functionDeclaration = getDeclaration(typeDeclarationS, 0); IASTDeclarator[] functionDeclarators = functionDeclaration.getDeclarators(); assertEquals(1, functionDeclarators.length); assertInstance(functionDeclarators[0], ICPPASTFunctionDeclarator.class); assertVirtualSpecifiers((ICPPASTFunctionDeclarator)functionDeclarators[0], false, true); ICPPASTFunctionDefinition functionDefinition = getDeclaration(typeDeclarationS, 1); IASTFunctionDeclarator declarator = functionDefinition.getDeclarator(); assertInstance(declarator, ICPPASTFunctionDeclarator.class); assertVirtualSpecifiers((ICPPASTFunctionDeclarator)declarator, false, true); BindingAssertionHelper bh= new BindingAssertionHelper(code, true); ICPPMethod funcDecl = bh.assertNonProblem("mFuncDecl()", 9); assertFalse(funcDecl.isOverride()); assertTrue(funcDecl.isFinal()); ICPPMethod funcDef = bh.assertNonProblem("mFuncDef()", 8); assertFalse(funcDef.isOverride()); assertTrue(funcDef.isFinal()); }

Target:
public void testFinalFunction() throws Exception { String code = getAboveComment(); parseAndCheckBindings(code); BindingAssertionHelper bindingHelper = new BindingAssertionHelper(code, true); CPPMethod functionDeclarationBinding = bindingHelper.assertNonProblem("mFuncDecl()", 9); assertFalse(functionDeclarationBinding.isOverride()); assertTrue(functionDeclarationBinding.isFinal()); IASTNode[] functionDeclarators = functionDeclarationBinding.getDeclarations(); assertEquals(1, functionDeclarators.length); assertInstance(functionDeclarators[0], ICPPASTFunctionDeclarator.class); assertVirtualSpecifiers((ICPPASTFunctionDeclarator)functionDeclarators[0], false, true); CPPMethod functionDefinitionBinding = bindingHelper.assertNonProblem("mFuncDef()", 8); assertFalse(functionDefinitionBinding.isOverride()); assertTrue(functionDefinitionBinding.isFinal()); IASTFunctionDeclarator declarator = functionDefinitionBinding.getDefinition(); assertInstance(declarator, ICPPASTFunctionDeclarator.class); assertVirtualSpecifiers((ICPPASTFunctionDeclarator)declarator, false, true); }
Source:
private void copySlaveJar(TaskListener listener, String workingDirectory) throws IOException, InterruptedException { String fileName = workingDirectory + "/slave.jar"; listener.getLogger().println(Messages.SSHLauncher_StartingSFTPClient(getTimestamp())); SFTPClient sftpClient = null; try { sftpClient = new SFTPClient(connection); try { SFTPv3FileAttributes fileAttributes = sftpClient._stat(workingDirectory); if (fileAttributes==null) { listener.getLogger().println(Messages.SSHLauncher_RemoteFSDoesNotExist(getTimestamp(), workingDirectory)); sftpClient.mkdirs(workingDirectory, 0700); } else if (fileAttributes.isRegularFile()) { throw new IOException(Messages.SSHLauncher_RemoteFSIsAFile(workingDirectory)); } try { sftpClient.rm(fileName); } catch (IOException e) { } listener.getLogger().println(Messages.SSHLauncher_CopyingSlaveJar(getTimestamp())); try { byte[] slaveJar = new Slave.JnlpJar("slave.jar").readFully(); OutputStream os = sftpClient.writeToFile(fileName); try { os.write(slaveJar); } finally { os.close(); } listener.getLogger().println(Messages.SSHLauncher_CopiedXXXBytes(getTimestamp(), slaveJar.length)); } catch (Throwable e) { throw new IOException2(Messages.SSHLauncher_ErrorCopyingSlaveJarTo(fileName), e); } } catch (Throwable e) { throw new IOException2(Messages.SSHLauncher_ErrorCopyingSlaveJarInto(workingDirectory), e); } } catch (IOException e) { if (sftpClient == null) { copySlaveJarUsingSCP(listener, workingDirectory); } else { throw e; } } finally { if (sftpClient != null) { sftpClient.close(); } } }

Target:
private void copySlaveJar(TaskListener listener, String workingDirectory) throws IOException, InterruptedException { String fileName = workingDirectory + "/slave.jar"; listener.getLogger().println(Messages.SSHLauncher_StartingSFTPClient(getTimestamp())); SFTPClient sftpClient = null; try { sftpClient = new SFTPClient(connection); try { SFTPv3FileAttributes fileAttributes = sftpClient._stat(workingDirectory); if (fileAttributes==null) { listener.getLogger().println(Messages.SSHLauncher_RemoteFSDoesNotExist(getTimestamp(), workingDirectory)); sftpClient.mkdirs(workingDirectory, 0700); } else if (fileAttributes.isRegularFile()) { throw new IOException(Messages.SSHLauncher_RemoteFSIsAFile(workingDirectory)); } try { sftpClient.rm(fileName); } catch (IOException e) { } listener.getLogger().println(Messages.SSHLauncher_CopyingSlaveJar(getTimestamp())); try { byte[] slaveJar = new Slave.JnlpJar("slave.jar").readFully(); OutputStream os = sftpClient.writeToFile(fileName); try { os.write(slaveJar); } finally { os.close(); } listener.getLogger().println(Messages.SSHLauncher_CopiedXXXBytes(getTimestamp(), slaveJar.length)); } catch (Error error) { throw error; } catch (Throwable e) { throw new IOException2(Messages.SSHLauncher_ErrorCopyingSlaveJarTo(fileName), e); } } catch (Error error) { throw error; } catch (Throwable e) { throw new IOException2(Messages.SSHLauncher_ErrorCopyingSlaveJarInto(workingDirectory), e); } } catch (IOException e) { if (sftpClient == null) { copySlaveJarUsingSCP(listener, workingDirectory); } else { throw e; } } finally { if (sftpClient != null) { sftpClient.close(); } } }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); long budgetId = intent.getLongExtra("BUDGET_ID", -1); int cycle = intent.getIntExtra("BUDGET_CYCLE", -1); for (Budget b : Budget.getBudgets()) { if (b.getId() == budgetId) { myBudget = b; break; } } if (myBudget == null) { throw new IllegalArgumentException(); } if (cycle == -1) { if (myBudget.isRecurring()) { cycle = myBudget.getCurrentCycle(); } else { cycle = 0; } } myEntries = new ArrayList<Entry>(); for (Entry e : myBudget.getEntries()) { if (e.getDate().isAfter(myBudget.getStartDate(cycle)) && e.getDate().isBefore(myBudget.getEndDate(cycle)) || e.getDate().isEqual(myBudget.getEndDate(cycle)) || e.getDate().isEqual(myBudget.getStartDate(cycle))) { myEntries.add(e); } } setContentView(R.layout.activity_budget_summary); budgetName = (TextView) findViewById(R.id.budget_name); budgetTotal = (TextView) findViewById(R.id.budget_total); budgetSpent = (TextView) findViewById(R.id.budget_spent); budgetBalance = (TextView) findViewById(R.id.budget_balance); Collections.sort(myEntries, new EntryLogAdapter.EntryDateComparator()); Collections.reverse(myEntries); ((DrawBudgetGraph) findViewById(R.id.BudgetGraph)).setProperties(myEntries, myBudget, cycle); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle = getIntent().getExtras(); long budgetId = bundle.getLong("BudgetId", -1); int cycle = bundle.getInt("BudgetCycle", -1); myBudget = Budget.getBudgetById(budgetId); if (cycle == -1) { if (myBudget.isRecurring()) { cycle = myBudget.getCurrentCycle(); } else { cycle = 0; } } myEntries = new ArrayList<Entry>(); for (Entry e : myBudget.getEntries()) { if (e.getDate().isAfter(myBudget.getStartDate(cycle)) && e.getDate().isBefore(myBudget.getEndDate(cycle)) || e.getDate().isEqual(myBudget.getEndDate(cycle)) || e.getDate().isEqual(myBudget.getStartDate(cycle))) { myEntries.add(e); } } setContentView(R.layout.activity_budget_summary); budgetName = (TextView) findViewById(R.id.budget_name); budgetTotal = (TextView) findViewById(R.id.budget_total); budgetSpent = (TextView) findViewById(R.id.budget_spent); budgetBalance = (TextView) findViewById(R.id.budget_balance); Collections.sort(myEntries, new EntryLogAdapter.EntryDateComparator()); Collections.reverse(myEntries); ((DrawBudgetGraph) findViewById(R.id.BudgetGraph)).setProperties(myEntries, myBudget, cycle); }
Source:
private StoreKey getKeyAt(ByteBuffer mmap, int index) throws IOException { mmap.position(firstKeyRelativeOffset + (index * (persistedEntrySize))); return factory.getStoreKey(new DataInputStream(new ByteBufferInputStream(mmap))); }

Target:
private StoreKey getKeyAt(ByteBuffer mmap, int index) throws IOException { mmap.position(firstKeyRelativeOffset + index * persistedEntrySize); return factory.getStoreKey(new DataInputStream(new ByteBufferInputStream(mmap))); }
Source:
public void persist_shouldSearchHistoryByChargeId() { ChargeEntity chargeEntity = new ChargeEntity(); chargeEntity.setId(chargeTestRecord.getChargeId()); RefundEntity refundEntity = new RefundEntity(chargeEntity, 100L, null); refundEntity.setStatus(RefundStatus.REFUND_SUBMITTED); refundEntity.setReference("test-refund-entity"); refundDao.persist(refundEntity); List<RefundHistory> refundHistoryList = refundDao.searchHistoryByChargeId(chargeEntity.getId()); assertThat(refundHistoryList.size(), is(1)); RefundHistory refundHistory = refundHistoryList.get(0); assertThat(refundHistory.getId(), is(refundEntity.getId())); assertThat(refundHistory.getExternalId(), is(refundEntity.getExternalId())); assertThat(refundHistory.getAmount(), is(refundEntity.getAmount())); assertThat(refundHistory.getStatus(), is(refundEntity.getStatus())); assertNotNull(refundHistory.getChargeEntity()); assertThat(refundHistory.getChargeEntity().getId(), is(refundEntity.getChargeEntity().getId())); assertThat(refundHistory.getCreatedDate(), is(refundEntity.getCreatedDate())); assertThat(refundHistory.getVersion(), is(refundEntity.getVersion())); assertThat(refundHistory.getReference(), is(refundEntity.getReference())); }

Target:
public void persist_shouldSearchHistoryByChargeId() { ChargeEntity chargeEntity = new ChargeEntity(); chargeEntity.setId(chargeTestRecord.getChargeId()); RefundEntity refundEntity = new RefundEntity(chargeEntity, 100L, userExternalId); refundEntity.setStatus(RefundStatus.REFUND_SUBMITTED); refundEntity.setReference("test-refund-entity"); refundDao.persist(refundEntity); List<RefundHistory> refundHistoryList = refundDao.searchHistoryByChargeId(chargeEntity.getId()); assertThat(refundHistoryList.size(), is(1)); RefundHistory refundHistory = refundHistoryList.get(0); assertThat(refundHistory.getId(), is(refundEntity.getId())); assertThat(refundHistory.getExternalId(), is(refundEntity.getExternalId())); assertThat(refundHistory.getAmount(), is(refundEntity.getAmount())); assertThat(refundHistory.getStatus(), is(refundEntity.getStatus())); assertNotNull(refundHistory.getChargeEntity()); assertThat(refundHistory.getChargeEntity().getId(), is(refundEntity.getChargeEntity().getId())); assertThat(refundHistory.getCreatedDate(), is(refundEntity.getCreatedDate())); assertThat(refundHistory.getVersion(), is(refundEntity.getVersion())); assertThat(refundHistory.getReference(), is(refundEntity.getReference())); assertThat(refundEntity.getUserExternalId(), is(userExternalId)); assertThat(refundHistory.getUserExternalId(), is(refundEntity.getUserExternalId())); }
Source:
public void shouldNotMakeRemoteCallsInAReadonlyTransactionIfNoWorkIsDone() { TimestampService mockTimestampService = mock(TimestampService.class); LockService mockLockService = mock(LockService.class); TransactionManager txnManagerWithMocks = new SerializableTransactionManager(getKeyValueService(), mockTimestampService, LockClient.of("foo"), mockLockService, transactionService, () -> AtlasDbConstraintCheckingMode.FULL_CONSTRAINT_CHECKING_THROWS_EXCEPTIONS, conflictDetectionManager, sweepStrategyManager, NoOpCleaner.INSTANCE, 16, 4); when(mockTimestampService.getFreshTimestamp()).thenReturn(1L); when(mockLockService.getMinLockedInVersionId("foo")).thenReturn(1L); txnManagerWithMocks.getImmutableTimestamp(); verify(mockTimestampService).getFreshTimestamp(); verify(mockLockService).getMinLockedInVersionId("foo"); txnManagerWithMocks.runTaskReadOnly(txn -> null); verifyNoMoreInteractions(mockLockService); verifyNoMoreInteractions(mockTimestampService); }

Target:
public void shouldNotMakeRemoteCallsInAReadonlyTransactionIfNoWorkIsDone() { TimestampService mockTimestampService = mock(TimestampService.class); LockService mockLockService = mock(LockService.class); TransactionManager txnManagerWithMocks = new SerializableTransactionManager(getKeyValueService(), mockTimestampService, LockClient.of("foo"), mockLockService, transactionService, () -> AtlasDbConstraintCheckingMode.FULL_CONSTRAINT_CHECKING_THROWS_EXCEPTIONS, conflictDetectionManager, sweepStrategyManager, NoOpCleaner.INSTANCE, AbstractTransactionTest.GET_RANGES_THREAD_POOL_SIZE, AbstractTransactionTest.DEFAULT_GET_RANGES_CONCURRENCY); when(mockTimestampService.getFreshTimestamp()).thenReturn(1L); when(mockLockService.getMinLockedInVersionId("foo")).thenReturn(1L); txnManagerWithMocks.getImmutableTimestamp(); verify(mockTimestampService).getFreshTimestamp(); verify(mockLockService).getMinLockedInVersionId("foo"); txnManagerWithMocks.runTaskReadOnly(txn -> null); verifyNoMoreInteractions(mockLockService); verifyNoMoreInteractions(mockTimestampService); }
Source:
private File createNewSplitSegmentFile(Integer zipSplitSegmentSuffixIndex) throws IOException { int newZipSplitSegmentSuffixIndex = zipSplitSegmentSuffixIndex == null ? (currentSplitSegmentIndex + 2) : zipSplitSegmentSuffixIndex; String baseName = FileNameUtil.getBaseName(zipFile.getName()); String extension = ".z"; if (newZipSplitSegmentSuffixIndex <= 9) { extension += "0" + newZipSplitSegmentSuffixIndex; } else { extension += newZipSplitSegmentSuffixIndex; } String newFileName = zipFile.getParent() + File.separatorChar + baseName + extension; File newFile = new File(newFileName); if (newFile.exists()) { throw new IOException("split zip segment " + newFileName + " already exists"); } return newFile; }

Target:
private File createNewSplitSegmentFile(Integer zipSplitSegmentSuffixIndex) throws IOException { int newZipSplitSegmentSuffixIndex = zipSplitSegmentSuffixIndex == null ? (currentSplitSegmentIndex + 2) : zipSplitSegmentSuffixIndex; String baseName = FileNameUtils.getBaseName(zipFile.getName()); String extension = ".z"; if (newZipSplitSegmentSuffixIndex <= 9) { extension += "0" + newZipSplitSegmentSuffixIndex; } else { extension += newZipSplitSegmentSuffixIndex; } File newFile = new File(zipFile.getParent(), baseName + extension); if (newFile.exists()) { throw new IOException("split zip segment " + baseName + extension + " already exists"); } return newFile; }
Source:
public void run() { Map<Project, File> directoriesOnFs = getProjectDirectoriesOnFileSystem(); if (directoriesOnFs.size() != mDb.getNumProjects() || mDb.projectsNeedingResync(directoriesOnFs.keySet()).size() > 0) { fullResync(mDb, directoriesOnFs); } mDb.close(); onTaskCompleteDelegator(); }

Target:
public void run() { Map<Project, File> directoriesOnFs = getProjectDirectoriesOnFileSystem(); boolean projectCountDiffers = directoriesOnFs.size() != db.getNumProjects(); boolean projectsNeedResync = db.projectsNeedingResync(directoriesOnFs.keySet()).size() > 0; if (projectCountDiffers || projectsNeedResync) { fullResync(directoriesOnFs); } onTaskCompleteDelegator(); }
Source:
protected List<ITimeEvent> createTimeEvents(TimeGraphEntry entry, List<ITimeGraphState> values) { List<ITimeEvent> events = new ArrayList<>(values.size()); ITimeEvent prev = null; for (ITimeGraphState state : values) { ITimeEvent event = createTimeEvent(entry, state); if (prev != null) { long prevEnd = prev.getTime() + prev.getDuration(); if (prevEnd < event.getTime() && !prev.isPropertyActive(IFilterProperty.isDimmed()) && !event.isPropertyActive(IFilterProperty.isDimmed())) { events.add(new TimeEvent(entry, prevEnd, event.getTime() - prevEnd)); } } prev = event; events.add(event); } return events; }

Target:
protected List<ITimeEvent> createTimeEvents(TimeGraphEntry entry, List<ITimeGraphState> values) { List<ITimeEvent> events = new ArrayList<>(values.size()); ITimeEvent prev = null; for (ITimeGraphState state : values) { ITimeEvent event = createTimeEvent(entry, state); if (prev != null) { long prevEnd = prev.getTime() + prev.getDuration(); if (prevEnd < event.getTime() && (getTimeEventFilterDialog() == null || !getTimeEventFilterDialog().hasActiveSavedFilters())) { TimeEvent timeEvent = new TimeEvent(entry, prevEnd, event.getTime() - prevEnd); if (getTimeEventFilterDialog() != null && getTimeEventFilterDialog().isFilterActive()) { timeEvent.setProperty(IFilterProperty.isDimmed(), true); } events.add(timeEvent); } } prev = event; events.add(event); } return events; }
Source:
public byte[] readHeader() { LOGGER.fine("Reading header"); Request request = new Request.Builder() .url(uri.toString()) .header("range", "bytes=" + 0 + "-" + (headerLength - 1)) .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) { throw new IOException(); } String contentRange = response.header(CONTENT_RANGE_HEADER); if (contentRange.contains("/")) { String length = contentRange.split("/")[1]; try { filesize = Integer.parseInt(length); buffer = ByteBuffer.allocate(filesize); } catch (Exception e) { e.printStackTrace(); } } byte[] headerBytes = response.body().bytes(); writeValue(0, headerBytes); return headerBytes; } catch (IOException e) { LOGGER.severe("Unable to read header for " + uri); throw new RuntimeException("Unable to read header for " + uri, e); } }

Target:
public byte[] readHeader() { LOGGER.fine("Reading header"); Request.Builder requestBuilder = new Request.Builder() .url(uri.toString()) .header("range", "bytes=" + 0 + "-" + (headerLength - 1)); if (credentials != null) { requestBuilder.header("Authorization", credentials); } Request request = requestBuilder.build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) { throw new IOException("Unable to read header for " + uri + ". " + "Code: " + response.code() + ". Reason: " + response.message()); } byte[] headerBytes = response.body().bytes(); data.put(0L, headerBytes); return headerBytes; } catch (IOException e) { throw new RuntimeException("Unable to read header for " + uri, e); } }
Source:
private static String buildOutput( String message, LiveChatMessageAuthorDetails author, LiveChatSuperChatDetails superChatDetails) { StringBuilder output = new StringBuilder(); if (superChatDetails != null) { output.append(superChatDetails.getAmountDisplayString()); output.append("SUPERCHAT RECEIVED FROM "); } output.append(author.getDisplayName()); if (author.getIsChatOwner() || author.getIsChatOwner() || author.getIsChatSponsor()) { output.append(" ("); boolean appendComma = false; if (author.getIsChatOwner()) { output.append("OWNER"); appendComma = true; } if (author.getIsChatModerator()) { if (appendComma) { output.append(", "); } output.append("MODERATOR"); appendComma = true; } if (author.getIsChatSponsor()) { if (appendComma) { output.append(", "); } output.append("SPONSER"); } output.append(")"); } if (message != null && !message.isEmpty()) { output.append(": "); output.append(message); } return output.toString(); }

Target:
private static String buildOutput( String message, LiveChatMessageAuthorDetails author, LiveChatSuperChatDetails superChatDetails) { StringBuilder output = new StringBuilder(); if (superChatDetails != null) { output.append(superChatDetails.getAmountDisplayString()); output.append("SUPERCHAT RECEIVED FROM "); } output.append(author.getDisplayName()); List<String> roles = new ArrayList<String>(); if (author.getIsChatOwner()) { roles.add("OWNER"); } if (author.getIsChatModerator()) { roles.add("MODERATOR"); } if (author.getIsChatSponsor()) { roles.add("SPONSOR"); } if (roles.size() > 0) { output.append(" ("); String delim = ""; for (String role : roles) { output.append(delim).append(role); delim = ", "; } output.append(")"); } if (message != null && !message.isEmpty()) { output.append(": "); output.append(message); } return output.toString(); }
Source:
public void testDefaults() { ConfigAssertions.assertRecordedDefaults(ConfigAssertions.recordDefaults(HttpServerConfig.class) .setHttpEnabled(true) .setHttpPort(8080) .setHttpAcceptQueueSize(8000) .setHttpsEnabled(false) .setHttpsPort(8443) .setSecureRandomAlgorithm(null) .setHttpsIncludedCipherSuites("") .setHttpsExcludedCipherSuites("") .setKeystorePath(null) .setKeystorePassword(null) .setKeyManagerPassword(null) .setLogPath("var/log/http-request.log") .setLogEnabled(true) .setLogMaxFileSize(new DataSize(Long.MAX_VALUE, BYTE)) .setLogHistory(15) .setQueueSize(10_000) .setHttpAcceptorThreads(null) .setHttpSelectorThreads(null) .setHttpsAcceptorThreads(null) .setHttpsSelectorThreads(null) .setMinThreads(2) .setMaxThreads(200) .setThreadMaxIdleTime(new Duration(1, MINUTES)) .setNetworkMaxIdleTime(new Duration(200, SECONDS)) .setUserAuthFile(null) .setAdminEnabled(true) .setAdminPort(0) .setAdminMinThreads(2) .setAdminMaxThreads(200) .setMaxRequestHeaderSize(null) .setHttp2MaxConcurrentStreams(16384) .setShowStackTrace(true) .setHttp2InitialSessionReceiveWindowSize(new DataSize(16, MEGABYTE)) .setHttp2InputBufferSize(new DataSize(8, KILOBYTE)) .setHttp2InitialStreamReceiveWindowSize(new DataSize(16, MEGABYTE)) .setHttp2StreamIdleTimeout(new Duration(15, SECONDS)) .setLogCompressionEnabled(true)); }

Target:
public void testDefaults() { ConfigAssertions.assertRecordedDefaults(ConfigAssertions.recordDefaults(HttpServerConfig.class) .setHttpEnabled(true) .setHttpPort(8080) .setHttpAcceptQueueSize(8000) .setHttpsEnabled(false) .setHttpsPort(8443) .setSecureRandomAlgorithm(null) .setHttpsIncludedCipherSuites("") .setHttpsExcludedCipherSuites("") .setKeystorePath(null) .setKeystorePassword(null) .setKeyManagerPassword(null) .setLogPath("var/log/http-request.log") .setLogEnabled(true) .setLogMaxFileSize(new DataSize(Long.MAX_VALUE, BYTE)) .setLogHistory(15) .setLogQueueSize(10_000) .setLogCompressionEnabled(true) .setHttpAcceptorThreads(null) .setHttpSelectorThreads(null) .setHttpsAcceptorThreads(null) .setHttpsSelectorThreads(null) .setMinThreads(2) .setMaxThreads(200) .setThreadMaxIdleTime(new Duration(1, MINUTES)) .setNetworkMaxIdleTime(new Duration(200, SECONDS)) .setUserAuthFile(null) .setAdminEnabled(true) .setAdminPort(0) .setAdminMinThreads(2) .setAdminMaxThreads(200) .setMaxRequestHeaderSize(null) .setHttp2MaxConcurrentStreams(16384) .setShowStackTrace(true) .setHttp2InitialSessionReceiveWindowSize(new DataSize(16, MEGABYTE)) .setHttp2InputBufferSize(new DataSize(8, KILOBYTE)) .setHttp2InitialStreamReceiveWindowSize(new DataSize(16, MEGABYTE)) .setHttp2StreamIdleTimeout(new Duration(15, SECONDS))); }
Source:
public static IGraph<Diff> mapDifferencesWithSubDiffs(Collection<Diff> differences, IMerger.Registry mergerRegistry, boolean mergeRightToLeft, MergeMode mergeMode) { IGraph<Diff> differencesGraph = new Graph<Diff>(); final Predicate<? super Diff> filter; if (mergeMode == MergeMode.RIGHT_TO_LEFT) { filter = fromSide(DifferenceSource.RIGHT); } else if (mergeMode == MergeMode.LEFT_TO_RIGHT) { filter = fromSide(DifferenceSource.LEFT); } else { filter = Predicates.alwaysTrue(); } for (Diff diff : Iterables.filter(differences, filter)) { final IMerger merger = mergerRegistry.getHighestRankingMerger(diff); differencesGraph.add(diff); if (merger instanceof IMerger2) { final Set<Diff> directMergeDependencies = ((IMerger2)merger).getDirectMergeDependencies(diff, mergeRightToLeft); for (Diff dependency : directMergeDependencies) { differencesGraph.addChildren(dependency, Collections.singleton(diff)); } } if (MergerOptionsUtil.isSubDiffAware(merger)) { Set<Diff> subDiffs = Sets .newLinkedHashSet(ComparisonUtil.getDirectSubDiffs(!mergeRightToLeft).apply(diff)); differencesGraph.addChildren(diff, subDiffs); } } return differencesGraph; }

Target:
public static IGraph<Diff> mapDifferencesWithSubDiffs(Collection<Diff> differences, IMerger.Registry mergerRegistry, boolean mergeRightToLeft, MergeMode mergeMode) { IGraph<Diff> differencesGraph = new Graph<Diff>(); final Predicate<? super Diff> filter; if (mergeMode == MergeMode.RIGHT_TO_LEFT) { filter = fromSide(DifferenceSource.RIGHT); } else if (mergeMode == MergeMode.LEFT_TO_RIGHT) { filter = fromSide(DifferenceSource.LEFT); } else { filter = Predicates.alwaysTrue(); } for (Diff diff : Iterables.filter(differences, filter)) { addToGraph(mergerRegistry, differencesGraph, diff, mergeRightToLeft); } return differencesGraph; }
Source:
public synchronized void stop() { if (!isStarted) { throw new SystemProducerException("Attempting to stop a producer that was not started."); } if (isStopped) { throw new SystemProducerException("Attempting to stop an already stopped producer."); } try { writerMap.forEach((source, sourceWriterMap) -> flush(source)); asyncBlobThreadPool.shutdown(); isStarted = false; } catch (Exception e) { throw new SystemProducerException("Stop failed with exception.", e); } finally { writerMap.clear(); isStopped = true; } }

Target:
public synchronized void stop() { if (!isStarted) { LOG.warn("Attempting to stop a producer that was not started."); return; } if (isStopped) { LOG.warn("Attempting to stop an already stopped producer."); return; } try { writerMap.forEach((source, sourceWriterMap) -> flush(source)); asyncBlobThreadPool.shutdown(); isStarted = false; } catch (Exception e) { throw new SystemProducerException("Stop failed with exception.", e); } finally { writerMap.clear(); isStopped = true; } }
Source:
public void map(WALKey key, WALEdit value, Context context) throws IOException { context.getCounter(Counter.WALEDITS).increment(1); try { if (tables.isEmpty() || tables.containsKey(key.getTableName())) { TableName targetTable = tables.isEmpty() ? key.getTableName() : tables.get(key.getTableName()); ImmutableBytesWritable tableOut = new ImmutableBytesWritable(targetTable.getName()); Put put = null; Delete del = null; Cell lastCell = null; for (Cell cell : value.getCells()) { context.getCounter(Counter.CELLS_READ).increment(1); if (WALEdit.isMetaEditFamily(cell)) { continue; } if (filter(context, cell)) { if (lastCell == null || lastCell.getTypeByte() != cell.getTypeByte() || !CellUtil.matchingRows(lastCell, cell)) { if (put != null) { context.write(tableOut, put); context.getCounter(Counter.PUTS).increment(1); } if (del != null) { context.write(tableOut, del); context.getCounter(Counter.DELETES).increment(1); } if (CellUtil.isDelete(cell)) { del = new Delete(CellUtil.cloneRow(cell)); } else { put = new Put(CellUtil.cloneRow(cell)); } } if (CellUtil.isDelete(cell)) { context.getCounter(Counter.CELLS_WRITTEN).increment(1); del.add(cell); } else { context.getCounter(Counter.CELLS_WRITTEN).increment(1); put.add(cell); } } lastCell = cell; } if (put != null) { context.write(tableOut, put); context.getCounter(Counter.PUTS).increment(1); } if (del != null) { context.getCounter(Counter.DELETES).increment(1); context.write(tableOut, del); } } } catch (InterruptedException e) { e.printStackTrace(); } }

Target:
public void map(WALKey key, WALEdit value, Context context) throws IOException { context.getCounter(Counter.WALEDITS).increment(1); try { if (tables.isEmpty() || tables.containsKey(key.getTableName())) { TableName targetTable = tables.isEmpty() ? key.getTableName() : tables.get(key.getTableName()); ImmutableBytesWritable tableOut = new ImmutableBytesWritable(targetTable.getName()); Put put = null; Delete del = null; Cell lastCell = null; for (Cell cell : value.getCells()) { context.getCounter(Counter.CELLS_READ).increment(1); if (WALEdit.isMetaEditFamily(cell)) { continue; } if (filter(context, cell)) { if (lastCell == null || lastCell.getTypeByte() != cell.getTypeByte() || !CellUtil.matchingRows(lastCell, cell)) { if (put != null) { context.write(tableOut, put); context.getCounter(Counter.PUTS).increment(1); } if (del != null) { context.write(tableOut, del); context.getCounter(Counter.DELETES).increment(1); } if (CellUtil.isDelete(cell)) { del = new Delete(CellUtil.cloneRow(cell)); } else { put = new Put(CellUtil.cloneRow(cell)); } } if (CellUtil.isDelete(cell)) { del.add(cell); } else { put.add(cell); } context.getCounter(Counter.CELLS_WRITTEN).increment(1); } lastCell = cell; } if (put != null) { context.write(tableOut, put); context.getCounter(Counter.PUTS).increment(1); } if (del != null) { context.getCounter(Counter.DELETES).increment(1); context.write(tableOut, del); } } } catch (InterruptedException e) { e.printStackTrace(); } }
Source:
public void subscribe(ActionEvent e) throws SystemException, PortalException { if (Helper.isUserLoggedIn()) { StringBuilder extraData = new StringBuilder(); if (pageType == DiscussionPageType.CATEGORY) { extraData.append(currentCategory.getId()); } else if (pageType == DiscussionPageType.THREAD) { extraData.append(currentThread.getCategoryId()); extraData.append(","); extraData.append(currentThread.getId()); } final User liferayUser = Helper.getLiferayUser(); if (liferayUser != null) { if (isSubscribed()) { ; ActivitiesClient.deleteSubscription(new Long(liferayUser.getUserId()), ActivityEntryType .DISCUSSION, getDiscussionId(), extraData.toString()); } else { ActivitiesClient.addSubscription(new Long(liferayUser.getUserId()), ActivityEntryType.DISCUSSION, getDiscussionId(), extraData.toString()); } } else { _log.error("Could not retrieve user for subscription: user was null"); } } }

Target:
public void subscribe(ActionEvent e) throws SystemException, PortalException { if (Helper.isUserLoggedIn()) { StringBuilder extraData = new StringBuilder(); if (pageType == DiscussionPageType.CATEGORY) { extraData.append(currentCategory.getId()); } else if (pageType == DiscussionPageType.THREAD) { extraData.append(currentThread.getCategoryId()); extraData.append(","); extraData.append(currentThread.getId()); } final User liferayUser = Helper.getLiferayUser(); if (liferayUser != null) { if (isSubscribed()) { ActivitiesClient.deleteSubscription(liferayUser.getUserId(), ActivityEntryType .DISCUSSION, getDiscussionId(), extraData.toString()); ; } else { ActivitiesClient.addSubscription(liferayUser.getUserId(),ActivityEntryType.DISCUSSION, getDiscussionId(), extraData.toString()); } } else { _log.error("Could not retrieve user for subscription: user was null"); } } }
Source:
private void cleanUsingTime(final String metricName, final Date firstAllowedDate) { if (historyListMapping.containsKey(metricName) && historyListMapping.get(metricName) != null) { synchronized (historyListMapping.get(metricName)) { InMemoryHistoryNode firstNode = historyListMapping.get(metricName).peekFirst(); long localCopyOfInterval = 0; synchronized (this) { localCopyOfInterval = interval; } while (firstNode != null && TimeUnit.MILLISECONDS.toMillis(firstAllowedDate.getTime() - firstNode.getTimestamp().getTime()) > localCopyOfInterval) { historyListMapping.get(metricName).removeFirst(); firstNode = historyListMapping.get(metricName).peekFirst(); } } } }

Target:
private void cleanUsingTime(final String metricName, final Date firstAllowedDate) { if (historyListMapping.containsKey(metricName) && historyListMapping.get(metricName) != null) { synchronized (historyListMapping.get(metricName)) { InMemoryHistoryNode firstNode = historyListMapping.get(metricName).peekFirst(); long localCopyOfTimeWindow = 0; synchronized (this) { localCopyOfTimeWindow = timeWindow; } while (firstNode != null && TimeUnit.MILLISECONDS.toMillis(firstAllowedDate.getTime() - firstNode.getTimestamp().getTime()) > localCopyOfTimeWindow) { historyListMapping.get(metricName).removeFirst(); firstNode = historyListMapping.get(metricName).peekFirst(); } } } }
Source:
private void afterHypervisorMigrationCleanup(StoragePool destPool, VMInstanceVO vm, HostVO srcHost, Long srcClusterId, Answer[] hypervisorMigrationResults) throws InsufficientCapacityException { if(s_logger.isDebugEnabled()) { String msg = String.format("cleaning up after hypervisor pool migration volumes for VM %s(%s) to pool %s(%s)", vm.getInstanceName(), vm.getUuid(), destPool.getName(), destPool.getUuid()); s_logger.debug(msg); } setDestinationPoolAndReallocateNetwork(destPool, vm); Long destPodId = destPool.getPodId(); Long vmPodId = vm.getPodIdToDeployIn(); if (destPodId == null || ! destPodId.equals(vmPodId)) { if(s_logger.isDebugEnabled()) { String msg = String.format("resetting lasHost for VM %s(%s) as pod (%s) is no good.", vm.getInstanceName(), vm.getUuid(), destPodId); s_logger.debug(msg); } vm.setLastHostId(null); vm.setPodIdToDeployIn(destPodId); } markVolumesInPool(vm,destPool, hypervisorMigrationResults); }

Target:
private void afterHypervisorMigrationCleanup(StoragePool destPool, VMInstanceVO vm, HostVO srcHost, Long srcClusterId, Answer[] hypervisorMigrationResults) throws InsufficientCapacityException { boolean isDebugEnabled = s_logger.isDebugEnabled(); if(isDebugEnabled) { String msg = String.format("cleaning up after hypervisor pool migration volumes for VM %s(%s) to pool %s(%s)", vm.getInstanceName(), vm.getUuid(), destPool.getName(), destPool.getUuid()); s_logger.debug(msg); } setDestinationPoolAndReallocateNetwork(destPool, vm); Long destPodId = destPool.getPodId(); Long vmPodId = vm.getPodIdToDeployIn(); if (destPodId == null || ! destPodId.equals(vmPodId)) { if(isDebugEnabled) { String msg = String.format("resetting lasHost for VM %s(%s) as pod (%s) is no good.", vm.getInstanceName(), vm.getUuid(), destPodId); s_logger.debug(msg); } vm.setLastHostId(null); vm.setPodIdToDeployIn(destPodId); } markVolumesInPool(vm,destPool, hypervisorMigrationResults); }
Source:
public void testItAcceptsSharePhotoContent() throws MalformedURLException, URISyntaxException { String AppId = "200"; PowerMockito.mockStatic(Validate.class); when(Validate.hasContentProvider(RuntimeEnvironment.application)).thenReturn(true); FacebookSdk.sdkInitialize(RuntimeEnvironment.application); FacebookSdk.setApplicationId(AppId); SharePhotoContent.Builder spcBuilder = new SharePhotoContent.Builder(); SharePhoto sharePhoto = new SharePhoto.Builder().setBitmap(createStubBitmap()).build(); SharePhotoContent sharePhotoContent = spcBuilder.addPhoto(sharePhoto).build(); ShareContentValidation.validateForApiShare(sharePhotoContent); ShareContentValidation.validateForMessage(sharePhotoContent); ShareContentValidation.validateForNativeShare(sharePhotoContent); }

Target:
public void testItAcceptsSharePhotoContent() throws Exception { String AppId = "200"; PowerMockito.spy(Validate.class); doNothing().when(Validate.class, "hasContentProvider", Mockito.any(Context.class)); FacebookSdk.sdkInitialize(RuntimeEnvironment.application); FacebookSdk.setApplicationId(AppId); SharePhotoContent.Builder spcBuilder = new SharePhotoContent.Builder(); SharePhoto sharePhoto = new SharePhoto.Builder().setBitmap(createStubBitmap()).build(); SharePhotoContent sharePhotoContent = spcBuilder.addPhoto(sharePhoto).build(); ShareContentValidation.validateForApiShare(sharePhotoContent); ShareContentValidation.validateForMessage(sharePhotoContent); ShareContentValidation.validateForNativeShare(sharePhotoContent); }
Source:
public void handleAnalysisStarted(TmfStartAnalysisSignal signal) { IAnalysisModule module = signal.getAnalysisModule(); if (module instanceof ITmfAnalysisModuleWithStateSystems && !module.isAutomatic()) { fStartedAnalysis.add((ITmfAnalysisModuleWithStateSystems) module); rebuild(); } }

Target:
public void handleAnalysisStarted(TmfStartAnalysisSignal signal) { IAnalysisModule module = signal.getAnalysisModule(); if (module instanceof ITmfAnalysisModuleWithStateSystems && !module.isAutomatic()) { fStartedAnalysis.add((ITmfAnalysisModuleWithStateSystems) module); if (Iterables.contains(allModules(getTrace()), module)) { rebuild(); } } }
Source:
public String toString() { return "#" + Integer.toHexString(toInt()); }

Target:
public String toString() { return String.format("#%08h", toInt()); }
Source:
private ItemKey[] sort(final Set<ItemKey> keys) { final List<ItemKey> res = new ArrayList<>(keys.size()); for (ItemKey key : SORT_ORDER) { if (keys.remove(key)) { res.add(key); } } final List<ItemKey> sortedKeys = new ArrayList<>(keys); Collections.sort(sortedKeys); final Map<String, List<ItemKey>> groupedItems = new HashMap<>(); for (ItemKey key : sortedKeys) { ItemKey parent = key; ItemKey tmp = parent.getParent(); while (tmp != null) { parent = tmp; tmp = parent.getParent(); } List<ItemKey> lst = groupedItems.get(parent.getName()); if (lst == null) { lst = new ArrayList<>(); groupedItems.put(parent.getName(), lst); } lst.add(key); } List<ItemKey> lst = groupedItems.remove("instrument"); if (lst != null) res.addAll(lst); lst = groupedItems.remove("telescope"); if (lst != null) res.addAll(lst); lst = groupedItems.remove("calibration"); if (lst != null) res.addAll(lst); for (String category : groupedItems.keySet()) { res.addAll(groupedItems.get(category)); } return res.toArray(new ItemKey[res.size()]); }

Target:
private ItemKey[] sort(final Set<ItemKey> keys) { final List<ItemKey> res = new ArrayList<>(keys.size()); for (ItemKey key : SORT_ORDER) { if (keys.remove(key)) { res.add(key); } } final List<ItemKey> sortedKeys = new ArrayList<>(keys); Collections.sort(sortedKeys); final Map<String, List<ItemKey>> groupedItems = new HashMap<>(); for (final ItemKey key : sortedKeys) { ItemKey parent = key; ItemKey tmp = parent.getParent(); while (tmp != null) { parent = tmp; tmp = parent.getParent(); } List<ItemKey> lst = groupedItems.get(parent.getName()); if (lst == null) { lst = new ArrayList<>(); groupedItems.put(parent.getName(), lst); } lst.add(key); } List<ItemKey> lst = groupedItems.remove("instrument"); if (lst != null) res.addAll(lst); lst = groupedItems.remove("telescope"); if (lst != null) res.addAll(lst); lst = groupedItems.remove("calibration"); if (lst != null) res.addAll(lst); for (final String category : groupedItems.keySet()) { res.addAll(groupedItems.get(category)); } return res.toArray(new ItemKey[res.size()]); }