auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { if (!children.get(0).evaluate(tuple, ptr)) { return false; } if (ptr.getLength() == 0) { return true; } byte[] lhsBytes = ptr.get(); int lhsOffset = ptr.getOffset(); int lhsLength = ptr.getLength(); PDataType lhsDataType = children.get(0).getDataType(); SortOrder lhsSortOrder = children.get(0).getSortOrder(); if (!children.get(1).evaluate(tuple, ptr)) { return false; } if (ptr.getLength() == 0) { return true; } byte[] rhsBytes = ptr.get(); int rhsOffset = ptr.getOffset(); int rhsLength = ptr.getLength(); PDataType rhsDataType = children.get(1).getDataType(); SortOrder rhsSortOrder = children.get(1).getSortOrder(); if(children.get(0) instanceof BaseJSONExpression && ((BaseJSONExpression)children.get(0)).getRealDataType() != null){ lhsDataType=((BaseJSONExpression)children.get(0)).getRealDataType(); if(!(lhsDataType.isComparableTo(rhsDataType))){ ptr.set(PDataType.FALSE_BYTES); return true; } } if (rhsDataType == PChar.INSTANCE) { rhsLength = StringUtil.getUnpaddedCharLength(rhsBytes, rhsOffset, rhsLength, rhsSortOrder); } if (lhsDataType == PChar.INSTANCE) { lhsLength = StringUtil.getUnpaddedCharLength(lhsBytes, lhsOffset, lhsLength, lhsSortOrder); } int comparisonResult = lhsDataType.compareTo(lhsBytes, lhsOffset, lhsLength, lhsSortOrder, rhsBytes, rhsOffset, rhsLength, rhsSortOrder, rhsDataType); ptr.set(ByteUtil.compare(op, comparisonResult) ? PDataType.TRUE_BYTES : PDataType.FALSE_BYTES); return true; }

Target:
public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { if (!children.get(0).evaluate(tuple, ptr)) { return false; } if (ptr.getLength() == 0) { return true; } byte[] lhsBytes = ptr.get(); int lhsOffset = ptr.getOffset(); int lhsLength = ptr.getLength(); PDataType lhsDataType = children.get(0).getDataType(); SortOrder lhsSortOrder = children.get(0).getSortOrder(); if (!children.get(1).evaluate(tuple, ptr)) { return false; } if (ptr.getLength() == 0) { return true; } byte[] rhsBytes = ptr.get(); int rhsOffset = ptr.getOffset(); int rhsLength = ptr.getLength(); PDataType rhsDataType = children.get(1).getDataType(); SortOrder rhsSortOrder = children.get(1).getSortOrder(); if (rhsDataType == PChar.INSTANCE) { rhsLength = StringUtil.getUnpaddedCharLength(rhsBytes, rhsOffset, rhsLength, rhsSortOrder); } if (lhsDataType == PChar.INSTANCE) { lhsLength = StringUtil.getUnpaddedCharLength(lhsBytes, lhsOffset, lhsLength, lhsSortOrder); } int comparisonResult = lhsDataType.compareTo(lhsBytes, lhsOffset, lhsLength, lhsSortOrder, rhsBytes, rhsOffset, rhsLength, rhsSortOrder, rhsDataType); ptr.set(ByteUtil.compare(op, comparisonResult) ? PDataType.TRUE_BYTES : PDataType.FALSE_BYTES); return true; }
Source:
public void testRemovingCacheConfigurationListener() { Listener configurationListener = new Listener(); List<CacheConfigurationChangeListener> cacheConfigurationChangeListeners = new ArrayList<>(); cacheConfigurationChangeListeners.add(configurationListener); this.runtimeConfiguration.addCacheConfigurationListener(cacheConfigurationChangeListeners); this.cache.getRuntimeConfiguration().updateResourcePools(createResourcePools()); assertThat(configurationListener.eventSet.size(), is(1)); this.runtimeConfiguration.removeCacheConfigurationListener(configurationListener); this.cache.getRuntimeConfiguration().updateResourcePools(createResourcePools()); assertThat(configurationListener.eventSet.size(), is(1) ); }

