auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void unselectsSelection() throws Exception { bot.radio("SWT.MULTI").click(); bot.checkBox("Listen").select(); bot.button("Clear").click(); table = bot.tableInGroup("Table"); table.select(new int[] {1, 2, 3}); SWTBotText text = bot.textInGroup("Listeners"); bot.button("Clear").click(); table.unselect(1); assertEquals(2, table.selectionCount()); assertEventMatches(text, "Selection [13]: SelectionEvent{Table time=-550222256 data=null item=TableItem {Index:1} detail=0 x=0 y=0 width=0 height=0 stateMask=0xc0000 text=null doit=true}"); assertEventMatches(text, "MouseDown [3]: MouseEvent{Table time=-550222259 data=null button=1 stateMask=0x40000 x=0 y=0 count=1}"); assertEventMatches(text, "MouseUp [4]: MouseEvent{Table time=-550222255 data=null button=1 stateMask=0xc0000 x=0 y=0 count=1}"); table.unselect(); assertEquals(0, table.selectionCount()); }

Target:
public void unselectsSelection() throws Exception { bot.radio("SWT.MULTI").click(); bot.checkBox("Listen").select(); bot.button("Clear").click(); table = bot.tableInGroup("Table"); table.select(new int[] { 1, 2, 3 }); SWTBotText text = bot.textInGroup("Listeners"); bot.button("Clear").click(); table.unselect(1); assertEquals(2, table.selectionCount()); assertEventMatches(text, "MouseDown [3]: MouseEvent{Table time=-550222259 data=null button=1 stateMask=0x40000 x=0 y=0 count=1}"); assertEventMatches(text, "Selection [13]: SelectionEvent{Table time=-550222256 data=null item=TableItem {Index:1} detail=0 x=0 y=0 width=0 height=0 stateMask=0xc0000 text=null doit=true}"); assertEventMatches(text, "MouseUp [4]: MouseEvent{Table time=-550222255 data=null button=1 stateMask=0xc0000 x=0 y=0 count=1}"); table.unselect(); assertEquals(0, table.selectionCount()); table.select(new int[] { 1, 2, 3 }); assertEquals(3, table.selectionCount()); table.select(new int[] {}); assertEquals(0, table.selectionCount()); }
Source:
public List<IEventDeclaration> getEventDeclarations() { ArrayList<IEventDeclaration> retVal = new ArrayList<>(fEvents); retVal.removeAll(Collections.singletonList(null)); return retVal; }

Target:
public Collection<IEventDeclaration> getEventDeclarations() { ArrayList<IEventDeclaration> retVal = new ArrayList<>(fEvents); retVal.removeAll(Collections.singletonList(null)); return retVal; }
Source:
private String argAdditionalConf( File backupTarget ) { if ( additionalConfig == null ) { return ""; } File configFile = neo4jHomeFromTarget( backupTarget ).resolve( "../additional_neo4j.conf" ).toFile(); writeConfigToFile( additionalConfig, configFile ); return String.format( "--additional-config=%s", configFile ); }

Target:
private String argAdditionalConf( File backupTarget ) throws IOException { if ( additionalConfig == null ) { return ""; } File configFile = neo4jHomeFromTarget( backupTarget ).resolve( "../additional_neo4j.conf" ).toFile(); writeConfigToFile( additionalConfig, configFile ); return String.format( "--additional-config=%s", configFile ); }
Source:
public void setup() throws Exception { clock = new ManualClock(); slotPool = new SlotPoolBuilder(mainThreadExecutor).build(); bulkSlotProvider = new BulkSlotProviderImpl(LocationPreferenceSlotSelectionStrategy.createDefault(), slotPool); bulkSlotProvider.start(mainThreadExecutor); slotOwner = new TestingSlotOwner(); slotOwner.setReturnAllocatedSlotConsumer( logicalSlot -> slotPool.releaseSlot( logicalSlot.getSlotRequestId(), new FlinkException("Slot is being returned to the SlotPool."))); }

Target:
public void setup() throws Exception { clock = new ManualClock(); slotPool = new SlotPoolBuilder(mainThreadExecutor).build(); bulkSlotProvider = new BulkSlotProviderImpl(LocationPreferenceSlotSelectionStrategy.createDefault(), slotPool); bulkSlotProvider.start(mainThreadExecutor); }
Source:
private List<String> getKerberosNamedNodeList(Map<String, Object> hdfsSettings) { kerberosNamedNodes = getString(hdfsSettings, "kerberosNamedNodes", kerberosNamedNodes); return Arrays.stream(kerberosNamedNodes.split(",")).distinct().collect(Collectors.toList()); }

Target:
private List<String> getKerberosNamedNodeList(Map<String, Object> hdfsSettings) { kerberosNamedNodes = getString(hdfsSettings, "kerberosNamedNodes", kerberosNamedNodes); if (isNotEmpty(kerberosNamedNodes)) { return Arrays.stream(kerberosNamedNodes.split(",")).distinct().collect(Collectors.toList()); } return Collections.emptyList(); }
Source:
public static List<CigarElement> clipEndOfRead(final int clipFrom, final List<CigarElement> oldCigar, final CigarOperator clippingOperator) { ValidationUtils.validateArg(clippingOperator.isClipping(), "Clipping operator should be SOFT or HARD clip, found " + clippingOperator.toString()); final int clippedBases = (int)CoordMath.getLength(clipFrom, Cigar.getReadLength(oldCigar)); List<CigarElement> newCigar = new LinkedList<CigarElement>(); int pos = 1; for (CigarElement c : oldCigar) { final CigarOperator op = c.getOperator(); final int length = op.consumesReadBases()? c.getLength() : 0; final int endPos = pos + length - 1; if (endPos < (clipFrom - 1)) { newCigar.add(c); } else if (endPos >= (clipFrom - 1)) { elementStraddlesClippedRead(newCigar, c, (clipFrom -1) - (pos -1) , clippedBases, clippingOperator); break; } pos = endPos + 1; } return newCigar; }

Target:
public static List<CigarElement> clipEndOfRead(final int clipFrom, final List<CigarElement> oldCigar, final CigarOperator clippingOperator) { ValidationUtils.validateArg(clippingOperator.isClipping(), () -> "Clipping operator should be SOFT or HARD clip, found " + clippingOperator.toString()); final int clippedBases = (int)CoordMath.getLength(clipFrom, Cigar.getReadLength(oldCigar)); List<CigarElement> newCigar = new LinkedList<CigarElement>(); int pos = 1; for (CigarElement c : oldCigar) { final CigarOperator op = c.getOperator(); final int length = op.consumesReadBases()? c.getLength() : 0; final int endPos = pos + length - 1; if (endPos < (clipFrom - 1)) { newCigar.add(c); } else if (endPos >= (clipFrom - 1)) { addClippingCigarElement(newCigar, c, (clipFrom - 1) - (pos - 1) , clippedBases, clippingOperator); break; } pos = endPos + 1; } return newCigar; }
Source:
public Location newLocationFromString(Map locationFlags, String spec, LocationRegistry registry) { String id = spec.substring(NAME.length()+1); CatalogItem<?, ?> item = CatalogUtils.getCatalogItemOptionalVersion(managementContext, id); if (item.isDeprecated()) { log.warn("Use of deprecated catalog item "+item.getSymbolicName()+":"+item.getVersion()); } else if (item.isDisabled()) { throw new IllegalStateException("Illegal use of disabled catalog item "+item.getSymbolicName()+":"+item.getVersion()); } LocationSpec<?> origLocSpec = managementContext.getCatalog().createSpec((CatalogItem<Location, LocationSpec<?>>)item); LocationSpec<?> locSpec = LocationSpec.create(origLocSpec) .configure(locationFlags); return managementContext.getLocationManager().createLocation(locSpec); }

Target:
public Location newLocationFromString(Map locationFlags, String spec, LocationRegistry registry) { String id = spec.substring(NAME.length()+1); CatalogItem<?, ?> item = CatalogUtils.getCatalogItemOptionalVersion(managementContext, id); if (item.isDisabled()) { throw new IllegalStateException("Illegal use of disabled catalog item "+item.getSymbolicName()+":"+item.getVersion()); } else if (item.isDeprecated()) { log.warn("Use of deprecated catalog item "+item.getSymbolicName()+":"+item.getVersion()); } LocationSpec<?> origLocSpec = managementContext.getCatalog().createSpec((CatalogItem<Location, LocationSpec<?>>)item); LocationSpec<?> locSpec = LocationSpec.create(origLocSpec) .configure(locationFlags); return managementContext.getLocationManager().createLocation(locSpec); }
Source:
public void testWatermarkBeforeRecords() { final TestingWatermarkOutput output = new TestingWatermarkOutput(); final WatermarkGenerator<Object> watermarks = WatermarkStrategy .forBoundedOutOfOrderness(Duration.ofMillis(10)) .createWatermarkGenerator(() -> null); watermarks.onPeriodicEmit(output); assertNotNull(output.lastWatermark()); assertEquals(Long.MIN_VALUE, output.lastWatermark().getTimestamp()); }

Target:
public void testWatermarkBeforeRecords() { final TestingWatermarkOutput output = new TestingWatermarkOutput(); final BoundedOutOfOrdernessWatermarks<Object> watermarks = new BoundedOutOfOrdernessWatermarks<>(Duration.ofMillis(10)); watermarks.onPeriodicEmit(output); assertNotNull(output.lastWatermark()); assertEquals(Long.MIN_VALUE, output.lastWatermark().getTimestamp()); }
Source:
public void setSearchTweets(boolean flag) { searchtweets = flag; }

Target:
public void setSearchTweets(boolean flag) { this.searchtweets = flag; this.analyzer = flag? new TweetAnalyzer(true) : new EnglishAnalyzer(); }
Source:
public void testResultsUri() { final String expected = "<LINK_1>"; assertEquals(expected, engine.resultsUriForQuery("query")); }

Target:
public void testResultsUri() { final String query = "test query"; final Uri uri = Uri.parse(engine.resultsUriForQuery(query)); assertEquals("www.google.com", uri.getAuthority()); assertEquals(query, uri.getQueryParameter("q")); assertEquals("utf-8", uri.getQueryParameter("ie")); }
Source:
private boolean containsCompileDirectiveWithOption(@NotNull String option) { for (ErlangExpression expression : getCompileDirectiveExpressions()) { if (expression instanceof ErlangListExpression) { for (ErlangExpression e : ((ErlangListExpression) expression).getExpressionList()) { if (e instanceof ErlangMaxExpression && option.equals(ErlangPsiImplUtil.getAtomName((ErlangMaxExpression) e))) return true; } } else if (expression instanceof ErlangMaxExpression && option.equals(ErlangPsiImplUtil.getAtomName((ErlangMaxExpression) expression))) return true; } return false; }

Target:
private boolean containsCompileDirectiveWithOption(@NotNull String option) { for (ErlangExpression expression : getCompileDirectiveExpressions()) { if (expression instanceof ErlangListExpression) { for (ErlangExpression e : ((ErlangListExpression) expression).getExpressionList()) { if (e instanceof ErlangMaxExpression && option.equals(ErlangPsiImplUtil.getAtomName((ErlangMaxExpression) e))) { return true; } } } else if (expression instanceof ErlangMaxExpression && option.equals(ErlangPsiImplUtil.getAtomName((ErlangMaxExpression) expression))) { return true; } } return false; }
Source:
private Ds3ClientHelpers.Job buildRestoreJob(final Ds3ClientHelpers helper) throws IOException, CommandException { if (!this.pipe && !this.sync && Guard.isNullOrEmpty(this.prefixes)) { return helper.startReadAllJob(this.bucketName, ReadJobOptions.create().withPriority(this.priority)); } final Iterable<Ds3Object>objects = helper.toDs3Iterable(getObjects(helper), FolderNameFilter.filter());; return helper.startReadJob(this.bucketName, objects, ReadJobOptions.create().withPriority(this.priority)); }

Target:
private Ds3ClientHelpers.Job buildRestoreJob(final Ds3ClientHelpers helper) throws IOException, CommandException { if (!this.pipe && !this.sync && Guard.isNullOrEmpty(this.prefixes)) { return helper.startReadAllJob(this.bucketName, ReadJobOptions.create().withPriority(this.priority)); } final Iterable<Ds3Object>objects = helper.toDs3Iterable(getObjects(helper), FolderNameFilter.filter()); return helper.startReadJob(this.bucketName, objects, ReadJobOptions.create().withPriority(this.priority)); }
Source:
protected static void appendAttributes(Map<String, Object> parameters, Object config, String prefix) { if (config == null) { return; } Method[] methods = config.getClass().getMethods(); for (Method method : methods) { try { Parameter parameter = method.getAnnotation(Parameter.class); if (parameter == null || !parameter.attribute()) continue; String name = method.getName(); if ((name.startsWith("get") || name.startsWith("is")) && !"getClass".equals(name) && Modifier.isPublic(method.getModifiers()) && method.getParameterTypes().length == 0 && isPrimitive(method.getReturnType())) { String key; if (parameter.key().length() > 0) { key = parameter.key(); } else { int i = name.startsWith("get") ? 3 : 2; key = name.substring(i, i + 1).toLowerCase() + name.substring(i + 1); } Object value = method.invoke(config); if (value != null) { if (prefix != null && prefix.length() > 0) { key = prefix + "." + key; } parameters.put(key, value); } } } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } }

Target:
protected static void appendAttributes(Map<String, Object> parameters, Object config, String prefix) { if (config == null) { return; } Method[] methods = config.getClass().getMethods(); for (Method method : methods) { try { Parameter parameter = method.getAnnotation(Parameter.class); if (parameter == null || !parameter.attribute()) { continue; } String name = method.getName(); if ((name.startsWith("get") || name.startsWith("is")) && !"getClass".equals(name) && Modifier.isPublic(method.getModifiers()) && method.getParameterTypes().length == 0 && isPrimitive(method.getReturnType())) { String key; if (parameter.key().length() > 0) { key = parameter.key(); } else { int i = name.startsWith("get") ? 3 : 2; key = name.substring(i, i + 1).toLowerCase() + name.substring(i + 1); } Object value = method.invoke(config); if (value != null) { if (prefix != null && prefix.length() > 0) { key = prefix + "." + key; } parameters.put(key, value); } } } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } }
Source:
public void createNameFirstWordsHashBucketMatcher() { AffOrgMatcher matcher = FirstWordsHashBucketMatcherFactory.createNameFirstWordsHashBucketMatcher(); AffOrgJoiner joiner = getInternalState(matcher, AffOrgJoiner.class); assertTrue(joiner instanceof AffOrgHashBucketJoiner); BucketHasher<AffMatchAffiliation> affHasher = getInternalState(joiner, "affiliationBucketHasher"); assertTrue(affHasher instanceof AffiliationOrgNameBucketHasher); assertInternalStringPartFirstLettersHasher(affHasher, 2, 2); BucketHasher<AffMatchOrganization> orgHasher = getInternalState(joiner, "organizationBucketHasher"); assertTrue(orgHasher instanceof OrganizationNameBucketHasher); assertInternalStringPartFirstLettersHasher(affHasher, 2, 2); AffOrgMatchComputer computer = getInternalState(matcher, AffOrgMatchComputer.class); List<AffOrgMatchVoter> voters = getInternalState(computer, "affOrgMatchVoters"); assertNameFirstWordsHashBucketMatcherVoters(voters); }

Target:
public void createNameFirstWordsHashBucketMatcher() { AffOrgMatcher matcher = FirstWordsHashBucketMatcherFactory.createNameFirstWordsHashBucketMatcher(); AffOrgJoiner joiner = getInternalState(matcher, AffOrgJoiner.class); assertTrue(joiner instanceof AffOrgHashBucketJoiner); BucketHasher<AffMatchAffiliation> affHasher = getInternalState(joiner, "affiliationBucketHasher"); assertTrue(affHasher instanceof AffiliationOrgNameBucketHasher); assertInternalStringPartFirstLettersHasher(affHasher, 2, 2); BucketHasher<AffMatchOrganization> orgHasher = getInternalState(joiner, "organizationBucketHasher"); assertTrue(orgHasher instanceof OrganizationNameBucketHasher); assertInternalStringPartFirstLettersHasher(orgHasher, 2, 2); AffOrgMatchComputer computer = getInternalState(matcher, AffOrgMatchComputer.class); List<AffOrgMatchVoter> voters = getInternalState(computer, "affOrgMatchVoters"); assertNameFirstWordsHashBucketMatcherVoters(voters); }
Source:
public FormValidation doCheckProjects(@AncestorInPath Job<?,?> project, @QueryParameter String value ) { if(!project.hasPermission(Item.CONFIGURE)){ return FormValidation.ok(); } StringTokenizer tokens = new StringTokenizer(Util.fixNull(value),","); boolean hasProjects = false; while(tokens.hasMoreTokens()) { String projectName = tokens.nextToken().trim(); if (StringUtils.isBlank(projectName)) { return FormValidation.error(Messages.BuildTrigger_NoSuchProject(" ", "?")); } Item item = Jenkins.getInstance().getItem(projectName,project,Item.class); if(item==null){ Item nearest = Items.findNearest(Job.class, projectName, Jenkins.getInstance()); String alternative = nearest != null ? nearest.getRelativeNameFrom(project) : "?"; return FormValidation.error(Messages.BuildTrigger_NoSuchProject(projectName, alternative)); } if(!(item instanceof Job) || !(item instanceof ParameterizedJobMixIn.ParameterizedJob)) { return FormValidation.error(Messages.BuildTrigger_NotBuildable(projectName)); } Authentication auth = Tasks.getAuthenticationOf((ParameterizedJobMixIn.ParameterizedJob)project); if (auth.equals(ACL.SYSTEM) && !QueueItemAuthenticatorConfiguration.get().getAuthenticators().isEmpty()) { auth = Jenkins.ANONYMOUS; } if (!item.getACL().hasPermission(auth, Item.BUILD)) { return FormValidation.error(Messages.BuildTrigger_you_have_no_permission_to_build_(projectName)); } hasProjects = true; } if (!hasProjects) { return FormValidation.error(Messages.BuildTrigger_NoProjectSpecified()); } return FormValidation.ok(); }

Target:
public FormValidation doCheckProjects(@AncestorInPath Job<?,?> project, @QueryParameter String value ) { if(!project.hasPermission(Item.CONFIGURE)){ return FormValidation.ok(); } StringTokenizer tokens = new StringTokenizer(Util.fixNull(value),","); boolean hasProjects = false; while(tokens.hasMoreTokens()) { String projectName = tokens.nextToken().trim(); if (StringUtils.isBlank(projectName)) { return FormValidation.error("Blank project name in the list"); } Item item = Jenkins.getInstance().getItem(projectName,project,Item.class); if(item==null){ Item nearest = Items.findNearest(Job.class, projectName, Jenkins.getInstance()); String alternative = nearest != null ? nearest.getRelativeNameFrom(project) : "?"; return FormValidation.error(Messages.BuildTrigger_NoSuchProject(projectName, alternative)); } if(!(item instanceof Job) || !(item instanceof ParameterizedJobMixIn.ParameterizedJob)) { return FormValidation.error(Messages.BuildTrigger_NotBuildable(projectName)); } Authentication auth = Tasks.getAuthenticationOf((ParameterizedJobMixIn.ParameterizedJob)project); if (auth.equals(ACL.SYSTEM) && !QueueItemAuthenticatorConfiguration.get().getAuthenticators().isEmpty()) { auth = Jenkins.ANONYMOUS; } if (!item.getACL().hasPermission(auth, Item.BUILD)) { return FormValidation.error(Messages.BuildTrigger_you_have_no_permission_to_build_(projectName)); } hasProjects = true; } if (!hasProjects) { return FormValidation.error(Messages.BuildTrigger_NoProjectSpecified()); } return FormValidation.ok(); }
Source:
public void visitToken(DetailAST ast) { final String commentContent = JavadocUtil.getBlockCommentContent(ast); if (JavadocUtil.isJavadocComment(commentContent)) { final String[] commentLines = MATCH_COMMENT_SEPARATOR.split(commentContent); for (int i = 0; i < commentLines.length - 1; i++) { final String comment = commentLines[i]; if (CommonUtil.isBlank(comment) || comment.trim().charAt(0) != '*') { log(ast, MSG_MISSING_ASTERISK); } } } }