Target:
public void testRemovingCacheConfigurationListener() { Listener configurationListener = new Listener(); List<CacheConfigurationChangeListener> cacheConfigurationChangeListeners = new ArrayList<>(); cacheConfigurationChangeListeners.add(configurationListener); this.runtimeConfiguration.addCacheConfigurationListener(cacheConfigurationChangeListeners); this.cache.getRuntimeConfiguration().updateResourcePools(createResourcePools(20L)); assertThat(configurationListener.eventSet.size(), is(1)); this.runtimeConfiguration.removeCacheConfigurationListener(configurationListener); this.cache.getRuntimeConfiguration().updateResourcePools(createResourcePools(5L)); assertThat(configurationListener.eventSet.size(), is(1) ); }
Source:
private void passwordObservable() { Observable<String> observable = RxTextView.textChanges(password1EditText).skip(1).debounce(600, TimeUnit.MILLISECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(AndroidSchedulers.mainThread()) .map(CharSequence::toString); observable.subscribe(this::passwordCheck, LOG::error); Observable<String> observable1 = RxTextView.textChanges(password2EditText).skip(1).debounce(600, TimeUnit.MILLISECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(AndroidSchedulers.mainThread()) .map(CharSequence::toString); observable.subscribe(this::checkConfirmPassword); Observable<Boolean> observable2 = Observable.combineLatest(observable, observable1, (s, s2) -> { return checkMatchpassword(s, s2); }); observable2.subscribe(this::showMatchError, LOG::error); }

Target:
private void passwordObservable() { RxTextView.textChanges(password1EditText) .skipInitialValue() .debounce(600, TimeUnit.MILLISECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(AndroidSchedulers.mainThread()) .map(CharSequence::toString) .subscribe(this::passwordCheck, LOG::error); RxTextView.textChanges(password2EditText) .skipInitialValue() .debounce(600, TimeUnit.MILLISECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(AndroidSchedulers.mainThread()) .map(CharSequence::toString) .subscribe(this::checkConfirmPassword); }
Source:
public void findById() throws Exception { Optional<Capability> actual = catalog.findById(2); Capability expected = new Capability(2, "B"); assertThat(actual.get(), deepEquals(expected)); }

Target:
public void findById() throws Exception { Capability actual = catalog.findById(2).get(); Capability expected = new Capability(2, "B"); assertThat(actual, deepEquals(expected)); }
Source:
private int getattrInternal(String path, FileStat stat) { final AlluxioURI uri = mPathResolverCache.getUnchecked(path); try { URIStatus status = mFileSystem.getStatus(uri); long size = status.getLength(); stat.st_size.set(size); stat.st_blocks.set((int) Math.ceil((double) size / 512)); final long ctime_sec = status.getLastModificationTimeMs() / 1000; final long ctime_nsec = (status.getLastModificationTimeMs() % 1000) * 1000; stat.st_ctim.tv_sec.set(ctime_sec); stat.st_ctim.tv_nsec.set(ctime_nsec); stat.st_mtim.tv_sec.set(ctime_sec); stat.st_mtim.tv_nsec.set(ctime_nsec); if (mIsUserGroupTranslation) { stat.st_uid.set(mUidCache.get(status.getOwner())); stat.st_gid.set(mGidCache.get(status.getGroup())); } else { stat.st_uid.set(DEFAULT_UID); stat.st_gid.set(DEFAULT_GID); } int mode = status.getMode(); if (status.isFolder()) { mode |= FileStat.S_IFDIR; } else { mode |= FileStat.S_IFREG; } stat.st_mode.set(mode); stat.st_nlink.set(1); } catch (FileDoesNotExistException | InvalidPathException e) { LOG.debug("Failed to get info of {}, path does not exist or is invalid", path); return -ErrorCodes.ENOENT(); } catch (Throwable e) { LOG.error("Failed to getattr {}: ", path, e); return -ErrorCodes.EIO(); } return 0; }

Target:
private int getattrInternal(String path, FileStat stat) { final AlluxioURI uri = mPathResolverCache.getUnchecked(path); try { URIStatus status = mFileSystem.getStatus(uri); long size = status.getLength(); stat.st_size.set(size); stat.st_blocks.set((int) Math.ceil((double) size / 512)); final long ctime_sec = status.getLastModificationTimeMs() / 1000; final long ctime_nsec = (status.getLastModificationTimeMs() % 1000) * 1_000_000L; stat.st_ctim.tv_sec.set(ctime_sec); stat.st_ctim.tv_nsec.set(ctime_nsec); stat.st_mtim.tv_sec.set(ctime_sec); stat.st_mtim.tv_nsec.set(ctime_nsec); if (mIsUserGroupTranslation) { stat.st_uid.set(mUidCache.get(status.getOwner())); stat.st_gid.set(mGidCache.get(status.getGroup())); } else { stat.st_uid.set(DEFAULT_UID); stat.st_gid.set(DEFAULT_GID); } int mode = status.getMode(); if (status.isFolder()) { mode |= FileStat.S_IFDIR; } else { mode |= FileStat.S_IFREG; } stat.st_mode.set(mode); stat.st_nlink.set(1); } catch (FileDoesNotExistException | InvalidPathException e) { LOG.debug("Failed to get info of {}, path does not exist or is invalid", path); return -ErrorCodes.ENOENT(); } catch (Throwable e) { LOG.error("Failed to getattr {}: ", path, e); return -ErrorCodes.EIO(); } return 0; }
Source:
public void given__mockScm__when__uninstantiating__then__noRaw$class() throws Exception { MockSCMController c = MockSCMController.create(); try { c.createRepository("test"); MockSCM instance = new MockSCM(c, "test", new MockSCMHead("master"), new MockSCMRevision( new MockSCMHead("master"), c.getRevision("test", "master"))); assertThat(DescribableModel.uninstantiate2_(instance).toString(), allOf( startsWith("@"), not(containsString(", $")), not(containsString("=$")), not(containsString("[$")), not(containsString("{$")) )); } finally { c.close(); } }

Target:
public void given__mockScm__when__uninstantiating__then__noRaw$class() throws Exception { MockSCMController c = MockSCMController.create(); try { c.createRepository("test"); MockSCM instance = new MockSCM(c, "test", new MockSCMHead("master"), new MockSCMRevision( new MockSCMHead("master"), c.getRevision("test", "master"))); assertThat(DescribableModel.uninstantiate2_(instance).toString(), allOf( startsWith("@"), not(containsString(", $")), not(containsString("=$")), not(containsString("[$")), not(containsString("{$")) )); assertThat(DescribableModel.uninstantiate2_(instance).toString(), is("@mockScm(" + "controllerId=" + c.getId() + "," + "head=master," + "repository=test," + "revision=" + c.getRevision("test", "master") + ")")); } finally { c.close(); } }
Source:
private void getUserDb() { DbUser u = getParameters().getUserToAdd(); user = dbUserDao.getByExternalId(u.getDomain(), u.getExternalId()); }

Target:
private void getUserDb() { DbUser u = getParameters().getUserToUpdate(); user = dbUserDao.getByExternalId(u.getDomain(), u.getExternalId()); }
Source:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_crime_list, container, false); mCrimeRecyclerView = (RecyclerView) view.findViewById(R.id.crime_recycler_view); mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); CrimeExpandableAdapter mCrimeExpandableAdapter = new CrimeExpandableAdapter(getActivity(), generateCrimes()); mCrimeExpandableAdapter.setCustomParentAnimationViewId(R.id.parent_list_item_expand_arrow); mCrimeExpandableAdapter.setParentClickableViewAnimationDefaultDuration(); mCrimeExpandableAdapter.setParentAndIconExpandOnClick(true); mCrimeRecyclerView.setAdapter(mCrimeExpandableAdapter); return view; }

Target:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_crime_list, container, false); mCrimeRecyclerView = (RecyclerView) view.findViewById(R.id.crime_recycler_view); mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); CrimeExpandableAdapter crimeExpandableAdapter = new CrimeExpandableAdapter(getActivity(), generateCrimes()); crimeExpandableAdapter.setCustomParentAnimationViewId(R.id.parent_list_item_expand_arrow); crimeExpandableAdapter.setParentClickableViewAnimationDefaultDuration(); crimeExpandableAdapter.setParentAndIconExpandOnClick(true); mCrimeRecyclerView.setAdapter(crimeExpandableAdapter); return view; }
Source:
private String extractArchive(String fileName, File outputDirectory) { if (StringUtils.isEmpty(fileName)) { return null; } logger.info("Extracting OpenShift archive {}.", fileName); String extractedDirectory = null; if (fileName.endsWith(SUFFIX_ZIP)) { extractedDirectory = StringUtils.chomp(fileName, SUFFIX_ZIP); FileHelper.unzipFile(new File(fileName), outputDirectory); } else if (fileName.endsWith(SUFFIX_TAR_GZ)) { extractedDirectory = StringUtils.chomp(fileName, SUFFIX_TAR_GZ); FileHelper.extractTarGz(new File(fileName), outputDirectory); } return extractedDirectory; }