Target:
public void visitToken(DetailAST ast) { final String commentContent = JavadocUtil.getBlockCommentContent(ast); if (JavadocUtil.isJavadocComment(commentContent)) { final String[] commentLines = MATCH_COMMENT_SEPARATOR.split(commentContent); for (int i = 0; i < commentLines.length - 1; i++) { final String commentLine = commentLines[i]; if (!isValidLine(commentLine)) { log(ast, MSG_MISSING_ASTERISK); } } final String lastCommentLine = commentLines[commentLines.length - 1]; if (!CommonUtil.isBlank(lastCommentLine) && lastCommentLine.trim().charAt(0) != '*') { log(ast, MSG_MISSING_ASTERISK); } } }
Source:
public ImmutableSpongeBrewingStandData(Integer value) { super(ImmutableBrewingStandData.class, value, Keys.REMAINING_BREW_TIME); this.immutableValue = SpongeValueBuilder.boundedBuilder(Keys.REMAINING_BREW_TIME) .maximum(0).maximum(Integer.MAX_VALUE).defaultValue(0).actualValue(this.getValue()) .build().asImmutable(); }

Target:
public ImmutableSpongeBrewingStandData(Integer value) { super(ImmutableBrewingStandData.class, value, Keys.REMAINING_BREW_TIME); }
Source:
private boolean filter(Position position) { if (allowAlarms && position.getAttributes().containsKey(Position.KEY_ALARM)) { return false; } StringBuilder filterType = new StringBuilder(); Position last = null; if (Context.getIdentityManager() != null) { last = Context.getIdentityManager().getLastPosition(position.getDeviceId()); } if (filterInvalid(position)) { filterType.append("Invalid "); } if (filterZero(position)) { filterType.append("Zero "); } if (filterDuplicate(position, last)) { filterType.append("Duplicate "); } if (filterFuture(position)) { filterType.append("Future "); } if (filterApproximate(position)) { filterType.append("Approximate "); } if (filterStatic(position)) { filterType.append("Static "); } if (filterDistance(position, last)) { filterType.append("Distance "); } if (filterMaxSpeed(position, last)) { filterType.append("MaxSpeed "); } if (filterType.length() > 0 && !filterLimit(position, last)) { StringBuilder message = new StringBuilder(); message.append("Position filtered by "); message.append(filterType.toString()); message.append("filters from device: "); message.append(Context.getIdentityManager().getById(position.getDeviceId()).getUniqueId()); message.append(" with id: "); message.append(position.getDeviceId()); Log.info(message.toString()); return true; } return false; }

Target:
private boolean filter(Position position) { StringBuilder filterType = new StringBuilder(); Position last = null; if (Context.getIdentityManager() != null) { last = Context.getIdentityManager().getLastPosition(position.getDeviceId()); } if (skipLimit(position, last) || skipAlarms(position)) { return false; } if (filterInvalid(position)) { filterType.append("Invalid "); } if (filterZero(position)) { filterType.append("Zero "); } if (filterDuplicate(position, last)) { filterType.append("Duplicate "); } if (filterFuture(position)) { filterType.append("Future "); } if (filterApproximate(position)) { filterType.append("Approximate "); } if (filterStatic(position)) { filterType.append("Static "); } if (filterDistance(position, last)) { filterType.append("Distance "); } if (filterMaxSpeed(position, last)) { filterType.append("MaxSpeed "); } if (filterType.length() > 0) { StringBuilder message = new StringBuilder(); message.append("Position filtered by "); message.append(filterType.toString()); message.append("filters from device: "); message.append(Context.getIdentityManager().getById(position.getDeviceId()).getUniqueId()); message.append(" with id: "); message.append(position.getDeviceId()); Log.info(message.toString()); return true; } return false; }
Source:
public void stop() throws Exception { if (started) { server.stop(); serverThread.join(); started = false; currentLeader = null; if (curatorFramework.getState().equals(CuratorFrameworkState.STARTED)) { pathChildrenCache.getListenable().removeListener(this); pathChildrenCache.close(); leaderSelector.close(); curatorFramework.getConnectionStateListenable().removeListener(this); curatorFramework.close(); } log.info("Oracle server has been stopped."); } }

Target:
public synchronized void stop() throws Exception { if (started) { server.stop(); serverThread.join(); started = false; currentLeader = null; if (curatorFramework.getState().equals(CuratorFrameworkState.STARTED)) { pathChildrenCache.getListenable().removeListener(this); pathChildrenCache.close(); leaderSelector.close(); curatorFramework.getConnectionStateListenable().removeListener(this); curatorFramework.close(); } log.info("Oracle server has been stopped."); } }
Source:
public void testCreateRegionWithMinAndSize() { List<Vector3i> mins = Arrays.asList(new Vector3i(), new Vector3i(1, 1, 1), new Vector3i(3, 4, 5)); List<Vector3i> size = Arrays.asList(new Vector3i(1, 1, 1), new Vector3i(3, 3, 3), new Vector3i(8, 5, 2)); List<Vector3i> expectedMax = Arrays.asList(new Vector3i(1, 1, 1), new Vector3i(4, 4, 4), new Vector3i(11, 9, 7)); for (int i = 0; i < mins.size(); ++i) { BlockRegion region = new BlockRegion().union(mins.get(i)).setSize(size.get(i)); assertEquals(mins.get(i), region.getMin(new Vector3i())); assertEquals(size.get(i), region.getSize(new Vector3i())); assertEquals(expectedMax.get(i), region.getMax(new Vector3i())); } }

Target:
public void testCreateRegionWithMinAndSize() { List<Vector3i> mins = Arrays.asList(new Vector3i(), new Vector3i(1, 1, 1), new Vector3i(3, 4, 5)); List<Vector3i> size = Arrays.asList(new Vector3i(1, 1, 1), new Vector3i(3, 3, 3), new Vector3i(8, 5, 2)); List<Vector3i> expectedMax = Arrays.asList(new Vector3i(), new Vector3i(3, 3, 3), new Vector3i(10, 8, 6)); for (int i = 0; i < mins.size(); ++i) { BlockRegion region = new BlockRegion().setMin(mins.get(i)).setSize(size.get(i)); assertEquals(mins.get(i), region.getMin(new Vector3i())); assertEquals(size.get(i), region.getSize(new Vector3i())); assertEquals(expectedMax.get(i), region.getMax(new Vector3i())); } }
Source:
private void getRandomReadingListPage() { ReadingListPageDao.instance().randomPage(new CallbackTask.Callback<PageTitle>() { @Override public void success(@Nullable PageTitle title) { setProgress(false); if (getCallback() != null) { if (title != null) { getCallback().onSelectPage(new HistoryEntry(title, HistoryEntry.SOURCE_FEED_RANDOM)); } else { getCallback().onError(new RuntimeException(getString(R.string.view_random_card_error))); } } } }); }

Target:
private void getRandomReadingListPage() { ReadingListPageDao.instance().randomPage(new CallbackTask.Callback<PageTitle>() { @Override public void success(@Nullable PageTitle title) { if (getCallback() != null) { if (title != null) { getCallback().onSelectPage(new HistoryEntry(title, HistoryEntry.SOURCE_FEED_RANDOM)); } else { getCallback().onError(new RuntimeException(getString(R.string.view_random_card_error))); } } } }); }
Source:
public void onReceive(Context context, Intent intent) { if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { Pushwoosh.getInstance().registerForPushNotifications(result -> { if (result.isSuccess()) { Log.d(TAG, "Successfully registered for push notifications with token: " + result.getData()); } else { if (result.getException() != null) { Log.d(TAG, "Failed to register for push notifications:u " + result.getException().getMessage()); } } }); } }

Target:
public void onReceive(Context context, Intent intent) { if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { Pushwoosh.getInstance().registerForPushNotifications(result -> { if (result.isSuccess()) { Log.d(TAG, "Successfully registered for push notifications with token: " + result.getData()); } else { if (result.getException() != null) { Log.d(TAG, "Failed to register for push notifications: " + result.getException().getMessage()); } } }); } }
Source:
public void startGroup() { if (DEBUG_ENABLED) { ++indent; } if (DEBUG_ENABLED) { log("<!-- start group -->"); } delegate.startGroup(); }

Target:
public void startGroup() { ++indent; log("<!-- start group -->"); delegate.startGroup(); }
Source:
public void sendSMSMessage(StudyIdentifier studyId, Phone phone, String message) { checkNotNull(studyId); checkNotNull(phone); checkNotNull(message); if (message.length() > BridgeConstants.SMS_CHARACTER_LIMIT) { throw new BridgeServiceException("SMS message cannot be longer than 140 UTF-8/ASCII characters."); } Map<String, MessageAttributeValue> smsAttributes = Maps.newHashMap(); smsAttributes.put(SENDER_ID, attribute("Bridge")); smsAttributes.put(SMS_TYPE, attribute(SMS_TYPE_TRANSACTIONAL)); PublishResult result = snsClient.publish(new PublishRequest() .withMessage(message) .withPhoneNumber(phone.getNumber()) .withMessageAttributes(smsAttributes)); LOG.debug("Sent SMS message, study=" + studyId.getIdentifier() + ", message ID=" + result.getMessageId()); }

Target:
public void sendSMSMessage(StudyIdentifier studyId, Phone phone, String message) { checkNotNull(studyId); checkNotNull(phone); checkNotNull(message); if (message.getBytes(Charset.forName("US-ASCII")).length > BridgeConstants.SMS_CHARACTER_LIMIT) { throw new BridgeServiceException("SMS message cannot be longer than 140 UTF-8/ASCII characters."); } Map<String, MessageAttributeValue> smsAttributes = Maps.newHashMap(); smsAttributes.put(SENDER_ID, attribute("Bridge")); smsAttributes.put(SMS_TYPE, attribute(SMS_TYPE_TRANSACTIONAL)); PublishResult result = snsClient.publish(new PublishRequest() .withMessage(message) .withPhoneNumber(phone.getNumber()) .withMessageAttributes(smsAttributes)); LOG.debug("Sent SMS message, study=" + studyId.getIdentifier() + ", message ID=" + result.getMessageId()); }
Source:
public void setupTest() { EXTERNAL_ID.setHealthCode(null); EXTERNAL_ID.setSubstudyId(null); dao = new DynamoExternalIdDao(); dao.setMapper(mapper); dao.setGetExternalIdRateLimiter(rateLimiter); }

Target:
public void setupTest() { externalId = ExternalIdentifier.create(TEST_STUDY, ID); dao = new DynamoExternalIdDao(); dao.setMapper(mapper); dao.setGetExternalIdRateLimiter(rateLimiter); }
Source:
public CounterStateProvider(ITmfTrace trace) { super(trace, CounterAnalysis.ID); ImmutableSet.Builder<CounterAspect> counterAspects = new Builder<>(); Iterable<@NonNull ITmfEventAspect<?>> aspects = trace.getEventAspects(); for (ITmfEventAspect<?> aspect : aspects) { if (aspect instanceof CounterAspect) { counterAspects.add((CounterAspect) aspect); } } fCounterAspects = counterAspects.build(); }

Target:
public CounterStateProvider(ITmfTrace trace) { super(trace, CounterAnalysis.ID); Iterable<ITmfEventAspect<?>> counterAspects = Iterables.filter(trace.getEventAspects(), aspect -> aspect instanceof CounterAspect); fCounterAspects = ImmutableSet.copyOf(counterAspects); }
Source:
public int getRowCount() { HPCCJDBCUtils.traceoutln(Level.WARNING, "HPCCResultSet getRowCount - ONLY REPORTS THE CURRENT NUMBER OF ROWS RETRIEVED"); synchronized (rowsLock) { HPCCJDBCUtils.traceoutln(Level.WARNING, "HPCCResultSet getRowCount before"); if (wasrowspopulated) return rows.size(); else return -1; } }

Target:
public int getRowCount() { HPCCJDBCUtils.traceoutln(Level.WARNING, "HPCCResultSet getRowCount - ONLY REPORTS THE CURRENT NUMBER OF ROWS RETRIEVED"); synchronized (rowsLock) { HPCCJDBCUtils.traceoutln(Level.WARNING, "HPCCResultSet getRowCount before"); if (wasRowsObjPopulated) return rows.size(); else return InvalidRowCount; } }
Source:
public int hashCode() { return new HashCodeBuilder(17, 37).append(owner).append(created).append(failed).toHashCode(); }