Target:
private String extractArchive(String fileName, File outputDirectory) { if (StringUtils.isEmpty(fileName)) { return null; } LOGGER.info(NLS.bind("Extracting OpenShift archive {0}.", fileName)); String extractedDirectory = null; if (fileName.endsWith(SUFFIX_ZIP)) { extractedDirectory = StringUtils.chomp(fileName, SUFFIX_ZIP); FileHelper.unzipFile(new File(fileName), outputDirectory); } else if (fileName.endsWith(SUFFIX_TAR_GZ)) { extractedDirectory = StringUtils.chomp(fileName, SUFFIX_TAR_GZ); FileHelper.extractTarGz(new File(fileName), outputDirectory); } return extractedDirectory; }
Source:
public static boolean[] populateNullVector( @Nullable final boolean[] nullVector, final ReadableVectorOffset offset, final PeekableIntIterator nullIterator ) { if (!nullIterator.hasNext()) { return null; } final boolean[] retVal; if (nullVector != null) { retVal = nullVector; } else { retVal = new boolean[offset.getMaxVectorSize()]; } if (offset.isContiguous()) { final int startOffset = offset.getStartOffset(); nullIterator.advanceIfNeeded(startOffset); if (!nullIterator.hasNext()) { return null; } for (int i = 0; i < offset.getCurrentVectorSize(); i++) { final int row = i + startOffset; nullIterator.advanceIfNeeded(row); if (!nullIterator.hasNext()) { retVal[i] = false; continue; } retVal[i] = row == nullIterator.peekNext(); } } else { final int[] currentOffsets = offset.getOffsets(); nullIterator.advanceIfNeeded(currentOffsets[0]); if (!nullIterator.hasNext()) { return null; } for (int i = 0; i < offset.getCurrentVectorSize(); i++) { final int row = currentOffsets[i]; nullIterator.advanceIfNeeded(row); if (!nullIterator.hasNext()) { retVal[i] = false; continue; } retVal[i] = row == nullIterator.peekNext(); } } return retVal; }

Target:
public static boolean[] populateNullVector( @Nullable final boolean[] nullVector, final ReadableVectorOffset offset, final PeekableIntIterator nullIterator ) { if (!nullIterator.hasNext()) { return null; } final boolean[] retVal; if (nullVector != null) { retVal = nullVector; } else { retVal = new boolean[offset.getMaxVectorSize()]; } if (offset.isContiguous()) { final int startOffset = offset.getStartOffset(); nullIterator.advanceIfNeeded(startOffset); if (!nullIterator.hasNext()) { return null; } for (int i = 0; i < offset.getCurrentVectorSize(); i++) { final int row = i + startOffset; nullIterator.advanceIfNeeded(row); if (!nullIterator.hasNext()) { Arrays.fill(retVal, i, offset.getCurrentVectorSize(), false); break; } retVal[i] = row == nullIterator.peekNext(); } } else { final int[] currentOffsets = offset.getOffsets(); nullIterator.advanceIfNeeded(currentOffsets[0]); if (!nullIterator.hasNext()) { return null; } for (int i = 0; i < offset.getCurrentVectorSize(); i++) { final int row = currentOffsets[i]; nullIterator.advanceIfNeeded(row); if (!nullIterator.hasNext()) { Arrays.fill(retVal, i, offset.getCurrentVectorSize(), false); break; } retVal[i] = row == nullIterator.peekNext(); } } return retVal; }
Source:
public void determineOptions() { String uri = getResourceUri(); if (StringUtils.isNotBlank(uri)) { Response optionsResponse = buildBaseRequestSpecification().options(uri); Headers headers = optionsResponse.getHeaders(); List<Header> allowHeaders = headers.getList(ALLOW); if (allowHeaders.size() == 1) { Header allowHeader = allowHeaders.get(0); String allow = allowHeader.getValue(); if (allow != null) { String[] methods = allow.split("\\s*,\\s*"); for (String method : methods) { options.add(method); } } } else { for (Header allowHeader : allowHeaders) { options.add(allowHeader.getValue()); } } } }

Target:
public void determineOptions() { String uri = getResourceUri(); if (StringUtils.isNotBlank(uri)) { Response optionsResponse = buildBaseRequestSpecification().options(uri); Headers headers = optionsResponse.getHeaders(); List<Header> allowHeaders = headers.getList(ALLOW); for (Header allowHeader : allowHeaders) { String allow = allowHeader.getValue(); if (allow != null) { String[] methods = allow.split("\\s*,\\s*"); for (String method : methods) { options.add(method); } } } } }
Source:
public void testAddingInvalidElements() { MApplication app = MApplicationFactory.INSTANCE.createApplication(); List l = app.getChildren(); l.add(MBasicFactory.INSTANCE.createWindow()); try { l.add(MBasicFactory.INSTANCE.createPart()); fail("The adding of this should have failed"); } catch (IllegalArgumentException | ArrayStoreException | ClassCastException e) { } catch (Exception e) { throw new RuntimeException(e); } l.add(MBasicFactory.INSTANCE.createWindow()); assertEquals(2, l.size()); }

Target:
public void testAddingInvalidElements() { MApplication app = MApplicationFactory.INSTANCE.createApplication(); List l = app.getChildren(); l.add(MBasicFactory.INSTANCE.createWindow()); try { l.add(MBasicFactory.INSTANCE.createPart()); fail("The adding of this should have failed"); } catch (IllegalArgumentException e) { } catch (ArrayStoreException e) { } catch (ClassCastException e) { } catch (Exception e) { throw new RuntimeException(e); } l.add(MBasicFactory.INSTANCE.createWindow()); assertEquals(2, l.size()); }
Source:
private static CompilerPass createPeepholeOptimizationsPass( AbstractCompiler compiler, String passName) { final boolean late = false; final boolean useTypesForOptimization = compiler.getOptions().useTypesForLocalOptimization; List<AbstractPeepholeOptimization> optimizations = new ArrayList<>(); optimizations.add(new MinimizeExitPoints()); optimizations.add(new PeepholeMinimizeConditions(late)); optimizations.add(new PeepholeSubstituteAlternateSyntax(late)); optimizations.add(new PeepholeReplaceKnownMethods(late, useTypesForOptimization)); optimizations.add(new PeepholeRemoveDeadCode()); if (compiler.getOptions().j2clPassMode.shouldAddJ2clPasses()) { optimizations.add(new J2clEqualitySameRewriterPass(useTypesForOptimization)); optimizations.add(new J2clStringValueOfRewriterPass()); } optimizations.add(new PeepholeFoldConstants(late, useTypesForOptimization)); optimizations.add(new PeepholeCollectPropertyAssignments()); optimizations.add(new PeepholeCombineArrayPush()); return new PeepholeOptimizationsPass(compiler, passName, optimizations); }

Target:
private static CompilerPass createPeepholeOptimizationsPass( AbstractCompiler compiler, String passName) { final boolean late = false; final boolean useTypesForOptimization = compiler.getOptions().useTypesForLocalOptimization; List<AbstractPeepholeOptimization> optimizations = new ArrayList<>(); optimizations.add(new MinimizeExitPoints()); optimizations.add(new PeepholeMinimizeConditions(late)); optimizations.add(new PeepholeSubstituteAlternateSyntax(late)); optimizations.add(new PeepholeReplaceKnownMethods(late, useTypesForOptimization)); optimizations.add(new PeepholeRemoveDeadCode()); if (compiler.getOptions().j2clPassMode.shouldAddJ2clPasses()) { optimizations.add(new J2clEqualitySameRewriterPass(useTypesForOptimization)); optimizations.add(new J2clStringValueOfRewriterPass()); } optimizations.add(new PeepholeFoldConstants(late, useTypesForOptimization)); optimizations.add(new PeepholeCollectPropertyAssignments()); if (useTypesForOptimization) { optimizations.add(new PeepholeCombineArrayPush()); } return new PeepholeOptimizationsPass(compiler, passName, optimizations); }
Source:
static Stream<Arguments> performSearchParameters() { ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class); when(importFormatPreferences.getFieldContentFormatterPreferences()) .thenReturn(mock(FieldContentFormatterPreferences.class)); List<Set<SearchBasedFetcher>> fetcherParameters = new ArrayList<>(); List<SearchBasedFetcher> list = new ArrayList<>(); list.add(new ArXiv(importFormatPreferences)); list.add(new INSPIREFetcher(importFormatPreferences)); list.add(new GvkFetcher()); list.add(new AstrophysicsDataSystem(importFormatPreferences)); list.add(new MathSciNet(importFormatPreferences)); list.add(new ZbMATH(importFormatPreferences)); list.add(new GoogleScholar(importFormatPreferences)); list.add(new DBLPFetcher(importFormatPreferences)); list.add(new SpringerFetcher()); list.add(new CrossRef()); list.add(new CiteSeer()); list.add(new DOAJFetcher(importFormatPreferences)); list.add(new IEEE(importFormatPreferences)); for (int i = 1; i < list.size(); i++) { fetcherParameters.add(new HashSet<>(list.subList(0, i))); } return fetcherParameters.stream().map(Arguments::of); }

Target:
static Stream<Arguments> performSearchParameters() { ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class); when(importFormatPreferences.getFieldContentFormatterPreferences()) .thenReturn(mock(FieldContentFormatterPreferences.class)); List<Set<SearchBasedFetcher>> fetcherParameters = new ArrayList<>(); List<SearchBasedFetcher> list = new ArrayList<>(); list.add(new ArXiv(importFormatPreferences)); list.add(new INSPIREFetcher(importFormatPreferences)); list.add(new GvkFetcher()); list.add(new AstrophysicsDataSystem(importFormatPreferences)); list.add(new MathSciNet(importFormatPreferences)); list.add(new ZbMATH(importFormatPreferences)); list.add(new GoogleScholar(importFormatPreferences)); list.add(new DBLPFetcher(importFormatPreferences)); list.add(new SpringerFetcher()); list.add(new CrossRef()); list.add(new CiteSeer()); list.add(new DOAJFetcher(importFormatPreferences)); list.add(new IEEE(importFormatPreferences)); for (int i = 1; i < Math.pow(2, list.size()); i += 273) { Set<SearchBasedFetcher> fetchers = new HashSet<>(); for (int j = 0; Math.pow(2, j) <= i; j++) { if ((i >> j) % 2 == 1) { fetchers.add(list.get(j)); } } fetcherParameters.add(fetchers); } return fetcherParameters.stream().map(Arguments::of); }
Source:
public void fetch(Callback callback) { long started = System.nanoTime(); if (deferred) { throw new IllegalStateException("Fit cannot be used with fetch."); } if (data.hasImage()) { if (!data.hasPriority()) { data.priority(Priority.LOW); } Request request = createRequest(started); String key = createKey(request, new StringBuilder()); Bitmap bitmap = picasso.quickMemoryCacheCheck(key); if (bitmap != null) { if (picasso.loggingEnabled) { log(OWNER_MAIN, VERB_COMPLETED, request.plainId(), "from " + MEMORY); } if (callback != null) { callback.onSuccess(); } return; } Action action = new FetchAction(picasso, request, skipMemoryCache, key, tag, callback); picasso.submit(action); } }

Target:
public void fetch(Callback callback) { long started = System.nanoTime(); if (deferred) { throw new IllegalStateException("Fit cannot be used with fetch."); } if (data.hasImage()) { if (!data.hasPriority()) { data.priority(Priority.LOW); } Request request = createRequest(started); String key = createKey(request, new StringBuilder()); Bitmap bitmap = picasso.quickMemoryCacheCheck(key); if (bitmap != null) { if (picasso.loggingEnabled) { log(OWNER_MAIN, VERB_COMPLETED, request.plainId(), "from " + MEMORY); } if (callback != null) { callback.onSuccess(); } return; } Action action = new FetchAction(picasso, request, memoryPolicy, networkPolicy, tag, key, callback); picasso.submit(action); } }
Source:
public ValidationResult mixedClusterServicesSupported() { boolean mixedClusterEnavled = Config.<Boolean> getValue(ConfigValues.AllowClusterWithVirtGlusterEnabled); return ValidationResult.failWith(VdcBllMessages.VDS_GROUP_ENABLING_BOTH_VIRT_AND_GLUSTER_SERVICES_NOT_ALLOWED) .when(cluster.supportsGlusterService() && cluster.supportsVirtService() && !mixedClusterEnavled); }

Target:
public ValidationResult mixedClusterServicesSupported() { boolean mixedClusterEnabled = Config.<Boolean> getValue(ConfigValues.AllowClusterWithVirtGlusterEnabled); return ValidationResult.failWith(VdcBllMessages.VDS_GROUP_ENABLING_BOTH_VIRT_AND_GLUSTER_SERVICES_NOT_ALLOWED) .when(cluster.supportsGlusterService() && cluster.supportsVirtService() && !mixedClusterEnabled); }
Source:
public void eventReceived(Object output) { if (output instanceof MIOutput) { MIOOBRecord[] records = ((MIOutput)output).getMIOOBRecords(); for (MIOOBRecord r : records) { if (r instanceof MINotifyAsyncOutput) { MINotifyAsyncOutput notifyOutput = (MINotifyAsyncOutput)r; String asyncClass = notifyOutput.getAsyncClass(); if ("record-started".equals(asyncClass) || "record-stopped".equals(asyncClass)) { if ("record-stopped".equals(asyncClass)) { fReverseTraceMethod = ReverseTraceMethod.STOP_TRACE; setReverseModeEnabled(false); } else { getConnection().queueCommand( fCommandFactory.createCLIInfoRecord(getConnection().getContext()), new DataRequestMonitor<CLIInfoRecordInfo>(getExecutor(), null) { @Override public void handleSuccess() { CLIInfoRecordInfo output = getData(); fReverseTraceMethod = output.getReverseMethod(); setReverseModeEnabled(true); } }); } } } } } }