Target:
public int hashCode() { return Objects.hash(owner, created, failed); }
Source:
public int getEstimatedSizeInBytes() { int result = INSTANCE_SIZE; result += path.length() * Character.BYTES; result += sizeOfObjectArray(blocks.size()); for (InternalHiveBlock block : blocks) { result += block.getEstimatedSizeInBytes(); } int numBuckets = 1; if (partitionInfo.getBucketConversion().isPresent()) { numBuckets = partitionInfo.getBucketConversion().get().getPartitionBucketCount(); } result += partitionInfo.getEstimatedSizeInBytes() / numBuckets; return result; }

Target:
public int getEstimatedSizeInBytes() { int result = INSTANCE_SIZE; result += relativeUri.length; result += blockEndOffsets.length * Long.BYTES; result += sizeOfObjectArray(blockAddresses.size()); for (List<HostAddress> addresses : blockAddresses) { result += sizeOfObjectArray(addresses.size()); for (HostAddress address : addresses) { result += HOST_ADDRESS_INSTANCE_SIZE + address.getHostText().length() * Character.BYTES; } } return result; }
Source:
public AdColonyAdOptions getAdOptionsFromAdConfig(MediationAdConfiguration adConfiguration) { AdColonyAdOptions adColonyAdOptions = null; if (adConfiguration.getMediationExtras() != null) { adColonyAdOptions = getAdOptionsFromExtras(adConfiguration.getMediationExtras()); } String bidResponse = adConfiguration.getBidResponse(); if (bidResponse != null && !bidResponse.equals("")) { if (adColonyAdOptions == null) { adColonyAdOptions = new AdColonyAdOptions(); } adColonyAdOptions.setOption(KEY_ADCOLONY_BID_RESPONSE, bidResponse); } return adColonyAdOptions; }

Target:
public AdColonyAdOptions getAdOptionsFromAdConfig(MediationAdConfiguration adConfiguration) { AdColonyAdOptions adColonyAdOptions = getAdOptionsFromExtras(adConfiguration.getMediationExtras()); String bidResponse = adConfiguration.getBidResponse(); if (bidResponse != null && !bidResponse.equals("")) { adColonyAdOptions.setOption(KEY_ADCOLONY_BID_RESPONSE, bidResponse); } return adColonyAdOptions; }
Source:
private OffsetResponse getLatestOffsetResponse(SimpleConsumer consumer, Map<TopicAndPartition, PartitionOffsetRequestInfo> offsetInfo, JobContext context) { for (int i = 0; i <= FETCH_FROM_LEADER_MAX_RETRIES; i++) { try { OffsetResponse offsetResponse = consumer.getOffsetsBefore(new OffsetRequest(offsetInfo, kafka.api.OffsetRequest.CurrentVersion(), CamusJob.getKafkaClientName(context))); if (offsetResponse == null || offsetResponse.hasError()) { throw new RuntimeException(); } return offsetResponse; } catch (RuntimeException e) { log.warn("Fetching offset from leader " + consumer.host() + ":" + consumer.port() + " has failed " + (i + 1) + " time(s). " + (FETCH_FROM_LEADER_MAX_RETRIES - i) + " retries left."); } } return null; }

Target:
private OffsetResponse getLatestOffsetResponse(SimpleConsumer consumer, Map<TopicAndPartition, PartitionOffsetRequestInfo> offsetInfo, JobContext context) { for (int i = 0; i < NUM_TRIES_FETCH_FROM_LEADER; i++) { try { OffsetResponse offsetResponse = consumer.getOffsetsBefore(new OffsetRequest(offsetInfo, kafka.api.OffsetRequest.CurrentVersion(), CamusJob.getKafkaClientName(context))); if (offsetResponse.hasError()) { throw new RuntimeException("offsetReponse has error."); } return offsetResponse; } catch (Exception e) { log.warn("Fetching offset from leader " + consumer.host() + ":" + consumer.port() + " has failed " + (i + 1) + " time(s). Reason: " + e.getMessage() + " " + (NUM_TRIES_FETCH_FROM_LEADER - i - 1) + " retries left."); if (i < NUM_TRIES_FETCH_FROM_LEADER - 1) { try { Thread.sleep((long)(Math.random() * (i + 1) * 1000)); } catch (InterruptedException e1) { log.error("Caught interrupted exception between retries of getting latest offsets. " + e1.getMessage()); } } } } return null; }
Source:
public String exportFile(HttpServletRequest req, HttpServletResponse response) { String fileName = this.userLabelPrinting.getFilenameDL(); if (fileName.indexOf(".pdf") != -1) { response.setContentType("application/pdf"); } else { response.setContentType("application/vnd.ms-excel"); } String encodedFilename = FileUtils.encodeFilenameForDownload(fileName); final String userAgent = req.getHeader("User-Agent"); if (userAgent.indexOf("MSIE") != -1 || userAgent.indexOf("Trident") != -1) { response.setHeader("Content-disposition", "attachment; filename=\"" + encodedFilename + "\";"); } else { response.setHeader("Content-disposition", "attachment; filename=\"" + encodedFilename + "\"; filename*=\"UTF-8''" + encodedFilename + "\";"); } response.setCharacterEncoding("UTF-8"); File xls = new File(this.userLabelPrinting.getFilenameDLLocation()); FileInputStream in; try { in = new FileInputStream(xls); OutputStream out = response.getOutputStream(); byte[] buffer = new byte[LabelPrintingController.BUFFER_SIZE]; int length = 0; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } in.close(); out.close(); } catch (FileNotFoundException e) { LabelPrintingController.LOG.error(e.getMessage(), e); } catch (IOException e) { LabelPrintingController.LOG.error(e.getMessage(), e); } return ""; }