Target:
public void eventReceived(Object output) { if (output instanceof MIOutput) { MIOOBRecord[] records = ((MIOutput)output).getMIOOBRecords(); for (MIOOBRecord r : records) { if (r instanceof MINotifyAsyncOutput) { MINotifyAsyncOutput notifyOutput = (MINotifyAsyncOutput)r; String asyncClass = notifyOutput.getAsyncClass(); if ("record-started".equals(asyncClass) || "record-stopped".equals(asyncClass)) { if ("record-stopped".equals(asyncClass)) { fReverseTraceMethod = ReverseTraceMethod.STOP_TRACE; setReverseModeEnabled(false); } else { getConnection().queueCommand( fCommandFactory.createCLIInfoRecord(getConnection().getContext()), new DataRequestMonitor<CLIInfoRecordInfo>(getExecutor(), null) { @Override public void handleCompleted() { if (isSuccess()) { CLIInfoRecordInfo output = getData(); fReverseTraceMethod = output.getReverseMethod(); setReverseModeEnabled(true); } else { fReverseTraceMethod = ReverseTraceMethod.FULL_TRACE; } } }); } } } } } }
Source:
public void runReadWithFilterUsingUri() throws Exception { final CountDownLatch latch = new CountDownLatch(1); HttpProviderFactory factory = mock(HttpProviderFactory.class); when(factory.get(anyObject())).thenReturn(mock(HttpProvider.class)); RestAdapter<Data> adapter = new RestAdapter<Data>(Data.class, url); Object restRunner = UnitTestUtils.getPrivateField(adapter, "restRunner"); UnitTestUtils.setPrivateField(restRunner, "httpProviderFactory", factory); ReadFilter filter = new ReadFilter(); filter.setLinkUri(URI.create("rail%2Ftrails?limit=10&where=%7B%22model%22:%22BMW%22%7D")); adapter.read(filter, new Callback<List<Data>>() { @Override public void onSuccess(List<Data> data) { latch.countDown(); } @Override public void onFailure(Exception e) { latch.countDown(); } }); latch.await(500, TimeUnit.MILLISECONDS); verify(factory).get(eq(new URL(url.toString() + "rail%2Ftrails?limit=10&where=%7B%22model%22:%22BMW%22%7D"))); }

Target:
public void runReadWithFilterUsingUri() throws Exception { final CountDownLatch latch = new CountDownLatch(1); HttpProviderFactory factory = mock(HttpProviderFactory.class); when(factory.get(anyObject())).thenReturn(mock(HttpProvider.class)); RestAdapter<Data> adapter = new RestAdapter<Data>(Data.class, url); Object restRunner = UnitTestUtils.getPrivateField(adapter, "restRunner"); UnitTestUtils.setPrivateField(restRunner, "httpProviderFactory", factory); ReadFilter filter = new ReadFilter(); filter.setLinkUri(URI.create("rail%2Ftrails?limit=10&where=%7B%22model%22:%22BMW%22%7D")); adapter.read(filter, new Callback<List<Data>>() { @Override public void onSuccess(List<Data> data) { latch.countDown(); } @Override public void onFailure(Exception e) { latch.countDown(); } }); latch.await(500, TimeUnit.MILLISECONDS); verify(factory).get(Mockito.argThat(new ObjectVarArgsMatcher(new URL(url.toString() + "rail%2Ftrails?limit=10&where=%7B%22model%22:%22BMW%22%7D"), 60000))); }
Source:
public HeliumBundleFactory( ZeppelinConfiguration conf, File nodeInstallationDir, File moduleDownloadPath) throws TaskRunnerException { this.heliumLocalRepoDirectory = new File(moduleDownloadPath, HELIUM_LOCAL_REPO); this.heliumBundleDirectory = new File(heliumLocalRepoDirectory, HELIUM_BUNDLES_DIR); this.heliumLocalModuleDirectory = new File(heliumLocalRepoDirectory, HELIUM_LOCAL_MODULE_DIR); this.yarnCacheDir = new File(heliumLocalRepoDirectory, YARN_CACHE_DIR); this.defaultNpmRegistryUrl = conf.getHeliumNpmRegistryUrl(); this.defaultNpmRegistryRepo = conf.getHeliumNpmRegistryRepo(); nodeInstallationDirectory = (nodeInstallationDir == null) ? heliumLocalRepoDirectory : nodeInstallationDir; frontEndPluginFactory = new FrontendPluginFactory( heliumLocalRepoDirectory, nodeInstallationDirectory); gson = new Gson(); }

Target:
public HeliumBundleFactory( ZeppelinConfiguration conf, File nodeInstallationDir, File moduleDownloadPath) throws TaskRunnerException { this.heliumLocalRepoDirectory = new File(moduleDownloadPath, HELIUM_LOCAL_REPO); this.heliumBundleDirectory = new File(heliumLocalRepoDirectory, HELIUM_BUNDLES_DIR); this.heliumLocalModuleDirectory = new File(heliumLocalRepoDirectory, HELIUM_LOCAL_MODULE_DIR); this.yarnCacheDir = new File(heliumLocalRepoDirectory, YARN_CACHE_DIR); this.defaultNodeInstallerUrl = conf.getHeliumNodeInstallerUrl(); this.defaultNpmInstallerUrl = conf.getHeliumNpmInstallerUrl(); this.defaultYarnInstallerUrl = conf.getHeliumYarnInstallerUrl(); nodeInstallationDirectory = (nodeInstallationDir == null) ? heliumLocalRepoDirectory : nodeInstallationDir; frontEndPluginFactory = new FrontendPluginFactory( heliumLocalRepoDirectory, nodeInstallationDirectory); gson = new Gson(); }
Source:
@Override public PMMLExportable getPMMLExportable() throws MLPmmlExportException { if (model instanceof PMMLExportable) { return (PMMLExportable)model; } else { throw new MLPmmlExportException("PMML export not supported for model type"); } }

Target:
public PMMLExportable getPMMLExportable() throws MLPmmlExportException { if (model instanceof PMMLExportable) { return (PMMLExportable)model; } else { throw new MLPmmlExportException("PMML export not supported for model type"); } }
Source:
public void testCreateLabelWhereNoneExists() throws UnsupportedOperationException, Exception { PID pid = makePid(); Path file = createTempFile("test", "txt"); FileObject fileObj = repositoryObjectFactory.createFileObject(pid, ModelFactory.createDefaultModel()); fileObj.addOriginalFile(file.toUri(), filename, mimetype, null, null); String label = "work_filename"; MvcResult result = mvc.perform(put("/edit/filename/" + pid.getUUID()) .param("label", label)) .andExpect(status().is2xxSuccessful()) .andReturn(); Map<String, Object> respMap = getMapFromResponse(result); assertEquals(pid.getUUID(), respMap.get("pid")); assertEquals("editLabel", respMap.get("action")); assertEquals("work_filename", fileObj.getOriginalFile().getModel().getRequiredProperty( fileObj.getOriginalFile().getResource(), Ebucore.filename).getLiteral().toString()); }

Target:
public void testCreateLabelWhereNoneExists() throws UnsupportedOperationException, Exception { PID pid = makePid(); Path file = createTempFile("test", "txt"); FileObject fileObj = repositoryObjectFactory.createFileObject(pid, null); fileObj.addOriginalFile(file.toUri(), filename, mimetype, null, null); String label = "work_filename"; MvcResult result = mvc.perform(put("/edit/filename/" + pid.getUUID()) .param("label", label)) .andExpect(status().is2xxSuccessful()) .andReturn(); Map<String, Object> respMap = getMapFromResponse(result); assertEquals(pid.getUUID(), respMap.get("pid")); assertEquals("editLabel", respMap.get("action")); assertEquals("work_filename", fileObj.getOriginalFile().getResource().getProperty(Ebucore.filename) .getLiteral().toString()); }
Source:
public void nodeSkipped(JupiterEngineExecutionContext context, TestDescriptor descriptor, SkipResult result) { invokeTestWatchers(context, t -> { t.testSkipped(createTestIdentifier(), result.getReason(), context.getExtensionContext()); }); }

Target:
public void nodeSkipped(JupiterEngineExecutionContext context, TestDescriptor descriptor, SkipResult result) { if (context != null) { invokeTestWatchers(context, watcher -> { watcher.testDisabled(context.getExtensionContext(), result.getReason()); }, false); } }
Source:
public String getGeneralProblemsMessage() { StringBuilder message = new StringBuilder(); for (Object error: getErrors()) { message.append(error.toString()).append("\n"); } for (Object warning: getWarnings()) { message.append(warning.toString()).append("\n"); } return message.toString(); }

Target:
private String getGeneralProblemsMessage() { StringBuilder message = new StringBuilder(); addMessages(message, getErrors().values()); addMessages(message, getWarnings().values()); return message.toString(); }
Source:
public void getAttribute_shouldReturnNullWhenExistingPersonAttributeTypeIsVoided () throws Exception { Person person = personHelper(true, 1, 2, 3, "name1", "name2", "name3", "value1", "value2", "value3"); PersonAttributeType type = new PersonAttributeType(new Integer(3)); type.setName("name3"); Assert.assertNull(null, person.getAttribute(type)); }

Target:
public void getAttribute_shouldReturnNullWhenExistingPersonAttributeTypeIsVoided () throws Exception { Person person = personHelper(true, 1, 2, 3, "name1", "name2", "name3", "value1", "value2", "value3"); PersonAttributeType type = new PersonAttributeType(new Integer(3)); type.setName("name3"); Assert.assertNull(person.getAttribute(type)); }
Source:
private EcoTopologyDefinition loadTopologyFromYaml(Yaml yaml, InputStream inputStream, InputStream propsIn, boolean envFilter) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); int b; while ((b = inputStream.read()) != -1) { bos.write(b); } String yamlDefinitionStr = bos.toString(); if (propsIn != null) { LOG.info("Performing property substitution."); Properties props = new Properties(); props.load(propsIn); for (Object key : props.keySet()) { yamlDefinitionStr = yamlDefinitionStr.replace("${" + key + "}", props.getProperty((String) key)); } } else { LOG.info("Not performing property substitution."); } if (envFilter) { LOG.info("Performing environment variable substitution."); Map<String, String> envs = System.getenv(); for (String key : envs.keySet()) { yamlDefinitionStr = yamlDefinitionStr.replace("${ENV-" + key + "}", envs.get(key)); } } else { LOG.info("Not performing environment variable substitution."); } return (EcoTopologyDefinition) yaml.load(yamlDefinitionStr); }

Target:
private EcoTopologyDefinition loadTopologyFromYaml(Yaml yaml, InputStream inputStream, InputStream propsIn, boolean envFilter) throws IOException { LOG.info("Parsing eco config file"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); int b; while ((b = inputStream.read()) != -1) { bos.write(b); } String yamlDefinitionStr = bos.toString(); if (propsIn != null) { LOG.info("Performing property substitution."); Properties props = new Properties(); props.load(propsIn); for (Object key : props.keySet()) { yamlDefinitionStr = yamlDefinitionStr.replace("${" + key + "}", props.getProperty((String) key)); } } else { LOG.info("Not performing property substitution."); } if (envFilter) { LOG.info("Performing environment variable substitution."); Map<String, String> envs = System.getenv(); for (String key : envs.keySet()) { yamlDefinitionStr = yamlDefinitionStr.replace("${ENV-" + key + "}", envs.get(key)); } } else { LOG.info("Not performing environment variable substitution."); } return (EcoTopologyDefinition) yaml.load(yamlDefinitionStr); }
Source:
private boolean updateThumbnailEvent(CatalogModifyEvent event) { for (int i = 0; i < event.getNewValues().size(); i++) { if (event.getNewValues().get(i) instanceof MetadataMap) { MetadataMap oldMap = (MetadataMap)event.getOldValues().get(i); MetadataMap newMap = (MetadataMap)event.getNewValues().get(i); if (oldMap.containsKey(Metadata.THUMBNAIL) && newMap.containsKey(Metadata.THUMBNAIL) && oldMap.get(Metadata.THUMBNAIL) != newMap.get(Metadata.THUMBNAIL) ) { return true; } if ((oldMap.containsKey(Metadata.THUMBNAIL) && !newMap.containsKey(Metadata.THUMBNAIL)) || (!oldMap.containsKey(Metadata.THUMBNAIL) && newMap.containsKey(Metadata.THUMBNAIL))) { return true; } if (oldMap.containsKey(Metadata.THUMBNAIL) && newMap.containsKey(Metadata.THUMBNAIL) && oldMap.get(Metadata.THUMBNAIL) == newMap.get(Metadata.THUMBNAIL) ) { newMap.remove(Metadata.THUMBNAIL); } } } return false; }