Target:
public String exportFile(HttpServletRequest req, HttpServletResponse response) { String fileName = this.userLabelPrinting.getFilenameDL(); if (fileName.indexOf(".pdf") != -1) { response.setContentType("application/pdf"); } else { response.setContentType("application/vnd.ms-excel"); } FieldbookUtil.resolveContentDisposition(fileName, response, req.getHeader("User-Agent")); response.setCharacterEncoding("UTF-8"); File xls = new File(this.userLabelPrinting.getFilenameDLLocation()); FileInputStream in; try { in = new FileInputStream(xls); OutputStream out = response.getOutputStream(); byte[] buffer = new byte[LabelPrintingController.BUFFER_SIZE]; int length = 0; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } in.close(); out.close(); } catch (FileNotFoundException e) { LabelPrintingController.LOG.error(e.getMessage(), e); } catch (IOException e) { LabelPrintingController.LOG.error(e.getMessage(), e); } return ""; }
Source:
public void testJobQueueAddingJobsOneByOne() throws InterruptedException { String queueName = TestHelper.getTestMethodName(); JobQueue.Builder builder = TaskTestUtil.buildJobQueue(queueName); WorkflowConfig.Builder workflowCfgBuilder = new WorkflowConfig.Builder() .setWorkflowId(queueName) .setParallelJobs(1) .setJobPurgeInterval(-1); _driver.start(builder.setWorkflowConfig(workflowCfgBuilder.build()).build()); JobConfig.Builder jobBuilder = new JobConfig.Builder().setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setCommand(MockTask.TASK_COMMAND).setMaxAttemptsPerTask(2); _driver.enqueueJob(queueName, "JOB0", jobBuilder); for (int i = 1; i < 5; i++) { _driver.pollForJobState(queueName, TaskUtil.getNamespacedJobName(queueName, "JOB" + (i - 1)), 10000L, TaskState.COMPLETED); _driver.waitToStop(queueName, 5000L); _driver.enqueueJob(queueName, "JOB" + i, jobBuilder); _driver.resume(queueName); } _driver.pollForJobState(queueName, TaskUtil.getNamespacedJobName(queueName, "JOB" + 4), TaskState.COMPLETED); }

Target:
public void testJobQueueAddingJobsOneByOne() throws InterruptedException { String queueName = TestHelper.getTestMethodName(); JobQueue.Builder builder = TaskTestUtil.buildJobQueue(queueName); WorkflowConfig.Builder workflowCfgBuilder = new WorkflowConfig.Builder().setWorkflowId(queueName).setParallelJobs(1); _driver.start(builder.setWorkflowConfig(workflowCfgBuilder.build()).build()); JobConfig.Builder jobBuilder = new JobConfig.Builder().setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setCommand(MockTask.TASK_COMMAND).setMaxAttemptsPerTask(2); _driver.enqueueJob(queueName, "JOB0", jobBuilder); for (int i = 1; i < 5; i++) { _driver.pollForJobState(queueName, TaskUtil.getNamespacedJobName(queueName, "JOB" + (i - 1)), 10000L, TaskState.COMPLETED); _driver.waitToStop(queueName, 5000L); _driver.enqueueJob(queueName, "JOB" + i, jobBuilder); _driver.resume(queueName); } _driver.pollForJobState(queueName, TaskUtil.getNamespacedJobName(queueName, "JOB" + 4), TaskState.COMPLETED); }
Source:
public void multi_filter() { control = 0; server.configure(routes -> routes. get("/", "NOT FILTERED"). get("/other", "OTHER"). filter((uri, context, nextFilter) -> { control += 5; System.out.println("I'm a basic LOGGING filter"); return nextFilter.get(); }) .filter((uri, context, nextFilter) -> { control *= 3; if ("/".equals(uri)) { return new Payload("text/html", "FILTERED"); } return nextFilter.get(); })); control = 0; get("/other").produces("OTHER"); Assert.assertEquals(15, control); control = 0; get("/").produces("FILTERED"); Assert.assertEquals(15, control); }

Target:
public void multi_filter() { List<String> filters = new ArrayList<>(); server.configure(routes -> routes. get("/", "NOT FILTERED"). get("/other", "OTHER"). filter((uri, context, nextFilter) -> { filters.add("filter 1"); return nextFilter.get(); }) .filter((uri, context, nextFilter) -> { filters.add("filter 2"); if ("/".equals(uri)) { return new Payload("text/html", "FILTERED"); } return nextFilter.get(); })); get("/other").produces("OTHER"); assertThat(filters).containsExactly("filter 1", "filter 2"); filters.clear(); get("/").produces("FILTERED"); assertThat(filters).containsExactly("filter 1", "filter 2"); }
Source:
public ServicePort expose( KubernetesEnvironment k8sEnv, String backendServiceName, int backendServicePort, String protocol) throws InfrastructureException { ensureJwtProxyInjected(k8sEnv); int listenPort = availablePort++; proxyConfigBuilder.addVerifierProxy( listenPort, "http://" + backendServiceName + ":" + backendServicePort); k8sEnv .getConfigMaps() .get(getConfigMapName()) .getData() .put(JWT_PROXY_CONFIG_FILE, proxyConfigBuilder.build()); ServicePort exposedPort = new ServicePortBuilder() .withName(backendServiceName + "-" + listenPort) .withPort(listenPort) .withProtocol(protocol) .withNewTargetPort(listenPort) .build(); k8sEnv.getServices().get(getServiceName()).getSpec().getPorts().add(exposedPort); return exposedPort; }

Target:
public ServicePort expose( KubernetesEnvironment k8sEnv, String backendServiceName, int backendServicePort, String protocol) throws InfrastructureException { ensureJwtProxyInjected(k8sEnv); int listenPort = availablePort++; proxyConfigBuilder.addVerifierProxy( listenPort, "http://" + backendServiceName + ":" + backendServicePort); k8sEnv .getConfigMaps() .get(getConfigMapName()) .getData() .put(JWT_PROXY_CONFIG_FILE, proxyConfigBuilder.build()); ServicePort exposedPort = new ServicePortBuilder() .withName("server-" + listenPort) .withPort(listenPort) .withProtocol(protocol) .withNewTargetPort(listenPort) .build(); k8sEnv.getServices().get(getServiceName()).getSpec().getPorts().add(exposedPort); return exposedPort; }
Source:
public void startServerLazily(SensorContext context) throws IOException { if (failedToStart) { throw new NodeCommandException("Failed to start SonarJS eslint-bridge before, will not attempt again."); } try { if (isAlive()) { LOG.debug("SonarJS eslint-bridge server is up, no need to start."); return; } deploy(); startServer(context); } catch (NodeCommandException e) { LOG.error(e.getMessage(), e); failedToStart = true; throw e; } }

Target:
public void startServerLazily(SensorContext context) throws IOException, ServerAlreadyFailedException, NodeCommandException { if (failedToStart) { throw new ServerAlreadyFailedException(); } try { if (isAlive()) { LOG.debug("SonarJS eslint-bridge server is up, no need to start."); return; } deploy(); startServer(context); } catch (NodeCommandException e) { failedToStart = true; throw e; } }
Source:
public void onCreateSessionSafe(Bundle savedInstanceState) { super.onCreateSessionSafe(savedInstanceState); uiController.setupUI(); appUpdateController = AppUpdateControllerFactory.create(this::handleAppUpdate, getApplicationContext()); appUpdateController.register(); }