Target:
private boolean updateThumbnailEvent(CatalogModifyEvent event) { for (int i = 0; i < event.getNewValues().size(); i++) { if (event.getNewValues().get(i) instanceof MetadataMap) { MetadataMap oldMap = (MetadataMap)event.getOldValues().get(i); MetadataMap newMap = (MetadataMap)event.getNewValues().get(i); if (updateMetadataMap(oldMap, newMap)) { return true; } } } return false; }
Source:
public static void assertEqualsNoEol(String expected, String actual) { assertEquals(normalizeEolInTextBlock(expected, EOL), normalizeEolInTextBlock(actual, EOL)); }

Target:
public static void assertEqualsNoEol(String expected, String actual) { assertEqualsStringIgnoringEol(expected, actual); }
Source:
public Collection<AKContentOverride> getContentOverrides() { return this.contentOverrides; }

Target:
public Collection<AKContentOverride> getContentOverrides() { return Collections.unmodifiableCollection(this.contentOverrides); }
Source:
public static boolean showMarkers(IWorkbenchPage page, IMarker[] markers, boolean showView) { boolean returnValue = false; IMarker marker = markers[0]; try { String viewId = getViewId(marker); IMarker[] markersSameView = getMarkersOfView(viewId, markers); if (viewId == null) viewId = IPageLayout.ID_PROBLEM_VIEW; IViewPart view = showView ? page.showView(viewId) : page .findView(viewId); if (view != null) returnValue = MarkerSupportInternalUtilities.showMarkers(view, markersSameView); } catch (CoreException e) { Policy.handle(e); } return returnValue; }

Target:
public static boolean showMarkers(IWorkbenchPage page, IMarker[] markers, boolean showView) { if (null == markers || 0 == markers.length || null == markers[0]) return false; boolean returnValue = false; try { String viewId = getViewId(markers[0]); IMarker[] markersSameView = getMarkersOfView(viewId, markers); if (viewId == null) viewId = IPageLayout.ID_PROBLEM_VIEW; IViewPart view = showView ? page.showView(viewId) : page .findView(viewId); if (view != null) returnValue = MarkerSupportInternalUtilities.showMarkers(view, markersSameView); } catch (CoreException e) { Policy.handle(e); } return returnValue; }
Source:
void propogateInputChange() { if (!inputChangeListeners.isEmpty()) { Object[] allListeners = inputChangeListeners.getListeners(); for (Object allListener : allListeners) { final ICompareInputChangeListener listener = (ICompareInputChangeListener) allListener; SafeRunner.run(new ISafeRunnable() { @Override public void run() throws Exception { listener.compareInputChanged((ICompareInput)SaveableCompareEditorInput.this.getCompareResult()); } @Override public void handleException(Throwable exception) { } }); } } }

Target:
void propogateInputChange() { if (!inputChangeListeners.isEmpty()) { Object[] allListeners = inputChangeListeners.getListeners(); for (Object l : allListeners) { final ICompareInputChangeListener listener = (ICompareInputChangeListener)l; SafeRunner.run(new ISafeRunnable() { @Override public void run() throws Exception { listener.compareInputChanged((ICompareInput)SaveableCompareEditorInput.this.getCompareResult()); } @Override public void handleException(Throwable exception) { } }); } } }
Source:
public void stop() { log.info("Stopping DerbyConnector...."); storage.stop(); }

Target:
public void stop() { log.info("Stopping DerbyConnector..."); storage.stop(); }
Source:
public TaskListenerExecutor getObject() { beforeTaskInstances = new HashMap<>(); afterTaskInstances = new HashMap<>(); failedTaskInstances = new HashMap<>(); initializeExecutor(); return new TaskListenerExecutor(beforeTaskInstances, afterTaskInstances, failedTaskInstances); }

Target:
public TaskListenerExecutor getObject() { this.beforeTaskInstances = new HashMap<>(); this.afterTaskInstances = new HashMap<>(); this.failedTaskInstances = new HashMap<>(); initializeExecutor(); return new TaskListenerExecutor(beforeTaskInstances, afterTaskInstances, failedTaskInstances); }
Source:
public void visitFilter(VisitableXmlElement<FilterType> visitable) { JAXBElement<FilterType> element = visitable.getElement(); String localPart = element.getName().getLocalPart(); logLocalPart(localPart); FilterType filterType = element.getValue(); JAXBElement<?> root = Stream.of( filterType.getComparisonOps(), filterType.getLogicOps(), filterType.getSpatialOps(), filterType.getTemporalOps()) .filter(Objects::nonNull) .findAny() .orElse(null); if (root != null) { LOGGER.debug("Valid root found, beginning traversal..."); makeVisitable(root).accept(this); return; } handleUnsupported(filterType.getId()); handleUnsupported(filterType.getExtensionOps()); handleUnsupported(filterType.getFunction()); throw new FilterProcessingException("No valid starting element for the filter was found"); }

Target:
public void visitFilter(VisitableXmlElement<FilterType> visitable) { JAXBElement<FilterType> element = visitable.getElement(); String localPart = element.getName().getLocalPart(); traceLocalPart(localPart); FilterType filterType = element.getValue(); JAXBElement<?> root = Stream.of( filterType.getComparisonOps(), filterType.getLogicOps(), filterType.getSpatialOps(), filterType.getTemporalOps()) .filter(Objects::nonNull) .findAny() .orElse(null); if (root != null) { LOGGER.trace("Valid root found, beginning traversal..."); makeVisitable(root).accept(this); return; } handleUnsupported(filterType.getId()); handleUnsupported(filterType.getExtensionOps()); handleUnsupported(filterType.getFunction()); throw new FilterProcessingException("No valid starting element for the filter was found"); }
Source:
public void getConditionsByPatientUuid_shouldReturnListOfActiveConditions() { Condition condition = new Condition(); IdType id = new IdType(); id.setValue(CONDITION_UUID); condition.setId(id); Patient patientRef = Context.getPatientService().getPatient(2); Reference patient = FHIRUtils.buildPatientOrPersonResourceReference(patientRef); condition.setSubject(patient); condition.setClinicalStatus(Condition.ConditionClinicalStatus.ACTIVE); condition.setCode(new CodeableConcept().addCoding( new Coding().setCode("999").setDisplay("NO").setSystem(FHIRConstants.OPENMRS_URI)).setText("NO")); getService().createFHIRCondition(condition); List<Condition> activeConditions = getService().getConditionsByPatientUuid(patientRef.getUuid()); assertFalse(activeConditions.isEmpty()); assertEquals(activeConditions.get(0).getClinicalStatus().getDisplay(), "Active"); assertEquals(activeConditions.get(0).getClinicalStatus().name(), "ACTIVE"); }