Target:
public void onCreateSessionSafe(Bundle savedInstanceState) { super.onCreateSessionSafe(savedInstanceState); uiController.setupUI(); }
Source:
protected Class<? extends BaseBlockRender> getRenderer() { return RenderQNB.class; }

Target:
protected Class<? extends RenderQNB> getRenderer() { return RenderQNB.class; }
Source:
private static byte readByte(ByteBuffer buffer, DataInput input, IntRef bytesRemaining) throws IOException { boolean needMore = false; while (true) { if (needMore) { readMore(buffer, input, bytesRemaining); needMore = false; } if (buffer.remaining() < 1 && bytesRemaining.value > 0) { needMore = true; } else { return buffer.get(); } } }

Target:
private static byte readByte(ByteBuffer buffer, DataInput input, IntRef bytesRemaining) throws IOException { if (buffer.remaining() < 1 && bytesRemaining.value > 0) { readMore(buffer, input, bytesRemaining); } return buffer.get(); }
Source:
protected AbstractConfig getConfig() { if(config == null) { throw new IllegalStateException("The configuration has not been set yet. Invoke start(props) first."); } return config; }

Target:
protected AbstractConfig getConfig() { if(config == null) { throw new IllegalStateException("The configuration has not been set yet. Invoke start(Map) first."); } return config; }
Source:
public String getLabel() { return "Drop Association as ReadLinkAction"; }

Target:
public String getLabel() { return Messages.AssociationToReadLinkActionDropStrategy_Label; }
Source:
private boolean isWithSecurityEnforced(final AbstractApexNode<?> node){ if(node instanceof ASTSoqlExpression){ String pattern = "(?i).*[^']\\s*WITH SECURITY_ENFORCED\\s*[^']*"; String query = ((ASTSoqlExpression) node).getQuery(); return query.matches(pattern); } return false; }

Target:
private boolean isWithSecurityEnforced(final AbstractApexNode<?> node) { if (node instanceof ASTSoqlExpression) { boolean temp = WITH_SECURITY_ENFORCED.matcher(((ASTSoqlExpression) node).getQuery()).matches(); return temp; } return false; }
Source:
public TaskExecution startTaskExecution(long executionId, String taskName, Date startTime, List<String> arguments, String externalExecutionId) { TaskExecution taskExecution = new TaskExecution(executionId, null, taskName, startTime, null, null, arguments, null, externalExecutionId); Object[] queryParameters = new Object[]{ startTime, taskName, new Date(), externalExecutionId, executionId}; int[] argTypes = new int[]{ Types.TIMESTAMP, Types.VARCHAR, Types.TIMESTAMP, Types.VARCHAR, Types.BIGINT }; String updateString = START_TASK_EXECUTION_PREFIX + START_TASK_EXECUTION_EXTERNAL_ID_SUFFIX; if(externalExecutionId == null) { queryParameters = new Object[]{startTime, taskName, new Date(), executionId}; updateString = START_TASK_EXECUTION_PREFIX + START_TASK_EXECUTION_SUFFIX; argTypes = new int[]{Types.TIMESTAMP, Types.VARCHAR, Types.TIMESTAMP, Types.BIGINT}; } jdbcTemplate.update(getQuery(updateString), queryParameters, argTypes); insertTaskArguments(executionId, arguments); return taskExecution; }

Target:
public TaskExecution startTaskExecution(long executionId, String taskName, Date startTime, List<String> arguments, String externalExecutionId) { return startTaskExecution(executionId, taskName, startTime, arguments, externalExecutionId, null); }
Source:
public void failuresSavedIfFetchKeysThrows() throws Exception { PartitionedRegion spyPartitionedRegion = spy(partitionedRegion); VersionedObjectList values = mock(VersionedObjectList.class); ServerConnection serverConnection = mock(ServerConnection.class); Set<Integer> failures = mock(Set.class); InternalDistributedMember member = mock(InternalDistributedMember.class); Set<Integer> buckets = new HashSet<>(); buckets.add(1); doThrow(new ForceReattemptException("")).when(spyPartitionedRegion).getFetchKeysResponse(member, 1); spyPartitionedRegion.fetchKeysAndValues(values, serverConnection, failures, member, null, buckets); verify(failures).add(1); verify(spyPartitionedRegion, never()).getValuesForKeys(values, serverConnection, null); }

Target:
public void failuresSavedIfFetchKeysThrows() throws Exception { PartitionedRegion spyPartitionedRegion = spy(partitionedRegion); VersionedObjectList values = mock(VersionedObjectList.class); ServerConnection serverConnection = mock(ServerConnection.class); Set<Integer> failures = new HashSet<>(); InternalDistributedMember member = mock(InternalDistributedMember.class); Set<Integer> buckets = new HashSet<>(); buckets.add(1); doThrow(new ForceReattemptException("")).when(spyPartitionedRegion).getFetchKeysResponse(member, 1); spyPartitionedRegion.fetchKeysAndValues(values, serverConnection, failures, member, null, buckets); verify(spyPartitionedRegion, never()).getValuesForKeys(values, serverConnection, null); assertThat(failures.contains(1)).isTrue(); }
Source:
private void initializeDefaultProjectAfterDelete() { getActivity().findViewById(R.id.fragment_container).setVisibility(View.GONE); getActivity().findViewById(R.id.progress_circle).setVisibility(View.VISIBLE); asyncTask = new AsyncTask<Void, Void, Activity>() { @Override protected Activity doInBackground(Void... params) { ProjectManager.getInstance().initializeDefaultProject(getActivity()); return getActivity(); } @Override protected void onPostExecute(Activity activity) { activity.findViewById(R.id.fragment_container).setVisibility(View.VISIBLE); activity.findViewById(R.id.progress_circle).setVisibility(View.GONE); initializeList(); } }.execute(); }

Target:
private void initializeDefaultProjectAfterDelete() { final Activity activity = getActivity(); projectInitializer = new AsyncTask<Void, Void, Void>() { @Override protected void onPreExecute() { activity.findViewById(R.id.fragment_container).setVisibility(View.GONE); activity.findViewById(R.id.progress_circle).setVisibility(View.VISIBLE); } @Override protected Void doInBackground(Void... params) { ProjectManager.getInstance().initializeDefaultProject(activity); return null; } @Override protected void onPostExecute(Void aVoid) { activity.findViewById(R.id.fragment_container).setVisibility(View.VISIBLE); activity.findViewById(R.id.progress_circle).setVisibility(View.GONE); initializeList(); } }.execute(); }