Target:
public void getConditionsByPatientUuid_shouldReturnListOfActiveConditions() { Condition condition = new Condition(); IdType id = new IdType(); id.setValue(CONDITION_UUID); condition.setId(id); Patient patient = Context.getPatientService().getPatient(2); Reference patientReference = FHIRUtils.buildPatientOrPersonResourceReference(patient); condition.setSubject(patientReference); condition.setClinicalStatus(Condition.ConditionClinicalStatus.ACTIVE); condition.setCode(new CodeableConcept().addCoding( new Coding().setCode("999").setDisplay("NO").setSystem(FHIRConstants.OPENMRS_URI)).setText("NO")); List<Condition> activeConditions = getService().getConditionsByPatientUuid(patient.getUuid()); assertTrue(activeConditions.isEmpty()); getService().createFHIRCondition(condition); activeConditions = getService().getConditionsByPatientUuid(patient.getUuid()); assertNotNull(activeConditions); assertFalse(activeConditions.isEmpty()); assertEquals(activeConditions.get(0).getClinicalStatus().getDisplay(), "Active"); assertEquals(activeConditions.get(0).getClinicalStatus().name(), "ACTIVE"); }
Source:
private SpawnResult downloadAndFinalizeSpawnResult( ActionResult actionResult, boolean cacheHit, Spawn spawn, SpawnExecutionContext context, RemoteOutputsMode remoteOutputsMode) throws ExecException, IOException, InterruptedException { boolean spawnHasTopLevelOutputs = remoteOutputsMode.downloadToplevelOutputsOnly() && hasTopLevelOutputs(spawn.getOutputFiles(), topLevelOutputs); SpawnResult.Status actionStatus = actionResult.getExitCode() == 0 ? Status.SUCCESS : Status.NON_ZERO_EXIT; RemoteOutputsMode effectiveOutputsMode; if (actionStatus != Status.SUCCESS || spawnHasTopLevelOutputs) { effectiveOutputsMode = RemoteOutputsMode.ALL; } else if (remoteOutputsMode == RemoteOutputsMode.TOPLEVEL) { effectiveOutputsMode = RemoteOutputsMode.MINIMAL; } else { effectiveOutputsMode = remoteOutputsMode; } PathFragment inMemoryOutputPath = getInMemoryOutputPath(spawn); InMemoryOutput inMemoryOutput = null; switch (effectiveOutputsMode) { case MINIMAL: try (SilentCloseable c = Profiler.instance().profile(REMOTE_DOWNLOAD, "download outputs minimal")) { inMemoryOutput = remoteCache.downloadMinimal( actionResult, spawn.getOutputFiles(), inMemoryOutputPath, context.getFileOutErr(), execRoot, context.getMetadataInjector()); } break; case ALL: try (SilentCloseable c = Profiler.instance().profile(REMOTE_DOWNLOAD, "download outputs")) { remoteCache.download(actionResult, execRoot, context.getFileOutErr()); } break; default: throw new IllegalStateException("Should never reach this."); } return createSpawnResult(actionResult.getExitCode(), cacheHit, getName(), inMemoryOutput); }

Target:
private SpawnResult downloadAndFinalizeSpawnResult( ActionResult actionResult, boolean cacheHit, Spawn spawn, SpawnExecutionContext context, RemoteOutputsMode remoteOutputsMode) throws ExecException, IOException, InterruptedException { boolean downloadOutputs = shouldDownloadAllSpawnOutputs(remoteOutputsMode, actionResult.getExitCode(), hasTopLevelOutputs(spawn.getOutputFiles(), topLevelOutputs)); InMemoryOutput inMemoryOutput = null; if (downloadOutputs) { try (SilentCloseable c = Profiler.instance().profile(REMOTE_DOWNLOAD, "download outputs")) { remoteCache.download(actionResult, execRoot, context.getFileOutErr()); } } else { PathFragment inMemoryOutputPath = getInMemoryOutputPath(spawn); try (SilentCloseable c = Profiler.instance().profile(REMOTE_DOWNLOAD, "download outputs minimal")) { inMemoryOutput = remoteCache.downloadMinimal( actionResult, spawn.getOutputFiles(), inMemoryOutputPath, context.getFileOutErr(), execRoot, context.getMetadataInjector()); } } return createSpawnResult(actionResult.getExitCode(), cacheHit, getName(), inMemoryOutput); }
Source:
public void testTruncateInvalidTxBefore() throws Exception { Transaction tx1 = txClient.startLong(); TimeUnit.SECONDS.sleep(1); long beforeTx2 = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()); Transaction tx2 = txClient.startLong(); ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream err = new ByteArrayOutputStream(); TransactionAdmin txAdmin = new TransactionAdmin(new PrintStream(out), new PrintStream(err)); txAdmin.doMain(new String[] {"--truncate-invalid-tx-before", String.valueOf(beforeTx2)}, conf); List<String> expectedOut = ImmutableList.of("Invalid list size before truncation: 0", ""); List<String> expectedErr = ImmutableList.of("Transactions started earlier than " + beforeTx2 + " are in-progress", ""); Assert.assertEquals(Joiner.on("\n").join(expectedOut), Bytes.toString(out.toByteArray())); Assert.assertEquals(Joiner.on("\n").join(expectedErr), Bytes.toString(err.toByteArray())); txClient.invalidate(tx1.getWritePointer()); txClient.invalidate(tx2.getWritePointer()); out.reset(); err.reset(); txAdmin.doMain(new String[]{"--truncate-invalid-tx-before", String.valueOf(beforeTx2)}, conf); expectedOut = ImmutableList.of("Invalid list size before truncation: 2", "Invalid list size after truncation: 1", ""); Assert.assertEquals(Joiner.on("\n").join(expectedOut), Bytes.toString(out.toByteArray())); Assert.assertEquals(0, err.toByteArray().length); }

Target:
public void testTruncateInvalidTxBefore() throws Exception { Transaction tx1 = txClient.startLong(); TimeUnit.MILLISECONDS.sleep(1); long beforeTx2 = System.currentTimeMillis(); Transaction tx2 = txClient.startLong(); Assert.assertEquals(0, txClient.getInvalidSize()); TransactionAdmin txAdmin = new TransactionAdmin(new PrintStream(System.out), new PrintStream(System.err)); int status = txAdmin.doMain(new String[]{"--truncate-invalid-tx-before", String.valueOf(beforeTx2)}, conf); Assert.assertEquals(1, status); Assert.assertEquals(0, txClient.getInvalidSize()); txClient.invalidate(tx1.getWritePointer()); txClient.invalidate(tx2.getWritePointer()); Assert.assertEquals(2, txClient.getInvalidSize()); status = txAdmin.doMain(new String[]{"--truncate-invalid-tx-before", String.valueOf(beforeTx2)}, conf); Assert.assertEquals(0, status); Assert.assertEquals(1, txClient.getInvalidSize()); }